// Copyright 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
document.createElement("canvas").getContext||function(){function C(){}function B(a){this.type_=a,this.r1_=this.y1_=this.x1_=this.r0_=this.y0_=this.x0_=0,this.colors_=[]}function A(a,b,c){!z(b)||(a.m_=b,c&&(a.lineScale_=f(e(b[0][0]*b[1][1]-b[0][1]*b[1][0]))))}function z(a){var b=0;for(;b<3;b++){var c=0;for(;c<2;c++)if(!isFinite(a[b][c])||isNaN(a[b][c]))return!1}return!0}function y(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function w(a){this.m_=r(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.fillStyle=this.strokeStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=g*1,this.globalAlpha=1,this.canvas=a;var b=a.ownerDocument.createElement("div");b.style.width=a.clientWidth+"px",b.style.height=a.clientHeight+"px",b.style.overflow="hidden",b.style.position="absolute",a.appendChild(b),this.element_=b,this.lineScale_=this.arcScaleY_=this.arcScaleX_=1}function v(a){switch(a){case"butt":return"flat";case"round":return"round";case"square":default:return"square"}}function u(a){var b,c=1;a=String(a);if(a.substring(0,3)=="rgb"){var d=a.indexOf("(",3),e=a.indexOf(")",d+1),f=a.substring(d+1,e).split(",");b="#";var g=0;for(;g<3;g++)b+=o[Number(f[g])];f.length==4&&a.substr(3,1)=="a"&&(c=f[3])}else b=a;return{color:b,alpha:c}}function t(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function s(a,b){var c=r(),d=0;for(;d<3;d++){var e=0;for(;e<3;e++){var f=0,g=0;for(;g<3;g++)f+=a[d][g]*b[g][e];c[d][e]=f}}return c}function r(){return[[1,0,0],[0,1,0],[0,0,1]]}function n(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function m(a){var b=a.srcElement;switch(a.propertyName){case"width":b.style.width=b.attributes.width.nodeValue+"px",b.getContext().clearRect();break;case"height":b.style.height=b.attributes.height.nodeValue+"px",b.getContext().clearRect()}}function k(a,b){var c=j.call(arguments,2);return function(){return a.apply(b,c.concat(j.call(arguments)))}}function i(){return this.context_||(this.context_=new w(this))}var a=Math,b=a.round,c=a.sin,d=a.cos,e=a.abs,f=a.sqrt,g=10,h=g/2,j=Array.prototype.slice,l={init:function(a){if(/MSIE/.test(navigator.userAgent)&&!window.opera){var b=a||document;b.createElement("canvas"),b.attachEvent("onreadystatechange",k(this.init_,this,b))}},init_:function(a){a.namespaces.g_vml_||a.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml","#default#VML"),a.namespaces.g_o_||a.namespaces.add("g_o_","urn:schemas-microsoft-com:office:office","#default#VML");if(!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}g_vml_\\:*{behavior:url(#default#VML)}g_o_\\:*{behavior:url(#default#VML)}"}var c=a.getElementsByTagName("canvas"),d=0;for(;d<c.length;d++)this.initElement(c[d])},initElement:function(a){if(!a.getContext){a.getContext=i,a.innerHTML="",a.attachEvent("onpropertychange",m),a.attachEvent("onresize",n);var b=a.attributes;b.width&&b.width.specified?a.style.width=b.width.nodeValue+"px":a.width=a.clientWidth,b.height&&b.height.specified?a.style.height=b.height.nodeValue+"px":a.height=a.clientHeight}return a}};l.init();var o=[],p=0;for(;p<16;p++){var q=0;for(;q<16;q++)o[p*16+q]=p.toString(16)+q.toString(16)}var x=w.prototype;x.clearRect=function(){this.element_.innerHTML=""},x.beginPath=function(){this.currentPath_=[]},x.moveTo=function(a,b){var c=this.getCoords_(a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},x.lineTo=function(a,b){var c=this.getCoords_(a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},x.bezierCurveTo=function(a,b,c,d,e,f){var g=this.getCoords_(e,f),h=this.getCoords_(a,b),i=this.getCoords_(c,d);y(this,h,i,g)},x.quadraticCurveTo=function(a,b,c,d){var e=this.getCoords_(a,b),f=this.getCoords_(c,d),g={x:this.currentX_+.6666666666666666*(e.x-this.currentX_),y:this.currentY_+.6666666666666666*(e.y-this.currentY_)};y(this,g,{x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3},f)},x.arc=function(a,b,e,f,i,j){e*=g;var k=j?"at":"wa",l=a+d(f)*e-h,m=b+c(f)*e-h,n=a+d(i)*e-h,o=b+c(i)*e-h;l==n&&!j&&(l+=.125);var p=this.getCoords_(a,b),q=this.getCoords_(l,m),r=this.getCoords_(n,o);this.currentPath_.push({type:k,x:p.x,y:p.y,radius:e,xStart:q.x,yStart:q.y,xEnd:r.x,yEnd:r.y})},x.rect=function(a,b,c,d){this.moveTo(a,b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath()},x.strokeRect=function(a,b,c,d){var e=this.currentPath_;this.beginPath(),this.moveTo(a,b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath(),this.stroke(),this.currentPath_=e},x.fillRect=function(a,b,c,d){var e=this.currentPath_;this.beginPath(),this.moveTo(a,b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath(),this.fill(),this.currentPath_=e},x.createLinearGradient=function(a,b,c,d){var e=new B("gradient");e.x0_=a,e.y0_=b,e.x1_=c,e.y1_=d;return e},x.createRadialGradient=function(a,b,c,d,e,f){var g=new B("gradientradial");g.x0_=a,g.y0_=b,g.r0_=c,g.x1_=d,g.y1_=e,g.r1_=f;return g},x.drawImage=function(c){var d,e,f,h,i,j,k,l,m=c.runtimeStyle.width,n=c.runtimeStyle.height;c.runtimeStyle.width="auto",c.runtimeStyle.height="auto";var o=c.width,p=c.height;c.runtimeStyle.width=m,c.runtimeStyle.height=n;if(arguments.length==3)d=arguments[1],e=arguments[2],i=j=0,k=f=o,l=h=p;else if(arguments.length==5)d=arguments[1],e=arguments[2],f=arguments[3],h=arguments[4],i=j=0,k=o,l=p;else if(arguments.length==9)i=arguments[1],j=arguments[2],k=arguments[3],l=arguments[4],d=arguments[5],e=arguments[6],f=arguments[7],h=arguments[8];else throw Error("Invalid number of arguments");var q=this.getCoords_(d,e),r=[];r.push(" <g_vml_:group",' coordsize="',g*10,",",g*10,'"',' coordorigin="0,0"',' style="width:',10,"px;height:",10,"px;position:absolute;");if(this.m_[0][0]!=1||this.m_[0][1]){var s=[];s.push("M11=",this.m_[0][0],",","M12=",this.m_[1][0],",","M21=",this.m_[0][1],",","M22=",this.m_[1][1],",","Dx=",b(q.x/g),",","Dy=",b(q.y/g),"");var t=q,u=this.getCoords_(d+f,e),v=this.getCoords_(d,e+h),w=this.getCoords_(d+f,e+h);t.x=a.max(t.x,u.x,v.x,w.x),t.y=a.max(t.y,u.y,v.y,w.y),r.push("padding:0 ",b(t.x/g),"px ",b(t.y/g),"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",s.join(""),", sizingmethod='clip');")}else r.push("top:",b(q.y/g),"px;left:",b(q.x/g),"px;");r.push(' ">','<g_vml_:image src="',c.src,'"',' style="width:',g*f,"px;"," height:",g*h,'px;"',' cropleft="',i/o,'"',' croptop="',j/p,'"',' cropright="',(o-i-k)/o,'"',' cropbottom="',(p-j-l)/p,'"'," />","</g_vml_:group>"),this.element_.insertAdjacentHTML("BeforeEnd",r.join(""))},x.stroke=function(c){var d=[],e=u(c?this.fillStyle:this.strokeStyle),f=e.color,h=e.alpha*this.globalAlpha;d.push("<g_vml_:shape",' filled="',!!c,'"',' style="position:absolute;width:',10,"px;height:",10,'px;"',' coordorigin="0 0" coordsize="',g*10," ",g*10,'"',' stroked="',!c,'"',' path="');var i={x:null,y:null},j={x:null,y:null},k=0;for(;k<this.currentPath_.length;k++){var l=this.currentPath_[k];switch(l.type){case"moveTo":d.push(" m ",b(l.x),",",b(l.y));break;case"lineTo":d.push(" l ",b(l.x),",",b(l.y));break;case"close":d.push(" x "),l=null;break;case"bezierCurveTo":d.push(" c ",b(l.cp1x),",",b(l.cp1y),",",b(l.cp2x),",",b(l.cp2y),",",b(l.x),",",b(l.y));break;case"at":case"wa":d.push(" ",l.type," ",b(l.x-this.arcScaleX_*l.radius),",",b(l.y-this.arcScaleY_*l.radius)," ",b(l.x+this.arcScaleX_*l.radius),",",b(l.y+this.arcScaleY_*l.radius)," ",b(l.xStart),",",b(l.yStart)," ",b(l.xEnd),",",b(l.yEnd))}if(l){if(i.x==null||l.x<i.x)i.x=l.x;if(j.x==null||l.x>j.x)j.x=l.x;if(i.y==null||l.y<i.y)i.y=l.y;if(j.y==null||l.y>j.y)j.y=l.y}}d.push(' ">');if(c)if(typeof this.fillStyle=="object"){var m=this.fillStyle,n=0,o={x:0,y:0},p=0,q=1;if(m.type_=="gradient"){var r=m.x1_/this.arcScaleX_,s=m.y1_/this.arcScaleY_,t=this.getCoords_(m.x0_/this.arcScaleX_,m.y0_/this.arcScaleY_),w=this.getCoords_(r,s);n=Math.atan2(w.x-t.x,w.y-t.y)*180/Math.PI,n<0&&(n+=360),n<1e-6&&(n=0)}else{var t=this.getCoords_(m.x0_,m.y0_),x=j.x-i.x,y=j.y-i.y;o={x:(t.x-i.x)/x,y:(t.y-i.y)/y},x/=this.arcScaleX_*g,y/=this.arcScaleY_*g;var z=a.max(x,y);p=2*m.r0_/z,q=2*m.r1_/z-p}var A=m.colors_;A.sort(function(a,b){return a.offset-b.offset});var B=A.length,C=A[0].color,D=A[B-1].color,E=A[0].alpha*this.globalAlpha,F=A[B-1].alpha*this.globalAlpha,G=[],k=0;for(;k<B;k++){var H=A[k];G.push(H.offset*q+p+" "+H.color)}d.push('<g_vml_:fill type="',m.type_,'"',' method="none" focus="100%"',' color="',C,'"',' color2="',D,'"',' colors="',G.join(","),'"',' opacity="',F,'"',' g_o_:opacity2="',E,'"',' angle="',n,'"',' focusposition="',o.x,",",o.y,'" />')}else d.push('<g_vml_:fill color="',f,'" opacity="',h,'" />');else{var I=this.lineScale_*this.lineWidth;I<1&&(h*=I),d.push("<g_vml_:stroke",' opacity="',h,'"',' joinstyle="',this.lineJoin,'"',' miterlimit="',this.miterLimit,'"',' endcap="',v(this.lineCap),'"',' weight="',I,'px"',' color="',f,'" />')}d.push("</g_vml_:shape>"),this.element_.insertAdjacentHTML("beforeEnd",d.join(""))},x.fill=function(){this.stroke(!0)},x.closePath=function(){this.currentPath_.push({type:"close"})},x.getCoords_=function(a,b){var c=this.m_;return{x:g*(a*c[0][0]+b*c[1][0]+c[2][0])-h,y:g*(a*c[0][1]+b*c[1][1]+c[2][1])-h}},x.save=function(){var a={};t(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=s(r(),this.m_)},x.restore=function(){t(this.aStack_.pop(),this),this.m_=this.mStack_.pop()},x.translate=function(a,b){A(this,s([[1,0,0],[0,1,0],[a,b,1]],this.m_),!1)},x.rotate=function(a){var b=d(a),e=c(a);A(this,s([[b,e,0],[-e,b,0],[0,0,1]],this.m_),!1)},x.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b,A(this,s([[a,0,0],[0,b,0],[0,0,1]],this.m_),!0)},x.transform=function(a,b,c,d,e,f){A(this,s([[a,b,0],[c,d,0],[e,f,1]],this.m_),!0)},x.setTransform=function(a,b,c,d,e,f){A(this,[[a,b,0],[c,d,0],[e,f,1]],!0)},x.clip=function(){},x.arcTo=function(){},x.createPattern=function(){return new C},B.prototype.addColorStop=function(a,b){b=u(b),this.colors_.push({offset:a,color:b.color,alpha:b.alpha})},G_vmlCanvasManager=l,CanvasRenderingContext2D=w,CanvasGradient=B,CanvasPattern=C}();


/**
 * Version: 1.0 Alpha-1 
 * Build Date: 13-Nov-2007
 * Copyright (c) 2006-2007, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * License: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/. 
 * Website: http://www.datejs.com/ or http://www.coolite.com/datejs/
 */

Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|after|from)/i,subtract:/^(\-|before|ago)/i,yesterday:/^yesterday/i,today:/^t(oday)?/i,tomorrow:/^tomorrow/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^min(ute)?s?/i,hour:/^h(ou)?rs?/i,week:/^w(ee)?k/i,month:/^m(o(nth)?s?)?/i,day:/^d(ays?)?/i,year:/^y((ea)?rs?)?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a|p)/i},abbreviatedTimeZoneStandard:{GMT:"-000",EST:"-0400",CST:"-0500",MST:"-0600",PST:"-0700"},abbreviatedTimeZoneDST:{GMT:"-000",EDT:"-0500",CDT:"-0600",MDT:"-0700",PDT:"-0800"}};
Date.getMonthNumberFromName=function(name){var n=Date.CultureInfo.monthNames,m=Date.CultureInfo.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.getDayNumberFromName=function(name){var n=Date.CultureInfo.dayNames,m=Date.CultureInfo.abbreviatedDayNames,o=Date.CultureInfo.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.isLeapYear=function(year){return(((year%4===0)&&(year%100!==0))||(year%400===0));};Date.getDaysInMonth=function(year,month){return[31,(Date.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};Date.getTimezoneOffset=function(s,dst){return(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST[s.toUpperCase()]:Date.CultureInfo.abbreviatedTimeZoneStandard[s.toUpperCase()];};Date.getTimezoneAbbreviation=function(offset,dst){var n=(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard,p;for(p in n){if(n[p]===offset){return p;}}
return null;};Date.prototype.clone=function(){return new Date(this.getTime());};Date.prototype.compareTo=function(date){if(isNaN(this)){throw new Error(this);}
if(date instanceof Date&&!isNaN(date)){return(this>date)?1:(this<date)?-1:0;}else{throw new TypeError(date);}};Date.prototype.equals=function(date){return(this.compareTo(date)===0);};Date.prototype.between=function(start,end){var t=this.getTime();return t>=start.getTime()&&t<=end.getTime();};Date.prototype.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};Date.prototype.addSeconds=function(value){return this.addMilliseconds(value*1000);};Date.prototype.addMinutes=function(value){return this.addMilliseconds(value*60000);};Date.prototype.addHours=function(value){return this.addMilliseconds(value*3600000);};Date.prototype.addDays=function(value){return this.addMilliseconds(value*86400000);};Date.prototype.addWeeks=function(value){return this.addMilliseconds(value*604800000);};Date.prototype.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,this.getDaysInMonth()));return this;};Date.prototype.addYears=function(value){return this.addMonths(value*12);};Date.prototype.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.millisecond||x.milliseconds){this.addMilliseconds(x.millisecond||x.milliseconds);}
if(x.second||x.seconds){this.addSeconds(x.second||x.seconds);}
if(x.minute||x.minutes){this.addMinutes(x.minute||x.minutes);}
if(x.hour||x.hours){this.addHours(x.hour||x.hours);}
if(x.month||x.months){this.addMonths(x.month||x.months);}
if(x.year||x.years){this.addYears(x.year||x.years);}
if(x.day||x.days){this.addDays(x.day||x.days);}
return this;};Date._validate=function(value,min,max,name){if(typeof value!="number"){throw new TypeError(value+" is not a Number.");}else if(value<min||value>max){throw new RangeError(value+" is not a valid value for "+name+".");}
return true;};Date.validateMillisecond=function(n){return Date._validate(n,0,999,"milliseconds");};Date.validateSecond=function(n){return Date._validate(n,0,59,"seconds");};Date.validateMinute=function(n){return Date._validate(n,0,59,"minutes");};Date.validateHour=function(n){return Date._validate(n,0,23,"hours");};Date.validateDay=function(n,year,month){return Date._validate(n,1,Date.getDaysInMonth(year,month),"days");};Date.validateMonth=function(n){return Date._validate(n,0,11,"months");};Date.validateYear=function(n){return Date._validate(n,1,9999,"seconds");};Date.prototype.set=function(config){var x=config;if(!x.millisecond&&x.millisecond!==0){x.millisecond=-1;}
if(!x.second&&x.second!==0){x.second=-1;}
if(!x.minute&&x.minute!==0){x.minute=-1;}
if(!x.hour&&x.hour!==0){x.hour=-1;}
if(!x.day&&x.day!==0){x.day=-1;}
if(!x.month&&x.month!==0){x.month=-1;}
if(!x.year&&x.year!==0){x.year=-1;}
if(x.millisecond!=-1&&Date.validateMillisecond(x.millisecond)){this.addMilliseconds(x.millisecond-this.getMilliseconds());}
if(x.second!=-1&&Date.validateSecond(x.second)){this.addSeconds(x.second-this.getSeconds());}
if(x.minute!=-1&&Date.validateMinute(x.minute)){this.addMinutes(x.minute-this.getMinutes());}
if(x.hour!=-1&&Date.validateHour(x.hour)){this.addHours(x.hour-this.getHours());}
if(x.month!==-1&&Date.validateMonth(x.month)){this.addMonths(x.month-this.getMonth());}
if(x.year!=-1&&Date.validateYear(x.year)){this.addYears(x.year-this.getFullYear());}
if(x.day!=-1&&Date.validateDay(x.day,this.getFullYear(),this.getMonth())){this.addDays(x.day-this.getDate());}
if(x.timezone){this.setTimezone(x.timezone);}
if(x.timezoneOffset){this.setTimezoneOffset(x.timezoneOffset);}
return this;};Date.prototype.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};Date.prototype.isLeapYear=function(){var y=this.getFullYear();return(((y%4===0)&&(y%100!==0))||(y%400===0));};Date.prototype.isWeekday=function(){return!(this.is().sat()||this.is().sun());};Date.prototype.getDaysInMonth=function(){return Date.getDaysInMonth(this.getFullYear(),this.getMonth());};Date.prototype.moveToFirstDayOfMonth=function(){return this.set({day:1});};Date.prototype.moveToLastDayOfMonth=function(){return this.set({day:this.getDaysInMonth()});};Date.prototype.moveToDayOfWeek=function(day,orient){var diff=(day-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};Date.prototype.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};Date.prototype.getDayOfYear=function(){return Math.floor((this-new Date(this.getFullYear(),0,1))/86400000);};Date.prototype.getWeekOfYear=function(firstDayOfWeek){var y=this.getFullYear(),m=this.getMonth(),d=this.getDate();var dow=firstDayOfWeek||Date.CultureInfo.firstDayOfWeek;var offset=7+1-new Date(y,0,1).getDay();if(offset==8){offset=1;}
var daynum=((Date.UTC(y,m,d,0,0,0)-Date.UTC(y,0,1,0,0,0))/86400000)+1;var w=Math.floor((daynum-offset+7)/7);if(w===dow){y--;var prevOffset=7+1-new Date(y,0,1).getDay();if(prevOffset==2||prevOffset==8){w=53;}else{w=52;}}
return w;};Date.prototype.isDST=function(){console.log('isDST');return this.toString().match(/(E|C|M|P)(S|D)T/)[2]=="D";};Date.prototype.getTimezone=function(){return Date.getTimezoneAbbreviation(this.getUTCOffset,this.isDST());};Date.prototype.setTimezoneOffset=function(s){var here=this.getTimezoneOffset(),there=Number(s)*-6/10;this.addMinutes(there-here);return this;};Date.prototype.setTimezone=function(s){return this.setTimezoneOffset(Date.getTimezoneOffset(s));};Date.prototype.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r[0]+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};Date.prototype.getDayName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedDayNames[this.getDay()]:Date.CultureInfo.dayNames[this.getDay()];};Date.prototype.getMonthName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedMonthNames[this.getMonth()]:Date.CultureInfo.monthNames[this.getMonth()];};if(Date.prototype._toString==undefined) {Date.prototype._toString=Date.prototype.toString;};Date.prototype.toString=function(format){var self=this;var p=function p(s){return(s.toString().length==1)?"0"+s:s;};return format?format.replace(/dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?/g,function(format){switch(format){case"hh":return p(self.getHours()<13?self.getHours():(self.getHours()-12));case"h":return self.getHours()<13?self.getHours():(self.getHours()-12);case"HH":return p(self.getHours());case"H":return self.getHours();case"mm":return p(self.getMinutes());case"m":return self.getMinutes();case"ss":return p(self.getSeconds());case"s":return self.getSeconds();case"yyyy":return self.getFullYear();case"yy":return self.getFullYear().toString().substring(2,4);case"dddd":return self.getDayName();case"ddd":return self.getDayName(true);case"dd":return p(self.getDate());case"d":return self.getDate().toString();case"MMMM":return self.getMonthName();case"MMM":return self.getMonthName(true);case"MM":return p((self.getMonth()+1));case"M":return self.getMonth()+1;case"t":return self.getHours()<12?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case"tt":return self.getHours()<12?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case"zzz":case"zz":case"z":return"";}}):this._toString();};
Date.now=function(){return new Date();};Date.today=function(){return Date.now().clearTime();};Date.prototype._orient=+1;Date.prototype.next=function(){this._orient=+1;return this;};Date.prototype.last=Date.prototype.prev=Date.prototype.previous=function(){this._orient=-1;return this;};Date.prototype._is=false;Date.prototype.is=function(){this._is=true;return this;};Number.prototype._dateElement="day";Number.prototype.fromNow=function(){var c={};c[this._dateElement]=this;return Date.now().add(c);};Number.prototype.ago=function(){var c={};c[this._dateElement]=this*-1;return Date.now().add(c);};(function(){var $D=Date.prototype,$N=Number.prototype;var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),de;var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
return this.moveToDayOfWeek(n,this._orient);};};for(var i=0;i<dx.length;i++){$D[dx[i]]=$D[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};for(var j=0;j<mx.length;j++){$D[mx[j]]=$D[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$D[de]=$D[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}}());Date.prototype.toJSONString=function(){return this.toString("yyyy-MM-ddThh:mm:ssZ");};Date.prototype.toShortDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortDatePattern);};Date.prototype.toLongDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.longDatePattern);};Date.prototype.toShortTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortTimePattern);};Date.prototype.toLongTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.longTimePattern);};Date.prototype.getOrdinal=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};Date.Grammar={};Date.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=((s.length==3)?Date.getMonthNumberFromName(s):(Number(s)-1));};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<Date.CultureInfo.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];var now=new Date();this.year=now.getFullYear();this.month=now.getMonth();this.day=1;this.hour=0;this.minute=0;this.second=0;for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
this.hour=(this.meridian=="p"&&this.hour<13)?this.hour+12:this.hour;if(this.day>Date.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
if(this.now){return new Date();}
var today=Date.today();var method=null;var expression=!!(this.days!=null||this.orient||this.operator);if(expression){var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(this.weekday){this.unit="day";gap=(Date.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
if(this.unit=="week"){this.unit="day";this.value=this.value*7;}
this[this.unit+"s"]=this.value*orient;}
return today.add(this);}else{if(this.meridian&&this.hour){this.hour=(this.hour<13&&this.meridian=="p")?this.hour+12:this.hour;}
if(this.weekday&&!this.day){this.day=(today.addDays((Date.getDayNumberFromName(this.weekday)-today.getDay()))).getDate();}
if(this.month&&!this.day){this.day=1;}
return today.set(this);}}};var _=Date.Parsing.Operators,g=Date.Grammar,t=Date.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=Date.CultureInfo.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken(Date.CultureInfo.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.mm,g.ss],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^(\+|\-)?\s*\d\d\d\d?/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^(\+|\-)\s*\d\d\d\d/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[Date.CultureInfo.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw Date.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["yyyy-MM-ddTHH:mm:ss","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};}());Date._parse=Date.parse;Date.parse=function(s){var r=null;if(!s){return null;}
try{r=Date.Grammar.start.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};Date.getParseFunction=function(fx){var fn=Date.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};Date.parseExact=function(s,fx){return Date.getParseFunction(fx)(s);};
cfTables = {};

cfTables.serializeTable = function (table_id, raw_value_id) {
  var dataInput = $j(raw_value_id);
  var dataRows = $j(table_id + ' tbody tr.cf-table-data-row').map(function (_index, row) {
    var inputs = $j(row).find('.cf-table-input');

    var dataRow = {};

    inputs.each(function (_index, i) {
      dataRow[i.name] = i.value;
    });

    return dataRow;
  }).get();

  dataInput.val(JSON.stringify(dataRows));
};

cfTables.deserializeTable = function (table_id, raw_value_id) {
  var dataInput = $j(raw_value_id);

  try
  {
    var dataRows = JSON.parse($j(dataInput).val());
    // BP compatibility fix
    if ("string" == typeof(dataRows[0])) {
      dataRows = JSON.parse(dataRows[0]);
    }
    dataRows.forEach(function (dataRow, _index) {
      var emptyRow = cfTables.createEmptyRow(table_id, raw_value_id);
      var inputs = emptyRow.children().map(function (_index, e) {
        return $j(e).children()[0];
      });

      for(key in dataRow) {
        if (hasOwnProperty(dataRow,key)) {
          var value = dataRow[key];
          var input = inputs.get().find(function (e) { return e.name == key; });
          input.value = value;
        }
      }
    });
  } catch (e) {
    if (e instanceof SyntaxError) {
     // swallow this error. burrp.
    } else {
      throw e; // let others bubble up
    }
  }
}

cfTables.createEmptyRow = function (table_id, raw_value_id) {
  var handleChangeRow = function (e) { cfTables.serializeTable(table_id, raw_value_id); };
  var $templateRow = $j(table_id + '_cf-table-template-row').clone();
  var count = parseInt($j(table_id + ' .add_x_rows').val()) || 1;

  var emptyRow = null;

  for (var i=0; i < count; i++) {
    $emptyRow = $templateRow.clone();

    $emptyRow.id = null;
    $emptyRow.removeClass('cf-table-template-row');
    $emptyRow.addClass('cf-table-data-row');
    $j(table_id + ' tbody').append($emptyRow);
    var inputs = $emptyRow.children().map(function (_index, e) { return $j(e).children()[0]; });
    inputs.each(function (_index, i) {
      if(i.tagName.toUpperCase() == 'A') {
        $j(i).on('click', handleChangeRow);
      }
      else {
        $j(i).on('change', handleChangeRow);
      }
    });
  }

  return $emptyRow;
}

cfTables.removeRow = function (thisRemoveButton) {
  thisRemoveButton.parentNode.parentNode.remove();
};
/*
        TableSort revisited v5.0 by frequency-decoder.com

        Released under a creative commons Attribution-ShareAlike 2.5 license (http://creativecommons.org/licenses/by-sa/2.5/)

        Please credit frequency decoder in any derivative work - thanks

        You are free:

        * to copy, distribute, display, and perform the work
        * to make derivative works
        * to make commercial use of the work

        Under the following conditions:

                by Attribution.
                --------------
                You must attribute the work in the manner specified by the author or licensor.

                sa
                --
                Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one.

        * For any reuse or distribution, you must make clear to others the license terms of this work.
        * Any of these conditions can be waived if you get permission from the copyright holder.
*/


(function() {
fdTableSort = {
        regExp_Currency:        /^[£$€¥¤]/,
        regExp_Number:          /^(\-)?[0-9]+(\.[0-9]*)?$/,
        pos:                    -1,
        uniqueHash:             1,
        thNode:                 null,
        tableId:                null,
        tableCache:             {},
        tmpCache:               {},
        sortActiveClass:        "sort-active",
        /*@cc_on
        /*@if (@_win32)
        colspan:                "colSpan",
        rowspan:                "rowSpan",
        @else @*/
        colspan:                "colspan",
        rowspan:                "rowspan",
        /*@end
        @*/

        addEvent: function(obj, type, fn, tmp) {
                tmp || (tmp = true);
                if( obj.attachEvent ) {
                        obj["e"+type+fn] = fn;
                        obj[type+fn] = function(){obj["e"+type+fn]( window.event );};
                        obj.attachEvent( "on"+type, obj[type+fn] );
                } else {
                        obj.addEventListener( type, fn, true );
                };
        },
        removeEvent: function(obj, type, fn, tmp) {
                tmp || (tmp = true);
                try {
                        if( obj.detachEvent ) {
                                obj.detachEvent( "on"+type, obj[type+fn] );
                                obj[type+fn] = null;
                        } else {
                                obj.removeEventListener( type, fn, true );
                        };
                } catch(err) {};
        },
        stopEvent: function(e) {
                e = e || window.event;

                if(e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                };

                /*@cc_on@*/
                /*@if(@_win32)
                e.cancelBubble = true;
                e.returnValue  = false;
                /*@end@*/
                return false;
        },
        parseClassName: function(head, tbl) {
                var colMatch = tbl.className.match(new RegExp(head + "((-[\\d]+([r]){0,1})+)"));
                return colMatch && colMatch.length ? colMatch[0].replace(head, "").split("-") : [];
        },
        disableSelection: function(element) {
                element.onselectstart = function() {
                        return false;
                };
                element.unselectable = "on";
                element.style.MozUserSelect = "none";
        },
        removeTableCache: function(tableId) {
                if(!(tableId in fdTableSort.tableCache)) return;

                fdTableSort.tableCache[tableId] = null;
                delete fdTableSort.tableCache[tableId];

                var tbl = document.getElementById(tableId);
                if(!tbl) return;
                var ths = tbl.getElementsByTagName("th");
                var a;
                for(var i = 0, th; th = ths[i]; i++) {
                        a = th.getElementsByTagName("a");
                        if(a.length) a[0].onkeydown = a[0].onclick = null;
                        th.onclick = th.onselectstart = th = a = null;
                };
        },
        removeTmpCache: function(tableId) {
                if(!(tableId in fdTableSort.tmpCache)) return;
                var headers = fdTableSort.tmpCache[tableId].headers;
                var a;
                for(var i = 0, row; row = headers[i]; i++) {
                        for(var j = 0, th; th = row[j]; j++) {
                                a = th.getElementsByTagName("a");
                                if(a.length) a[0].onkeydown = a[0].onclick = null;
                                th.onclick = th.onselectstart = th = a = null;
                        };
                };
                fdTableSort.tmpCache[tableId] = null;
                delete fdTableSort.tmpCache[tableId];
        },
        initEvt: function(e) {
                fdTableSort.init(false);
        },
        init: function(tableId) {
                if (!document.getElementsByTagName || !document.createElement || !document.getElementById) return;

                var tables = tableId && document.getElementById(tableId) ? [document.getElementById(tableId)] : document.getElementsByTagName("table");
                var c, ii, len, colMatch, showOnly, match, showArrow, columnNumSortObj, obj, workArr, headers, thtext, aclone, multi, colCnt, cel, allRowArr, rowArr, sortableTable, celCount, colspan, rowspan, rowLength;

                var a          = document.createElement("a");
                a.href         = "#";
                a.className    = "fdTableSortTrigger";

                var span       = document.createElement("span");

                for(var k = 0, tbl; tbl = tables[k]; k++) {

                        if(tbl.id) {
                                fdTableSort.removeTableCache(tbl.id);
                                fdTableSort.removeTmpCache(tbl.id);
                        };

                        allRowArr     = tbl.getElementsByTagName('thead').length ? tbl.getElementsByTagName('thead')[0].getElementsByTagName('tr') : tbl.getElementsByTagName('tr');
                        rowArr        = [];
                        sortableTable = false;

                        for(var i = 0, tr; tr = allRowArr[i]; i++) {
                                if(tr.getElementsByTagName('td').length || !tr.getElementsByTagName('th').length) { continue; };
                                rowArr[rowArr.length] = tr.getElementsByTagName('th');
                                for(var j = 0, th; th = rowArr[rowArr.length - 1][j]; j++) {
                                        if(th.className.search(/sortable/) != -1) { sortableTable = true; };
                                };
                        };

                        if(!sortableTable) continue;

                        if(!tbl.id) { tbl.id = "fd-table-" + fdTableSort.uniqueHash++; };

                        showArrow   = tbl.className.search("no-arrow") == -1;
                        showOnly    = tbl.className.search("sortable-onload-show") != -1;

                        columnNumSortObj = {};
                        colMatch         = fdTableSort.parseClassName(showOnly ? "sortable-onload-show" : "sortable-onload", tbl);
                        for(match = 1; match < colMatch.length; match++) {
                                columnNumSortObj[parseInt(colMatch[match], 10)] = { "reverse":colMatch[match].search("r") != -1 };
                        };

                        rowLength = rowArr[0].length;

                        for(c = 0;c < rowArr[0].length;c++){
                                if(rowArr[0][c].getAttribute(fdTableSort.colspan) && rowArr[0][c].getAttribute(fdTableSort.colspan) > 1){
                                        rowLength = rowLength + (rowArr[0][c].getAttribute(fdTableSort.colspan) - 1);
                                };
                        };

                        workArr = new Array(rowArr.length);
                        for(c = rowArr.length;c--;){ workArr[c]= new Array(rowLength); };

                        for(c = 0;c < workArr.length;c++){
                                celCount = 0;
                                for(i = 0;i < rowLength;i++){
                                        if(!workArr[c][i]){
                                                cel = rowArr[c][celCount];
                                                colspan = (cel.getAttribute(fdTableSort.colspan) > 1) ? cel.getAttribute(fdTableSort.colspan):1;
                                                rowspan = (cel.getAttribute(fdTableSort.rowspan) > 1) ? cel.getAttribute(fdTableSort.rowspan):1;
                                                for(var t = 0;((t < colspan)&&((i+t) < rowLength));t++){
                                                        for(var n = 0;((n < rowspan)&&((c+n) < workArr.length));n++) {
                                                                workArr[(c+n)][(i+t)] = cel;
                                                        };
                                                };
                                                if(++celCount == rowArr[c].length) break;
                                        };
                                };
                        };

                        for(c = 0;c < workArr.length;c++) {
                                for(i = 0;i < workArr[c].length;i++){

                                        if(workArr[c][i].className.search("fd-column-") == -1 && workArr[c][i].className.search("sortable") != -1) workArr[c][i].className = workArr[c][i].className + " fd-column-" + i;

                                        if(workArr[c][i].className.match('sortable')) {
                                                workArr[c][i].className = workArr[c][i].className.replace(/forwardSort|reverseSort/, "");

                                                if(i in columnNumSortObj) {
                                                        columnNumSortObj[i]["thNode"] = workArr[c][i];
                                                        columnNumSortObj["active"] = true;
                                                };

                                                thtext = fdTableSort.getInnerText(workArr[c][i], true);

                                                for(var cn = workArr[c][i].childNodes.length; cn--;) {
                                                        // Skip image nodes and links created by the filter script.
                                                        if(workArr[c][i].childNodes[cn].nodeType == 1 && (workArr[c][i].childNodes[cn].className == "fdFilterTrigger" || /img/i.test(workArr[c][i].childNodes[cn].nodeName))) {
                                                                continue;
                                                        };
                                                        if(workArr[c][i].childNodes[cn].nodeType == 1 && /^a$/i.test(workArr[c][i].childNodes[cn].nodeName)) {
                                                                workArr[c][i].childNodes[cn].onclick = workArr[c][i].childNodes[cn].onkeydown = null;
                                                        };
                                                        workArr[c][i].removeChild(workArr[c][i].childNodes[cn]);
                                                };

                                                aclone = a.cloneNode(true);
                                                //aclone.appendChild(document.createTextNode(thtext));
                                                aclone.innerHTML = thtext;
                                                aclone.title = "Sort on \u201c" + thtext.replace('<br />', '') + "\u201d";
                                                aclone.onclick = aclone.onkeydown = workArr[c][i].onclick = fdTableSort.initWrapper;
                                                workArr[c][i].appendChild(aclone);
                                                if(showArrow) workArr[c][i].appendChild(span.cloneNode(false));
                                                workArr[c][i].className = workArr[c][i].className.replace(/fd-identical|fd-not-identical/, "");
                                                fdTableSort.disableSelection(workArr[c][i]);
                                                aclone = null;
                                        };
                                };
                        };

                        fdTableSort.tmpCache[tbl.id] = {cols:rowLength, headers:workArr};

                        workArr = null;
                        multi   = 0;

                        if("active" in columnNumSortObj) {
                                fdTableSort.tableId = tbl.id;
                                fdTableSort.prepareTableData(document.getElementById(fdTableSort.tableId));

                                delete columnNumSortObj["active"];

                                for(col in columnNumSortObj) {
                                        obj = columnNumSortObj[col];
                                        if(!("thNode" in obj)) { continue; };
                                        fdTableSort.multi = true;

                                        len = obj.reverse ? 2 : 1;

                                        for(ii = 0; ii < len; ii++) {
                                                fdTableSort.thNode = obj.thNode;
                                                if(!showOnly) {
                                                        fdTableSort.initSort(false, true);
                                                } else {
                                                        fdTableSort.addThNode();
                                                };
                                        };

                                        if(showOnly) {
                                                fdTableSort.removeClass(obj.thNode, "(forwardSort|reverseSort)");
                                                fdTableSort.addClass(obj.thNode, obj.reverse ? "reverseSort" : "forwardSort");
                                                if(showArrow) {
                                                        span = fdTableSort.thNode.getElementsByTagName('span')[0];
                                                        if(span.firstChild) { span.removeChild(span.firstChild); };
                                                        span.appendChild(document.createTextNode(len == 1 ? " \u2193" : " \u2191"));
                                                };
                                        };
                                };
                                if(showOnly && (fdTableSort.tableCache[tbl.id].colStyle || fdTableSort.tableCache[tbl.id].rowStyle)) {
                                        fdTableSort.redraw(tbl.id, false);
                                };
                        } else if(tbl.className.search(/onload-zebra/) != -1) {
                                fdTableSort.tableId = tbl.id;
                                fdTableSort.prepareTableData(tbl);
                                if(fdTableSort.tableCache[tbl.id].rowStyle) { fdTableSort.redraw(tbl.id, false); };
                        };
                };

                fdTableSort.thNode = aclone = a = span = columnNumSortObj = thNode = tbl = allRowArr = rowArr = null;
        },
        initWrapper: function(e) {
                e = e || window.event;
                var kc = e.type == "keydown" ? e.keyCode != null ? e.keyCode : e.charCode : -1;
                if(fdTableSort.thNode == null && (e.type == "click" || kc == 13)) {
                        var targ = this;
                        while(targ.tagName.toLowerCase() != "th") { targ = targ.parentNode; };
                        fdTableSort.thNode = targ;
                        while(targ.tagName.toLowerCase() != "table") { targ = targ.parentNode; };
                        fdTableSort.tableId = targ.id;
                        fdTableSort.multi = e.shiftKey;
                        fdTableSort.addSortActiveClass();
                        setTimeout(fdTableSort.initSort,5,false);
                        return fdTableSort.stopEvent(e);
                };
                return kc != -1 ? true : fdTableSort.stopEvent(e);
        },
        jsWrapper: function(tableid, colNums) {
                if(!(tableid in fdTableSort.tmpCache)) { return false; };
                if(!(tableid in fdTableSort.tableCache)) { fdTableSort.prepareTableData(document.getElementById(tableid)); };
                if(!(colNums instanceof Array)) { colNums = [colNums]; };

                fdTableSort.tableId = tableid;
                var len = colNums.length, colNum;

                if(fdTableSort.tableCache[tableid].thList.length == colNums.length) {
                        var identical = true;
                        var th;
                        for(var i = 0; i < len; i++) {
                                colNum = colNums[i];
                                th = fdTableSort.tmpCache[tableid].headers[0][colNum];
                                if(th != fdTableSort.tableCache[tableid].thList[i]) {
                                        identical = false;
                                        break;
                                };
                        };
                        if(identical) {
                                fdTableSort.thNode = th;
                                fdTableSort.initSort(true);
                                return;
                        };
                };

                fdTableSort.addSortActiveClass();

                for(var i = 0; i < len; i++) {
                        fdTableSort.multi = i;
                        colNum = colNums[i];
                        fdTableSort.thNode = fdTableSort.tmpCache[tableid].headers[0][colNum];
                        fdTableSort.initSort(true);
                };
        },
        addSortActiveClass: function() {
                if(fdTableSort.thNode == null) { return; };
                fdTableSort.addClass(fdTableSort.thNode, fdTableSort.sortActiveClass);
                fdTableSort.addClass(document.getElementsByTagName('body')[0], fdTableSort.sortActiveClass);
        },
        removeSortActiveClass: function() {
                if(fdTableSort.thNode == null) return;
                fdTableSort.removeClass(fdTableSort.thNode, fdTableSort.sortActiveClass);
                fdTableSort.removeClass(document.getElementsByTagName('body')[0], fdTableSort.sortActiveClass);
        },
        doCallback: function(init) {
                if(!fdTableSort.tableId || !(fdTableSort.tableId in fdTableSort.tableCache)) { return; };
                fdTableSort.callback(fdTableSort.tableId, init ? fdTableSort.tableCache[fdTableSort.tableId].initiatedCallback : fdTableSort.tableCache[fdTableSort.tableId].completeCallback);
        },
        addClass: function(e,c) {
                if(new RegExp("(^|\\s)" + c + "(\\s|$)").test(e.className)) { return; };
                e.className += ( e.className ? " " : "" ) + c;
        },
        /*@cc_on
        /*@if (@_win32)
        removeClass: function(e,c) {
                e.className = !c ? "" : e.className.replace(new RegExp("(^|\\s)" + c + "(\\s|$)"), " ").replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');
        },
        @else @*/
        removeClass: function(e,c) {
                e.className = !c ? "" : e.className.replace(new RegExp("(^|\\s)" + c + "(\\s|$)"), " ").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        },
        /*@end
        @*/
        callback: function(tblId, cb) {
                var func, parts;
                try {
                        if(cb.indexOf(".") != -1) {
                                parts = cb.split('.');
                                obj   = window;
                                for (var x = 0, part; part = obj[parts[x]]; x++) {
                                        if(part instanceof Function) {
                                                (function() {
                                                        var method = part;
                                                        func = function (data) { method.apply(obj, [data]) };
                                                })();
                                        } else {
                                                obj = part;
                                        };
                                };
                        } else if(cb + tblId in window) {
                                func = window[cb + tblId];
                        } else if(cb in window) {
                                func = window[cb];
                        } else {
                                func = null;
                        };
                 } catch(err) {};

                if(!(func instanceof Function)) return;
                func(tblId, fdTableSort.tableCache[tblId].thList);
        },
        prepareTableData: function(table) {
                var data = [];

                var start = table.getElementsByTagName('tbody');
                start = start.length ? start[0] : table;

                var trs = start.rows;
                var ths = table.getElementsByTagName('th');

                var numberOfRows = trs.length;
                var numberOfCols = fdTableSort.tmpCache[table.id].cols;

                var data = [];
                var identical = new Array(numberOfCols);
                var identVal  = new Array(numberOfCols);

                for(var tmp = 0; tmp < numberOfCols; tmp++) identical[tmp] = true;

                var tr, td, th, txt, tds, col, row;

                var re = new RegExp(/fd-column-([0-9]+)/);
                var rowCnt = 0;

                var sortableColumnNumbers = [];

                for(var tmp = 0, th; th = ths[tmp]; tmp++) {
                        if(th.className.search(re) == -1) continue;
                        sortableColumnNumbers[sortableColumnNumbers.length] = th;
                };

                for(row = 0; row < numberOfRows; row++) {

                        tr              = trs[row];
                        if(tr.parentNode != start || tr.getElementsByTagName("th").length || (tr.parentNode && tr.parentNode.tagName.toLowerCase().search(/thead|tfoot/) != -1)) continue;
                        data[rowCnt]    = [];
                        tds             = tr.cells;

                        for(var tmp = 0, th; th = sortableColumnNumbers[tmp]; tmp++) {
                                col = th.className.match(re)[1];

                                td  = tds[col];
                                txt = fdTableSort.getInnerText(td) + " ";
                                txt = txt.replace(/^\s+/,'').replace(/\s+$/,'');

                                if(th.className.search(/sortable-date/) != -1) {
                                        txt = fdTableSort.dateFormat(txt, th.className.search(/sortable-date-dmy/) != -1);
                                } else if(th.className.search(/sortable-numeric|sortable-currency/) != -1) {
                                        txt = parseFloat(txt.replace(/[^0-9\.\-]/g,''));
                                        if(isNaN(txt)) txt = "";
                                } else if(th.className.search(/sortable-text/) != -1) {
                                        txt = txt.toLowerCase();
                                } else if (th.className.search(/sortable-keep/) != -1) {
                                        txt = rowCnt;
                                } else if(th.className.search(/sortable-([a-zA-Z\_]+)/) != -1) {
                                        if((th.className.match(/sortable-([a-zA-Z\_]+)/)[1] + "PrepareData") in window) {
                                                txt = window[th.className.match(/sortable-([a-zA-Z\_]+)/)[1] + "PrepareData"](td, txt);
                                        };
                                } else if(txt != "") {
                                        fdTableSort.removeClass(th, "sortable");
                                        if(fdTableSort.dateFormat(txt) != 0) {
                                                fdTableSort.addClass(th, "sortable-date");
                                                txt = fdTableSort.dateFormat(txt);
                                        } else if(txt.search(fdTableSort.regExp_Number) != -1 || txt.search(fdTableSort.regExp_Currency) != -1) {
                                                fdTableSort.addClass(th, "sortable-numeric");
                                                txt = parseFloat(txt.replace(/[^0-9\.\-]/g,''));
                                                if(isNaN(txt)) txt = "";
                                        } else {
                                                fdTableSort.addClass(th, "sortable-text");
                                                txt = txt.toLowerCase();
                                        };
                                };

                                if(rowCnt > 0 && identical[col] && identVal[col] != txt) { identical[col] = false; };

                                identVal[col]     = txt;
                                data[rowCnt][col] = txt;
                        };
                        data[rowCnt][numberOfCols] = tr;
                        rowCnt++;
                };

                var colStyle = table.className.search(/colstyle-([\S]+)/) != -1 ? table.className.match(/colstyle-([\S]+)/)[1] : false;
                var rowStyle = table.className.search(/rowstyle-([\S]+)/) != -1 ? table.className.match(/rowstyle-([\S]+)/)[1] : false;
                var iCBack   = table.className.search(/sortinitiatedcallback-([\S-]+)/) == -1 ? "sortInitiatedCallback" : table.className.match(/sortinitiatedcallback-([\S]+)/)[1];
                var cCBack   = table.className.search(/sortcompletecallback-([\S-]+)/) == -1 ? "sortCompleteCallback" : table.className.match(/sortcompletecallback-([\S]+)/)[1];
                iCBack = iCBack.replace("-", ".");
                cCBack = cCBack.replace("-", ".");
                fdTableSort.tableCache[table.id] = { hook:start, initiatedCallback:iCBack, completeCallback:cCBack, thList:[], colOrder:{}, data:data, identical:identical, colStyle:colStyle, rowStyle:rowStyle, noArrow:table.className.search(/no-arrow/) != -1 };
                sortableColumnNumbers = data = tr = td = th = trs = identical = identVal = null;
        },
        onUnload: function() {
                for(tbl in fdTableSort.tableCache) { fdTableSort.removeTableCache(tbl); };
                for(tbl in fdTableSort.tmpCache) { fdTableSort.removeTmpCache(tbl); };
                fdTableSort.removeEvent(window, "load", fdTableSort.initEvt);
                fdTableSort.removeEvent(window, "unload", fdTableSort.onUnload);
                fdTableSort.tmpCache = fdTableSort.tableCache = null;
        },
        addThNode: function() {
                var dataObj = fdTableSort.tableCache[fdTableSort.tableId];
                var pos     = fdTableSort.thNode.className.match(/fd-column-([0-9]+)/)[1];
                var alt     = false;

                if(!fdTableSort.multi) {
                        if(dataObj.colStyle) {
                                var len = dataObj.thList.length;
                                for(var i = 0; i < len; i++) {
                                        dataObj.colOrder[dataObj.thList[i].className.match(/fd-column-([0-9]+)/)[1]] = false;
                                };
                        };
                        if(dataObj.thList.length && dataObj.thList[0] == fdTableSort.thNode) alt = true;
                        dataObj.thList = [];
                };

                var found = false;
                var l = dataObj.thList.length;

                for(var i = 0, n; n = dataObj.thList[i]; i++) {
                        if(n == fdTableSort.thNode) {
                                found = true;
                                break;
                        };
                };

                if(!found) {
                        dataObj.thList.push(fdTableSort.thNode);
                        if(dataObj.colStyle) { dataObj.colOrder[pos] = true; };
                };

                var ths = document.getElementById(fdTableSort.tableId).getElementsByTagName("th");
                for(var i = 0, th; th = ths[i]; i++) {
                        found = false;
                        for(var z = 0, n; n = dataObj.thList[z]; z++) {
                                if(n == th) {
                                        found = true;
                                        break;
                                };
                        };
                        if(!found) {
                                fdTableSort.removeClass(th, "(forwardSort|reverseSort)");
                                if(!dataObj.noArrow) {
                                        span = th.getElementsByTagName('span');
                                        if(span.length) {
                                                span = span[0];
                                                while(span.firstChild) span.removeChild(span.firstChild);
                                        };
                                };
                        };
                };

                if(dataObj.thList.length > 1) {
                        classToAdd = fdTableSort.thNode.className.search(/forwardSort/) != -1 ? "reverseSort" : "forwardSort";
                        fdTableSort.removeClass(fdTableSort.thNode, "(forwardSort|reverseSort)");
                        fdTableSort.addClass(fdTableSort.thNode, classToAdd);
                        dataObj.pos = -1
                } else if(alt) { dataObj.pos = fdTableSort.thNode };
        },
        initSort: function(noCallback, ident) {
                var thNode      = fdTableSort.thNode;
                var tableElem   = document.getElementById(fdTableSort.tableId);

                if(!(fdTableSort.tableId in fdTableSort.tableCache)) { fdTableSort.prepareTableData(document.getElementById(fdTableSort.tableId)); };

                fdTableSort.addThNode();

                if(!noCallback) { fdTableSort.doCallback(true); };

                fdTableSort.pos = thNode.className.match(/fd-column-([0-9]+)/)[1];
                var dataObj     = fdTableSort.tableCache[tableElem.id];
                var lastPos     = dataObj.pos && dataObj.pos.className ? dataObj.pos.className.match(/fd-column-([0-9]+)/)[1] : -1;
                var len1        = dataObj.data.length;
                var len2        = dataObj.data.length > 0 ? dataObj.data[0].length - 1 : 0;
                var identical   = dataObj.identical[fdTableSort.pos];
                var classToAdd  = "forwardSort";

                if(dataObj.thList.length > 1) {
                        var js  = "var sortWrapper = function(a,b) {\n";
                        var l   = dataObj.thList.length;
                        var cnt = 0;
                        var e,d,th,p,f;

                        for(var i=0; i < l; i++) {
                                th = dataObj.thList[i];
                                p  = th.className.match(/fd-column-([0-9]+)/)[1];
                                if(dataObj.identical[p]) { continue; };
                                cnt++;

                                if(th.className.match(/sortable-(numeric|currency|date|keep)/)) {
                                        f = "fdTableSort.sortNumeric";
                                } else if(th.className.match('sortable-text')) {
                                        f = "fdTableSort.sortText";
                                } else if(th.className.search(/sortable-([a-zA-Z\_]+)/) != -1 && th.className.match(/sortable-([a-zA-Z\_]+)/)[1] in window) {
                                        f = "window['" + th.className.match(/sortable-([a-zA-Z\_]+)/)[1] + "']";
                                } else  f = "fdTableSort.sortText";

                                e = "e" + i;
                                d = th.className.search('forwardSort') != -1 ? "a,b" : "b,a";
                                js += "fdTableSort.pos   = " + p + ";\n";
                                js += "var " + e + " = "+f+"(" + d +");\n";
                                js += "if(" + e + ") return " + e + ";\n";
                                js += "else { \n";
                        };

                        js += "return 0;\n";

                        for(var i=0; i < cnt; i++) {
                                js += "};\n";
                        };

                        if(cnt) js += "return 0;\n";
                        js += "};\n";

                        eval(js);
                        dataObj.data.sort(sortWrapper);
                        identical = false;
                } else if((lastPos == fdTableSort.pos && !identical) || (thNode.className.search(/sortable-keep/) != -1 && lastPos == -1)) {
                        dataObj.data.reverse();
                        classToAdd = thNode.className.search(/reverseSort/) != -1 ? "forwardSort" : "reverseSort";
                        if(thNode.className.search(/sortable-keep/) != -1 && lastPos == -1) fdTableSort.tableCache[tableElem.id].pos = thNode;
                } else {
                        fdTableSort.tableCache[tableElem.id].pos = thNode;
                        classToAdd = thNode.className.search(/forwardSort/) != -1 ? "reverseSort" : "forwardSort";
                        if(!identical) {
                                console.log(window)
                                if(thNode.className.match(/sortable-(numeric|currency|date|keep)/)) {
                                        dataObj.data.sort(fdTableSort.sortNumeric);
                                } else if(thNode.className.match('sortable-text')) {
                                        dataObj.data.sort(fdTableSort.sortText);
                                } else if(thNode.className.search(/sortable-([a-zA-Z\_]+)/) != -1 && thNode.className.match(/sortable-([a-zA-Z\_]+)/)[1] in window) {
                                        dataObj.data.sort(window[thNode.className.match(/sortable-([a-zA-Z\_]+)/)[1]]);

                                };

                                if(thNode.className.search(/(^|\s)favour-reverse($|\s)/) != -1) {
                                        classToAdd = classToAdd == "forwardSort" ? "reverseSort" : "forwardSort";
                                        dataObj.data.reverse();
                                };
                        };
                };
                if(ident) { identical = false; };
                if(dataObj.thList.length == 1) {
                        fdTableSort.removeClass(thNode, "(forwardSort|reverseSort)");
                        fdTableSort.addClass(thNode, classToAdd);
                };
                if(!dataObj.noArrow) {
                        var span = fdTableSort.thNode.getElementsByTagName('span')[0];
                        if(span.firstChild) span.removeChild(span.firstChild);
                        span.appendChild(document.createTextNode(fdTableSort.thNode.className.search(/forwardSort/) != -1 ? " \u2193" : " \u2191"));
                };
                if(!dataObj.rowStyle && !dataObj.colStyle && identical) {
                        fdTableSort.removeSortActiveClass();
                        if(!noCallback) { fdTableSort.doCallback(false); };
                        fdTableSort.thNode = null;
                        return;
                };
                if("tablePaginater" in window && tablePaginater.tableIsPaginated(fdTableSort.tableId)) {
                        tablePaginater.redraw(fdTableSort.tableId, identical);
                } else {
                        fdTableSort.redraw(fdTableSort.tableId, identical);
                };
                fdTableSort.removeSortActiveClass();
                if(!noCallback) { fdTableSort.doCallback(false); };
                fdTableSort.thNode = null;
        },
        redraw: function(tableid, identical) {
                if(!tableid || !(tableid in fdTableSort.tableCache)) { return; };
                var dataObj     = fdTableSort.tableCache[tableid];
                var data        = dataObj.data;
                var len1        = data.length;
                var len2        = len1 ? data[0].length - 1 : 0;
                var hook        = dataObj.hook;
                var colStyle    = dataObj.colStyle;
                var rowStyle    = dataObj.rowStyle;
                var colOrder    = dataObj.colOrder;
                var highLight   = 0;
                var reg         = /(^|\s)invisibleRow(\s|$)/;
                var tr, tds;

                for(var i = 0; i < len1; i++) {
                        tr = data[i][len2];
                        if(colStyle) {
                                tds = tr.cells;
                                for(thPos in colOrder) {
                                        if(!colOrder[thPos]) fdTableSort.removeClass(tds[thPos], colStyle);
                                        else fdTableSort.addClass(tds[thPos], colStyle);
                                };
                        };
                        if(!identical) {
                                if(rowStyle && tr.className.search(reg) == -1) {
                                        if(highLight++ & 1) fdTableSort.addClass(tr, rowStyle);
                                        else fdTableSort.removeClass(tr, rowStyle);
                                };

                                // Netscape 8.1.2 requires the removeChild call or it freaks out, so add the line if you want to support this browser
                                // hook.removeChild(tr);
                                hook.appendChild(tr);
                        };
                };
                tr = tds = hook = null;
        },
        getInnerText: function(el, allowBrTags) {
                if (typeof el == "string" || typeof el == "undefined") return el;
                if(el.innerText) return el.innerText;
                var txt = '', i;
                for(i = el.firstChild; i; i = i.nextSibling) {
                        if(allowBrTags && i.nodeName && i.nodeName == "BR") txt += "<br />";
                        else if(i.nodeType == 3)       txt += i.nodeValue;
                        else if(i.nodeType == 1)       txt += fdTableSort.getInnerText(i);
                };
                return txt;
        },
        dateFormat: function(dateIn, favourDMY) {
                var dateTest = [
                        { regExp:/^(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])([- \/.])((\d\d)?\d\d)$/, d:3, m:1, y:5 },  // mdy
                        { regExp:/^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, d:1, m:3, y:5 },  // dmy
                        { regExp:/^(\d\d\d\d)([- \/.])(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])$/, d:5, m:3, y:1 }      // ymd
                        ];
                var start, cnt = 0, numFormats = dateTest.length;
                while(cnt < numFormats) {
                        start = (cnt + (favourDMY ? numFormats + 1 : numFormats)) % numFormats;
                        if(dateIn.match(dateTest[start].regExp)) {
                                res = dateIn.match(dateTest[start].regExp);
                                y = res[dateTest[start].y];
                                m = res[dateTest[start].m];
                                d = res[dateTest[start].d];
                                if(m.length == 1) m = "0" + String(m);
                                if(d.length == 1) d = "0" + String(d);
                                if(y.length != 4) y = (parseInt(y) < 50) ? "20" + String(y) : "19" + String(y);

                                return y+String(m)+d;
                        };
                        cnt++;
                };
                return 0;
        },
        sortNumeric:function(a,b) {
                var aa = a[fdTableSort.pos];
                var bb = b[fdTableSort.pos];
                if(aa == bb) return 0;
                if(aa === "" && !isNaN(bb)) return -1;
                if(bb === "" && !isNaN(aa)) return 1;
                return aa - bb;
        },
        sortText:function(a,b) {
                var aa = a[fdTableSort.pos];
                var bb = b[fdTableSort.pos];
                if(aa == bb) return 0;
                if(aa < bb)  return -1;
                return 1;
        }
};

})();
fdTableSort.addEvent(window, "load",   fdTableSort.initEvt);
fdTableSort.addEvent(window, "unload", fdTableSort.onUnload);
/**
 * jscolor, JavaScript Color Picker
 *
 * @version 1.3.1
 * @license GNU Lesser General Public License, http://www.gnu.org/copyleft/lesser.html
 * @author  Jan Odvarko, http://odvarko.cz
 * @created 2008-06-15
 * @updated 2010-01-23
 * @link    http://jscolor.com
 */



var jscolor = {


	dir : '/javascripts/jscolor/', // location of jscolor directory (leave empty to autodetect)
	bindClass : 'color', // class name
	binding : true, // automatic binding via <input class="...">
	preloading : true, // use image preloading?


	install : function() {
		jscolor.addEvent(window, 'load', jscolor.init);
	},


	init : function() {
		if(jscolor.binding) {
			jscolor.bind();
		}
		if(jscolor.preloading) {
			jscolor.preload();
		}
	},


	getDir : function() {
		if(!jscolor.dir) {
			var detected = jscolor.detectDir();
			jscolor.dir = detected!==false ? detected : 'jscolor/';
		}
		return jscolor.dir;
	},


	detectDir : function() {
		var base = location.href;

		var e = document.getElementsByTagName('base');
		for(var i=0; i<e.length; i+=1) {
			if(e[i].href) { base = e[i].href; }
		}

		var e = document.getElementsByTagName('script');
		for(var i=0; i<e.length; i+=1) {
			if(e[i].src && /(^|\/)jscolor\.js([?#].*)?$/i.test(e[i].src)) {
				var src = new jscolor.URI(e[i].src);
				var srcAbs = src.toAbsolute(base);
				srcAbs.path = srcAbs.path.replace(/[^\/]+$/, ''); // remove filename
				srcAbs.query = null;
				srcAbs.fragment = null;
				return srcAbs.toString();
			}
		}
		return false;
	},


	bind : function() {
		var matchClass = new RegExp('(^|\\s)('+jscolor.bindClass+')\\s*(\\{[^}]*\\})?', 'i');
		var e = document.getElementsByTagName('input');
		for(var i=0; i<e.length; i+=1) {
			var m;
			if(!e[i].color && e[i].className && (m = e[i].className.match(matchClass))) {
				var prop = {};
				if(m[3]) {
					try {
						eval('prop='+m[3]);
					} catch(eInvalidProp) {}
				}
				e[i].color = new jscolor.color(e[i], prop);
			}
		}
	},


	preload : function() {
		for(var fn in jscolor.imgRequire) {
			if(jscolor.imgRequire.hasOwnProperty(fn)) {
				jscolor.loadImage(fn);
			}
		}
	},


	images : {
		pad : [ 181, 101 ],
		sld : [ 16, 101 ],
		cross : [ 15, 15 ],
		arrow : [ 7, 11 ]
	},


	imgRequire : {},
	imgLoaded : {},


	requireImage : function(filename) {
		jscolor.imgRequire[filename] = true;
	},


	loadImage : function(filename) {
		if(!jscolor.imgLoaded[filename]) {
			jscolor.imgLoaded[filename] = new Image();
			jscolor.imgLoaded[filename].src = jscolor.getDir()+filename;
		}
	},


	fetchElement : function(mixed) {
		return typeof mixed === 'string' ? document.getElementById(mixed) : mixed;
	},


	addEvent : function(el, evnt, func) {
		if(el.addEventListener) {
			el.addEventListener(evnt, func, false);
		} else if(el.attachEvent) {
			el.attachEvent('on'+evnt, func);
		}
	},


	fireEvent : function(el, evnt) {
		if(!el) {
			return;
		}
		if(document.createEventObject) {
			var ev = document.createEventObject();
			el.fireEvent('on'+evnt, ev);
		} else if(document.createEvent) {
			var ev = document.createEvent('HTMLEvents');
			ev.initEvent(evnt, true, true);
			el.dispatchEvent(ev);
		} else if(el['on'+evnt]) { // alternatively use the traditional event model (IE5)
			el['on'+evnt]();
		}
	},


	getElementPos : function(e) {
		var e1=e, e2=e;
		var x=0, y=0;
		if(e1.offsetParent) {
			do {
				x += e1.offsetLeft;
				y += e1.offsetTop;
			} while(e1 = e1.offsetParent);
		}
		while((e2 = e2.parentNode) && e2.nodeName.toUpperCase() !== 'BODY') {
			x -= e2.scrollLeft;
			y -= e2.scrollTop;
		}
		return [x, y];
	},


	getElementSize : function(e) {
		return [e.offsetWidth, e.offsetHeight];
	},


	getMousePos : function(e) {
		if(!e) { e = window.event; }
		if(typeof e.pageX === 'number') {
			return [e.pageX, e.pageY];
		} else if(typeof e.clientX === 'number') {
			return [
				e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft,
				e.clientY + document.body.scrollTop + document.documentElement.scrollTop
			];
		}
	},


	getViewPos : function() {
		if(typeof window.pageYOffset === 'number') {
			return [window.pageXOffset, window.pageYOffset];
		} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			return [document.body.scrollLeft, document.body.scrollTop];
		} else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
		} else {
			return [0, 0];
		}
	},


	getViewSize : function() {
		if(typeof window.innerWidth === 'number') {
			return [window.innerWidth, window.innerHeight];
		} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
			return [document.body.clientWidth, document.body.clientHeight];
		} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
			return [document.documentElement.clientWidth, document.documentElement.clientHeight];
		} else {
			return [0, 0];
		}
	},


	URI : function(uri) { // See RFC3986

		this.scheme = null;
		this.authority = null;
		this.path = '';
		this.query = null;
		this.fragment = null;

		this.parse = function(uri) {
			var m = uri.match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/);
			this.scheme = m[3] ? m[2] : null;
			this.authority = m[5] ? m[6] : null;
			this.path = m[7];
			this.query = m[9] ? m[10] : null;
			this.fragment = m[12] ? m[13] : null;
			return this;
		};

		this.toString = function() {
			var result = '';
			if(this.scheme !== null) { result = result + this.scheme + ':'; }
			if(this.authority !== null) { result = result + '//' + this.authority; }
			if(this.path !== null) { result = result + this.path; }
			if(this.query !== null) { result = result + '?' + this.query; }
			if(this.fragment !== null) { result = result + '#' + this.fragment; }
			return result;
		};

		this.toAbsolute = function(base) {
			var base = new jscolor.URI(base);
			var r = this;
			var t = new jscolor.URI;

			if(base.scheme === null) { return false; }

			if(r.scheme !== null && r.scheme.toLowerCase() === base.scheme.toLowerCase()) {
				r.scheme = null;
			}

			if(r.scheme !== null) {
				t.scheme = r.scheme;
				t.authority = r.authority;
				t.path = removeDotSegments(r.path);
				t.query = r.query;
			} else {
				if(r.authority !== null) {
					t.authority = r.authority;
					t.path = removeDotSegments(r.path);
					t.query = r.query;
				} else {
					if(r.path === '') { // TODO: == or === ?
						t.path = base.path;
						if(r.query !== null) {
							t.query = r.query;
						} else {
							t.query = base.query;
						}
					} else {
						if(r.path.substr(0,1) === '/') {
							t.path = removeDotSegments(r.path);
						} else {
							if(base.authority !== null && base.path === '') { // TODO: == or === ?
								t.path = '/'+r.path;
							} else {
								t.path = base.path.replace(/[^\/]+$/,'')+r.path;
							}
							t.path = removeDotSegments(t.path);
						}
						t.query = r.query;
					}
					t.authority = base.authority;
				}
				t.scheme = base.scheme;
			}
			t.fragment = r.fragment;

			return t;
		};

		function removeDotSegments(path) {
			var out = '';
			while(path) {
				if(path.substr(0,3)==='../' || path.substr(0,2)==='./') {
					path = path.replace(/^\.+/,'').substr(1);
				} else if(path.substr(0,3)==='/./' || path==='/.') {
					path = '/'+path.substr(3);
				} else if(path.substr(0,4)==='/../' || path==='/..') {
					path = '/'+path.substr(4);
					out = out.replace(/\/?[^\/]*$/, '');
				} else if(path==='.' || path==='..') {
					path = '';
				} else {
					var rm = path.match(/^\/?[^\/]*/)[0];
					path = path.substr(rm.length);
					out = out + rm;
				}
			}
			return out;
		}

		if(uri) {
			this.parse(uri);
		}

	},


	/*
	 * Usage example:
	 * var myColor = new jscolor.color(myInputElement)
	 */

	color : function(target, prop) {


		this.required = true; // refuse empty values?
		this.adjust = true; // adjust value to uniform notation?
		this.hash = false; // prefix color with # symbol?
		this.caps = true; // uppercase?
		this.valueElement = target; // value holder
		this.styleElement = target; // where to reflect current color
		this.hsv = [0, 0, 1]; // read-only  0-6, 0-1, 0-1
		this.rgb = [1, 1, 1]; // read-only  0-1, 0-1, 0-1

		this.pickerOnfocus = true; // display picker on focus?
		this.pickerMode = 'HSV'; // HSV | HVS
		this.pickerPosition = 'bottom'; // left | right | top | bottom
		this.pickerFace = 10; // px
		this.pickerFaceColor = 'ThreeDFace'; // CSS color
		this.pickerBorder = 1; // px
		this.pickerBorderColor = 'ThreeDHighlight ThreeDShadow ThreeDShadow ThreeDHighlight'; // CSS color
		this.pickerInset = 1; // px
		this.pickerInsetColor = 'ThreeDShadow ThreeDHighlight ThreeDHighlight ThreeDShadow'; // CSS color
		this.pickerZIndex = 10000;


		for(var p in prop) {
			if(prop.hasOwnProperty(p)) {
				this[p] = prop[p];
			}
		}


		this.hidePicker = function() {
			if(isPickerOwner()) {
				removePicker();
			}
		};


		this.showPicker = function() {
			if(!isPickerOwner()) {
				var tp = jscolor.getElementPos(target); // target pos
				var ts = jscolor.getElementSize(target); // target size
				var vp = jscolor.getViewPos(); // view pos
				var vs = jscolor.getViewSize(); // view size
				var ps = [ // picker size
					2*this.pickerBorder + 4*this.pickerInset + 2*this.pickerFace + jscolor.images.pad[0] + 2*jscolor.images.arrow[0] + jscolor.images.sld[0],
					2*this.pickerBorder + 2*this.pickerInset + 2*this.pickerFace + jscolor.images.pad[1]
				];
				var a, b, c;
				switch(this.pickerPosition.toLowerCase()) {
					case 'left': a=1; b=0; c=-1; break;
					case 'right':a=1; b=0; c=1; break;
					case 'top':  a=0; b=1; c=-1; break;
					default:     a=0; b=1; c=1; break;
				}
				var l = (ts[b]+ps[b])/2;
				var pp = [ // picker pos
					-vp[a]+tp[a]+ps[a] > vs[a] ?
						(-vp[a]+tp[a]+ts[a]/2 > vs[a]/2 && tp[a]+ts[a]-ps[a] >= 0 ? tp[a]+ts[a]-ps[a] : tp[a]) :
						tp[a],
					-vp[b]+tp[b]+ts[b]+ps[b]-l+l*c > vs[b] ?
						(-vp[b]+tp[b]+ts[b]/2 > vs[b]/2 && tp[b]+ts[b]-l-l*c >= 0 ? tp[b]+ts[b]-l-l*c : tp[b]+ts[b]-l+l*c) :
						(tp[b]+ts[b]-l+l*c >= 0 ? tp[b]+ts[b]-l+l*c : tp[b]+ts[b]-l-l*c)
				];
				drawPicker(pp[a], pp[b]);
			}
		};


		this.importColor = function() {
			if(!valueElement) {
				this.exportColor();
			} else {
				if(!this.adjust) {
					if(!this.fromString(valueElement.value, leaveValue)) {
						styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
						styleElement.style.color = styleElement.jscStyle.color;
						this.exportColor(leaveValue | leaveStyle);
					}
				} else if(!this.required && /^\s*$/.test(valueElement.value)) {
					valueElement.value = '';
					styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
					styleElement.style.color = styleElement.jscStyle.color;
					this.exportColor(leaveValue | leaveStyle);

				} else if(this.fromString(valueElement.value)) {
					// OK
				} else {
					this.exportColor();
				}
			}
		};


		this.exportColor = function(flags) {
			if(!(flags & leaveValue) && valueElement) {
				var value = this.toString();
				if(this.caps) { value = value.toUpperCase(); }
				if(this.hash) { value = '#'+value; }
				valueElement.value = value;
			}
			if(!(flags & leaveStyle) && styleElement) {
				styleElement.style.backgroundColor =
					'#'+this.toString();
				styleElement.style.color =
					0.213 * this.rgb[0] +
					0.715 * this.rgb[1] +
					0.072 * this.rgb[2]
					< 0.5 ? '#FFF' : '#000';
			}
			if(!(flags & leavePad) && isPickerOwner()) {
				redrawPad();
			}
			if(!(flags & leaveSld) && isPickerOwner()) {
				redrawSld();
			}
		};


		this.fromHSV = function(h, s, v, flags) { // null = don't change
			h<0 && (h=0) || h>6 && (h=6);
			s<0 && (s=0) || s>1 && (s=1);
			v<0 && (v=0) || v>1 && (v=1);
			this.rgb = HSV_RGB(
				h===null ? this.hsv[0] : (this.hsv[0]=h),
				s===null ? this.hsv[1] : (this.hsv[1]=s),
				v===null ? this.hsv[2] : (this.hsv[2]=v)
			);
			this.exportColor(flags);
		};


		this.fromRGB = function(r, g, b, flags) { // null = don't change
			r<0 && (r=0) || r>1 && (r=1);
			g<0 && (g=0) || g>1 && (g=1);
			b<0 && (b=0) || b>1 && (b=1);
			var hsv = RGB_HSV(
				r===null ? this.rgb[0] : (this.rgb[0]=r),
				g===null ? this.rgb[1] : (this.rgb[1]=g),
				b===null ? this.rgb[2] : (this.rgb[2]=b)
			);
			if(hsv[0] !== null) {
				this.hsv[0] = hsv[0];
			}
			if(hsv[2] !== 0) {
				this.hsv[1] = hsv[1];
			}
			this.hsv[2] = hsv[2];
			this.exportColor(flags);
		};


		this.fromString = function(hex, flags) {
			var m = hex.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i);
			if(!m) {
				return false;
			} else {
				if(m[1].length === 6) { // 6-char notation
					this.fromRGB(
						parseInt(m[1].substr(0,2),16) / 255,
						parseInt(m[1].substr(2,2),16) / 255,
						parseInt(m[1].substr(4,2),16) / 255,
						flags
					);
				} else { // 3-char notation
					this.fromRGB(
						parseInt(m[1].charAt(0)+m[1].charAt(0),16) / 255,
						parseInt(m[1].charAt(1)+m[1].charAt(1),16) / 255,
						parseInt(m[1].charAt(2)+m[1].charAt(2),16) / 255,
						flags
					);
				}
				return true;
			}
		};


		this.toString = function() {
			return (
				(0x100 | Math.round(255*this.rgb[0])).toString(16).substr(1) +
				(0x100 | Math.round(255*this.rgb[1])).toString(16).substr(1) +
				(0x100 | Math.round(255*this.rgb[2])).toString(16).substr(1)
			);
		};


		function RGB_HSV(r, g, b) {
			var n = Math.min(Math.min(r,g),b);
			var v = Math.max(Math.max(r,g),b);
			var m = v - n;
			if(m === 0) { return [ null, 0, v ]; }
			var h = r===n ? 3+(b-g)/m : (g===n ? 5+(r-b)/m : 1+(g-r)/m);
			return [ h===6?0:h, m/v, v ];
		}


		function HSV_RGB(h, s, v) {
			if(h === null) { return [ v, v, v ]; }
			var i = Math.floor(h);
			var f = i%2 ? h-i : 1-(h-i);
			var m = v * (1 - s);
			var n = v * (1 - s*f);
			switch(i) {
				case 6:
				case 0: return [v,n,m];
				case 1: return [n,v,m];
				case 2: return [m,v,n];
				case 3: return [m,n,v];
				case 4: return [n,m,v];
				case 5: return [v,m,n];
			}
		}


		function removePicker() {
			delete jscolor.picker.owner;
			document.getElementsByTagName('body')[0].removeChild(jscolor.picker.boxB);
		}


		function drawPicker(x, y) {
			if(!jscolor.picker) {
				jscolor.picker = {
					box : document.createElement('div'),
					boxB : document.createElement('div'),
					pad : document.createElement('div'),
					padB : document.createElement('div'),
					padM : document.createElement('div'),
					sld : document.createElement('div'),
					sldB : document.createElement('div'),
					sldM : document.createElement('div')
				};
				for(var i=0,segSize=4; i<jscolor.images.sld[1]; i+=segSize) {
					var seg = document.createElement('div');
					seg.style.height = segSize+'px';
					seg.style.fontSize = '1px';
					seg.style.lineHeight = '0';
					jscolor.picker.sld.appendChild(seg);
				}
				jscolor.picker.sldB.appendChild(jscolor.picker.sld);
				jscolor.picker.box.appendChild(jscolor.picker.sldB);
				jscolor.picker.box.appendChild(jscolor.picker.sldM);
				jscolor.picker.padB.appendChild(jscolor.picker.pad);
				jscolor.picker.box.appendChild(jscolor.picker.padB);
				jscolor.picker.box.appendChild(jscolor.picker.padM);
				jscolor.picker.boxB.appendChild(jscolor.picker.box);
			}

			var p = jscolor.picker;

			// recompute controls positions
			posPad = [
				x+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset,
				y+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset ];
			posSld = [
				null,
				y+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset ];

			// controls interaction
			p.box.onmouseup =
			p.box.onmouseout = function() { target.focus(); };
			p.box.onmousedown = function() { abortBlur=true; };
			p.box.onmousemove = function(e) { holdPad && setPad(e); holdSld && setSld(e); };
			p.padM.onmouseup =
			p.padM.onmouseout = function() { if(holdPad) { holdPad=false; jscolor.fireEvent(valueElement,'change'); } };
			p.padM.onmousedown = function(e) { holdPad=true; setPad(e); };
			p.sldM.onmouseup =
			p.sldM.onmouseout = function() { if(holdSld) { holdSld=false; jscolor.fireEvent(valueElement,'change'); } };
			p.sldM.onmousedown = function(e) { holdSld=true; setSld(e); };

			// picker
			p.box.style.width = 4*THIS.pickerInset + 2*THIS.pickerFace + jscolor.images.pad[0] + 2*jscolor.images.arrow[0] + jscolor.images.sld[0] + 'px';
			p.box.style.height = 2*THIS.pickerInset + 2*THIS.pickerFace + jscolor.images.pad[1] + 'px';

			// picker border
			p.boxB.style.position = 'absolute';
			p.boxB.style.clear = 'both';
			p.boxB.style.left = x+'px';
			p.boxB.style.top = y+'px';
			p.boxB.style.zIndex = THIS.pickerZIndex;
			p.boxB.style.border = THIS.pickerBorder+'px solid';
			p.boxB.style.borderColor = THIS.pickerBorderColor;
			p.boxB.style.background = THIS.pickerFaceColor;

			// pad image
			p.pad.style.width = jscolor.images.pad[0]+'px';
			p.pad.style.height = jscolor.images.pad[1]+'px';

			// pad border
			p.padB.style.position = 'absolute';
			p.padB.style.left = THIS.pickerFace+'px';
			p.padB.style.top = THIS.pickerFace+'px';
			p.padB.style.border = THIS.pickerInset+'px solid';
			p.padB.style.borderColor = THIS.pickerInsetColor;

			// pad mouse area
			p.padM.style.position = 'absolute';
			p.padM.style.left = '0';
			p.padM.style.top = '0';
			p.padM.style.width = THIS.pickerFace + 2*THIS.pickerInset + jscolor.images.pad[0] + jscolor.images.arrow[0] + 'px';
			p.padM.style.height = p.box.style.height;
			p.padM.style.cursor = 'crosshair';

			// slider image
			p.sld.style.overflow = 'hidden';
			p.sld.style.width = jscolor.images.sld[0]+'px';
			p.sld.style.height = jscolor.images.sld[1]+'px';

			// slider border
			p.sldB.style.position = 'absolute';
			p.sldB.style.right = THIS.pickerFace+'px';
			p.sldB.style.top = THIS.pickerFace+'px';
			p.sldB.style.border = THIS.pickerInset+'px solid';
			p.sldB.style.borderColor = THIS.pickerInsetColor;

			// slider mouse area
			p.sldM.style.position = 'absolute';
			p.sldM.style.right = '0';
			p.sldM.style.top = '0';
			p.sldM.style.width = jscolor.images.sld[0] + jscolor.images.arrow[0] + THIS.pickerFace + 2*THIS.pickerInset + 'px';
			p.sldM.style.height = p.box.style.height;
			try {
				p.sldM.style.cursor = 'pointer';
			} catch(eOldIE) {
				p.sldM.style.cursor = 'hand';
			}

			// load images in optimal order
			switch(modeID) {
				case 0: var padImg = 'hs.png'; break;
				case 1: var padImg = 'hv.png'; break;
			}
			p.padM.style.background = "url('"+jscolor.getDir()+"cross.gif') no-repeat";
			p.sldM.style.background = "url('"+jscolor.getDir()+"arrow.gif') no-repeat";
			p.pad.style.background = "url('"+jscolor.getDir()+padImg+"') 0 0 no-repeat";

			// place pointers
			redrawPad();
			redrawSld();

			jscolor.picker.owner = THIS;
			document.getElementsByTagName('body')[0].appendChild(p.boxB);
		}


		function redrawPad() {
			// redraw the pad pointer
			switch(modeID) {
				case 0: var yComponent = 1; break;
				case 1: var yComponent = 2; break;
			}
			var x = Math.round((THIS.hsv[0]/6) * (jscolor.images.pad[0]-1));
			var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.pad[1]-1));
			jscolor.picker.padM.style.backgroundPosition =
				(THIS.pickerFace+THIS.pickerInset+x - Math.floor(jscolor.images.cross[0]/2)) + 'px ' +
				(THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.cross[1]/2)) + 'px';

			// redraw the slider image
			var seg = jscolor.picker.sld.childNodes;

			switch(modeID) {
				case 0:
					var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 1);
					for(var i=0; i<seg.length; i+=1) {
						seg[i].style.backgroundColor = 'rgb('+
							(rgb[0]*(1-i/seg.length)*100)+'%,'+
							(rgb[1]*(1-i/seg.length)*100)+'%,'+
							(rgb[2]*(1-i/seg.length)*100)+'%)';
					}
					break;
				case 1:
					var rgb, s, c = [ THIS.hsv[2], 0, 0 ];
					var i = Math.floor(THIS.hsv[0]);
					var f = i%2 ? THIS.hsv[0]-i : 1-(THIS.hsv[0]-i);
					switch(i) {
						case 6:
						case 0: rgb=[0,1,2]; break;
						case 1: rgb=[1,0,2]; break;
						case 2: rgb=[2,0,1]; break;
						case 3: rgb=[2,1,0]; break;
						case 4: rgb=[1,2,0]; break;
						case 5: rgb=[0,2,1]; break;
					}
					for(var i=0; i<seg.length; i+=1) {
						s = 1 - 1/(seg.length-1)*i;
						c[1] = c[0] * (1 - s*f);
						c[2] = c[0] * (1 - s);
						seg[i].style.backgroundColor = 'rgb('+
							(c[rgb[0]]*100)+'%,'+
							(c[rgb[1]]*100)+'%,'+
							(c[rgb[2]]*100)+'%)';
					}
					break;
			}
		}


		function redrawSld() {
			// redraw the slider pointer
			switch(modeID) {
				case 0: var yComponent = 2; break;
				case 1: var yComponent = 1; break;
			}
			var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.sld[1]-1));
			jscolor.picker.sldM.style.backgroundPosition =
				'0 ' + (THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.arrow[1]/2)) + 'px';
		}


		function isPickerOwner() {
			return jscolor.picker && jscolor.picker.owner === THIS;
		}


		function blurTarget() {
			if(valueElement === target) {
				THIS.importColor();
			}
			if(THIS.pickerOnfocus) {
				THIS.hidePicker();
			}
		}


		function blurValue() {
			if(valueElement !== target) {
				THIS.importColor();
			}
		}


		function setPad(e) {
			var posM = jscolor.getMousePos(e);
			var x = posM[0]-posPad[0];
			var y = posM[1]-posPad[1];
			switch(modeID) {
				case 0: THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), 1 - y/(jscolor.images.pad[1]-1), null, leaveSld); break;
				case 1: THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), null, 1 - y/(jscolor.images.pad[1]-1), leaveSld); break;
			}
		}


		function setSld(e) {
			var posM = jscolor.getMousePos(e);
			var y = posM[1]-posPad[1];
			switch(modeID) {
				case 0: THIS.fromHSV(null, null, 1 - y/(jscolor.images.sld[1]-1), leavePad); break;
				case 1: THIS.fromHSV(null, 1 - y/(jscolor.images.sld[1]-1), null, leavePad); break;
			}
		}


		var THIS = this;
		var modeID = this.pickerMode.toLowerCase()==='hvs' ? 1 : 0;
		var abortBlur = false;
		var
			valueElement = jscolor.fetchElement(this.valueElement),
			styleElement = jscolor.fetchElement(this.styleElement);
		var
			holdPad = false,
			holdSld = false;
		var
			posPad,
			posSld;
		var
			leaveValue = 1<<0,
			leaveStyle = 1<<1,
			leavePad = 1<<2,
			leaveSld = 1<<3;

		// target
		jscolor.addEvent(target, 'focus', function() {
			if(THIS.pickerOnfocus) { THIS.showPicker(); }
		});
		jscolor.addEvent(target, 'blur', function() {
			if(!abortBlur) {
				window.setTimeout(function(){ abortBlur || blurTarget(); abortBlur=false; }, 0);
			} else {
				abortBlur = false;
			}
		});

		// valueElement
		if(valueElement) {
			var updateField = function() {
				THIS.fromString(valueElement.value, leaveValue);
			};
			jscolor.addEvent(valueElement, 'keyup', updateField);
			jscolor.addEvent(valueElement, 'input', updateField);
			jscolor.addEvent(valueElement, 'blur', blurValue);
			valueElement.setAttribute('autocomplete', 'off');
		}

		// styleElement
		if(styleElement) {
			styleElement.jscStyle = {
				backgroundColor : styleElement.style.backgroundColor,
				color : styleElement.style.color
			};
		}

		// require images
		switch(modeID) {
			case 0: jscolor.requireImage('hs.png'); break;
			case 1: jscolor.requireImage('hv.png'); break;
		}
		jscolor.requireImage('cross.gif');
		jscolor.requireImage('arrow.gif');

		this.importColor();
	}

};


jscolor.install();
/**
 * http://github.com/valums/file-uploader
 * 
 * Multiple file upload component with progress-bar, drag-and-drop. 
 * © 2010 Andrew Valums ( andrew(at)valums.com ) 
 * 
 * Licensed under GNU GPL 2 or later and GNU LGPL 2 or later, see license.txt.
 */    

//
// Helper functions
//

var qq = qq || {};

/**
 * Adds all missing properties from second obj to first obj
 */ 
qq.extend = function(first, second){
    for (var prop in second){
        first[prop] = second[prop];
    }
};  

/**
 * Searches for a given element in the array, returns -1 if it is not present.
 * @param {Number} [from] The index at which to begin the search
 */
qq.indexOf = function(arr, elt, from){
    if (arr.indexOf) return arr.indexOf(elt, from);
    
    from = from || 0;
    var len = arr.length;    
    
    if (from < 0) from += len;  

    for (; from < len; from++){  
        if (from in arr && arr[from] === elt){  
            return from;
        }
    }  
    return -1;  
}; 
    
qq.getUniqueId = (function(){
    var id = 0;
    return function(){ return id++; };
})();

//
// Events

qq.attach = function(element, type, fn){
    if (element.addEventListener){
        element.addEventListener(type, fn, false);
    } else if (element.attachEvent){
        element.attachEvent('on' + type, fn);
    }
};
qq.detach = function(element, type, fn){
    if (element.removeEventListener){
        element.removeEventListener(type, fn, false);
    } else if (element.attachEvent){
        element.detachEvent('on' + type, fn);
    }
};

qq.preventDefault = function(e){
    if (e.preventDefault){
        e.preventDefault();
    } else{
        e.returnValue = false;
    }
};

//
// Node manipulations

/**
 * Insert node a before node b.
 */
qq.insertBefore = function(a, b){
    b.parentNode.insertBefore(a, b);
};
qq.remove = function(element){
    element.parentNode.removeChild(element);
};

qq.contains = function(parent, descendant){       
    // compareposition returns false in this case
    if (parent == descendant) return true;
    
    if (parent.contains){
        return parent.contains(descendant);
    } else {
        return !!(descendant.compareDocumentPosition(parent) & 8);
    }
};

/**
 * Creates and returns element from html string
 * Uses innerHTML to create an element
 */
qq.toElement = (function(){
    var div = document.createElement('div');
    return function(html){
        div.innerHTML = html;
        var element = div.firstChild;
        div.removeChild(element);
        return element;
    };
})();

//
// Node properties and attributes

/**
 * Sets styles for an element.
 * Fixes opacity in IE6-8.
 */
qq.css = function(element, styles){
    if (styles.opacity != null){
        if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
            styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
        }
    }
    qq.extend(element.style, styles);
};
qq.hasClass = function(element, name){
    var re = new RegExp('(^| )' + name + '( |$)');
    return re.test(element.className);
};
qq.addClass = function(element, name){
    if (!qq.hasClass(element, name)){
        element.className += ' ' + name;
    }
};
qq.removeClass = function(element, name){
    var re = new RegExp('(^| )' + name + '( |$)');
    element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
};
qq.setText = function(element, text){
    element.innerText = text;
    element.textContent = text;
};

//
// Selecting elements

qq.children = function(element){
    var children = [],
    child = element.firstChild;

    while (child){
        if (child.nodeType == 1){
            children.push(child);
        }
        child = child.nextSibling;
    }

    return children;
};

qq.getByClass = function(element, className){
    if (element.querySelectorAll){
        return element.querySelectorAll('.' + className);
    }

    var result = [];
    var candidates = element.getElementsByTagName("*");
    var len = candidates.length;

    for (var i = 0; i < len; i++){
        if (qq.hasClass(candidates[i], className)){
            result.push(candidates[i]);
        }
    }
    return result;
};

/**
 * obj2url() takes a json-object as argument and generates
 * a querystring. pretty much like jQuery.param()
 * 
 * how to use:
 *
 *    `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
 *
 * will result in:
 *
 *    `http://any.url/upload?otherParam=value&a=b&c=d`
 *
 * @param  Object JSON-Object
 * @param  String current querystring-part
 * @return String encoded querystring
 */
qq.obj2url = function(obj, temp, prefixDone){
    var uristrings = [],
        prefix = '&',
        add = function(nextObj, i){
            var nextTemp = temp 
                ? (/\[\]$/.test(temp)) // prevent double-encoding
                   ? temp
                   : temp+'['+i+']'
                : i;
            if ((nextTemp != 'undefined') && (i != 'undefined')) {  
                uristrings.push(
                    (typeof nextObj === 'object') 
                        ? qq.obj2url(nextObj, nextTemp, true)
                        : (Object.prototype.toString.call(nextObj) === '[object Function]')
                            ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
                            : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)                                                          
                );
            }
        }; 

    if (!prefixDone && temp) {
      prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
      uristrings.push(temp);
      uristrings.push(qq.obj2url(obj));
    } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
        // we wont use a for-in-loop on an array (performance)
        for (var i = 0, len = obj.length; i < len; ++i){
            add(obj[i], i);
        }
    } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){
        // for anything else but a scalar, we will use for-in-loop
        for (var i in obj){
            add(obj[i], i);
        }
    } else {
        uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
    }

    return uristrings.join(prefix)
                     .replace(/^&/, '')
                     .replace(/%20/g, '+'); 
};

//
//
// Uploader Classes
//
//

var qq = qq || {};
    
/**
 * Creates upload button, validates upload, but doesn't create file list or dd. 
 */
qq.FileUploaderBasic = function(o){
    this._options = {
        // set to true to see the server response
        debug: false,
        action: '/server/upload',
        params: {},
        button: null,
        multiple: true,
        maxConnections: 3,
        // validation        
        allowedExtensions: [],               
        sizeLimit: 0,   
        minSizeLimit: 0,                             
        // events
        // return false to cancel submit
        onSubmit: function(id, fileName){},
        onProgress: function(id, fileName, loaded, total){},
        onComplete: function(id, fileName, responseJSON){},
        onCancel: function(id, fileName){},
        // messages                
        messages: {
            typeError: "{file} has invalid extension. Only {extensions} are allowed.",
            sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
            minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
            emptyError: "{file} is empty, please select files again without it.",
            onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."            
        },
        showMessage: function(message){
            alert(message);
        }               
    };
    qq.extend(this._options, o);
        
    // number of files being uploaded
    this._filesInProgress = 0;
    this._handler = this._createUploadHandler(); 
    
    if (this._options.button){ 
        this._button = this._createUploadButton(this._options.button);
    }
                        
    this._preventLeaveInProgress();         
};
   
qq.FileUploaderBasic.prototype = {
    setParams: function(params){
        this._options.params = params;
    },
    getInProgress: function(){
        return this._filesInProgress;         
    },
    _createUploadButton: function(element){
        var self = this;
        
        return new qq.UploadButton({
            element: element,
            multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
            onChange: function(input){
                self._onInputChange(input);
            }        
        });           
    },    
    _createUploadHandler: function(){
        var self = this,
            handlerClass;        
        
        if(qq.UploadHandlerXhr.isSupported()){           
            handlerClass = 'UploadHandlerXhr';                        
        } else {
            handlerClass = 'UploadHandlerForm';
        }

        var handler = new qq[handlerClass]({
            debug: this._options.debug,
            action: this._options.action,         
            maxConnections: this._options.maxConnections,   
            onProgress: function(id, fileName, loaded, total){                
                self._onProgress(id, fileName, loaded, total);
                self._options.onProgress(id, fileName, loaded, total);                    
            },            
            onComplete: function(id, fileName, result){
                self._onComplete(id, fileName, result);
                self._options.onComplete(id, fileName, result);
            },
            onCancel: function(id, fileName){
                self._onCancel(id, fileName);
                self._options.onCancel(id, fileName);
            }
        });

        return handler;
    },    
    _preventLeaveInProgress: function(){
        var self = this;
        
        qq.attach(window, 'beforeunload', function(e){
            if (!self._filesInProgress){return;}
            
            var e = e || window.event;
            // for ie, ff
            e.returnValue = self._options.messages.onLeave;
            // for webkit
            return self._options.messages.onLeave;             
        });        
    },    
    _onSubmit: function(id, fileName){
        this._filesInProgress++;  
    },
    _onProgress: function(id, fileName, loaded, total){        
    },
    _onComplete: function(id, fileName, result){
        this._filesInProgress--;                 
        if (result.error){
            this._options.showMessage(result.error);
        }             
    },
    _onCancel: function(id, fileName){
        this._filesInProgress--;        
    },
    _onInputChange: function(input){
        if (this._handler instanceof qq.UploadHandlerXhr){                
            this._uploadFileList(input.files);                   
        } else {             
            if (this._validateFile(input)){                
                this._uploadFile(input);                                    
            }                      
        }               
        this._button.reset();   
    },  
    _uploadFileList: function(files){
        for (var i=0; i<files.length; i++){
            if ( !this._validateFile(files[i])){
                return;
            }            
        }
        
        for (var i=0; i<files.length; i++){
            this._uploadFile(files[i]);        
        }        
    },       
    _uploadFile: function(fileContainer){      
        var id = this._handler.add(fileContainer);
        var fileName = this._handler.getName(id);
        
        if (this._options.onSubmit(id, fileName) !== false){
            this._onSubmit(id, fileName);
            this._handler.upload(id, this._options.params);
        }
    },      
    _validateFile: function(file){
        var name, size;
        
        if (file.value){
            // it is a file input            
            // get input value and remove path to normalize
            name = file.value.replace(/.*(\/|\\)/, "");
        } else {
            // fix missing properties in Safari
            name = file.fileName != null ? file.fileName : file.name;
            size = file.fileSize != null ? file.fileSize : file.size;
        }
                    
        if (! this._isAllowedExtension(name)){            
            this._error('typeError', name);
            return false;
            
        } else if (size === 0){            
            this._error('emptyError', name);
            return false;
                                                     
        } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){            
            this._error('sizeError', name);
            return false;
                        
        } else if (size && size < this._options.minSizeLimit){
            this._error('minSizeError', name);
            return false;            
        }
        
        return true;                
    },
    _error: function(code, fileName){
        var message = this._options.messages[code];        
        function r(name, replacement){ message = message.replace(name, replacement); }
        
        r('{file}', this._formatFileName(fileName));        
        r('{extensions}', this._options.allowedExtensions.join(', '));
        r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
        r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
        
        this._options.showMessage(message);                
    },
    _formatFileName: function(name){
        if (name.length > 33){
            name = name.slice(0, 19) + '...' + name.slice(-13);    
        }
        return name;
    },
    _isAllowedExtension: function(fileName){
        var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
        var allowed = this._options.allowedExtensions;
        
        if (!allowed.length){return true;}        
        
        for (var i=0; i<allowed.length; i++){
            if (allowed[i].toLowerCase() == ext){ return true;}    
        }
        
        return false;
    },    
    _formatSize: function(bytes){
        var i = -1;                                    
        do {
            bytes = bytes / 1024;
            i++;  
        } while (bytes > 99);
        
        return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];          
    }
};
    
       
/**
 * Class that creates upload widget with drag-and-drop and file list
 * @inherits qq.FileUploaderBasic
 */
qq.FileUploader = function(o){
    // call parent constructor
    qq.FileUploaderBasic.apply(this, arguments);
    
    // additional options    
    qq.extend(this._options, {
        element: null,
        // if set, will be used instead of qq-upload-list in template
        listElement: null,
                
        template: '<div class="qq-uploader">' + 
                '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
                '<div class="qq-upload-button">' +
                  '<img src="/images/attach.png" style="float:left;margin: 0 0 0 5px;">' +
                  'Upload a file' +
                '</div>' +
                '<ul class="qq-upload-list"></ul>' +
             '</div>',

        // template for one item in file list
        fileTemplate: '<li>' +
                '<span class="qq-upload-file"></span>' +
                '<span class="qq-upload-spinner"></span>' +
                '<span class="qq-upload-size"></span>' +
                '<a class="qq-upload-cancel" href="#">Cancel</a>' +
                '<span class="qq-upload-failed-text">Failed</span>' +
            '</li>',        
        
        classes: {
            // used to get elements from templates
            button: 'qq-upload-button',
            drop: 'qq-upload-drop-area',
            dropActive: 'qq-upload-drop-area-active',
            list: 'qq-upload-list',
                        
            file: 'qq-upload-file',
            spinner: 'qq-upload-spinner',
            size: 'qq-upload-size',
            cancel: 'qq-upload-cancel',

            // added to list item when upload completes
            // used in css to hide progress spinner
            success: 'qq-upload-success',
            fail: 'qq-upload-fail'
        }
    });
    // overwrite options with user supplied    
    qq.extend(this._options, o);       

    this._element = this._options.element;
    this._element.innerHTML = this._options.template;        
    this._listElement = this._options.listElement || this._find(this._element, 'list');
    
    this._classes = this._options.classes;
        
    this._button = this._createUploadButton(this._find(this._element, 'button'));        
    
    this._bindCancelEvent();
    this._setupDragDrop();
};

// inherit from Basic Uploader
qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);

qq.extend(qq.FileUploader.prototype, {
    /**
     * Gets one of the elements listed in this._options.classes
     **/
    _find: function(parent, type){                                
        var element = qq.getByClass(parent, this._options.classes[type])[0];        
        if (!element){
            throw new Error('element not found ' + type);
        }
        
        return element;
    },
    _setupDragDrop: function(){
        var self = this,
            dropArea = this._find(this._element, 'drop');                        

        var dz = new qq.UploadDropZone({
            element: dropArea,
            onEnter: function(e){
                qq.addClass(dropArea, self._classes.dropActive);
                e.stopPropagation();
            },
            onLeave: function(e){
                e.stopPropagation();
            },
            onLeaveNotDescendants: function(e){
                qq.removeClass(dropArea, self._classes.dropActive);  
            },
            onDrop: function(e){
                dropArea.style.display = 'none';
                qq.removeClass(dropArea, self._classes.dropActive);
                self._uploadFileList(e.dataTransfer.files);    
            }
        });
                
        dropArea.style.display = 'none';

        qq.attach(document, 'dragenter', function(e){     
            if (!dz._isValidFileDrag(e)) return; 
            
            dropArea.style.display = 'block';            
        });                 
        qq.attach(document, 'dragleave', function(e){
            if (!dz._isValidFileDrag(e)) return;            
            
            var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
            // only fire when leaving document out
            if ( ! relatedTarget || relatedTarget.nodeName == "HTML"){               
                dropArea.style.display = 'none';                                            
            }
        });                
    },
    _onSubmit: function(id, fileName){
        qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
        this._addToList(id, fileName);  
    },
    _onProgress: function(id, fileName, loaded, total){
        qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);

        var item = this._getItemByFileId(id);
        var size = this._find(item, 'size');
        size.style.display = 'inline';
        
        var text; 
        if (loaded != total){
            text = Math.round(loaded / total * 100) + '% from ' + this._formatSize(total);
        } else {                                   
            text = this._formatSize(total);
        }          
        
        qq.setText(size, text);         
    },
    _onComplete: function(id, fileName, result){
        qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);

        // mark completed
        var item = this._getItemByFileId(id);                
        qq.remove(this._find(item, 'cancel'));
        qq.remove(this._find(item, 'spinner'));
        
        if (result.success){
            qq.addClass(item, this._classes.success);    
        } else {
            qq.addClass(item, this._classes.fail);
        }         
    },
    _addToList: function(id, fileName){
        var item = qq.toElement(this._options.fileTemplate);                
        item.qqFileId = id;

        var fileElement = this._find(item, 'file');        
        qq.setText(fileElement, this._formatFileName(fileName));
        this._find(item, 'size').style.display = 'none';        

        this._listElement.appendChild(item);
    },
    _getItemByFileId: function(id){
        var item = this._listElement.firstChild;        
        
        // there can't be txt nodes in dynamically created list
        // and we can  use nextSibling
        while (item){            
            if (item.qqFileId == id) return item;            
            item = item.nextSibling;
        }          
    },
    /**
     * delegate click event for cancel link 
     **/
    _bindCancelEvent: function(){
        var self = this,
            list = this._listElement;            
        
        qq.attach(list, 'click', function(e){            
            e = e || window.event;
            var target = e.target || e.srcElement;
            
            if (qq.hasClass(target, self._classes.cancel)){                
                qq.preventDefault(e);
               
                var item = target.parentNode;
                self._handler.cancel(item.qqFileId);
                qq.remove(item);
            }
        });
    }    
});
    
qq.UploadDropZone = function(o){
    this._options = {
        element: null,  
        onEnter: function(e){},
        onLeave: function(e){},  
        // is not fired when leaving element by hovering descendants   
        onLeaveNotDescendants: function(e){},   
        onDrop: function(e){}                       
    };
    qq.extend(this._options, o); 
    
    this._element = this._options.element;
    
    this._disableDropOutside();
    this._attachEvents();   
};

qq.UploadDropZone.prototype = {
    _disableDropOutside: function(e){
        // run only once for all instances
        if (!qq.UploadDropZone.dropOutsideDisabled ){

            qq.attach(document, 'dragover', function(e){
                if (e.dataTransfer){
                    e.dataTransfer.dropEffect = 'none';
                    e.preventDefault(); 
                }           
            });
            
            qq.UploadDropZone.dropOutsideDisabled = true; 
        }        
    },
    _attachEvents: function(){
        var self = this;              
                  
        qq.attach(self._element, 'dragover', function(e){
            if (!self._isValidFileDrag(e)) return;
            
            var effect = e.dataTransfer.effectAllowed;
            if (effect == 'move' || effect == 'linkMove'){
                e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)    
            } else {                    
                e.dataTransfer.dropEffect = 'copy'; // for Chrome
            }
                                                     
            e.stopPropagation();
            e.preventDefault();                                                                    
        });
        
        qq.attach(self._element, 'dragenter', function(e){
            if (!self._isValidFileDrag(e)) return;
                        
            self._options.onEnter(e);
        });
        
        qq.attach(self._element, 'dragleave', function(e){
            if (!self._isValidFileDrag(e)) return;
            
            self._options.onLeave(e);
            
            var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);                      
            // do not fire when moving a mouse over a descendant
            if (qq.contains(this, relatedTarget)) return;
                        
            self._options.onLeaveNotDescendants(e); 
        });
                
        qq.attach(self._element, 'drop', function(e){
            if (!self._isValidFileDrag(e)) return;
            
            e.preventDefault();
            self._options.onDrop(e);
        });          
    },
    _isValidFileDrag: function(e){
        var dt = e.dataTransfer,
            // do not check dt.types.contains in webkit, because it crashes safari 4            
            isWebkit = navigator.userAgent.indexOf("AppleWebKit") > -1;                        

        // dt.effectAllowed is none in Safari 5
        // dt.types.contains check is for firefox            
        return dt && dt.effectAllowed != 'none' && 
            (dt.files || (!isWebkit && dt.types.contains && dt.types.contains('Files')));
        
    }        
}; 

qq.UploadButton = function(o){
    this._options = {
        element: null,  
        // if set to true adds multiple attribute to file input      
        multiple: false,
        // name attribute of file input
        name: 'file',
        onChange: function(input){},
        hoverClass: 'qq-upload-button-hover',
        focusClass: 'qq-upload-button-focus'                       
    };
    
    qq.extend(this._options, o);
        
    this._element = this._options.element;
    
    // make button suitable container for input
    qq.css(this._element, {
        position: 'relative',
        overflow: 'hidden',
        // Make sure browse button is in the right side
        // in Internet Explorer
        direction: 'ltr'
    });   
    
    this._input = this._createInput();
};

qq.UploadButton.prototype = {
    /* returns file input element */    
    getInput: function(){
        return this._input;
    },
    /* cleans/recreates the file input */
    reset: function(){
        if (this._input.parentNode){
            qq.remove(this._input);    
        }                
        
        qq.removeClass(this._element, this._options.focusClass);
        this._input = this._createInput();
    },    
    _createInput: function(){                
        var input = document.createElement("input");
        
        if (this._options.multiple){
            input.setAttribute("multiple", "multiple");
        }
                
        input.setAttribute("type", "file");
        input.setAttribute("name", this._options.name);
        
        qq.css(input, {
            position: 'absolute',
            // in Opera only 'browse' button
            // is clickable and it is located at
            // the right side of the input
            right: 0,
            top: 0,
            fontFamily: 'Arial',
            // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
            fontSize: '118px',
            margin: 0,
            padding: 0,
            cursor: 'pointer',
            opacity: 0
        });
        
        this._element.appendChild(input);

        var self = this;
        qq.attach(input, 'change', function(){
            self._options.onChange(input);
        });
                
        qq.attach(input, 'mouseover', function(){
            qq.addClass(self._element, self._options.hoverClass);
        });
        qq.attach(input, 'mouseout', function(){
            qq.removeClass(self._element, self._options.hoverClass);
        });
        qq.attach(input, 'focus', function(){
            qq.addClass(self._element, self._options.focusClass);
        });
        qq.attach(input, 'blur', function(){
            qq.removeClass(self._element, self._options.focusClass);
        });

        // IE and Opera, unfortunately have 2 tab stops on file input
        // which is unacceptable in our case, disable keyboard access
        if (window.attachEvent){
            // it is IE or Opera
            input.setAttribute('tabIndex', "-1");
        }

        return input;            
    }        
};

/**
 * Class for uploading files, uploading itself is handled by child classes
 */
qq.UploadHandlerAbstract = function(o){
    this._options = {
        debug: false,
        action: '/upload.php',
        // maximum number of concurrent uploads        
        maxConnections: 999,
        onProgress: function(id, fileName, loaded, total){},
        onComplete: function(id, fileName, response){},
        onCancel: function(id, fileName){}
    };
    qq.extend(this._options, o);    
    
    this._queue = [];
    // params for files in queue
    this._params = [];
};
qq.UploadHandlerAbstract.prototype = {
    log: function(str){
        if (this._options.debug && window.console) console.log('[uploader] ' + str);        
    },
    /**
     * Adds file or file input to the queue
     * @returns id
     **/    
    add: function(file){},
    /**
     * Sends the file identified by id and additional query params to the server
     */
    upload: function(id, params){
        var len = this._queue.push(id);

        var copy = {};        
        qq.extend(copy, params);
        this._params[id] = copy;        
                
        // if too many active uploads, wait...
        if (len <= this._options.maxConnections){               
            this._upload(id, this._params[id]);
        }
    },
    /**
     * Cancels file upload by id
     */
    cancel: function(id){
        this._cancel(id);
        this._dequeue(id);
    },
    /**
     * Cancells all uploads
     */
    cancelAll: function(){
        for (var i=0; i<this._queue.length; i++){
            this._cancel(this._queue[i]);
        }
        this._queue = [];
    },
    /**
     * Returns name of the file identified by id
     */
    getName: function(id){},
    /**
     * Returns size of the file identified by id
     */          
    getSize: function(id){},
    /**
     * Returns id of files being uploaded or
     * waiting for their turn
     */
    getQueue: function(){
        return this._queue;
    },
    /**
     * Actual upload method
     */
    _upload: function(id){},
    /**
     * Actual cancel method
     */
    _cancel: function(id){},     
    /**
     * Removes element from queue, starts upload of next
     */
    _dequeue: function(id){
        var i = qq.indexOf(this._queue, id);
        this._queue.splice(i, 1);
                
        var max = this._options.maxConnections;
        
        if (this._queue.length >= max && i < max){
            var nextId = this._queue[max-1];
            this._upload(nextId, this._params[nextId]);
        }
    }        
};

/**
 * Class for uploading files using form and iframe
 * @inherits qq.UploadHandlerAbstract
 */
qq.UploadHandlerForm = function(o){
    qq.UploadHandlerAbstract.apply(this, arguments);
       
    this._inputs = {};
};
// @inherits qq.UploadHandlerAbstract
qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);

qq.extend(qq.UploadHandlerForm.prototype, {
    add: function(fileInput){
        fileInput.setAttribute('name', 'qqfile');
        var id = 'qq-upload-handler-iframe' + qq.getUniqueId();       
        
        this._inputs[id] = fileInput;
        
        // remove file input from DOM
        if (fileInput.parentNode){
            qq.remove(fileInput);
        }
                
        return id;
    },
    getName: function(id){
        // get input value and remove path to normalize
        return this._inputs[id].value.replace(/.*(\/|\\)/, "");
    },    
    _cancel: function(id){
        this._options.onCancel(id, this.getName(id));
        
        delete this._inputs[id];        

        var iframe = document.getElementById(id);
        if (iframe){
            // to cancel request set src to something else
            // we use src="javascript:false;" because it doesn't
            // trigger ie6 prompt on https
            iframe.setAttribute('src', 'javascript:false;');

            qq.remove(iframe);
        }
    },     
    _upload: function(id, params){                        
        var input = this._inputs[id];
        
        if (!input){
            throw new Error('file with passed id was not added, or already uploaded or cancelled');
        }                

        var fileName = this.getName(id);
                
        var iframe = this._createIframe(id);
        var form = this._createForm(iframe, params);
        form.appendChild(input);

        var self = this;
        this._attachLoadEvent(iframe, function(){                                 
            self.log('iframe loaded');
            
            var response = self._getIframeContentJSON(iframe);

            self._options.onComplete(id, fileName, response);
            self._dequeue(id);
            
            delete self._inputs[id];
            // timeout added to fix busy state in FF3.6
            setTimeout(function(){
                qq.remove(iframe);
            }, 1);
        });

        form.submit();        
        qq.remove(form);        
        
        return id;
    }, 
    _attachLoadEvent: function(iframe, callback){
        qq.attach(iframe, 'load', function(){
            // when we remove iframe from dom
            // the request stops, but in IE load
            // event fires
            if (!iframe.parentNode){
                return;
            }

            // fixing Opera 10.53
            if (iframe.contentDocument &&
                iframe.contentDocument.body &&
                iframe.contentDocument.body.innerHTML == "false"){
                // In Opera event is fired second time
                // when body.innerHTML changed from false
                // to server response approx. after 1 sec
                // when we upload file with iframe
                return;
            }

            callback();
        });
    },
    /**
     * Returns json object received by iframe from server.
     */
    _getIframeContentJSON: function(iframe){
        // iframe.contentWindow.document - for IE<7
        var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
            response;
        
        this.log("converting iframe's innerHTML to JSON");
        this.log("innerHTML = " + doc.body.innerHTML);
                        
        try {
            // BP pre is from ie 11
            response = eval("(" + doc.body.innerHTML.replace('<pre>', '').replace('</pre>', '')  + ")");
        } catch(err){
            response = {};
        }        

        return response;
    },
    /**
     * Creates iframe with unique name
     */
    _createIframe: function(id){
        // We can't use following code as the name attribute
        // won't be properly registered in IE6, and new window
        // on form submit will open
        // var iframe = document.createElement('iframe');
        // iframe.setAttribute('name', id);

        var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
        // src="javascript:false;" removes ie6 prompt on https

        iframe.setAttribute('id', id);

        iframe.style.display = 'none';
        document.body.appendChild(iframe);

        return iframe;
    },
    /**
     * Creates form, that will be submitted to iframe
     */
    _createForm: function(iframe, params){
        // We can't use the following code in IE6
        // var form = document.createElement('form');
        // form.setAttribute('method', 'post');
        // form.setAttribute('enctype', 'multipart/form-data');
        // Because in this case file won't be attached to request
        var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>');
        // BP add csrf
        params['authenticity_token'] = jQuery('meta[name="csrf-token"]').attr('content')

        var queryString = qq.obj2url(params, this._options.action);

        form.setAttribute('action', queryString);
        form.setAttribute('target', iframe.name);
        form.style.display = 'none';
        document.body.appendChild(form);

        return form;
    }
});

/**
 * Class for uploading files using xhr
 * @inherits qq.UploadHandlerAbstract
 */
qq.UploadHandlerXhr = function(o){
    qq.UploadHandlerAbstract.apply(this, arguments);

    this._files = [];
    this._xhrs = [];
    
    // current loaded size in bytes for each file 
    this._loaded = [];
};

// static method
qq.UploadHandlerXhr.isSupported = function(){
    var input = document.createElement('input');
    input.type = 'file';        
    
    return (
        'multiple' in input &&
        typeof File != "undefined" &&
        typeof (new XMLHttpRequest()).upload != "undefined" );       
};

// @inherits qq.UploadHandlerAbstract
qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype)

qq.extend(qq.UploadHandlerXhr.prototype, {
    /**
     * Adds file to the queue
     * Returns id to use with upload, cancel
     **/    
    add: function(file){
        if (!(file instanceof File)){
            throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
        }
                
        return this._files.push(file) - 1;        
    },
    getName: function(id){        
        var file = this._files[id];
        // fix missing name in Safari 4
        return file.fileName != null ? file.fileName : file.name;       
    },
    getSize: function(id){
        var file = this._files[id];
        return file.fileSize != null ? file.fileSize : file.size;
    },    
    /**
     * Returns uploaded bytes for file identified by id 
     */    
    getLoaded: function(id){
        return this._loaded[id] || 0; 
    },
    /**
     * Sends the file identified by id and additional query params to the server
     * @param {Object} params name-value string pairs
     */    
    _upload: function(id, params){
        var file = this._files[id],
            name = this.getName(id),
            size = this.getSize(id);
                
        this._loaded[id] = 0;
                                
        var xhr = this._xhrs[id] = new XMLHttpRequest();
        var self = this;
                                        
        xhr.upload.onprogress = function(e){
            if (e.lengthComputable){
                self._loaded[id] = e.loaded;
                self._options.onProgress(id, name, e.loaded, e.total);
            }
        };

        xhr.onreadystatechange = function(){            
            if (xhr.readyState == 4){
                self._onComplete(id, xhr);                    
            }
        };

        // build query string
        params = params || {};
        params['qqfile'] = name;
        var queryString = qq.obj2url(params, this._options.action);

        xhr.open("POST", queryString, true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
        xhr.setRequestHeader('X-CSRF-Token', jQuery('meta[name="csrf-token"]').attr('content'));
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.send(file);
    },
    _onComplete: function(id, xhr){
        // the request was aborted/cancelled
        if (!this._files[id]) return;
        
        var name = this.getName(id);
        var size = this.getSize(id);
        
        this._options.onProgress(id, name, size, size);
                
        if (xhr.status == 200){
            this.log("xhr - server response received");
            this.log("responseText = " + xhr.responseText);
                        
            var response;
                    
            try {
                response = eval("(" + xhr.responseText + ")");
            } catch(err){
                response = {};
            }
            
            this._options.onComplete(id, name, response);
                        
        } else {                   
            this._options.onComplete(id, name, {});
        }
                
        this._files[id] = null;
        this._xhrs[id] = null;    
        this._dequeue(id);                    
    },
    _cancel: function(id){
        this._options.onCancel(id, this.getName(id));
        
        this._files[id] = null;
        
        if (this._xhrs[id]){
            this._xhrs[id].abort();
            this._xhrs[id] = null;                                   
        }
    }
});
if(!this.JSON){this.JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());






/*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */

!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="1.12.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}if(f=d.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return A.find(a);this.length=1,this[0]=f}return this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||(e=n.uniqueSort(e)),D.test(a)&&(e=e.reverse())),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=!0,c||j.disable(),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.addEventListener?(d.removeEventListener("DOMContentLoaded",K),a.removeEventListener("load",K)):(d.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(d.addEventListener||"load"===a.event.type||"complete"===d.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll)a.setTimeout(n.ready);else if(d.addEventListener)d.addEventListener("DOMContentLoaded",K),a.addEventListener("load",K);else{d.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&d.documentElement}catch(e){}c&&c.doScroll&&!function f(){if(!n.isReady){try{c.doScroll("left")}catch(b){return a.setTimeout(f,50)}J(),n.ready()}}()}return I.promise(b)},n.ready.promise();var L;for(L in n(l))break;l.ownFirst="0"===L,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c,e;c=d.getElementsByTagName("body")[0],c&&c.style&&(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",l.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(e))}),function(){var a=d.createElement("div");l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}a=null}();var M=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b},N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0;
}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(M(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),"object"!=typeof b&&"function"!=typeof b||(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(M(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=void 0)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}}),function(){var a;l.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,e;return c=d.getElementsByTagName("body")[0],c&&c.style?(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(d.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(e),a):void 0}}();var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),V=["Top","Right","Bottom","Left"],W=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function X(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&U.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var Y=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)Y(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},Z=/^(?:checkbox|radio)$/i,$=/<([\w:-]+)/,_=/^$|\/(?:java|ecma)script/i,aa=/^\s+/,ba="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";function ca(a){var b=ba.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}!function(){var a=d.createElement("div"),b=d.createDocumentFragment(),c=d.createElement("input");a.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",l.leadingWhitespace=3===a.firstChild.nodeType,l.tbody=!a.getElementsByTagName("tbody").length,l.htmlSerialize=!!a.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==d.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,b.appendChild(c),l.appendChecked=c.checked,a.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/<tbody/i;function ia(a){Z.test(a.type)&&(a.defaultChecked=a.checked)}function ja(a,b,c,d,e){for(var f,g,h,i,j,k,m,o=a.length,p=ca(b),q=[],r=0;o>r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?"<table>"!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)sa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=qa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ma.test(f)?this.mouseHooks:la.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=g.srcElement||d),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,h.filter?h.filter(a,g):a},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button,h=b.fromElement;return null==a.pageX&&null!=b.clientX&&(e=a.target.ownerDocument||d,f=e.documentElement,c=e.body,a.pageX=b.clientX+(f&&f.scrollLeft||c&&c.scrollLeft||0)-(f&&f.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(f&&f.scrollTop||c&&c.scrollTop||0)-(f&&f.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&h&&(a.relatedTarget=h===a.target?b.toElement:h),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ra()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ra()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b),d.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=d.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)}:function(a,b,c){var d="on"+b;a.detachEvent&&("undefined"==typeof a[d]&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?pa:qa):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:qa,isPropagationStopped:qa,isImmediatePropagationStopped:qa,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=pa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=pa,a&&!this.isSimulated&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=pa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submit||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?n.prop(b,"form"):void 0;c&&!n._data(c,"submit")&&(n.event.add(c,"submit._submit",function(a){a._submitBubble=!0}),n._data(c,"submit",!0))})},postDispatch:function(a){a._submitBubble&&(delete a._submitBubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.change||(n.event.special.change={setup:function(){return ka.test(this.nodeName)?("checkbox"!==this.type&&"radio"!==this.type||(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._justChanged=!0)}),n.event.add(this,"click._change",function(a){this._justChanged&&!a.isTrigger&&(this._justChanged=!1),n.event.simulate("change",this,a)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;ka.test(b.nodeName)&&!n._data(b,"change")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a)}),n._data(b,"change",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!ka.test(this.nodeName)}}),l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d){return sa(this,a,b,c,d)},one:function(a,b,c,d){return sa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=qa),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var ta=/ jQuery\d+="(?:null|\d+)"/g,ua=new RegExp("<(?:"+ba+")[\\s/>]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/<script|<style|<link/i,xa=/checked\s*(?:[^=]|=\s*.checked.)/i,ya=/^true\/(.*)/,za=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}}function Ha(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ja[0].contentWindow||Ja[0].contentDocument).document,b.write(),b.close(),c=La(a,b),Ja.detach()),Ka[a]=c),c}var Na=/^margin/,Oa=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Pa=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Qa=d.documentElement;!function(){var b,c,e,f,g,h,i=d.createElement("div"),j=d.createElement("div");if(j.style){j.style.cssText="float:left;opacity:.5",l.opacity="0.5"===j.style.opacity,l.cssFloat=!!j.style.cssFloat,j.style.backgroundClip="content-box",j.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===j.style.backgroundClip,i=d.createElement("div"),i.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",j.innerHTML="",i.appendChild(j),l.boxSizing=""===j.style.boxSizing||""===j.style.MozBoxSizing||""===j.style.WebkitBoxSizing,n.extend(l,{reliableHiddenOffsets:function(){return null==b&&k(),f},boxSizingReliable:function(){return null==b&&k(),e},pixelMarginRight:function(){return null==b&&k(),c},pixelPosition:function(){return null==b&&k(),b},reliableMarginRight:function(){return null==b&&k(),g},reliableMarginLeft:function(){return null==b&&k(),h}});function k(){var k,l,m=d.documentElement;m.appendChild(i),j.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",b=e=h=!1,c=g=!0,a.getComputedStyle&&(l=a.getComputedStyle(j),b="1%"!==(l||{}).top,h="2px"===(l||{}).marginLeft,e="4px"===(l||{width:"4px"}).width,j.style.marginRight="50%",c="4px"===(l||{marginRight:"4px"}).marginRight,k=j.appendChild(d.createElement("div")),k.style.cssText=j.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",k.style.marginRight=k.style.width="0",j.style.width="1px",g=!parseFloat((a.getComputedStyle(k)||{}).marginRight),j.removeChild(k)),j.style.display="none",f=0===j.getClientRects().length,f&&(j.style.display="",j.innerHTML="<table><tr><td></td><td>t</td></tr></table>",j.childNodes[0].style.borderCollapse="separate",k=j.getElementsByTagName("td"),k[0].style.cssText="margin:0;border:0;padding:0;display:none",f=0===k[0].offsetHeight,f&&(k[0].style.display="",k[1].style.display="none",f=0===k[0].offsetHeight)),m.removeChild(i)}}}();var Ra,Sa,Ta=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ra=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Oa.test(g)&&Na.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0===g?g:g+""}):Qa.currentStyle&&(Ra=function(a){return a.currentStyle},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Oa.test(g)&&!Ta.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Ua(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Va=/alpha\([^)]*\)/i,Wa=/opacity\s*=\s*([^)]*)/i,Xa=/^(none|table(?!-c[ea]).+)/,Ya=new RegExp("^("+T+")(.*)$","i"),Za={position:"absolute",visibility:"hidden",display:"block"},$a={letterSpacing:"0",fontWeight:"400"},_a=["Webkit","O","Moz","ms"],ab=d.createElement("div").style;function bb(a){if(a in ab)return a;var b=a.charAt(0).toUpperCase()+a.slice(1),c=_a.length;while(c--)if(a=_a[c]+b,a in ab)return a}function cb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&W(d)&&(f[g]=n._data(d,"olddisplay",Ma(d.nodeName)))):(e=W(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function db(a,b,c){var d=Ya.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function eb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+V[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+V[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+V[f]+"Width",!0,e))):(g+=n.css(a,"padding"+V[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+V[f]+"Width",!0,e)));return g}function fb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ra(a),g=l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Sa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Oa.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+eb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Sa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=U.exec(c))&&e[1]&&(c=X(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Sa(a,b,d)),"normal"===f&&b in $a&&(f=$a[b]),""===c||c?(e=parseFloat(f),c===!0||isFinite(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Xa.test(n.css(a,"display"))&&0===a.offsetWidth?Pa(a,Za,function(){return fb(a,b,d)}):fb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ra(a);return db(a,c,d?eb(a,b,d,l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Wa.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Va,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Va.test(f)?f.replace(Va,e):f+" "+e)}}),n.cssHooks.marginRight=Ua(l.reliableMarginRight,function(a,b){return b?Pa(a,{display:"inline-block"},Sa,[a,"marginRight"]):void 0}),n.cssHooks.marginLeft=Ua(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Sa(a,"marginLeft"))||(n.contains(a.ownerDocument,a)?a.getBoundingClientRect().left-Pa(a,{
marginLeft:0},function(){return a.getBoundingClientRect().left}):0))+"px":void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+V[d]+b]=f[d]||f[d-2]||f[0];return e}},Na.test(a)||(n.cssHooks[a+b].set=db)}),n.fn.extend({css:function(a,b){return Y(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ra(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return cb(this,!0)},hide:function(){return cb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){W(this)?n(this).show():n(this).hide()})}});function gb(a,b,c,d,e){return new gb.prototype.init(a,b,c,d,e)}n.Tween=gb,gb.prototype={constructor:gb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=gb.propHooks[this.prop];return a&&a.get?a.get(this):gb.propHooks._default.get(this)},run:function(a){var b,c=gb.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):gb.propHooks._default.set(this),this}},gb.prototype.init.prototype=gb.prototype,gb.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},gb.propHooks.scrollTop=gb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=gb.prototype.init,n.fx.step={};var hb,ib,jb=/^(?:toggle|show|hide)$/,kb=/queueHooks$/;function lb(){return a.setTimeout(function(){hb=void 0}),hb=n.now()}function mb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=V[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function nb(a,b,c){for(var d,e=(qb.tweeners[b]||[]).concat(qb.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ob(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&W(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k="none"===j?n._data(a,"olddisplay")||Ma(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==Ma(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],jb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(o))"inline"===("none"===j?Ma(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=nb(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function pb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function qb(a,b,c){var d,e,f=0,g=qb.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=hb||lb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:hb||lb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(pb(k,j.opts.specialEasing);g>f;f++)if(d=qb.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,nb,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(qb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return X(c.elem,a,U.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],qb.tweeners[c]=qb.tweeners[c]||[],qb.tweeners[c].unshift(b)},prefilters:[ob],prefilter:function(a,b){b?qb.prefilters.unshift(a):qb.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(W).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=qb(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&kb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(mb(b,!0),a,d,e)}}),n.each({slideDown:mb("show"),slideUp:mb("hide"),slideToggle:mb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(hb=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),hb=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ib||(ib=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(ib),ib=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a,b=d.createElement("input"),c=d.createElement("div"),e=d.createElement("select"),f=e.appendChild(d.createElement("option"));c=d.createElement("div"),c.setAttribute("className","t"),c.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],b.setAttribute("type","checkbox"),c.appendChild(b),a=c.getElementsByTagName("a")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==c.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=f.selected,l.enctype=!!d.createElement("form").enctype,e.disabled=!0,l.optDisabled=!f.disabled,b=d.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value}();var rb=/\r/g,sb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(sb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>-1)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var tb,ub,vb=n.expr.attrHandle,wb=/^(?:checked|selected)$/i,xb=l.getSetAttribute,yb=l.input;n.fn.extend({attr:function(a,b){return Y(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ub:tb)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?yb&&xb||!wb.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(xb?c:d)}}),ub={set:function(a,b,c){return b===!1?n.removeAttr(a,c):yb&&xb||!wb.test(c)?a.setAttribute(!xb&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=vb[b]||n.find.attr;yb&&xb||!wb.test(b)?vb[b]=function(a,b,d){var e,f;return d||(f=vb[b],vb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,vb[b]=f),e}:vb[b]=function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),yb&&xb||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):tb&&tb.set(a,b,c)}}),xb||(tb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},vb.id=vb.name=vb.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:tb.set},n.attrHooks.contenteditable={set:function(a,b,c){tb.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var zb=/^(?:input|select|textarea|button|object)$/i,Ab=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return Y(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):zb.test(a.nodeName)||Ab.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var Bb=/[\t\r\n\f]/g;function Cb(a){return n.attr(a,"class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,Cb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,Cb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,Cb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=Cb(this),b&&n._data(this,"__className__",b),n.attr(this,"class",b||a===!1?"":n._data(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+Cb(c)+" ").replace(Bb," ").indexOf(b)>-1)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Db=a.location,Eb=n.now(),Fb=/\?/,Gb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(Gb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new a.DOMParser,c=d.parseFromString(b,"text/xml")):(c=new a.ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var Hb=/#.*$/,Ib=/([?&])_=[^&]*/,Jb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Kb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Lb=/^(?:GET|HEAD)$/,Mb=/^\/\//,Nb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ob={},Pb={},Qb="*/".concat("*"),Rb=Db.href,Sb=Nb.exec(Rb.toLowerCase())||[];function Tb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Ub(a,b,c,d){var e={},f=a===Pb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Vb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Wb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Xb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Rb,type:"GET",isLocal:Kb.test(Sb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Qb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Vb(Vb(a,n.ajaxSettings),b):Vb(n.ajaxSettings,a)},ajaxPrefilter:Tb(Ob),ajaxTransport:Tb(Pb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var d,e,f,g,h,i,j,k,l=n.ajaxSetup({},c),m=l.context||l,o=l.context&&(m.nodeType||m.jquery)?n(m):n.event,p=n.Deferred(),q=n.Callbacks("once memory"),r=l.statusCode||{},s={},t={},u=0,v="canceled",w={readyState:0,getResponseHeader:function(a){var b;if(2===u){if(!k){k={};while(b=Jb.exec(g))k[b[1].toLowerCase()]=b[2]}b=k[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===u?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return u||(a=t[c]=t[c]||a,s[a]=b),this},overrideMimeType:function(a){return u||(l.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>u)for(b in a)r[b]=[r[b],a[b]];else w.always(a[w.status]);return this},abort:function(a){var b=a||v;return j&&j.abort(b),y(0,b),this}};if(p.promise(w).complete=q.add,w.success=w.done,w.error=w.fail,l.url=((b||l.url||Rb)+"").replace(Hb,"").replace(Mb,Sb[1]+"//"),l.type=c.method||c.type||l.method||l.type,l.dataTypes=n.trim(l.dataType||"*").toLowerCase().match(G)||[""],null==l.crossDomain&&(d=Nb.exec(l.url.toLowerCase()),l.crossDomain=!(!d||d[1]===Sb[1]&&d[2]===Sb[2]&&(d[3]||("http:"===d[1]?"80":"443"))===(Sb[3]||("http:"===Sb[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=n.param(l.data,l.traditional)),Ub(Ob,l,c,w),2===u)return w;i=n.event&&l.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!Lb.test(l.type),f=l.url,l.hasContent||(l.data&&(f=l.url+=(Fb.test(f)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=Ib.test(f)?f.replace(Ib,"$1_="+Eb++):f+(Fb.test(f)?"&":"?")+"_="+Eb++)),l.ifModified&&(n.lastModified[f]&&w.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&w.setRequestHeader("If-None-Match",n.etag[f])),(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&w.setRequestHeader("Content-Type",l.contentType),w.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+Qb+"; q=0.01":""):l.accepts["*"]);for(e in l.headers)w.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,w,l)===!1||2===u))return w.abort();v="abort";for(e in{success:1,error:1,complete:1})w[e](l[e]);if(j=Ub(Pb,l,c,w)){if(w.readyState=1,i&&o.trigger("ajaxSend",[w,l]),2===u)return w;l.async&&l.timeout>0&&(h=a.setTimeout(function(){w.abort("timeout")},l.timeout));try{u=1,j.send(s,y)}catch(x){if(!(2>u))throw x;y(-1,x)}}else y(-1,"No Transport");function y(b,c,d,e){var k,s,t,v,x,y=c;2!==u&&(u=2,h&&a.clearTimeout(h),j=void 0,g=e||"",w.readyState=b>0?4:0,k=b>=200&&300>b||304===b,d&&(v=Wb(l,w,d)),v=Xb(l,v,w,k),k?(l.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(n.lastModified[f]=x),x=w.getResponseHeader("etag"),x&&(n.etag[f]=x)),204===b||"HEAD"===l.type?y="nocontent":304===b?y="notmodified":(y=v.state,s=v.data,t=v.error,k=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),w.status=b,w.statusText=(c||y)+"",k?p.resolveWith(m,[s,y,w]):p.rejectWith(m,[w,y,t]),w.statusCode(r),r=void 0,i&&o.trigger(k?"ajaxSuccess":"ajaxError",[w,l,k?s:t]),q.fireWith(m,[w,y]),i&&(o.trigger("ajaxComplete",[w,l]),--n.active||n.event.trigger("ajaxStop")))}return w},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}});function Yb(a){return a.style&&a.style.display||n.css(a,"display")}function Zb(a){if(!n.contains(a.ownerDocument||d,a))return!0;while(a&&1===a.nodeType){if("none"===Yb(a)||"hidden"===a.type)return!0;a=a.parentNode}return!1}n.expr.filters.hidden=function(a){return l.reliableHiddenOffsets()?a.offsetWidth<=0&&a.offsetHeight<=0&&!a.getClientRects().length:Zb(a)},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var $b=/%20/g,_b=/\[\]$/,ac=/\r?\n/g,bc=/^(?:submit|button|image|reset|file)$/i,cc=/^(?:input|select|textarea|keygen)/i;function dc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||_b.test(a)?d(a,e):dc(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)dc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)dc(c,a[c],b,e);return d.join("&").replace($b,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&cc.test(this.nodeName)&&!bc.test(a)&&(this.checked||!Z.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(ac,"\r\n")}}):{name:b.name,value:c.replace(ac,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return this.isLocal?ic():d.documentMode>8?hc():/^(get|post|head|put|delete|options)$/i.test(this.type)&&hc()||ic()}:hc;var ec=0,fc={},gc=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in fc)fc[a](void 0,!0)}),l.cors=!!gc&&"withCredentials"in gc,gc=l.ajax=!!gc,gc&&n.ajaxTransport(function(b){if(!b.crossDomain||l.cors){var c;return{send:function(d,e){var f,g=b.xhr(),h=++ec;if(g.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(f in b.xhrFields)g[f]=b.xhrFields[f];b.mimeType&&g.overrideMimeType&&g.overrideMimeType(b.mimeType),b.crossDomain||d["X-Requested-With"]||(d["X-Requested-With"]="XMLHttpRequest");for(f in d)void 0!==d[f]&&g.setRequestHeader(f,d[f]+"");g.send(b.hasContent&&b.data||null),c=function(a,d){var f,i,j;if(c&&(d||4===g.readyState))if(delete fc[h],c=void 0,g.onreadystatechange=n.noop,d)4!==g.readyState&&g.abort();else{j={},f=g.status,"string"==typeof g.responseText&&(j.text=g.responseText);try{i=g.statusText}catch(k){i=""}f||!b.isLocal||b.crossDomain?1223===f&&(f=204):f=j.text?200:404}j&&e(f,i,j,g.getAllResponseHeaders())},b.async?4===g.readyState?a.setTimeout(c):g.onreadystatechange=fc[h]=c:c()},abort:function(){c&&c(void 0,!0)}}}});function hc(){try{return new a.XMLHttpRequest}catch(b){}}function ic(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=d.head||n("head")[0]||d.documentElement;return{send:function(e,f){b=d.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||f(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var jc=[],kc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=jc.pop()||n.expando+"_"+Eb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(kc.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&kc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(kc,"$1"+e):b.jsonp!==!1&&(b.url+=(Fb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,jc.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ja([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var lc=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&lc)return lc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h,a.length)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function mc(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?("undefined"!=typeof e.getBoundingClientRect&&(d=e.getBoundingClientRect()),c=mc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Qa})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return Y(this,function(a,d,e){var f=mc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ua(l.pixelPosition,function(a,c){return c?(c=Sa(a,b),Oa.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({
padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return Y(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var nc=a.jQuery,oc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=oc),b&&a.jQuery===n&&(a.jQuery=nc),n},b||(a.jQuery=a.$=n),n});
/*!
 * jQuery Migrate - v1.0.0 - 2013-01-14
 * https://github.com/jquery/jquery-migrate
 * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT
 */

(function( jQuery, window, undefined ) {
"use strict";


var warnedAbout = {};

// List of warnings already given; public read only
jQuery.migrateWarnings = [];

// Set to true to prevent console output; migrateWarnings still maintained
jQuery.migrateMute = true;

// Forget any warnings we've already given; public
jQuery.migrateReset = function() {
	warnedAbout = {};
	jQuery.migrateWarnings.length = 0;
};

function migrateWarn( msg) {
	if ( !warnedAbout[ msg ] ) {
		warnedAbout[ msg ] = true;
		jQuery.migrateWarnings.push( msg );
		if ( window.console && console.warn && !jQuery.migrateMute ) {
			console.warn( "JQMIGRATE: " + msg );
		}
	}
}

function migrateWarnProp( obj, prop, value, msg ) {
	if ( Object.defineProperty ) {
		// On ES5 browsers (non-oldIE), warn if the code tries to get prop;
		// allow property to be overwritten in case some other plugin wants it
		try {
			Object.defineProperty( obj, prop, {
				configurable: true,
				enumerable: true,
				get: function() {
					migrateWarn( msg );
					return value;
				},
				set: function( newValue ) {
					migrateWarn( msg );
					value = newValue;
				}
			});
			return;
		} catch( err ) {
			// IE8 is a dope about Object.defineProperty, can't warn there
		}
	}

	// Non-ES5 (or broken) browser; just set the property
	jQuery._definePropertyBroken = true;
	obj[ prop ] = value;
}

if ( document.compatMode === "BackCompat" ) {
	// jQuery has never supported or tested Quirks Mode
	migrateWarn( "jQuery is not compatible with Quirks Mode" );
}


var attrFn = {},
	attr = jQuery.attr,
	valueAttrGet = jQuery.attrHooks.value && jQuery.attrHooks.value.get ||
		function() { return null; },
	valueAttrSet = jQuery.attrHooks.value && jQuery.attrHooks.value.set ||
		function() { return undefined; },
	rnoType = /^(?:input|button)$/i,
	rnoAttrNodeType = /^[238]$/,
	rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
	ruseDefault = /^(?:checked|selected)$/i;

// jQuery.attrFn
migrateWarnProp( jQuery, "attrFn", attrFn, "jQuery.attrFn is deprecated" );

jQuery.attr = function( elem, name, value, pass ) {
	var lowerName = name.toLowerCase(),
		nType = elem && elem.nodeType;

	if ( pass ) {
		migrateWarn("jQuery.fn.attr( props, pass ) is deprecated");
		if ( elem && !rnoAttrNodeType.test( nType ) && jQuery.isFunction( jQuery.fn[ name ] ) ) {
			return jQuery( elem )[ name ]( value );
		}
	}

	// Warn if user tries to set `type` since it breaks on IE 6/7/8
	if ( name === "type" && value !== undefined && rnoType.test( elem.nodeName ) ) {
		migrateWarn("Can't change the 'type' of an input or button in IE 6/7/8");
	}

	// Restore boolHook for boolean property/attribute synchronization
	if ( !jQuery.attrHooks[ lowerName ] && rboolean.test( lowerName ) ) {
		jQuery.attrHooks[ lowerName ] = {
			get: function( elem, name ) {
				// Align boolean attributes with corresponding properties
				// Fall back to attribute presence where some booleans are not supported
				var attrNode,
					property = jQuery.prop( elem, name );
				return property === true || typeof property !== "boolean" &&
					( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?

					name.toLowerCase() :
					undefined;
			},
			set: function( elem, value, name ) {
				var propName;
				if ( value === false ) {
					// Remove boolean attributes when set to false
					jQuery.removeAttr( elem, name );
				} else {
					// value is true since we know at this point it's type boolean and not false
					// Set boolean attributes to the same name and set the DOM property
					propName = jQuery.propFix[ name ] || name;
					if ( propName in elem ) {
						// Only set the IDL specifically if it already exists on the element
						elem[ propName ] = true;
					}

					elem.setAttribute( name, name.toLowerCase() );
				}
				return name;
			}
		};

		// Warn only for attributes that can remain distinct from their properties post-1.9
		if ( ruseDefault.test( lowerName ) ) {
			migrateWarn( "jQuery.fn.attr(" + lowerName + ") may use property instead of attribute" );
		}
	}

	return attr.call( jQuery, elem, name, value );
};

// attrHooks: value
jQuery.attrHooks.value = {
	get: function( elem, name ) {
		var nodeName = ( elem.nodeName || "" ).toLowerCase();
		if ( nodeName === "button" ) {
			return valueAttrGet.apply( this, arguments );
		}
		if ( nodeName !== "input" && nodeName !== "option" ) {
			migrateWarn("property-based jQuery.fn.attr('value') is deprecated");
		}
		return name in elem ?
			elem.value :
			null;
	},
	set: function( elem, value ) {
		var nodeName = ( elem.nodeName || "" ).toLowerCase();
		if ( nodeName === "button" ) {
			return valueAttrSet.apply( this, arguments );
		}
		if ( nodeName !== "input" && nodeName !== "option" ) {
			migrateWarn("property-based jQuery.fn.attr('value', val) is deprecated");
		}
		// Does not return so that setAttribute is also used
		elem.value = value;
	}
};


var matched, browser,
	oldInit = jQuery.fn.init,
	// Note this does NOT include the # XSS fix from 1.7!
	rquickExpr = /^(?:.*(<[\w\W]+>)[^>]*|#([\w\-]*))$/;

// $(html) "looks like html" rule change
jQuery.fn.init = function( selector, context, rootjQuery ) {
	var match;

	if ( selector && typeof selector === "string" && !jQuery.isPlainObject( context ) &&
			(match = rquickExpr.exec( selector )) && match[1] ) {
		// This is an HTML string according to the "old" rules; is it still?
		if ( selector.charAt( 0 ) !== "<" ) {
			migrateWarn("$(html) HTML strings must start with '<' character");
		}
		// Now process using loose rules; let pre-1.8 play too
		if ( context && context.context ) {
			// jQuery object as context; parseHTML expects a DOM object
			context = context.context;
		}
		if ( jQuery.parseHTML ) {
			return oldInit.call( this, jQuery.parseHTML( jQuery.trim(selector), context, true ),
					context, rootjQuery );
		}
	}
	return oldInit.apply( this, arguments );
};
jQuery.fn.init.prototype = jQuery.fn;

jQuery.uaMatch = function( ua ) {
	ua = ua.toLowerCase();

	var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
		/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
		/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
		/(msie) ([\w.]+)/.exec( ua ) ||
		ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
		[];

	return {
		browser: match[ 1 ] || "",
		version: match[ 2 ] || "0"
	};
};

matched = jQuery.uaMatch( navigator.userAgent );
browser = {};

if ( matched.browser ) {
	browser[ matched.browser ] = true;
	browser.version = matched.version;
}

// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
	browser.webkit = true;
} else if ( browser.webkit ) {
	browser.safari = true;
}

jQuery.browser = browser;

// Warn if the code tries to get jQuery.browser
migrateWarnProp( jQuery, "browser", browser, "jQuery.browser is deprecated" );

jQuery.sub = function() {
	function jQuerySub( selector, context ) {
		return new jQuerySub.fn.init( selector, context );
	}
	jQuery.extend( true, jQuerySub, this );
	jQuerySub.superclass = this;
	jQuerySub.fn = jQuerySub.prototype = this();
	jQuerySub.fn.constructor = jQuerySub;
	jQuerySub.sub = this.sub;
	jQuerySub.fn.init = function init( selector, context ) {
		if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
			context = jQuerySub( context );
		}

		return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
	};
	jQuerySub.fn.init.prototype = jQuerySub.fn;
	var rootjQuerySub = jQuerySub(document);
	migrateWarn( "jQuery.sub() is deprecated" );
	return jQuerySub;
};


var oldFnData = jQuery.fn.data;

jQuery.fn.data = function( name ) {
	var ret, evt,
		elem = this[0];

	// Handles 1.7 which has this behavior and 1.8 which doesn't
	if ( elem && name === "events" && arguments.length === 1 ) {
		ret = jQuery.data( elem, name );
		evt = jQuery._data( elem, name );
		if ( ( ret === undefined || ret === evt ) && evt !== undefined ) {
			migrateWarn("Use of jQuery.fn.data('events') is deprecated");
			return evt;
		}
	}
	return oldFnData.apply( this, arguments );
};


var rscriptType = /\/(java|ecma)script/i,
	oldSelf = jQuery.fn.andSelf || jQuery.fn.addBack,
	oldFragment = jQuery.buildFragment;

jQuery.fn.andSelf = function() {
	migrateWarn("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()");
	return oldSelf.apply( this, arguments );
};

// Since jQuery.clean is used internally on older versions, we only shim if it's missing
if ( !jQuery.clean ) {
	jQuery.clean = function( elems, context, fragment, scripts ) {
		// Set context per 1.8 logic
		context = context || document;
		context = !context.nodeType && context[0] || context;
		context = context.ownerDocument || context;

		migrateWarn("jQuery.clean() is deprecated");

		var i, elem, handleScript, jsTags,
			ret = [];

		jQuery.merge( ret, jQuery.buildFragment( elems, context ).childNodes );

		// Complex logic lifted directly from jQuery 1.8
		if ( fragment ) {
			// Special handling of each script element
			handleScript = function( elem ) {
				// Check if we consider it executable
				if ( !elem.type || rscriptType.test( elem.type ) ) {
					// Detach the script and store it in the scripts array (if provided) or the fragment
					// Return truthy to indicate that it has been handled
					return scripts ?
						scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
						fragment.appendChild( elem );
				}
			};

			for ( i = 0; (elem = ret[i]) != null; i++ ) {
				// Check if we're done after handling an executable script
				if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
					// Append to fragment and handle embedded scripts
					fragment.appendChild( elem );
					if ( typeof elem.getElementsByTagName !== "undefined" ) {
						// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
						jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );

						// Splice the scripts into ret after their former ancestor and advance our index beyond them
						ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
						i += jsTags.length;
					}
				}
			}
		}

		return ret;
	};
}

jQuery.buildFragment = function( elems, context, scripts, selection ) {
	var ret,
		warning = "jQuery.buildFragment() is deprecated";

	// Set context per 1.8 logic
	context = context || document;
	context = !context.nodeType && context[0] || context;
	context = context.ownerDocument || context;

	try {
		ret = oldFragment.call( jQuery, elems, context, scripts, selection );

	// jQuery < 1.8 required arrayish context; jQuery 1.9 fails on it
	} catch( x ) {
		ret = oldFragment.call( jQuery, elems, context.nodeType ? [ context ] : context[ 0 ], scripts, selection );

		// Success from tweaking context means buildFragment was called by the user
		migrateWarn( warning );
	}

	// jQuery < 1.9 returned an object instead of the fragment itself
	if ( !ret.fragment ) {
		migrateWarnProp( ret, "fragment", ret, warning );
		migrateWarnProp( ret, "cacheable", false, warning );
	}

	return ret;
};

var eventAdd = jQuery.event.add,
	eventRemove = jQuery.event.remove,
	eventTrigger = jQuery.event.trigger,
	oldToggle = jQuery.fn.toggle,
	oldLive = jQuery.fn.live,
	oldDie = jQuery.fn.die,
	ajaxEvents = "ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",
	rajaxEvent = new RegExp( "\\b(?:" + ajaxEvents + ")\\b" ),
	rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
	hoverHack = function( events ) {
		if ( typeof( events ) != "string" || jQuery.event.special.hover ) {
			return events;
		}
		if ( rhoverHack.test( events ) ) {
			migrateWarn("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'");
		}
		return events && events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
	};

// Event props removed in 1.9, put them back if needed; no practical way to warn them
if ( jQuery.event.props && jQuery.event.props[ 0 ] !== "attrChange" ) {
	jQuery.event.props.unshift( "attrChange", "attrName", "relatedNode", "srcElement" );
}

// Undocumented jQuery.event.handle was "deprecated" in jQuery 1.7
migrateWarnProp( jQuery.event, "handle", jQuery.event.dispatch, "jQuery.event.handle is undocumented and deprecated" );

// Support for 'hover' pseudo-event and ajax event warnings
jQuery.event.add = function( elem, types, handler, data, selector ){
	if ( elem !== document && rajaxEvent.test( types ) ) {
		migrateWarn( "AJAX events should be attached to document: " + types );
	}
	eventAdd.call( this, elem, hoverHack( types || "" ), handler, data, selector );
};
jQuery.event.remove = function( elem, types, handler, selector, mappedTypes ){
	eventRemove.call( this, elem, hoverHack( types ) || "", handler, selector, mappedTypes );
};

jQuery.fn.error = function() {
	var args = Array.prototype.slice.call( arguments, 0);
	migrateWarn("jQuery.fn.error() is deprecated");
	args.splice( 0, 0, "error" );
	if ( arguments.length ) {
		return this.bind.apply( this, args );
	}
	// error event should not bubble to window, although it does pre-1.7
	this.triggerHandler.apply( this, args );
	return this;
};

jQuery.fn.toggle = function( fn, fn2 ) {

	// Don't mess with animation or css toggles
	if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) {
		return oldToggle.apply( this, arguments );
	}
	migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated");

	// Save reference to arguments for access in closure
	var args = arguments,
		guid = fn.guid || jQuery.guid++,
		i = 0,
		toggler = function( event ) {
			// Figure out which function to execute
			var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
			jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );

			// Make sure that clicks stop
			event.preventDefault();

			// and execute the function
			return args[ lastToggle ].apply( this, arguments ) || false;
		};

	// link all the functions, so any of them can unbind this click handler
	toggler.guid = guid;
	while ( i < args.length ) {
		args[ i++ ].guid = guid;
	}

	return this.click( toggler );
};

jQuery.fn.live = function( types, data, fn ) {
	migrateWarn("jQuery.fn.live() is deprecated");
	if ( oldLive ) {
		return oldLive.apply( this, arguments );
	}
	jQuery( this.context ).on( types, this.selector, data, fn );
	return this;
};

jQuery.fn.die = function( types, fn ) {
	migrateWarn("jQuery.fn.die() is deprecated");
	if ( oldDie ) {
		return oldDie.apply( this, arguments );
	}
	jQuery( this.context ).off( types, this.selector || "**", fn );
	return this;
};

// Turn global events into document-triggered events
jQuery.event.trigger = function( event, data, elem, onlyHandlers  ){
	if ( !elem & !rajaxEvent.test( event ) ) {
		migrateWarn( "Global events are undocumented and deprecated" );
	}
	return eventTrigger.call( this,  event, data, elem || document, onlyHandlers  );
};
jQuery.each( ajaxEvents.split("|"),
	function( _, name ) {
		jQuery.event.special[ name ] = {
			setup: function() {
				var elem = this;

				// The document needs no shimming; must be !== for oldIE
				if ( elem !== document ) {
					jQuery.event.add( document, name + "." + jQuery.guid, function() {
						jQuery.event.trigger( name, null, elem, true );
					});
					jQuery._data( this, name, jQuery.guid++ );
				}
				return false;
			},
			teardown: function() {
				if ( this !== document ) {
					jQuery.event.remove( document, name + "." + jQuery._data( this, name ) );
				}
				return false;
			}
		};
	}
);


})( jQuery, window );
/*! jQuery UI - v1.10.4 - 2014-04-03
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */


(function(e,t){function i(t,i){var s,a,o,r=t.nodeName.toLowerCase();return"area"===r?(s=t.parentNode,a=s.name,t.href&&a&&"map"===s.nodeName.toLowerCase()?(o=e("img[usemap=#"+a+"]")[0],!!o&&n(o)):!1):(/input|select|textarea|button|object/.test(r)?!t.disabled:"a"===r?t.href||i:i)&&n(t)}function n(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var s=0,a=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,n){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),n&&n.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var n,s,a=e(this[0]);a.length&&a[0]!==document;){if(n=a.css("position"),("absolute"===n||"relative"===n||"fixed"===n)&&(s=parseInt(a.css("zIndex"),10),!isNaN(s)&&0!==s))return s;a=a.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++s)})},removeUniqueId:function(){return this.each(function(){a.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,n){return!!e.data(t,n[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var n=e.attr(t,"tabindex"),s=isNaN(n);return(s||n>=0)&&i(t,!s)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,n){function s(t,i,n,s){return e.each(a,function(){i-=parseFloat(e.css(t,"padding"+this))||0,n&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var a="Width"===n?["Left","Right"]:["Top","Bottom"],o=n.toLowerCase(),r={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+n]=function(i){return i===t?r["inner"+n].call(this):this.each(function(){e(this).css(o,s(this,i)+"px")})},e.fn["outer"+n]=function(t,i){return"number"!=typeof t?r["outer"+n].call(this,t):this.each(function(){e(this).css(o,s(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,n){var s,a=e.ui[t].prototype;for(s in n)a.plugins[s]=a.plugins[s]||[],a.plugins[s].push([i,n[s]])},call:function(e,t,i){var n,s=e.plugins[t];if(s&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(n=0;s.length>n;n++)e.options[s[n][0]]&&s[n][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var n=i&&"left"===i?"scrollLeft":"scrollTop",s=!1;return t[n]>0?!0:(t[n]=1,s=t[n]>0,t[n]=0,s)}})})(jQuery);(function(t,e){var i=0,s=Array.prototype.slice,n=t.cleanData;t.cleanData=function(e){for(var i,s=0;null!=(i=e[s]);s++)try{t(i).triggerHandler("remove")}catch(o){}n(e)},t.widget=function(i,s,n){var o,a,r,h,l={},c=i.split(".")[0];i=i.split(".")[1],o=c+"-"+i,n||(n=s,s=t.Widget),t.expr[":"][o.toLowerCase()]=function(e){return!!t.data(e,o)},t[c]=t[c]||{},a=t[c][i],r=t[c][i]=function(t,i){return this._createWidget?(arguments.length&&this._createWidget(t,i),e):new r(t,i)},t.extend(r,a,{version:n.version,_proto:t.extend({},n),_childConstructors:[]}),h=new s,h.options=t.widget.extend({},h.options),t.each(n,function(i,n){return t.isFunction(n)?(l[i]=function(){var t=function(){return s.prototype[i].apply(this,arguments)},e=function(t){return s.prototype[i].apply(this,t)};return function(){var i,s=this._super,o=this._superApply;return this._super=t,this._superApply=e,i=n.apply(this,arguments),this._super=s,this._superApply=o,i}}(),e):(l[i]=n,e)}),r.prototype=t.widget.extend(h,{widgetEventPrefix:a?h.widgetEventPrefix||i:i},l,{constructor:r,namespace:c,widgetName:i,widgetFullName:o}),a?(t.each(a._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,r,i._proto)}),delete a._childConstructors):s._childConstructors.push(r),t.widget.bridge(i,r)},t.widget.extend=function(i){for(var n,o,a=s.call(arguments,1),r=0,h=a.length;h>r;r++)for(n in a[r])o=a[r][n],a[r].hasOwnProperty(n)&&o!==e&&(i[n]=t.isPlainObject(o)?t.isPlainObject(i[n])?t.widget.extend({},i[n],o):t.widget.extend({},o):o);return i},t.widget.bridge=function(i,n){var o=n.prototype.widgetFullName||i;t.fn[i]=function(a){var r="string"==typeof a,h=s.call(arguments,1),l=this;return a=!r&&h.length?t.widget.extend.apply(null,[a].concat(h)):a,r?this.each(function(){var s,n=t.data(this,o);return n?t.isFunction(n[a])&&"_"!==a.charAt(0)?(s=n[a].apply(n,h),s!==n&&s!==e?(l=s&&s.jquery?l.pushStack(s.get()):s,!1):e):t.error("no such method '"+a+"' for "+i+" widget instance"):t.error("cannot call methods on "+i+" prior to initialization; "+"attempted to call method '"+a+"'")}):this.each(function(){var e=t.data(this,o);e?e.option(a||{})._init():t.data(this,o,new n(a,this))}),l}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(e,s){s=t(s||this.defaultElement||this)[0],this.element=t(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this.bindings=t(),this.hoverable=t(),this.focusable=t(),s!==this&&(t.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===s&&this.destroy()}}),this.document=t(s.style?s.ownerDocument:s.document||s),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:t.noop,_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(t.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:t.noop,widget:function(){return this.element},option:function(i,s){var n,o,a,r=i;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof i)if(r={},n=i.split("."),i=n.shift(),n.length){for(o=r[i]=t.widget.extend({},this.options[i]),a=0;n.length-1>a;a++)o[n[a]]=o[n[a]]||{},o=o[n[a]];if(i=n.pop(),1===arguments.length)return o[i]===e?null:o[i];o[i]=s}else{if(1===arguments.length)return this.options[i]===e?null:this.options[i];r[i]=s}return this._setOptions(r),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return this.options[t]=e,"disabled"===t&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!e).attr("aria-disabled",e),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(i,s,n){var o,a=this;"boolean"!=typeof i&&(n=s,s=i,i=!1),n?(s=o=t(s),this.bindings=this.bindings.add(s)):(n=s,s=this.element,o=this.widget()),t.each(n,function(n,r){function h(){return i||a.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof r?a[r]:r).apply(a,arguments):e}"string"!=typeof r&&(h.guid=r.guid=r.guid||h.guid||t.guid++);var l=n.match(/^(\w+)\s*(.*)$/),c=l[1]+a.eventNamespace,u=l[2];u?o.delegate(u,c,h):s.bind(c,h)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(e).undelegate(e)},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){t(e.currentTarget).addClass("ui-state-hover")},mouseleave:function(e){t(e.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){t(e.currentTarget).addClass("ui-state-focus")},focusout:function(e){t(e.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}})})(jQuery);(function(t){var e=!1;t(document).mouseup(function(){e=!1}),t.widget("ui.mouse",{version:"1.10.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.bind("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).bind("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):undefined}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(i){if(!e){this._mouseStarted&&this._mouseUp(i),this._mouseDownEvent=i;var s=this,n=1===i.which,a="string"==typeof this.options.cancel&&i.target.nodeName?t(i.target).closest(this.options.cancel).length:!1;return n&&!a&&this._mouseCapture(i)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){s.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(i)&&this._mouseDelayMet(i)&&(this._mouseStarted=this._mouseStart(i)!==!1,!this._mouseStarted)?(i.preventDefault(),!0):(!0===t.data(i.target,this.widgetName+".preventClickEvent")&&t.removeData(i.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return s._mouseMove(t)},this._mouseUpDelegate=function(t){return s._mouseUp(t)},t(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),i.preventDefault(),e=!0,!0)):!0}},_mouseMove:function(e){return t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button?this._mouseUp(e):this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){return t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),!1},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(jQuery);(function(t,e){function i(t,e,i){return[parseFloat(t[0])*(p.test(t[0])?e/100:1),parseFloat(t[1])*(p.test(t[1])?i/100:1)]}function s(e,i){return parseInt(t.css(e,i),10)||0}function n(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}t.ui=t.ui||{};var a,o=Math.max,r=Math.abs,l=Math.round,h=/left|center|right/,c=/top|center|bottom/,u=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,p=/%$/,f=t.fn.position;t.position={scrollbarWidth:function(){if(a!==e)return a;var i,s,n=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=n.children()[0];return t("body").append(n),i=o.offsetWidth,n.css("overflow","scroll"),s=o.offsetWidth,i===s&&(s=n[0].clientWidth),n.remove(),a=i-s},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,a="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:a?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s?i.width():i.outerWidth(),height:s?i.height():i.outerHeight()}}},t.fn.position=function(e){if(!e||!e.of)return f.apply(this,arguments);e=t.extend({},e);var a,p,g,m,v,_,b=t(e.of),y=t.position.getWithinInfo(e.within),k=t.position.getScrollInfo(y),w=(e.collision||"flip").split(" "),D={};return _=n(b),b[0].preventDefault&&(e.at="left top"),p=_.width,g=_.height,m=_.offset,v=t.extend({},m),t.each(["my","at"],function(){var t,i,s=(e[this]||"").split(" ");1===s.length&&(s=h.test(s[0])?s.concat(["center"]):c.test(s[0])?["center"].concat(s):["center","center"]),s[0]=h.test(s[0])?s[0]:"center",s[1]=c.test(s[1])?s[1]:"center",t=u.exec(s[0]),i=u.exec(s[1]),D[this]=[t?t[0]:0,i?i[0]:0],e[this]=[d.exec(s[0])[0],d.exec(s[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===e.at[0]?v.left+=p:"center"===e.at[0]&&(v.left+=p/2),"bottom"===e.at[1]?v.top+=g:"center"===e.at[1]&&(v.top+=g/2),a=i(D.at,p,g),v.left+=a[0],v.top+=a[1],this.each(function(){var n,h,c=t(this),u=c.outerWidth(),d=c.outerHeight(),f=s(this,"marginLeft"),_=s(this,"marginTop"),x=u+f+s(this,"marginRight")+k.width,C=d+_+s(this,"marginBottom")+k.height,M=t.extend({},v),T=i(D.my,c.outerWidth(),c.outerHeight());"right"===e.my[0]?M.left-=u:"center"===e.my[0]&&(M.left-=u/2),"bottom"===e.my[1]?M.top-=d:"center"===e.my[1]&&(M.top-=d/2),M.left+=T[0],M.top+=T[1],t.support.offsetFractions||(M.left=l(M.left),M.top=l(M.top)),n={marginLeft:f,marginTop:_},t.each(["left","top"],function(i,s){t.ui.position[w[i]]&&t.ui.position[w[i]][s](M,{targetWidth:p,targetHeight:g,elemWidth:u,elemHeight:d,collisionPosition:n,collisionWidth:x,collisionHeight:C,offset:[a[0]+T[0],a[1]+T[1]],my:e.my,at:e.at,within:y,elem:c})}),e.using&&(h=function(t){var i=m.left-M.left,s=i+p-u,n=m.top-M.top,a=n+g-d,l={target:{element:b,left:m.left,top:m.top,width:p,height:g},element:{element:c,left:M.left,top:M.top,width:u,height:d},horizontal:0>s?"left":i>0?"right":"center",vertical:0>a?"top":n>0?"bottom":"middle"};u>p&&p>r(i+s)&&(l.horizontal="center"),d>g&&g>r(n+a)&&(l.vertical="middle"),l.important=o(r(i),r(s))>o(r(n),r(a))?"horizontal":"vertical",e.using.call(this,t,l)}),c.offset(t.extend(M,{using:h}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,l=n-r,h=r+e.collisionWidth-a-n;e.collisionWidth>a?l>0&&0>=h?(i=t.left+l+e.collisionWidth-a-n,t.left+=l-i):t.left=h>0&&0>=l?n:l>h?n+a-e.collisionWidth:n:l>0?t.left+=l:h>0?t.left-=h:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,l=n-r,h=r+e.collisionHeight-a-n;e.collisionHeight>a?l>0&&0>=h?(i=t.top+l+e.collisionHeight-a-n,t.top+=l-i):t.top=h>0&&0>=l?n:l>h?n+a-e.collisionHeight:n:l>0?t.top+=l:h>0?t.top-=h:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,a=n.offset.left+n.scrollLeft,o=n.width,l=n.isWindow?n.scrollLeft:n.offset.left,h=t.left-e.collisionPosition.marginLeft,c=h-l,u=h+e.collisionWidth-o-l,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-o-a,(0>i||r(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-l,(s>0||u>r(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,a=n.offset.top+n.scrollTop,o=n.height,l=n.isWindow?n.scrollTop:n.offset.top,h=t.top-e.collisionPosition.marginTop,c=h-l,u=h+e.collisionHeight-o-l,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-o-a,t.top+p+f+g>c&&(0>s||r(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-l,t.top+p+f+g>u&&(i>0||u>r(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}},function(){var e,i,s,n,a,o=document.getElementsByTagName("body")[0],r=document.createElement("div");e=document.createElement(o?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&t.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(a in s)e.style[a]=s[a];e.appendChild(r),i=o||document.documentElement,i.insertBefore(e,i.firstChild),r.style.cssText="position: absolute; left: 10.7432222px;",n=t(r).offset().left,t.support.offsetFractions=n>10&&11>n,e.innerHTML="",i.removeChild(e)}()})(jQuery);(function(t){t.widget("ui.draggable",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"!==this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(t(i.iframeFix===!0?"iframe":i.iframeFix).each(function(){t("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>").css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(t(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_mouseDrag:function(e,i){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp({}),!1;this.position=s.position}return this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"original"!==this.options.helper||t.contains(this.element[0].ownerDocument,this.element[0])?("invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1):!1},_mouseUp:function(e){return t("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return s.parents("body").length||s.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s[0]===this.element[0]||/(fixed|absolute)/.test(s.css("position"))||s.css("position","absolute"),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.element.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;return n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):"document"===n.containment?(this.containment=[0,0,t(document).width()-this.helperProportions.width-this.margins.left,(t(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):n.containment.constructor===Array?(this.containment=n.containment,undefined):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e="hidden"!==i.css("overflow"),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i),undefined):(this.containment=null,undefined)},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent;return this.offset.scroll||(this.offset.scroll={top:n.scrollTop(),left:n.scrollLeft()}),{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top)*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)*s}},_generatePosition:function(e){var i,s,n,a,o=this.options,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=e.pageX,h=e.pageY;return this.offset.scroll||(this.offset.scroll={top:r.scrollTop(),left:r.scrollLeft()}),this.originalPosition&&(this.containment&&(this.relative_container?(s=this.relative_container.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,e.pageX-this.offset.click.left<i[0]&&(l=i[0]+this.offset.click.left),e.pageY-this.offset.click.top<i[1]&&(h=i[1]+this.offset.click.top),e.pageX-this.offset.click.left>i[2]&&(l=i[2]+this.offset.click.left),e.pageY-this.offset.click.top>i[3]&&(h=i[3]+this.offset.click.top)),o.grid&&(n=o.grid[1]?this.originalPageY+Math.round((h-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,h=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-o.grid[1]:n+o.grid[1]:n,a=o.grid[0]?this.originalPageX+Math.round((l-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,l=i?a-this.offset.click.left>=i[0]||a-this.offset.click.left>i[2]?a:a-this.offset.click.left>=i[0]?a-o.grid[0]:a+o.grid[0]:a)),{top:h-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top),left:l-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s]),"drag"===e&&(this.positionAbs=this._convertPositionTo("absolute")),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i){var s=t(this).data("ui-draggable"),n=s.options,a=t.extend({},i,{item:s.element});s.sortables=[],t(n.connectToSortable).each(function(){var i=t.data(this,"ui-sortable");i&&!i.options.disabled&&(s.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",e,a))})},stop:function(e,i){var s=t(this).data("ui-draggable"),n=t.extend({},i,{item:s.element});t.each(s.sortables,function(){this.instance.isOver?(this.instance.isOver=0,s.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(e),this.instance.options.helper=this.instance.options._helper,"original"===s.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",e,n))})},drag:function(e,i){var s=t(this).data("ui-draggable"),n=this;t.each(s.sortables,function(){var a=!1,o=this;this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(a=!0,t.each(s.sortables,function(){return this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this!==o&&this.instance._intersectsWith(this.instance.containerCache)&&t.contains(o.instance.element[0],this.instance.element[0])&&(a=!1),a})),a?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=t(n).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},e.target=this.instance.currentItem[0],this.instance._mouseCapture(e,!0),this.instance._mouseStart(e,!0,!0),this.instance.offset.click.top=s.offset.click.top,this.instance.offset.click.left=s.offset.click.left,this.instance.offset.parent.left-=s.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=s.offset.parent.top-this.instance.offset.parent.top,s._trigger("toSortable",e),s.dropped=this.instance.element,s.currentItem=s.element,this.instance.fromOutside=s),this.instance.currentItem&&this.instance._mouseDrag(e)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",e,this.instance._uiHash(this.instance)),this.instance._mouseStop(e,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),s._trigger("fromSortable",e),s.dropped=!1)})}}),t.ui.plugin.add("draggable","cursor",{start:function(){var e=t("body"),i=t(this).data("ui-draggable").options;e.css("cursor")&&(i._cursor=e.css("cursor")),e.css("cursor",i.cursor)},stop:function(){var e=t(this).data("ui-draggable").options;e._cursor&&t("body").css("cursor",e._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i){var s=t(i.helper),n=t(this).data("ui-draggable").options;s.css("opacity")&&(n._opacity=s.css("opacity")),s.css("opacity",n.opacity)},stop:function(e,i){var s=t(this).data("ui-draggable").options;s._opacity&&t(i.helper).css("opacity",s._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(){var e=t(this).data("ui-draggable");e.scrollParent[0]!==document&&"HTML"!==e.scrollParent[0].tagName&&(e.overflowOffset=e.scrollParent.offset())},drag:function(e){var i=t(this).data("ui-draggable"),s=i.options,n=!1;i.scrollParent[0]!==document&&"HTML"!==i.scrollParent[0].tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+i.scrollParent[0].offsetHeight-e.pageY<s.scrollSensitivity?i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop+s.scrollSpeed:e.pageY-i.overflowOffset.top<s.scrollSensitivity&&(i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop-s.scrollSpeed)),s.axis&&"y"===s.axis||(i.overflowOffset.left+i.scrollParent[0].offsetWidth-e.pageX<s.scrollSensitivity?i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft+s.scrollSpeed:e.pageX-i.overflowOffset.left<s.scrollSensitivity&&(i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft-s.scrollSpeed))):(s.axis&&"x"===s.axis||(e.pageY-t(document).scrollTop()<s.scrollSensitivity?n=t(document).scrollTop(t(document).scrollTop()-s.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<s.scrollSensitivity&&(n=t(document).scrollTop(t(document).scrollTop()+s.scrollSpeed))),s.axis&&"y"===s.axis||(e.pageX-t(document).scrollLeft()<s.scrollSensitivity?n=t(document).scrollLeft(t(document).scrollLeft()-s.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<s.scrollSensitivity&&(n=t(document).scrollLeft(t(document).scrollLeft()+s.scrollSpeed)))),n!==!1&&t.ui.ddmanager&&!s.dropBehaviour&&t.ui.ddmanager.prepareOffsets(i,e)}}),t.ui.plugin.add("draggable","snap",{start:function(){var e=t(this).data("ui-draggable"),i=e.options;e.snapElements=[],t(i.snap.constructor!==String?i.snap.items||":data(ui-draggable)":i.snap).each(function(){var i=t(this),s=i.offset();this!==e.element[0]&&e.snapElements.push({item:this,width:i.outerWidth(),height:i.outerHeight(),top:s.top,left:s.left})})},drag:function(e,i){var s,n,a,o,r,l,h,c,u,d,p=t(this).data("ui-draggable"),g=p.options,f=g.snapTolerance,m=i.offset.left,_=m+p.helperProportions.width,v=i.offset.top,b=v+p.helperProportions.height;for(u=p.snapElements.length-1;u>=0;u--)r=p.snapElements[u].left,l=r+p.snapElements[u].width,h=p.snapElements[u].top,c=h+p.snapElements[u].height,r-f>_||m>l+f||h-f>b||v>c+f||!t.contains(p.snapElements[u].item.ownerDocument,p.snapElements[u].item)?(p.snapElements[u].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,e,t.extend(p._uiHash(),{snapItem:p.snapElements[u].item})),p.snapElements[u].snapping=!1):("inner"!==g.snapMode&&(s=f>=Math.abs(h-b),n=f>=Math.abs(c-v),a=f>=Math.abs(r-_),o=f>=Math.abs(l-m),s&&(i.position.top=p._convertPositionTo("relative",{top:h-p.helperProportions.height,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:c,left:0}).top-p.margins.top),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r-p.helperProportions.width}).left-p.margins.left),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:l}).left-p.margins.left)),d=s||n||a||o,"outer"!==g.snapMode&&(s=f>=Math.abs(h-v),n=f>=Math.abs(c-b),a=f>=Math.abs(r-m),o=f>=Math.abs(l-_),s&&(i.position.top=p._convertPositionTo("relative",{top:h,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:c-p.helperProportions.height,left:0}).top-p.margins.top),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r}).left-p.margins.left),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:l-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[u].snapping&&(s||n||a||o||d)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,e,t.extend(p._uiHash(),{snapItem:p.snapElements[u].item})),p.snapElements[u].snapping=s||n||a||o||d)}}),t.ui.plugin.add("draggable","stack",{start:function(){var e,i=this.data("ui-draggable").options,s=t.makeArray(t(i.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});s.length&&(e=parseInt(t(s[0]).css("zIndex"),10)||0,t(s).each(function(i){t(this).css("zIndex",e+i)}),this.css("zIndex",e+s.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i){var s=t(i.helper),n=t(this).data("ui-draggable").options;s.css("zIndex")&&(n._zIndex=s.css("zIndex")),s.css("zIndex",n.zIndex)},stop:function(e,i){var s=t(this).data("ui-draggable").options;s._zIndex&&t(i.helper).css("zIndex",s._zIndex)}})})(jQuery);(function(t){function e(t,e,i){return t>e&&e+i>t}t.widget("ui.droppable",{version:"1.10.4",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var e,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(s)?s:function(t){return t.is(s)},this.proportions=function(){return arguments.length?(e=arguments[0],undefined):e?e:e={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},t.ui.ddmanager.droppables[i.scope]=t.ui.ddmanager.droppables[i.scope]||[],t.ui.ddmanager.droppables[i.scope].push(this),i.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){for(var e=0,i=t.ui.ddmanager.droppables[this.options.scope];i.length>e;e++)i[e]===this&&i.splice(e,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(e,i){"accept"===e&&(this.accept=t.isFunction(i)?i:function(t){return t.is(i)}),t.Widget.prototype._setOption.apply(this,arguments)},_activate:function(e){var i=t.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var e=t.data(this,"ui-droppable");return e.options.greedy&&!e.options.disabled&&e.options.scope===s.options.scope&&e.accept.call(e.element[0],s.currentItem||s.element)&&t.ui.intersect(s,t.extend(e,{offset:e.element.offset()}),e.options.tolerance)?(n=!0,!1):undefined}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}}}),t.ui.intersect=function(t,i,s){if(!i.offset)return!1;var n,a,o=(t.positionAbs||t.position.absolute).left,r=(t.positionAbs||t.position.absolute).top,l=o+t.helperProportions.width,h=r+t.helperProportions.height,c=i.offset.left,u=i.offset.top,d=c+i.proportions().width,p=u+i.proportions().height;switch(s){case"fit":return o>=c&&d>=l&&r>=u&&p>=h;case"intersect":return o+t.helperProportions.width/2>c&&d>l-t.helperProportions.width/2&&r+t.helperProportions.height/2>u&&p>h-t.helperProportions.height/2;case"pointer":return n=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,a=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,e(a,u,i.proportions().height)&&e(n,c,i.proportions().width);case"touch":return(r>=u&&p>=r||h>=u&&p>=h||u>r&&h>p)&&(o>=c&&d>=o||l>=c&&d>=l||c>o&&l>d);default:return!1}},t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,a=t.ui.ddmanager.droppables[e.options.scope]||[],o=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;a.length>s;s++)if(!(a[s].options.disabled||e&&!a[s].accept.call(a[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===a[s].element[0]){a[s].proportions().height=0;continue t}a[s].visible="none"!==a[s].element.css("display"),a[s].visible&&("mousedown"===o&&a[s]._activate.call(a[s],i),a[s].offset=a[s].element.offset(),a[s].proportions({width:a[s].element[0].offsetWidth,height:a[s].element[0].offsetHeight}))}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&t.ui.intersect(e,this,this.options.tolerance)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").bind("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,a,o=t.ui.intersect(e,this,this.options.tolerance),r=!o&&this.isover?"isout":o&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,a=this.element.parents(":data(ui-droppable)").filter(function(){return t.data(this,"ui-droppable").options.scope===n}),a.length&&(s=t.data(a[0],"ui-droppable"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").unbind("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}}})(jQuery);(function(t){function e(t){return parseInt(t,10)||0}function i(t){return!isNaN(parseInt(t,10))}t.widget("ui.resizable",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_create:function(){var e,i,s,n,a,o=this,r=this.options;if(this.element.addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!r.aspectRatio,aspectRatio:r.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:r.helper||r.ghost||r.animate?r.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=r.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),e=this.handles.split(","),this.handles={},i=0;e.length>i;i++)s=t.trim(e[i]),a="ui-resizable-"+s,n=t("<div class='ui-resizable-handle "+a+"'></div>"),n.css({zIndex:r.zIndex}),"se"===s&&n.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(n);this._renderAxis=function(e){var i,s,n,a;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String&&(this.handles[i]=t(this.handles[i],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(s=t(this.handles[i],this.element),a=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,a),this._proportionallyResize()),t(this.handles[i]).length},this._renderAxis(this.element),this._handles=t(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=n&&n[1]?n[1]:"se")}),r.autoHide&&(this._handles.hide(),t(this.element).addClass("ui-resizable-autohide").mouseenter(function(){r.disabled||(t(this).removeClass("ui-resizable-autohide"),o._handles.show())}).mouseleave(function(){r.disabled||o.resizing||(t(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(i){var s,n,a,o=this.options,r=this.element.position(),h=this.element;return this.resizing=!0,/absolute/.test(h.css("position"))?h.css({position:"absolute",top:h.css("top"),left:h.css("left")}):h.is(".ui-draggable")&&h.css({position:"absolute",top:r.top,left:r.left}),this._renderProxy(),s=e(this.helper.css("left")),n=e(this.helper.css("top")),o.containment&&(s+=t(o.containment).scrollLeft()||0,n+=t(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:s,top:n},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:h.width(),height:h.height()},this.originalSize=this._helper?{width:h.outerWidth(),height:h.outerHeight()}:{width:h.width(),height:h.height()},this.originalPosition={left:s,top:n},this.sizeDiff={width:h.outerWidth()-h.width(),height:h.outerHeight()-h.height()},this.originalMousePosition={left:i.pageX,top:i.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,a=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===a?this.axis+"-resize":a),h.addClass("ui-resizable-resizing"),this._propagate("start",i),!0},_mouseDrag:function(e){var i,s=this.helper,n={},a=this.originalMousePosition,o=this.axis,r=this.position.top,h=this.position.left,l=this.size.width,c=this.size.height,u=e.pageX-a.left||0,d=e.pageY-a.top||0,p=this._change[o];return p?(i=p.apply(this,[e,u,d]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),this.position.top!==r&&(n.top=this.position.top+"px"),this.position.left!==h&&(n.left=this.position.left+"px"),this.size.width!==l&&(n.width=this.size.width+"px"),this.size.height!==c&&(n.height=this.size.height+"px"),s.css(n),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(n)||this._trigger("resize",e,this.ui()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,a,o,r,h,l=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&t.ui.hasScroll(i[0],"left")?0:c.sizeDiff.height,a=s?0:c.sizeDiff.width,o={width:c.helper.width()-a,height:c.helper.height()-n},r=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null,h=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null,l.animate||this.element.css(t.extend(o,{top:h,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(t){var e,s,n,a,o,r=this.options;o={minWidth:i(r.minWidth)?r.minWidth:0,maxWidth:i(r.maxWidth)?r.maxWidth:1/0,minHeight:i(r.minHeight)?r.minHeight:0,maxHeight:i(r.maxHeight)?r.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,n=o.minWidth/this.aspectRatio,s=o.maxHeight*this.aspectRatio,a=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),n>o.minHeight&&(o.minHeight=n),o.maxWidth>s&&(o.maxWidth=s),o.maxHeight>a&&(o.maxHeight=a)),this._vBoundaries=o},_updateCache:function(t){this.offset=this.helper.offset(),i(t.left)&&(this.position.left=t.left),i(t.top)&&(this.position.top=t.top),i(t.height)&&(this.size.height=t.height),i(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,s=this.size,n=this.axis;return i(t.height)?t.width=t.height*this.aspectRatio:i(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===n&&(t.left=e.left+(s.width-t.width),t.top=null),"nw"===n&&(t.top=e.top+(s.height-t.height),t.left=e.left+(s.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,s=this.axis,n=i(t.width)&&e.maxWidth&&e.maxWidth<t.width,a=i(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=i(t.width)&&e.minWidth&&e.minWidth>t.width,r=i(t.height)&&e.minHeight&&e.minHeight>t.height,h=this.originalPosition.left+this.originalSize.width,l=this.position.top+this.size.height,c=/sw|nw|w/.test(s),u=/nw|ne|n/.test(s);return o&&(t.width=e.minWidth),r&&(t.height=e.minHeight),n&&(t.width=e.maxWidth),a&&(t.height=e.maxHeight),o&&c&&(t.left=h-e.minWidth),n&&c&&(t.left=h-e.maxWidth),r&&u&&(t.top=l-e.minHeight),a&&u&&(t.top=l-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_proportionallyResize:function(){if(this._proportionallyResizeElements.length){var t,e,i,s,n,a=this.helper||this.element;for(t=0;this._proportionallyResizeElements.length>t;t++){if(n=this._proportionallyResizeElements[t],!this.borderDif)for(this.borderDif=[],i=[n.css("borderTopWidth"),n.css("borderRightWidth"),n.css("borderBottomWidth"),n.css("borderLeftWidth")],s=[n.css("paddingTop"),n.css("paddingRight"),n.css("paddingBottom"),n.css("paddingLeft")],e=0;i.length>e;e++)this.borderDif[e]=(parseInt(i[e],10)||0)+(parseInt(s[e],10)||0);n.css({height:a.height()-this.borderDif[0]-this.borderDif[2]||0,width:a.width()-this.borderDif[1]-this.borderDif[3]||0})}}},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).data("ui-resizable"),s=i.options,n=i._proportionallyResizeElements,a=n.length&&/textarea/i.test(n[0].nodeName),o=a&&t.ui.hasScroll(n[0],"left")?0:i.sizeDiff.height,r=a?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-o},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,c=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,c&&l?{top:c,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var i,s,n,a,o,r,h,l=t(this).data("ui-resizable"),c=l.options,u=l.element,d=c.containment,p=d instanceof t?d.get(0):/parent/.test(d)?u.parent().get(0):d;p&&(l.containerElement=t(p),/document/.test(d)||d===document?(l.containerOffset={left:0,top:0},l.containerPosition={left:0,top:0},l.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(i=t(p),s=[],t(["Top","Right","Left","Bottom"]).each(function(t,n){s[t]=e(i.css("padding"+n))}),l.containerOffset=i.offset(),l.containerPosition=i.position(),l.containerSize={height:i.innerHeight()-s[3],width:i.innerWidth()-s[1]},n=l.containerOffset,a=l.containerSize.height,o=l.containerSize.width,r=t.ui.hasScroll(p,"left")?p.scrollWidth:o,h=t.ui.hasScroll(p)?p.scrollHeight:a,l.parentData={element:p,left:n.left,top:n.top,width:r,height:h}))},resize:function(e){var i,s,n,a,o=t(this).data("ui-resizable"),r=o.options,h=o.containerOffset,l=o.position,c=o._aspectRatio||e.shiftKey,u={top:0,left:0},d=o.containerElement;d[0]!==document&&/static/.test(d.css("position"))&&(u=h),l.left<(o._helper?h.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-h.left:o.position.left-u.left),c&&(o.size.height=o.size.width/o.aspectRatio),o.position.left=r.helper?h.left:0),l.top<(o._helper?h.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-h.top:o.position.top),c&&(o.size.width=o.size.height*o.aspectRatio),o.position.top=o._helper?h.top:0),o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top,i=Math.abs((o._helper?o.offset.left-u.left:o.offset.left-u.left)+o.sizeDiff.width),s=Math.abs((o._helper?o.offset.top-u.top:o.offset.top-h.top)+o.sizeDiff.height),n=o.containerElement.get(0)===o.element.parent().get(0),a=/relative|absolute/.test(o.containerElement.css("position")),n&&a&&(i-=Math.abs(o.parentData.left)),i+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-i,c&&(o.size.height=o.size.width/o.aspectRatio)),s+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-s,c&&(o.size.width=o.size.height*o.aspectRatio))},stop:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.containerOffset,n=e.containerPosition,a=e.containerElement,o=t(e.helper),r=o.offset(),h=o.outerWidth()-e.sizeDiff.width,l=o.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(a.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(a.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).data("ui-resizable"),i=e.options,s=function(e){t(e).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseInt(e.width(),10),height:parseInt(e.height(),10),left:parseInt(e.css("left"),10),top:parseInt(e.css("top"),10)})})};"object"!=typeof i.alsoResize||i.alsoResize.parentNode?s(i.alsoResize):i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):t.each(i.alsoResize,function(t){s(t)})},resize:function(e,i){var s=t(this).data("ui-resizable"),n=s.options,a=s.originalSize,o=s.originalPosition,r={height:s.size.height-a.height||0,width:s.size.width-a.width||0,top:s.position.top-o.top||0,left:s.position.left-o.left||0},h=function(e,s){t(e).each(function(){var e=t(this),n=t(this).data("ui-resizable-alsoresize"),a={},o=s&&s.length?s:e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(n[e]||0)+(r[e]||0);i&&i>=0&&(a[e]=i||null)}),e.css(a)})};"object"!=typeof n.alsoResize||n.alsoResize.nodeType?h(n.alsoResize):t.each(n.alsoResize,function(t,e){h(t,e)})},stop:function(){t(this).removeData("resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof i.ghost?i.ghost:""),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).data("ui-resizable");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).data("ui-resizable");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.size,n=e.originalSize,a=e.originalPosition,o=e.axis,r="number"==typeof i.grid?[i.grid,i.grid]:i.grid,h=r[0]||1,l=r[1]||1,c=Math.round((s.width-n.width)/h)*h,u=Math.round((s.height-n.height)/l)*l,d=n.width+c,p=n.height+u,f=i.maxWidth&&d>i.maxWidth,g=i.maxHeight&&p>i.maxHeight,m=i.minWidth&&i.minWidth>d,v=i.minHeight&&i.minHeight>p;i.grid=r,m&&(d+=h),v&&(p+=l),f&&(d-=h),g&&(p-=l),/^(se|s|e)$/.test(o)?(e.size.width=d,e.size.height=p):/^(ne)$/.test(o)?(e.size.width=d,e.size.height=p,e.position.top=a.top-u):/^(sw)$/.test(o)?(e.size.width=d,e.size.height=p,e.position.left=a.left-c):(p-l>0?(e.size.height=p,e.position.top=a.top-u):(e.size.height=l,e.position.top=a.top+n.height-l),d-h>0?(e.size.width=d,e.position.left=a.left-c):(e.size.width=h,e.position.left=a.left+n.width-h))}})})(jQuery);(function(t){t.widget("ui.selectable",t.ui.mouse,{version:"1.10.4",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e,i=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e=t(i.options.filter,i.element[0]),e.addClass("ui-selectee"),e.each(function(){var e=t(this),i=e.offset();t.data(this,"selectable-item",{element:this,$element:e,left:i.left,top:i.top,right:i.left+e.outerWidth(),bottom:i.top+e.outerHeight(),startselected:!1,selected:e.hasClass("ui-selected"),selecting:e.hasClass("ui-selecting"),unselecting:e.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=e.addClass("ui-selectee"),this._mouseInit(),this.helper=t("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),n.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):undefined}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,a=this.opos[0],o=this.opos[1],r=e.pageX,l=e.pageY;return a>r&&(i=r,r=a,a=i),o>l&&(i=l,l=o,o=i),this.helper.css({left:a,top:o,width:r-a,height:l-o}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),h=!1;i&&i.element!==s.element[0]&&("touch"===n.tolerance?h=!(i.left>r||a>i.right||i.top>l||o>i.bottom):"fit"===n.tolerance&&(h=i.left>a&&r>i.right&&i.top>o&&l>i.bottom),h?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}})})(jQuery);(function(t){function e(t,e,i){return t>e&&e+i>t}function i(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))}t.widget("ui.sortable",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var t=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===t.axis||i(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_setOption:function(e,i){"disabled"===e?(this.options[e]=i,this.widget().toggleClass("ui-sortable-disabled",!!i)):t.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):undefined}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-a.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-a.scrollSpeed)):(e.pageY-t(document).scrollTop()<a.scrollSensitivity?r=t(document).scrollTop(t(document).scrollTop()-a.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<a.scrollSensitivity&&(r=t(document).scrollTop(t(document).scrollTop()+a.scrollSpeed)),e.pageX-t(document).scrollLeft()<a.scrollSensitivity?r=t(document).scrollLeft(t(document).scrollLeft()-a.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<a.scrollSensitivity&&(r=t(document).scrollLeft(t(document).scrollLeft()+a.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var i="x"===this.options.axis||e(this.positionAbs.top+this.offset.click.top,t.top,t.height),s="y"===this.options.axis||e(this.positionAbs.left+this.offset.click.left,t.left,t.width),n=i&&s,o=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return n?this.floating?a&&"right"===a||"down"===o?2:1:o&&("down"===o?2:1):!1},_intersectsWithSides:function(t){var i=e(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),s=e(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),n=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return this.floating&&o?"right"===o&&s||"left"===o&&!s:n&&("down"===n&&i||"up"===n&&!i)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function i(){r.push(this)}var s,n,o,a,r=[],h=[],l=this._connectWith();if(l&&e)for(s=l.length-1;s>=0;s--)for(o=t(l[s]),n=o.length-1;n>=0;n--)a=t.data(o[n],this.widgetFullName),a&&a!==this&&!a.options.disabled&&h.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(h.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",a),c.push({item:h,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]).addClass(i||e.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===s?e.currentItem.children().each(function(){t("<td>&#160;</td>",e.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(n)}):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_contactContainers:function(s){var n,o,a,r,h,l,c,u,d,p,f=null,g=null;for(n=this.containers.length-1;n>=0;n--)if(!t.contains(this.currentItem[0],this.containers[n].element[0]))if(this._intersectsWith(this.containers[n].containerCache)){if(f&&t.contains(this.containers[n].element[0],f.element[0]))continue;f=this.containers[n],g=n}else this.containers[n].containerCache.over&&(this.containers[n]._trigger("out",s,this._uiHash(this)),this.containers[n].containerCache.over=0);if(f)if(1===this.containers.length)this.containers[g].containerCache.over||(this.containers[g]._trigger("over",s,this._uiHash(this)),this.containers[g].containerCache.over=1);else{for(a=1e4,r=null,p=f.floating||i(this.currentItem),h=p?"left":"top",l=p?"width":"height",c=this.positionAbs[h]+this.offset.click[h],o=this.items.length-1;o>=0;o--)t.contains(this.containers[g].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!p||e(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))&&(u=this.items[o].item.offset()[h],d=!1,Math.abs(u-c)>Math.abs(u+this.items[o][l]-c)&&(d=!0,u+=this.items[o][l]),a>Math.abs(u-c)&&(a=Math.abs(u-c),r=this.items[o],this.direction=d?"up":"down"));if(!r&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[g])return;r?this._rearrange(s,r,null,!0):this._rearrange(s,null,this.containers[g].element,!0),this._trigger("change",s,this._uiHash()),this.containers[g]._trigger("change",s,this._uiHash(this)),this.currentContainer=this.containers[g],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[g]._trigger("over",s,this._uiHash(this)),this.containers[g].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,t("document"===n.containment?document:window).width()-this.helperProportions.width-this.margins.left,(t("document"===n.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!e){for(this._trigger("beforeStop",t,this._uiHash()),s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!1}if(e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}})})(jQuery);(function(e){e.widget("ui.autocomplete",{version:"1.10.4",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var t,i,s,n=this.element[0].nodeName.toLowerCase(),a="textarea"===n,o="input"===n;this.isMultiLine=a?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[a||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return t=!0,s=!0,i=!0,undefined;t=!1,s=!1,i=!1;var a=e.ui.keyCode;switch(n.keyCode){case a.PAGE_UP:t=!0,this._move("previousPage",n);break;case a.PAGE_DOWN:t=!0,this._move("nextPage",n);break;case a.UP:t=!0,this._keyEvent("previous",n);break;case a.DOWN:t=!0,this._keyEvent("next",n);break;case a.ENTER:case a.NUMPAD_ENTER:this.menu.active&&(t=!0,n.preventDefault(),this.menu.select(n));break;case a.TAB:this.menu.active&&this.menu.select(n);break;case a.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(t)return t=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),undefined;if(!i){var n=e.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(e){return s?(s=!1,e.preventDefault(),undefined):(this._searchTimeout(e),undefined)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,undefined):(clearTimeout(this.searching),this.close(e),this._change(e),undefined)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().data("ui-menu"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(s){s.target===t.element[0]||s.target===i||e.contains(i,s.target)||t.close()})})},menufocus:function(t,i){if(this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type)))return this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)}),undefined;var s=i.item.data("ui-autocomplete-item");!1!==this._trigger("focus",t,{item:s})?t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(s.value):this.liveRegion.text(s.value)},menuselect:function(e,t){var i=t.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",e,{item:i})&&this._value(i.value),this.term=this._value(),this.close(e),this.selectedItem=i}}),this.liveRegion=e("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertBefore(this.element),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),"source"===e&&this._initSource(),"appendTo"===e&&this.menu.element.appendTo(this._appendTo()),"disabled"===e&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_initSource:function(){var t,i,s=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(i,s){s(e.ui.autocomplete.filter(t,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(t,n){s.xhr&&s.xhr.abort(),s.xhr=e.ajax({url:i,data:t,dataType:"json",success:function(e){n(e)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){return e=null!=e?e:this._value(),this.term=this._value(),e.length<this.options.minLength?this.close(t):this._trigger("search",t)!==!1?this._search(e):undefined},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var t=++this.requestIndex;return e.proxy(function(e){t===this.requestIndex&&this.__response(e),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return"string"==typeof t?{label:t,value:t}:e.extend({label:t.label||t.value,value:t.value||t.label},t)})},_suggest:function(t){var i=this.menu.element.empty();this._renderMenu(i,t),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,i){var s=this;e.each(i,function(e,i){s._renderItemData(t,i)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,i){return e("<li>").append(e("<a>").text(i.label)).appendTo(t)},_move:function(e,t){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)?(this._value(this.term),this.menu.blur(),undefined):(this.menu[e](t),undefined):(this.search(null,t),undefined)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(e,t),t.preventDefault())}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,i){var s=RegExp(e.ui.autocomplete.escapeRegex(i),"i");return e.grep(t,function(e){return s.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var t;this._superApply(arguments),this.options.disabled||this.cancelSearch||(t=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.text(t))}})})(jQuery);(function(e){var t,i="ui-button ui-widget ui-state-default ui-corner-all",n="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",s=function(){var t=e(this);setTimeout(function(){t.find(":ui-button").button("refresh")},1)},a=function(t){var i=t.name,n=t.form,s=e([]);return i&&(i=i.replace(/'/g,"\\'"),s=n?e(n).find("[name='"+i+"']"):e("[name='"+i+"']",t.ownerDocument).filter(function(){return!this.form})),s};e.widget("ui.button",{version:"1.10.4",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,s),"boolean"!=typeof this.options.disabled?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var n=this,o=this.options,r="checkbox"===this.type||"radio"===this.type,h=r?"":"ui-state-active";null===o.label&&(o.label="input"===this.type?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(i).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){o.disabled||this===t&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){o.disabled||e(this).removeClass(h)}).bind("click"+this.eventNamespace,function(e){o.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this._on({focus:function(){this.buttonElement.addClass("ui-state-focus")},blur:function(){this.buttonElement.removeClass("ui-state-focus")}}),r&&this.element.bind("change"+this.eventNamespace,function(){n.refresh()}),"checkbox"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){return o.disabled?!1:undefined}):"radio"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){if(o.disabled)return!1;e(this).addClass("ui-state-active"),n.buttonElement.attr("aria-pressed","true");var t=n.element[0];a(t).not(t).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){return o.disabled?!1:(e(this).addClass("ui-state-active"),t=this,n.document.one("mouseup",function(){t=null}),undefined)}).bind("mouseup"+this.eventNamespace,function(){return o.disabled?!1:(e(this).removeClass("ui-state-active"),undefined)}).bind("keydown"+this.eventNamespace,function(t){return o.disabled?!1:((t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active"),undefined)}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",o.disabled),this._resetButton()},_determineButtonType:function(){var e,t,i;this.type=this.element.is("[type=checkbox]")?"checkbox":this.element.is("[type=radio]")?"radio":this.element.is("input")?"input":"button","checkbox"===this.type||"radio"===this.type?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),i=this.element.is(":checked"),i&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",i)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(i+" ui-state-active "+n).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){return this._super(e,t),"disabled"===e?(this.element.prop("disabled",!!t),t&&this.buttonElement.removeClass("ui-state-focus"),undefined):(this._resetButton(),undefined)},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),"radio"===this.type?a(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):"checkbox"===this.type&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if("input"===this.type)return this.options.label&&this.element.val(this.options.label),undefined;var t=this.buttonElement.removeClass(n),i=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),s=this.options.icons,a=s.primary&&s.secondary,o=[];s.primary||s.secondary?(this.options.text&&o.push("ui-button-text-icon"+(a?"s":s.primary?"-primary":"-secondary")),s.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+s.primary+"'></span>"),s.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+s.secondary+"'></span>"),this.options.text||(o.push(a?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(i)))):o.push("ui-button-text-only"),t.addClass(o.join(" "))}}),e.widget("ui.buttonset",{version:"1.10.4",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){"disabled"===e&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t="rtl"===this.element.css("direction");this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})})(jQuery);(function(e,t){function i(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},e.extend(this._defaults,this.regional[""]),this.dpDiv=a(e("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function a(t){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.delegate(i,"mouseout",function(){e(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).removeClass("ui-datepicker-next-hover")}).delegate(i,"mouseover",function(){e.datepicker._isDisabledDatepicker(n.inline?t.parent()[0]:n.input[0])||(e(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),e(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).addClass("ui-datepicker-next-hover"))})}function s(t,i){e.extend(t,i);for(var a in i)null==i[a]&&(t[a]=i[a]);return t}e.extend(e.ui,{datepicker:{version:"1.10.4"}});var n,r="datepicker";e.extend(i.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return s(this._defaults,e||{}),this},_attachDatepicker:function(t,i){var a,s,n;a=t.nodeName.toLowerCase(),s="div"===a||"span"===a,t.id||(this.uuid+=1,t.id="dp"+this.uuid),n=this._newInst(e(t),s),n.settings=e.extend({},i||{}),"input"===a?this._connectDatepicker(t,n):s&&this._inlineDatepicker(t,n)},_newInst:function(t,i){var s=t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?a(e("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(t,i){var a=e(t);i.append=e([]),i.trigger=e([]),a.hasClass(this.markerClassName)||(this._attachments(a,i),a.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(i),e.data(t,r,i),i.settings.disabled&&this._disableDatepicker(t))},_attachments:function(t,i){var a,s,n,r=this._get(i,"appendText"),o=this._get(i,"isRTL");i.append&&i.append.remove(),r&&(i.append=e("<span class='"+this._appendClass+"'>"+r+"</span>"),t[o?"before":"after"](i.append)),t.unbind("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),a=this._get(i,"showOn"),("focus"===a||"both"===a)&&t.focus(this._showDatepicker),("button"===a||"both"===a)&&(s=this._get(i,"buttonText"),n=this._get(i,"buttonImage"),i.trigger=e(this._get(i,"buttonImageOnly")?e("<img/>").addClass(this._triggerClass).attr({src:n,alt:s,title:s}):e("<button type='button'></button>").addClass(this._triggerClass).html(n?e("<img/>").attr({src:n,alt:s,title:s}):s)),t[o?"before":"after"](i.trigger),i.trigger.click(function(){return e.datepicker._datepickerShowing&&e.datepicker._lastInput===t[0]?e.datepicker._hideDatepicker():e.datepicker._datepickerShowing&&e.datepicker._lastInput!==t[0]?(e.datepicker._hideDatepicker(),e.datepicker._showDatepicker(t[0])):e.datepicker._showDatepicker(t[0]),!1}))},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t,i,a,s,n=new Date(2009,11,20),r=this._get(e,"dateFormat");r.match(/[DM]/)&&(t=function(e){for(i=0,a=0,s=0;e.length>s;s++)e[s].length>i&&(i=e[s].length,a=s);return a},n.setMonth(t(this._get(e,r.match(/MM/)?"monthNames":"monthNamesShort"))),n.setDate(t(this._get(e,r.match(/DD/)?"dayNames":"dayNamesShort"))+20-n.getDay())),e.input.attr("size",this._formatDate(e,n).length)}},_inlineDatepicker:function(t,i){var a=e(t);a.hasClass(this.markerClassName)||(a.addClass(this.markerClassName).append(i.dpDiv),e.data(t,r,i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(t),i.dpDiv.css("display","block"))},_dialogDatepicker:function(t,i,a,n,o){var u,c,h,l,d,p=this._dialogInst;return p||(this.uuid+=1,u="dp"+this.uuid,this._dialogInput=e("<input type='text' id='"+u+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),e("body").append(this._dialogInput),p=this._dialogInst=this._newInst(this._dialogInput,!1),p.settings={},e.data(this._dialogInput[0],r,p)),s(p.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(p,i):i,this._dialogInput.val(i),this._pos=o?o.length?o:[o.pageX,o.pageY]:null,this._pos||(c=document.documentElement.clientWidth,h=document.documentElement.clientHeight,l=document.documentElement.scrollLeft||document.body.scrollLeft,d=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[c/2-100+l,h/2-150+d]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),p.settings.onSelect=a,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),e.blockUI&&e.blockUI(this.dpDiv),e.data(this._dialogInput[0],r,p),this},_destroyDatepicker:function(t){var i,a=e(t),s=e.data(t,r);a.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),e.removeData(t,r),"input"===i?(s.append.remove(),s.trigger.remove(),a.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):("div"===i||"span"===i)&&a.removeClass(this.markerClassName).empty())},_enableDatepicker:function(t){var i,a,s=e(t),n=e.data(t,r);s.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!1,n.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(a=s.children("."+this._inlineClass),a.children().removeClass("ui-state-disabled"),a.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}))},_disableDatepicker:function(t){var i,a,s=e(t),n=e.data(t,r);s.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!0,n.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(a=s.children("."+this._inlineClass),a.children().addClass("ui-state-disabled"),a.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}),this._disabledInputs[this._disabledInputs.length]=t)},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;this._disabledInputs.length>t;t++)if(this._disabledInputs[t]===e)return!0;return!1},_getInst:function(t){try{return e.data(t,r)}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(i,a,n){var r,o,u,c,h=this._getInst(i);return 2===arguments.length&&"string"==typeof a?"defaults"===a?e.extend({},e.datepicker._defaults):h?"all"===a?e.extend({},h.settings):this._get(h,a):null:(r=a||{},"string"==typeof a&&(r={},r[a]=n),h&&(this._curInst===h&&this._hideDatepicker(),o=this._getDateDatepicker(i,!0),u=this._getMinMaxDate(h,"min"),c=this._getMinMaxDate(h,"max"),s(h.settings,r),null!==u&&r.dateFormat!==t&&r.minDate===t&&(h.settings.minDate=this._formatDate(h,u)),null!==c&&r.dateFormat!==t&&r.maxDate===t&&(h.settings.maxDate=this._formatDate(h,c)),"disabled"in r&&(r.disabled?this._disableDatepicker(i):this._enableDatepicker(i)),this._attachments(e(i),h),this._autoSize(h),this._setDate(h,o),this._updateAlternate(h),this._updateDatepicker(h)),t)},_changeDatepicker:function(e,t,i){this._optionDatepicker(e,t,i)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var i=this._getInst(e);i&&(this._setDate(i,t),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(e,t){var i=this._getInst(e);return i&&!i.inline&&this._setDateFromField(i,t),i?this._getDate(i):null},_doKeyDown:function(t){var i,a,s,n=e.datepicker._getInst(t.target),r=!0,o=n.dpDiv.is(".ui-datepicker-rtl");if(n._keyEvent=!0,e.datepicker._datepickerShowing)switch(t.keyCode){case 9:e.datepicker._hideDatepicker(),r=!1;break;case 13:return s=e("td."+e.datepicker._dayOverClass+":not(."+e.datepicker._currentClass+")",n.dpDiv),s[0]&&e.datepicker._selectDay(t.target,n.selectedMonth,n.selectedYear,s[0]),i=e.datepicker._get(n,"onSelect"),i?(a=e.datepicker._formatDate(n),i.apply(n.input?n.input[0]:null,[a,n])):e.datepicker._hideDatepicker(),!1;case 27:e.datepicker._hideDatepicker();break;case 33:e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(n,"stepBigMonths"):-e.datepicker._get(n,"stepMonths"),"M");break;case 34:e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(n,"stepBigMonths"):+e.datepicker._get(n,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&e.datepicker._clearDate(t.target),r=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&e.datepicker._gotoToday(t.target),r=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,o?1:-1,"D"),r=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(n,"stepBigMonths"):-e.datepicker._get(n,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,-7,"D"),r=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,o?-1:1,"D"),r=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(n,"stepBigMonths"):+e.datepicker._get(n,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,7,"D"),r=t.ctrlKey||t.metaKey;break;default:r=!1}else 36===t.keyCode&&t.ctrlKey?e.datepicker._showDatepicker(this):r=!1;r&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(i){var a,s,n=e.datepicker._getInst(i.target);return e.datepicker._get(n,"constrainInput")?(a=e.datepicker._possibleChars(e.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==i.charCode?i.keyCode:i.charCode),i.ctrlKey||i.metaKey||" ">s||!a||a.indexOf(s)>-1):t},_doKeyUp:function(t){var i,a=e.datepicker._getInst(t.target);if(a.input.val()!==a.lastVal)try{i=e.datepicker.parseDate(e.datepicker._get(a,"dateFormat"),a.input?a.input.val():null,e.datepicker._getFormatConfig(a)),i&&(e.datepicker._setDateFromField(a),e.datepicker._updateAlternate(a),e.datepicker._updateDatepicker(a))}catch(s){}return!0},_showDatepicker:function(t){if(t=t.target||t,"input"!==t.nodeName.toLowerCase()&&(t=e("input",t.parentNode)[0]),!e.datepicker._isDisabledDatepicker(t)&&e.datepicker._lastInput!==t){var i,a,n,r,o,u,c;i=e.datepicker._getInst(t),e.datepicker._curInst&&e.datepicker._curInst!==i&&(e.datepicker._curInst.dpDiv.stop(!0,!0),i&&e.datepicker._datepickerShowing&&e.datepicker._hideDatepicker(e.datepicker._curInst.input[0])),a=e.datepicker._get(i,"beforeShow"),n=a?a.apply(t,[t,i]):{},n!==!1&&(s(i.settings,n),i.lastVal=null,e.datepicker._lastInput=t,e.datepicker._setDateFromField(i),e.datepicker._inDialog&&(t.value=""),e.datepicker._pos||(e.datepicker._pos=e.datepicker._findPos(t),e.datepicker._pos[1]+=t.offsetHeight),r=!1,e(t).parents().each(function(){return r|="fixed"===e(this).css("position"),!r}),o={left:e.datepicker._pos[0],top:e.datepicker._pos[1]},e.datepicker._pos=null,i.dpDiv.empty(),i.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),e.datepicker._updateDatepicker(i),o=e.datepicker._checkOffset(i,o,r),i.dpDiv.css({position:e.datepicker._inDialog&&e.blockUI?"static":r?"fixed":"absolute",display:"none",left:o.left+"px",top:o.top+"px"}),i.inline||(u=e.datepicker._get(i,"showAnim"),c=e.datepicker._get(i,"duration"),i.dpDiv.zIndex(e(t).zIndex()+1),e.datepicker._datepickerShowing=!0,e.effects&&e.effects.effect[u]?i.dpDiv.show(u,e.datepicker._get(i,"showOptions"),c):i.dpDiv[u||"show"](u?c:null),e.datepicker._shouldFocusInput(i)&&i.input.focus(),e.datepicker._curInst=i))}},_updateDatepicker:function(t){this.maxRows=4,n=t,t.dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t),t.dpDiv.find("."+this._dayOverClass+" a").mouseover();var i,a=this._getNumberOfMonths(t),s=a[1],r=17;t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),s>1&&t.dpDiv.addClass("ui-datepicker-multi-"+s).css("width",r*s+"em"),t.dpDiv[(1!==a[0]||1!==a[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===e.datepicker._curInst&&e.datepicker._datepickerShowing&&e.datepicker._shouldFocusInput(t)&&t.input.focus(),t.yearshtml&&(i=t.yearshtml,setTimeout(function(){i===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year:first").replaceWith(t.yearshtml),i=t.yearshtml=null},0))},_shouldFocusInput:function(e){return e.input&&e.input.is(":visible")&&!e.input.is(":disabled")&&!e.input.is(":focus")},_checkOffset:function(t,i,a){var s=t.dpDiv.outerWidth(),n=t.dpDiv.outerHeight(),r=t.input?t.input.outerWidth():0,o=t.input?t.input.outerHeight():0,u=document.documentElement.clientWidth+(a?0:e(document).scrollLeft()),c=document.documentElement.clientHeight+(a?0:e(document).scrollTop());return i.left-=this._get(t,"isRTL")?s-r:0,i.left-=a&&i.left===t.input.offset().left?e(document).scrollLeft():0,i.top-=a&&i.top===t.input.offset().top+o?e(document).scrollTop():0,i.left-=Math.min(i.left,i.left+s>u&&u>s?Math.abs(i.left+s-u):0),i.top-=Math.min(i.top,i.top+n>c&&c>n?Math.abs(n+o):0),i},_findPos:function(t){for(var i,a=this._getInst(t),s=this._get(a,"isRTL");t&&("hidden"===t.type||1!==t.nodeType||e.expr.filters.hidden(t));)t=t[s?"previousSibling":"nextSibling"];return i=e(t).offset(),[i.left,i.top]},_hideDatepicker:function(t){var i,a,s,n,o=this._curInst;!o||t&&o!==e.data(t,r)||this._datepickerShowing&&(i=this._get(o,"showAnim"),a=this._get(o,"duration"),s=function(){e.datepicker._tidyDialog(o)},e.effects&&(e.effects.effect[i]||e.effects[i])?o.dpDiv.hide(i,e.datepicker._get(o,"showOptions"),a,s):o.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?a:null,s),i||s(),this._datepickerShowing=!1,n=this._get(o,"onClose"),n&&n.apply(o.input?o.input[0]:null,[o.input?o.input.val():"",o]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),e.blockUI&&(e.unblockUI(),e("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(t){if(e.datepicker._curInst){var i=e(t.target),a=e.datepicker._getInst(i[0]);(i[0].id!==e.datepicker._mainDivId&&0===i.parents("#"+e.datepicker._mainDivId).length&&!i.hasClass(e.datepicker.markerClassName)&&!i.closest("."+e.datepicker._triggerClass).length&&e.datepicker._datepickerShowing&&(!e.datepicker._inDialog||!e.blockUI)||i.hasClass(e.datepicker.markerClassName)&&e.datepicker._curInst!==a)&&e.datepicker._hideDatepicker()}},_adjustDate:function(t,i,a){var s=e(t),n=this._getInst(s[0]);this._isDisabledDatepicker(s[0])||(this._adjustInstDate(n,i+("M"===a?this._get(n,"showCurrentAtPos"):0),a),this._updateDatepicker(n))},_gotoToday:function(t){var i,a=e(t),s=this._getInst(a[0]);this._get(s,"gotoCurrent")&&s.currentDay?(s.selectedDay=s.currentDay,s.drawMonth=s.selectedMonth=s.currentMonth,s.drawYear=s.selectedYear=s.currentYear):(i=new Date,s.selectedDay=i.getDate(),s.drawMonth=s.selectedMonth=i.getMonth(),s.drawYear=s.selectedYear=i.getFullYear()),this._notifyChange(s),this._adjustDate(a)},_selectMonthYear:function(t,i,a){var s=e(t),n=this._getInst(s[0]);n["selected"+("M"===a?"Month":"Year")]=n["draw"+("M"===a?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(n),this._adjustDate(s)},_selectDay:function(t,i,a,s){var n,r=e(t);e(s).hasClass(this._unselectableClass)||this._isDisabledDatepicker(r[0])||(n=this._getInst(r[0]),n.selectedDay=n.currentDay=e("a",s).html(),n.selectedMonth=n.currentMonth=i,n.selectedYear=n.currentYear=a,this._selectDate(t,this._formatDate(n,n.currentDay,n.currentMonth,n.currentYear)))},_clearDate:function(t){var i=e(t);this._selectDate(i,"")},_selectDate:function(t,i){var a,s=e(t),n=this._getInst(s[0]);i=null!=i?i:this._formatDate(n),n.input&&n.input.val(i),this._updateAlternate(n),a=this._get(n,"onSelect"),a?a.apply(n.input?n.input[0]:null,[i,n]):n.input&&n.input.trigger("change"),n.inline?this._updateDatepicker(n):(this._hideDatepicker(),this._lastInput=n.input[0],"object"!=typeof n.input[0]&&n.input.focus(),this._lastInput=null)},_updateAlternate:function(t){var i,a,s,n=this._get(t,"altField");n&&(i=this._get(t,"altFormat")||this._get(t,"dateFormat"),a=this._getDate(t),s=this.formatDate(i,a,this._getFormatConfig(t)),e(n).each(function(){e(this).val(s)}))},noWeekends:function(e){var t=e.getDay();return[t>0&&6>t,""]},iso8601Week:function(e){var t,i=new Date(e.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),t=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((t-i)/864e5)/7)+1},parseDate:function(i,a,s){if(null==i||null==a)throw"Invalid arguments";if(a="object"==typeof a?""+a:a+"",""===a)return null;var n,r,o,u,c=0,h=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,l="string"!=typeof h?h:(new Date).getFullYear()%100+parseInt(h,10),d=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,p=(s?s.dayNames:null)||this._defaults.dayNames,g=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,m=(s?s.monthNames:null)||this._defaults.monthNames,f=-1,_=-1,v=-1,k=-1,y=!1,b=function(e){var t=i.length>n+1&&i.charAt(n+1)===e;return t&&n++,t},D=function(e){var t=b(e),i="@"===e?14:"!"===e?20:"y"===e&&t?4:"o"===e?3:2,s=RegExp("^\\d{1,"+i+"}"),n=a.substring(c).match(s);if(!n)throw"Missing number at position "+c;return c+=n[0].length,parseInt(n[0],10)},w=function(i,s,n){var r=-1,o=e.map(b(i)?n:s,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)});if(e.each(o,function(e,i){var s=i[1];return a.substr(c,s.length).toLowerCase()===s.toLowerCase()?(r=i[0],c+=s.length,!1):t}),-1!==r)return r+1;throw"Unknown name at position "+c},M=function(){if(a.charAt(c)!==i.charAt(n))throw"Unexpected literal at position "+c;c++};for(n=0;i.length>n;n++)if(y)"'"!==i.charAt(n)||b("'")?M():y=!1;else switch(i.charAt(n)){case"d":v=D("d");break;case"D":w("D",d,p);break;case"o":k=D("o");break;case"m":_=D("m");break;case"M":_=w("M",g,m);break;case"y":f=D("y");break;case"@":u=new Date(D("@")),f=u.getFullYear(),_=u.getMonth()+1,v=u.getDate();break;case"!":u=new Date((D("!")-this._ticksTo1970)/1e4),f=u.getFullYear(),_=u.getMonth()+1,v=u.getDate();break;case"'":b("'")?M():y=!0;break;default:M()}if(a.length>c&&(o=a.substr(c),!/^\s+/.test(o)))throw"Extra/unparsed characters found in date: "+o;if(-1===f?f=(new Date).getFullYear():100>f&&(f+=(new Date).getFullYear()-(new Date).getFullYear()%100+(l>=f?0:-100)),k>-1)for(_=1,v=k;;){if(r=this._getDaysInMonth(f,_-1),r>=v)break;_++,v-=r}if(u=this._daylightSavingAdjust(new Date(f,_-1,v)),u.getFullYear()!==f||u.getMonth()+1!==_||u.getDate()!==v)throw"Invalid date";return u},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(e,t,i){if(!t)return"";var a,s=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,n=(i?i.dayNames:null)||this._defaults.dayNames,r=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,o=(i?i.monthNames:null)||this._defaults.monthNames,u=function(t){var i=e.length>a+1&&e.charAt(a+1)===t;return i&&a++,i},c=function(e,t,i){var a=""+t;if(u(e))for(;i>a.length;)a="0"+a;return a},h=function(e,t,i,a){return u(e)?a[t]:i[t]},l="",d=!1;if(t)for(a=0;e.length>a;a++)if(d)"'"!==e.charAt(a)||u("'")?l+=e.charAt(a):d=!1;else switch(e.charAt(a)){case"d":l+=c("d",t.getDate(),2);break;case"D":l+=h("D",t.getDay(),s,n);break;case"o":l+=c("o",Math.round((new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()-new Date(t.getFullYear(),0,0).getTime())/864e5),3);break;case"m":l+=c("m",t.getMonth()+1,2);break;case"M":l+=h("M",t.getMonth(),r,o);break;case"y":l+=u("y")?t.getFullYear():(10>t.getYear()%100?"0":"")+t.getYear()%100;break;case"@":l+=t.getTime();break;case"!":l+=1e4*t.getTime()+this._ticksTo1970;break;case"'":u("'")?l+="'":d=!0;break;default:l+=e.charAt(a)}return l},_possibleChars:function(e){var t,i="",a=!1,s=function(i){var a=e.length>t+1&&e.charAt(t+1)===i;return a&&t++,a};for(t=0;e.length>t;t++)if(a)"'"!==e.charAt(t)||s("'")?i+=e.charAt(t):a=!1;else switch(e.charAt(t)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":s("'")?i+="'":a=!0;break;default:i+=e.charAt(t)}return i},_get:function(e,i){return e.settings[i]!==t?e.settings[i]:this._defaults[i]},_setDateFromField:function(e,t){if(e.input.val()!==e.lastVal){var i=this._get(e,"dateFormat"),a=e.lastVal=e.input?e.input.val():null,s=this._getDefaultDate(e),n=s,r=this._getFormatConfig(e);try{n=this.parseDate(i,a,r)||s}catch(o){a=t?"":a}e.selectedDay=n.getDate(),e.drawMonth=e.selectedMonth=n.getMonth(),e.drawYear=e.selectedYear=n.getFullYear(),e.currentDay=a?n.getDate():0,e.currentMonth=a?n.getMonth():0,e.currentYear=a?n.getFullYear():0,this._adjustInstDate(e)}},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(t,i,a){var s=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},n=function(i){try{return e.datepicker.parseDate(e.datepicker._get(t,"dateFormat"),i,e.datepicker._getFormatConfig(t))}catch(a){}for(var s=(i.toLowerCase().match(/^c/)?e.datepicker._getDate(t):null)||new Date,n=s.getFullYear(),r=s.getMonth(),o=s.getDate(),u=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,c=u.exec(i);c;){switch(c[2]||"d"){case"d":case"D":o+=parseInt(c[1],10);break;case"w":case"W":o+=7*parseInt(c[1],10);break;case"m":case"M":r+=parseInt(c[1],10),o=Math.min(o,e.datepicker._getDaysInMonth(n,r));break;case"y":case"Y":n+=parseInt(c[1],10),o=Math.min(o,e.datepicker._getDaysInMonth(n,r))}c=u.exec(i)}return new Date(n,r,o)},r=null==i||""===i?a:"string"==typeof i?n(i):"number"==typeof i?isNaN(i)?a:s(i):new Date(i.getTime());return r=r&&"Invalid Date"==""+r?a:r,r&&(r.setHours(0),r.setMinutes(0),r.setSeconds(0),r.setMilliseconds(0)),this._daylightSavingAdjust(r)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,i){var a=!t,s=e.selectedMonth,n=e.selectedYear,r=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=r.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=r.getMonth(),e.drawYear=e.selectedYear=e.currentYear=r.getFullYear(),s===e.selectedMonth&&n===e.selectedYear||i||this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(a?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&""===e.input.val()?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(t){var i=this._get(t,"stepMonths"),a="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){e.datepicker._adjustDate(a,-i,"M")},next:function(){e.datepicker._adjustDate(a,+i,"M")},hide:function(){e.datepicker._hideDatepicker()},today:function(){e.datepicker._gotoToday(a)},selectDay:function(){return e.datepicker._selectDay(a,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return e.datepicker._selectMonthYear(a,this,"M"),!1},selectYear:function(){return e.datepicker._selectMonthYear(a,this,"Y"),!1}};e(this).bind(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t,i,a,s,n,r,o,u,c,h,l,d,p,g,m,f,_,v,k,y,b,D,w,M,C,x,I,N,T,A,E,S,Y,F,P,O,j,K,R,H=new Date,W=this._daylightSavingAdjust(new Date(H.getFullYear(),H.getMonth(),H.getDate())),L=this._get(e,"isRTL"),U=this._get(e,"showButtonPanel"),B=this._get(e,"hideIfNoPrevNext"),z=this._get(e,"navigationAsDateFormat"),q=this._getNumberOfMonths(e),G=this._get(e,"showCurrentAtPos"),J=this._get(e,"stepMonths"),Q=1!==q[0]||1!==q[1],V=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),$=this._getMinMaxDate(e,"min"),X=this._getMinMaxDate(e,"max"),Z=e.drawMonth-G,et=e.drawYear;if(0>Z&&(Z+=12,et--),X)for(t=this._daylightSavingAdjust(new Date(X.getFullYear(),X.getMonth()-q[0]*q[1]+1,X.getDate())),t=$&&$>t?$:t;this._daylightSavingAdjust(new Date(et,Z,1))>t;)Z--,0>Z&&(Z=11,et--);for(e.drawMonth=Z,e.drawYear=et,i=this._get(e,"prevText"),i=z?this.formatDate(i,this._daylightSavingAdjust(new Date(et,Z-J,1)),this._getFormatConfig(e)):i,a=this._canAdjustMonth(e,-1,et,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(L?"e":"w")+"'>"+i+"</span></a>":B?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(L?"e":"w")+"'>"+i+"</span></a>",s=this._get(e,"nextText"),s=z?this.formatDate(s,this._daylightSavingAdjust(new Date(et,Z+J,1)),this._getFormatConfig(e)):s,n=this._canAdjustMonth(e,1,et,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+s+"'><span class='ui-icon ui-icon-circle-triangle-"+(L?"w":"e")+"'>"+s+"</span></a>":B?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+s+"'><span class='ui-icon ui-icon-circle-triangle-"+(L?"w":"e")+"'>"+s+"</span></a>",r=this._get(e,"currentText"),o=this._get(e,"gotoCurrent")&&e.currentDay?V:W,r=z?this.formatDate(r,o,this._getFormatConfig(e)):r,u=e.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(e,"closeText")+"</button>",c=U?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(L?u:"")+(this._isInRange(e,o)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+r+"</button>":"")+(L?"":u)+"</div>":"",h=parseInt(this._get(e,"firstDay"),10),h=isNaN(h)?0:h,l=this._get(e,"showWeek"),d=this._get(e,"dayNames"),p=this._get(e,"dayNamesMin"),g=this._get(e,"monthNames"),m=this._get(e,"monthNamesShort"),f=this._get(e,"beforeShowDay"),_=this._get(e,"showOtherMonths"),v=this._get(e,"selectOtherMonths"),k=this._getDefaultDate(e),y="",D=0;q[0]>D;D++){for(w="",this.maxRows=4,M=0;q[1]>M;M++){if(C=this._daylightSavingAdjust(new Date(et,Z,e.selectedDay)),x=" ui-corner-all",I="",Q){if(I+="<div class='ui-datepicker-group",q[1]>1)switch(M){case 0:I+=" ui-datepicker-group-first",x=" ui-corner-"+(L?"right":"left");break;case q[1]-1:I+=" ui-datepicker-group-last",x=" ui-corner-"+(L?"left":"right");break;default:I+=" ui-datepicker-group-middle",x=""}I+="'>"}for(I+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+x+"'>"+(/all|left/.test(x)&&0===D?L?n:a:"")+(/all|right/.test(x)&&0===D?L?a:n:"")+this._generateMonthYearHeader(e,Z,et,$,X,D>0||M>0,g,m)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",N=l?"<th class='ui-datepicker-week-col'>"+this._get(e,"weekHeader")+"</th>":"",b=0;7>b;b++)T=(b+h)%7,N+="<th"+((b+h+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[T]+"'>"+p[T]+"</span></th>";for(I+=N+"</tr></thead><tbody>",A=this._getDaysInMonth(et,Z),et===e.selectedYear&&Z===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,A)),E=(this._getFirstDayOfMonth(et,Z)-h+7)%7,S=Math.ceil((E+A)/7),Y=Q?this.maxRows>S?this.maxRows:S:S,this.maxRows=Y,F=this._daylightSavingAdjust(new Date(et,Z,1-E)),P=0;Y>P;P++){for(I+="<tr>",O=l?"<td class='ui-datepicker-week-col'>"+this._get(e,"calculateWeek")(F)+"</td>":"",b=0;7>b;b++)j=f?f.apply(e.input?e.input[0]:null,[F]):[!0,""],K=F.getMonth()!==Z,R=K&&!v||!j[0]||$&&$>F||X&&F>X,O+="<td class='"+((b+h+6)%7>=5?" ui-datepicker-week-end":"")+(K?" ui-datepicker-other-month":"")+(F.getTime()===C.getTime()&&Z===e.selectedMonth&&e._keyEvent||k.getTime()===F.getTime()&&k.getTime()===C.getTime()?" "+this._dayOverClass:"")+(R?" "+this._unselectableClass+" ui-state-disabled":"")+(K&&!_?"":" "+j[1]+(F.getTime()===V.getTime()?" "+this._currentClass:"")+(F.getTime()===W.getTime()?" ui-datepicker-today":""))+"'"+(K&&!_||!j[2]?"":" title='"+j[2].replace(/'/g,"&#39;")+"'")+(R?"":" data-handler='selectDay' data-event='click' data-month='"+F.getMonth()+"' data-year='"+F.getFullYear()+"'")+">"+(K&&!_?"&#xa0;":R?"<span class='ui-state-default'>"+F.getDate()+"</span>":"<a class='ui-state-default"+(F.getTime()===W.getTime()?" ui-state-highlight":"")+(F.getTime()===V.getTime()?" ui-state-active":"")+(K?" ui-priority-secondary":"")+"' href='#'>"+F.getDate()+"</a>")+"</td>",F.setDate(F.getDate()+1),F=this._daylightSavingAdjust(F);I+=O+"</tr>"}Z++,Z>11&&(Z=0,et++),I+="</tbody></table>"+(Q?"</div>"+(q[0]>0&&M===q[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),w+=I}y+=w}return y+=c,e._keyEvent=!1,y},_generateMonthYearHeader:function(e,t,i,a,s,n,r,o){var u,c,h,l,d,p,g,m,f=this._get(e,"changeMonth"),_=this._get(e,"changeYear"),v=this._get(e,"showMonthAfterYear"),k="<div class='ui-datepicker-title'>",y="";if(n||!f)y+="<span class='ui-datepicker-month'>"+r[t]+"</span>";else{for(u=a&&a.getFullYear()===i,c=s&&s.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",h=0;12>h;h++)(!u||h>=a.getMonth())&&(!c||s.getMonth()>=h)&&(y+="<option value='"+h+"'"+(h===t?" selected='selected'":"")+">"+o[h]+"</option>");y+="</select>"}if(v||(k+=y+(!n&&f&&_?"":"&#xa0;")),!e.yearshtml)if(e.yearshtml="",n||!_)k+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(l=this._get(e,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(e){var t=e.match(/c[+\-].*/)?i+parseInt(e.substring(1),10):e.match(/[+\-].*/)?d+parseInt(e,10):parseInt(e,10);
return isNaN(t)?d:t},g=p(l[0]),m=Math.max(g,p(l[1]||"")),g=a?Math.max(g,a.getFullYear()):g,m=s?Math.min(m,s.getFullYear()):m,e.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";m>=g;g++)e.yearshtml+="<option value='"+g+"'"+(g===i?" selected='selected'":"")+">"+g+"</option>";e.yearshtml+="</select>",k+=e.yearshtml,e.yearshtml=null}return k+=this._get(e,"yearSuffix"),v&&(k+=(!n&&f&&_?"":"&#xa0;")+y),k+="</div>"},_adjustInstDate:function(e,t,i){var a=e.drawYear+("Y"===i?t:0),s=e.drawMonth+("M"===i?t:0),n=Math.min(e.selectedDay,this._getDaysInMonth(a,s))+("D"===i?t:0),r=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(a,s,n)));e.selectedDay=r.getDate(),e.drawMonth=e.selectedMonth=r.getMonth(),e.drawYear=e.selectedYear=r.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(e)},_restrictMinMax:function(e,t){var i=this._getMinMaxDate(e,"min"),a=this._getMinMaxDate(e,"max"),s=i&&i>t?i:t;return a&&s>a?a:s},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return null==t?[1,1]:"number"==typeof t?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return new Date(e,t,1).getDay()},_canAdjustMonth:function(e,t,i,a){var s=this._getNumberOfMonths(e),n=this._daylightSavingAdjust(new Date(i,a+(0>t?t:s[0]*s[1]),1));return 0>t&&n.setDate(this._getDaysInMonth(n.getFullYear(),n.getMonth())),this._isInRange(e,n)},_isInRange:function(e,t){var i,a,s=this._getMinMaxDate(e,"min"),n=this._getMinMaxDate(e,"max"),r=null,o=null,u=this._get(e,"yearRange");return u&&(i=u.split(":"),a=(new Date).getFullYear(),r=parseInt(i[0],10),o=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(r+=a),i[1].match(/[+\-].*/)&&(o+=a)),(!s||t.getTime()>=s.getTime())&&(!n||t.getTime()<=n.getTime())&&(!r||t.getFullYear()>=r)&&(!o||o>=t.getFullYear())},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t="string"!=typeof t?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,i,a){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var s=t?"object"==typeof t?t:this._daylightSavingAdjust(new Date(a,i,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),s,this._getFormatConfig(e))}}),e.fn.datepicker=function(t){if(!this.length)return this;e.datepicker.initialized||(e(document).mousedown(e.datepicker._checkExternalClick),e.datepicker.initialized=!0),0===e("#"+e.datepicker._mainDivId).length&&e("body").append(e.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof t||"isDisabled"!==t&&"getDate"!==t&&"widget"!==t?"option"===t&&2===arguments.length&&"string"==typeof arguments[1]?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof t?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this].concat(i)):e.datepicker._attachDatepicker(this,t)}):e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i))},e.datepicker=new i,e.datepicker.initialized=!1,e.datepicker.uuid=(new Date).getTime(),e.datepicker.version="1.10.4"})(jQuery);(function(e){var t={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},i={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};e.widget("ui.dialog",{version:"1.10.4",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var i=e(this).css(t).offset().top;0>i&&e(this).css("top",t.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&e.fn.draggable&&this._makeDraggable(),this.options.resizable&&e.fn.resizable&&this._makeResizable(),this._isOpen=!1},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?e(t):this.document.find(t||"body").eq(0)},_destroy:function(){var e,t=this.originalPosition;this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},disable:e.noop,enable:e.noop,close:function(t){var i,a=this;if(this._isOpen&&this._trigger("beforeClose",t)!==!1){if(this._isOpen=!1,this._destroyOverlay(),!this.opener.filter(":focusable").focus().length)try{i=this.document[0].activeElement,i&&"body"!==i.nodeName.toLowerCase()&&e(i).blur()}catch(s){}this._hide(this.uiDialog,this.options.hide,function(){a._trigger("close",t)})}},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,t){var i=!!this.uiDialog.nextAll(":visible").insertBefore(this.uiDialog).length;return i&&!t&&this._trigger("focus",e),i},open:function(){var t=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),undefined):(this._isOpen=!0,this.opener=e(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this._show(this.uiDialog,this.options.show,function(){t._focusTabbable(),t._trigger("focus")}),this._trigger("open"),undefined)},_focusTabbable:function(){var e=this.element.find("[autofocus]");e.length||(e=this.element.find(":tabbable")),e.length||(e=this.uiDialogButtonPane.find(":tabbable")),e.length||(e=this.uiDialogTitlebarClose.filter(":tabbable")),e.length||(e=this.uiDialog),e.eq(0).focus()},_keepFocus:function(t){function i(){var t=this.document[0].activeElement,i=this.uiDialog[0]===t||e.contains(this.uiDialog[0],t);i||this._focusTabbable()}t.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=e("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===e.ui.keyCode.ESCAPE)return t.preventDefault(),this.close(t),undefined;if(t.keyCode===e.ui.keyCode.TAB){var i=this.uiDialog.find(":tabbable"),a=i.filter(":first"),s=i.filter(":last");t.target!==s[0]&&t.target!==this.uiDialog[0]||t.shiftKey?t.target!==a[0]&&t.target!==this.uiDialog[0]||!t.shiftKey||(s.focus(1),t.preventDefault()):(a.focus(1),t.preventDefault())}},mousedown:function(e){this._moveToTop(e)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=e("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(t){e(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=e("<button type='button'></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(e){e.preventDefault(),this.close(e)}}),t=e("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(t),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(e){this.options.title||e.html("&#160;"),e.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=e("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=e("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var t=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),e.isEmptyObject(i)||e.isArray(i)&&!i.length?(this.uiDialog.removeClass("ui-dialog-buttons"),undefined):(e.each(i,function(i,a){var s,n;a=e.isFunction(a)?{click:a,text:i}:a,a=e.extend({type:"button"},a),s=a.click,a.click=function(){s.apply(t.element[0],arguments)},n={icons:a.icons,text:a.showText},delete a.icons,delete a.showText,e("<button></button>",a).button(n).appendTo(t.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),undefined)},_makeDraggable:function(){function t(e){return{position:e.position,offset:e.offset}}var i=this,a=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(a,s){e(this).addClass("ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",a,t(s))},drag:function(e,a){i._trigger("drag",e,t(a))},stop:function(s,n){a.position=[n.position.left-i.document.scrollLeft(),n.position.top-i.document.scrollTop()],e(this).removeClass("ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",s,t(n))}})},_makeResizable:function(){function t(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}var i=this,a=this.options,s=a.resizable,n=this.uiDialog.css("position"),r="string"==typeof s?s:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:a.maxWidth,maxHeight:a.maxHeight,minWidth:a.minWidth,minHeight:this._minHeight(),handles:r,start:function(a,s){e(this).addClass("ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",a,t(s))},resize:function(e,a){i._trigger("resize",e,t(a))},stop:function(s,n){a.height=e(this).height(),a.width=e(this).width(),e(this).removeClass("ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",s,t(n))}}).css("position",n)},_minHeight:function(){var e=this.options;return"auto"===e.height?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(){var e=this.uiDialog.is(":visible");e||this.uiDialog.show(),this.uiDialog.position(this.options.position),e||this.uiDialog.hide()},_setOptions:function(a){var s=this,n=!1,r={};e.each(a,function(e,a){s._setOption(e,a),e in t&&(n=!0),e in i&&(r[e]=a)}),n&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",r)},_setOption:function(e,t){var i,a,s=this.uiDialog;"dialogClass"===e&&s.removeClass(this.options.dialogClass).addClass(t),"disabled"!==e&&(this._super(e,t),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:""+t}),"draggable"===e&&(i=s.is(":data(ui-draggable)"),i&&!t&&s.draggable("destroy"),!i&&t&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(a=s.is(":data(ui-resizable)"),a&&!t&&s.resizable("destroy"),a&&"string"==typeof t&&s.resizable("option","handles",t),a||t===!1||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var e,t,i,a=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),a.minWidth>a.width&&(a.width=a.minWidth),e=this.uiDialog.css({height:"auto",width:a.width}).outerHeight(),t=Math.max(0,a.minHeight-e),i="number"==typeof a.maxHeight?Math.max(0,a.maxHeight-e):"none","auto"===a.height?this.element.css({minHeight:t,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,a.height-e)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var t=e(this);return e("<div>").css({position:"absolute",width:t.outerWidth(),height:t.outerHeight()}).appendTo(t.parent()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(t){return e(t.target).closest(".ui-dialog").length?!0:!!e(t.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var t=this,i=this.widgetFullName;e.ui.dialog.overlayInstances||this._delay(function(){e.ui.dialog.overlayInstances&&this.document.bind("focusin.dialog",function(a){t._allowInteraction(a)||(a.preventDefault(),e(".ui-dialog:visible:last .ui-dialog-content").data(i)._focusTabbable())})}),this.overlay=e("<div>").addClass("ui-widget-overlay ui-front").appendTo(this._appendTo()),this._on(this.overlay,{mousedown:"_keepFocus"}),e.ui.dialog.overlayInstances++}},_destroyOverlay:function(){this.options.modal&&this.overlay&&(e.ui.dialog.overlayInstances--,e.ui.dialog.overlayInstances||this.document.unbind("focusin.dialog"),this.overlay.remove(),this.overlay=null)}}),e.ui.dialog.overlayInstances=0,e.uiBackCompat!==!1&&e.widget("ui.dialog",e.ui.dialog,{_position:function(){var t,i=this.options.position,a=[],s=[0,0];i?(("string"==typeof i||"object"==typeof i&&"0"in i)&&(a=i.split?i.split(" "):[i[0],i[1]],1===a.length&&(a[1]=a[0]),e.each(["left","top"],function(e,t){+a[e]===a[e]&&(s[e]=a[e],a[e]=t)}),i={my:a[0]+(0>s[0]?s[0]:"+"+s[0])+" "+a[1]+(0>s[1]?s[1]:"+"+s[1]),at:a.join(" ")}),i=e.extend({},e.ui.dialog.prototype.options.position,i)):i=e.ui.dialog.prototype.options.position,t=this.uiDialog.is(":visible"),t||this.uiDialog.show(),this.uiDialog.position(i),t||this.uiDialog.hide()}})})(jQuery);(function(t){t.widget("ui.menu",{version:"1.10.4",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,t.proxy(function(t){this.options.disabled&&t.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(t){t.preventDefault()},"click .ui-state-disabled > a":function(t){t.preventDefault()},"click .ui-menu-item:has(a)":function(e){var i=t(e.target).closest(".ui-menu-item");!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&t(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){var i=t(e.currentTarget);i.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(e,i)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.children(".ui-menu-item").eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){t.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){t(e.target).closest(".ui-menu").length||this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var e=t(this);e.data("ui-menu-submenu-carat")&&e.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(e){function i(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var s,n,a,o,r,l=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:l=!1,n=this.previousFilter||"",a=String.fromCharCode(e.keyCode),o=!1,clearTimeout(this.filterTimer),a===n?o=!0:a=n+a,r=RegExp("^"+i(a),"i"),s=this.activeMenu.children(".ui-menu-item").filter(function(){return r.test(t(this).children("a").text())}),s=o&&-1!==s.index(this.active.next())?this.active.nextAll(".ui-menu-item"):s,s.length||(a=String.fromCharCode(e.keyCode),r=RegExp("^"+i(a),"i"),s=this.activeMenu.children(".ui-menu-item").filter(function(){return r.test(t(this).children("a").text())})),s.length?(this.focus(e,s),s.length>1?(this.previousFilter=a,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}l&&e.preventDefault()},_activate:function(t){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i=this.options.icons.submenu,s=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),s.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),s=e.prev("a"),n=t("<span>").addClass("ui-menu-icon ui-icon "+i).data("ui-menu-submenu-carat",!0);s.attr("aria-haspopup","true").prepend(n),e.attr("aria-labelledby",s.attr("id"))}),e=s.add(this.element),e.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),e.children(":not(.ui-menu-item)").each(function(){var e=t(this);/[^\-\u2014\u2013\s]/.test(e.text())||e.addClass("ui-widget-content ui-menu-divider")}),e.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){"icons"===t&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(e.submenu),this._super(t,e)},focus:function(t,e){var i,s;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=e.height(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",t,{item:this.active}))},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.children(".ui-menu-item")[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())),undefined):(this.next(e),undefined)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.children(".ui-menu-item").first())),undefined):(this.next(e),undefined)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)}})})(jQuery);(function(t,e){t.widget("ui.progressbar",{version:"1.10.4",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=t("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove()},value:function(t){return t===e?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),e)},_constrainedValue:function(t){return t===e&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).toggleClass("ui-corner-right",e===this.options.max).width(i.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}})})(jQuery);(function(t){var e=5;t.widget("ui.slider",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this._refresh(),this._setOption("disabled",this.options.disabled),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),a="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",o=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)o.push(a);this.handles=n.add(t(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e)})},_createRange:function(){var e=this.options,i="";e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?this.range.removeClass("ui-slider-range-min ui-slider-range-max").css({left:"",bottom:""}):(this.range=t("<div></div>").appendTo(this.element),i="ui-slider-range ui-widget-header ui-corner-all"),this.range.addClass(i+("min"===e.range||"max"===e.range?" ui-slider-range-"+e.range:""))):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){var t=this.handles.add(this.range).filter("a");this._off(t),this._on(t,this._handleEvents),this._hoverable(t),this._focusable(t)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,a,o,r,l,h,u=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-u.values(e));(n>i||n===i&&(e===u._lastChangedValue||u.values(e)===c.min))&&(n=i,a=t(this),o=e)}),r=this._start(e,o),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,a.addClass("ui-state-active").focus(),l=a.offset(),h=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=h?{left:0,top:0}:{left:e.pageX-l.left-a.width()/2,top:e.pageY-l.top-a.height()/2-(parseInt(a.css("borderTopWidth"),10)||0)-(parseInt(a.css("borderBottomWidth"),10)||0)+(parseInt(a.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,o,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,a;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),a=this._valueMin()+s*n,this._trimAlignValue(a)},_start:function(t,e){var i={handle:this.handles[e],value:this.value()};return this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._trigger("start",t,i)},_slide:function(t,e,i){var s,n,a;this.options.values&&this.options.values.length?(s=this.values(e?0:1),2===this.options.values.length&&this.options.range===!0&&(0===e&&i>s||1===e&&s>i)&&(i=s),i!==this.values(e)&&(n=this.values(),n[e]=i,a=this._trigger("slide",t,{handle:this.handles[e],value:i,values:n}),s=this.values(e?0:1),a!==!1&&this.values(e,i))):i!==this.value()&&(a=this._trigger("slide",t,{handle:this.handles[e],value:i}),a!==!1&&this.value(i))},_stop:function(t,e){var i={handle:this.handles[e],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._trigger("stop",t,i)},_change:function(t,e){if(!this._keySliding&&!this._mouseSliding){var i={handle:this.handles[e],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._lastChangedValue=e,this._trigger("change",t,i)}},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),undefined):this._value()},values:function(e,i){var s,n,a;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),undefined;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(e):this.value();for(s=this.options.values,n=arguments[0],a=0;s.length>a;a+=1)s[a]=this._trimAlignValue(n[a]),this._change(null,a);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),t.Widget.prototype._setOption.apply(this,arguments),e){case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=0;n>s;s+=1)this._change(null,s);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this.options.values&&this.options.values.length){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var e,i,s,n,a,o=this.options.range,r=this.options,l=this,h=this._animateOff?!1:r.animate,u={};this.options.values&&this.options.values.length?this.handles.each(function(s){i=100*((l.values(s)-l._valueMin())/(l._valueMax()-l._valueMin())),u["horizontal"===l.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[h?"animate":"css"](u,r.animate),l.options.range===!0&&("horizontal"===l.orientation?(0===s&&l.range.stop(1,1)[h?"animate":"css"]({left:i+"%"},r.animate),1===s&&l.range[h?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&l.range.stop(1,1)[h?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&l.range[h?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),a=this._valueMax(),i=a!==n?100*((s-n)/(a-n)):0,u["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[h?"animate":"css"](u,r.animate),"min"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[h?"animate":"css"]({width:i+"%"},r.animate),"max"===o&&"horizontal"===this.orientation&&this.range[h?"animate":"css"]({width:100-i+"%"},{queue:!1,duration:r.animate}),"min"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[h?"animate":"css"]({height:i+"%"},r.animate),"max"===o&&"vertical"===this.orientation&&this.range[h?"animate":"css"]({height:100-i+"%"},{queue:!1,duration:r.animate}))},_handleEvents:{keydown:function(i){var s,n,a,o,r=t(i.target).data("ui-slider-handle-index");switch(i.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(i.preventDefault(),!this._keySliding&&(this._keySliding=!0,t(i.target).addClass("ui-state-active"),s=this._start(i,r),s===!1))return}switch(o=this.options.step,n=a=this.options.values&&this.options.values.length?this.values(r):this.value(),i.keyCode){case t.ui.keyCode.HOME:a=this._valueMin();break;case t.ui.keyCode.END:a=this._valueMax();break;case t.ui.keyCode.PAGE_UP:a=this._trimAlignValue(n+(this._valueMax()-this._valueMin())/e);break;case t.ui.keyCode.PAGE_DOWN:a=this._trimAlignValue(n-(this._valueMax()-this._valueMin())/e);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(n===this._valueMax())return;a=this._trimAlignValue(n+o);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(n===this._valueMin())return;a=this._trimAlignValue(n-o)}this._slide(i,r,a)},click:function(t){t.preventDefault()},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),t(e.target).removeClass("ui-state-active"))}}})})(jQuery);(function(t){function e(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.widget("ui.spinner",{version:"1.10.4",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e={},i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);void 0!==n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var t=this.element[0]===this.document[0].activeElement;t||(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var t=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=t.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(.5*t.height())&&t.height()>0&&t.height(t.height()),this.options.disabled&&this.disable()},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>&#9650;</span>"+"</a>"+"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>"+"<span class='ui-icon "+this.options.icons.down+"'>&#9660;</span>"+"</a>"},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){if("culture"===t||"numberFormat"===t){var i=this._parse(this.element.val());return this.options[t]=e,this.element.val(this._format(i)),void 0}("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(e.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(e.down)),this._super(t,e),"disabled"===t&&(e?(this.element.prop("disabled",!0),this.buttons.button("disable")):(this.element.prop("disabled",!1),this.buttons.button("enable")))},_setOptions:e(function(t){this._super(t),this._value(this.element.val())}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(e||(i=this._adjustValue(i)),t=this._format(i))),this.element.val(t),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:e(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:e(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:e(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:e(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(e(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}})})(jQuery);(function(t,e){function i(){return++n}function s(t){return t=t.cloneNode(!1),t.hash.length>1&&decodeURIComponent(t.href.replace(a,""))===decodeURIComponent(location.href.replace(a,""))}var n=0,a=/#.*$/;t.widget("ui.tabs",{version:"1.10.4",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var e=this,i=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",i.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var i=this.options.active,s=this.options.collapsible,n=location.hash.substring(1);return null===i&&(n&&this.tabs.each(function(s,a){return t(a).attr("aria-controls")===n?(i=s,!1):e}),null===i&&(i=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===i||-1===i)&&(i=this.tabs.length?0:!1)),i!==!1&&(i=this.tabs.index(this.tabs.eq(i)),-1===i&&(i=s?!1:0)),!s&&i===!1&&this.anchors.length&&(i=0),i},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(i){var s=t(this.document[0].activeElement).closest("li"),n=this.tabs.index(s),a=!0;if(!this._handlePageNav(i)){switch(i.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:n++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:a=!1,n--;break;case t.ui.keyCode.END:n=this.anchors.length-1;break;case t.ui.keyCode.HOME:n=0;break;case t.ui.keyCode.SPACE:return i.preventDefault(),clearTimeout(this.activating),this._activate(n),e;case t.ui.keyCode.ENTER:return i.preventDefault(),clearTimeout(this.activating),this._activate(n===this.options.active?!1:n),e;default:return}i.preventDefault(),clearTimeout(this.activating),n=this._focusNextTab(n,a),i.ctrlKey||(s.attr("aria-selected","false"),this.tabs.eq(n).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",n)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.focus())},_handlePageNav:function(i){return i.altKey&&i.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):i.altKey&&i.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):e},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).focus(),t},_setOption:function(t,i){return"active"===t?(this._activate(i),e):"disabled"===t?(this._setupDisabled(i),e):(this._super(t,i),"collapsible"===t&&(this.element.toggleClass("ui-tabs-collapsible",i),i||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(i),"heightStyle"===t&&this._setupHeightStyle(i),e)},_tabId:function(t){return t.attr("aria-controls")||"ui-tabs-"+i()},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=t(),this.anchors.each(function(i,n){var a,o,r,h=t(n).uniqueId().attr("id"),l=t(n).closest("li"),c=l.attr("aria-controls");s(n)?(a=n.hash,o=e.element.find(e._sanitizeSelector(a))):(r=e._tabId(l),a="#"+r,o=e.element.find(a),o.length||(o=e._createPanel(r),o.insertAfter(e.panels[i-1]||e.tablist)),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),c&&l.data("ui-tabs-aria-controls",c),l.attr({"aria-controls":a.substring(1),"aria-labelledby":h}),o.attr("aria-labelledby",h)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.tablist||this.element.find("ol,ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(e){t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1);for(var i,s=0;i=this.tabs[s];s++)e===!0||-1!==t.inArray(s,e)?t(i).addClass("ui-state-disabled").attr("aria-disabled","true"):t(i).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=e},_setupEvents:function(e){var i={click:function(t){t.preventDefault()}};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),a=n.closest("li"),o=a[0]===s[0],r=o&&i.collapsible,h=r?t():this._getPanelForTab(a),l=s.length?this._getPanelForTab(s):t(),c={oldTab:s,oldPanel:l,newTab:r?t():a,newPanel:h};e.preventDefault(),a.hasClass("ui-state-disabled")||a.hasClass("ui-tabs-loading")||this.running||o&&!i.collapsible||this._trigger("beforeActivate",e,c)===!1||(i.active=r?!1:this.tabs.index(a),this.active=o?t():a,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(a),e),this._toggle(e,c))},_toggle:function(e,i){function s(){a.running=!1,a._trigger("activate",e,i)}function n(){i.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),o.length&&a.options.show?a._show(o,a.options.show,s):(o.show(),s())}var a=this,o=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),n()}):(i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),r.hide(),n()),r.attr({"aria-expanded":"false","aria-hidden":"true"}),i.oldTab.attr("aria-selected","false"),o.length&&r.length?i.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),o.attr({"aria-expanded":"true","aria-hidden":"false"}),i.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(t){return"string"==typeof t&&(t=this.anchors.index(this.anchors.filter("[href$='"+t+"']"))),t},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(i){var s=this.options.disabled;s!==!1&&(i===e?s=!1:(i=this._getIndex(i),s=t.isArray(s)?t.map(s,function(t){return t!==i?t:null}):t.map(this.tabs,function(t,e){return e!==i?e:null})),this._setupDisabled(s))},disable:function(i){var s=this.options.disabled;if(s!==!0){if(i===e)s=!0;else{if(i=this._getIndex(i),-1!==t.inArray(i,s))return;s=t.isArray(s)?t.merge([i],s).sort():[i]}this._setupDisabled(s)}},load:function(e,i){e=this._getIndex(e);var n=this,a=this.tabs.eq(e),o=a.find(".ui-tabs-anchor"),r=this._getPanelForTab(a),h={tab:a,panel:r};s(o[0])||(this.xhr=t.ajax(this._ajaxSettings(o,i,h)),this.xhr&&"canceled"!==this.xhr.statusText&&(a.addClass("ui-tabs-loading"),r.attr("aria-busy","true"),this.xhr.success(function(t){setTimeout(function(){r.html(t),n._trigger("load",i,h)},1)}).complete(function(t,e){setTimeout(function(){"abort"===e&&n.panels.stop(!1,!0),a.removeClass("ui-tabs-loading"),r.removeAttr("aria-busy"),t===n.xhr&&delete n.xhr},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href"),beforeSend:function(e,a){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:a},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}})})(jQuery);(function(t){function e(e,i){var s=(e.attr("aria-describedby")||"").split(/\s+/);s.push(i),e.data("ui-tooltip-id",i).attr("aria-describedby",t.trim(s.join(" ")))}function i(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),s=t.trim(s.join(" ")),s?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")}var s=0;t.widget("ui.tooltip",{version:"1.10.4",options:{content:function(){var e=t(this).attr("title")||"";return t("<a>").text(e).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.options.disabled&&this._disable()},_setOption:function(e,i){var s=this;return"disabled"===e?(this[i?"_disable":"_enable"](),this.options[e]=i,void 0):(this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e)}),void 0)},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s[0],e.close(n,!0)}),this.element.find(this.options.items).addBack().each(function(){var e=t(this);e.is("[title]")&&e.data("ui-tooltip-title",e.attr("title")).attr("title","")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))})},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&(e=t.Event("blur"),e.target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,o=e?e.type:null;return"string"==typeof s?this._open(e,t,s):(i=s.call(t[0],function(i){t.data("ui-tooltip-open")&&n._delay(function(){e&&(e.type=o),this._open(e,t,i)})}),i&&this._open(e,t,i),void 0)},_open:function(i,s,n){function o(t){l.of=t,a.is(":hidden")||a.position(l)}var a,r,h,l=t.extend({},this.options.position);if(n){if(a=this._find(s),a.length)return a.find(".ui-tooltip-content").html(n),void 0;s.is("[title]")&&(i&&"mouseover"===i.type?s.attr("title",""):s.removeAttr("title")),a=this._tooltip(s),e(s,a.attr("id")),a.find(".ui-tooltip-content").html(n),this.options.track&&i&&/^mouse/.test(i.type)?(this._on(this.document,{mousemove:o}),o(i)):a.position(t.extend({of:s},this.options.position)),a.hide(),this._show(a,this.options.show),this.options.show&&this.options.show.delay&&(h=this.delayedShow=setInterval(function(){a.is(":visible")&&(o(l.of),clearInterval(h))},t.fx.interval)),this._trigger("open",i,{tooltip:a}),r={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var i=t.Event(e);i.currentTarget=s[0],this.close(i,!0)}},remove:function(){this._removeTooltip(a)}},i&&"mouseover"!==i.type||(r.mouseleave="close"),i&&"focusin"!==i.type||(r.focusout="close"),this._on(!0,s,r)}},close:function(e){var s=this,n=t(e?e.currentTarget:this.element),o=this._find(n);this.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&n.attr("title",n.data("ui-tooltip-title")),i(n),o.stop(!0),this._hide(o,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),this.closing=!0,this._trigger("close",e,{tooltip:o}),this.closing=!1)},_tooltip:function(e){var i="ui-tooltip-"+s++,n=t("<div>").attr({id:i,role:"tooltip"}).addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||""));return t("<div>").addClass("ui-tooltip-content").appendTo(n),n.appendTo(this.document[0].body),this.tooltips[i]=e,n},_find:function(e){var i=e.data("ui-tooltip-id");return i?t("#"+i):t()},_removeTooltip:function(t){t.remove(),delete this.tooltips[t.attr("id")]},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s[0],e.close(n,!0),t("#"+i).remove(),s.data("ui-tooltip-title")&&(s.attr("title",s.data("ui-tooltip-title")),s.removeData("ui-tooltip-title"))})}})})(jQuery);(function(t,e){var i="ui-effects-";t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=h(),n=s._rgba=[];return i=i.toLowerCase(),f(l,function(t,a){var o,r=a.re.exec(i),l=r&&a.parse(r),h=a.space||"rgba";return l?(o=s[h](l),s[c[h].cache]=o[c[h].cache],n=s._rgba=o._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,a.transparent),s):a[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var a,o="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,l=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],h=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=h.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),h.fn=t.extend(h.prototype,{parse:function(n,o,r,l){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(o),o=e);var u=this,d=t.type(n),p=this._rgba=[];return o!==e&&(n=[n,o,r,l],d="array"),"string"===d?this.parse(s(n)||a._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof h?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var a=s.cache;f(s.props,function(t,e){if(!u[a]&&s.to){if("alpha"===t||null==n[t])return;u[a]=s.to(u._rgba)}u[a][e.idx]=i(n[t],e,!0)}),u[a]&&0>t.inArray(null,u[a].slice(0,3))&&(u[a][3]=1,s.from&&(u._rgba=s.from(u[a])))}),this):e},is:function(t){var i=h(t),s=!0,n=this;return f(c,function(t,a){var o,r=i[a.cache];return r&&(o=n[a.cache]||a.to&&a.to(n._rgba)||[],f(a.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===o[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=h(t),n=s._space(),a=c[n],o=0===this.alpha()?h("transparent"):this,r=o[a.cache]||a.to(o._rgba),l=r.slice();return s=s[a.cache],f(a.props,function(t,n){var a=n.idx,o=r[a],h=s[a],c=u[n.type]||{};null!==h&&(null===o?l[a]=h:(c.mod&&(h-o>c.mod/2?o+=c.mod:o-h>c.mod/2&&(o-=c.mod)),l[a]=i((h-o)*e+o,n)))}),this[n](l)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=h(e)._rgba;return h(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),h.fn.parse.prototype=h.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,a=t[2]/255,o=t[3],r=Math.max(s,n,a),l=Math.min(s,n,a),h=r-l,c=r+l,u=.5*c;return e=l===r?0:s===r?60*(n-a)/h+360:n===r?60*(a-s)/h+120:60*(s-n)/h+240,i=0===h?0:.5>=u?h/c:h/(2-c),[Math.round(e)%360,i,u,null==o?1:o]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],a=t[3],o=.5>=s?s*(1+i):s+i-s*i,r=2*s-o;return[Math.round(255*n(r,o,e+1/3)),Math.round(255*n(r,o,e)),Math.round(255*n(r,o,e-1/3)),a]},f(c,function(s,n){var a=n.props,o=n.cache,l=n.to,c=n.from;h.fn[s]=function(s){if(l&&!this[o]&&(this[o]=l(this._rgba)),s===e)return this[o].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[o].slice();return f(a,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=h(c(d)),n[o]=d,n):h(d)},f(a,function(e,i){h.fn[e]||(h.fn[e]=function(n){var a,o=t.type(n),l="alpha"===e?this._hsla?"hsla":"rgba":s,h=this[l](),c=h[i.idx];return"undefined"===o?c:("function"===o&&(n=n.call(this,c),o=t.type(n)),null==n&&i.empty?this:("string"===o&&(a=r.exec(n),a&&(n=c+parseFloat(a[2])*("+"===a[1]?1:-1))),h[i.idx]=n,this[l](h)))})})}),h.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var a,o,r="";if("transparent"!==n&&("string"!==t.type(n)||(a=s(n)))){if(n=h(a||n),!d.rgba&&1!==n._rgba[3]){for(o="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&o&&o.style;)try{r=t.css(o,"backgroundColor"),o=o.parentNode}catch(l){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(l){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=h(e.elem,i),e.end=h(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},h.hook(o),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},a=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,a={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(a[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(a[i]=n[i]);return a}function s(e,i){var s,n,o={};for(s in i)n=i[s],e[s]!==n&&(a[s]||(t.fx.step[s]||!isNaN(parseFloat(n)))&&(o[s]=n));return o}var n=["add","remove","toggle"],a={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(jQuery.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(e,a,o,r){var l=t.speed(a,o,r);return this.queue(function(){var a,o=t(this),r=o.attr("class")||"",h=l.children?o.find("*").addBack():o;h=h.map(function(){var e=t(this);return{el:e,start:i(this)}}),a=function(){t.each(n,function(t,i){e[i]&&o[i+"Class"](e[i])})},a(),h=h.map(function(){return this.end=i(this.el[0]),this.diff=s(this.start,this.end),this}),o.attr("class",r),h=h.map(function(){var e=this,i=t.Deferred(),s=t.extend({},l,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,h.get()).done(function(){a(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),l.complete.call(o[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,a){return s?t.effects.animateClass.call(this,{add:i},s,n,a):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,a){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,a):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(i){return function(s,n,a,o,r){return"boolean"==typeof n||n===e?a?t.effects.animateClass.call(this,n?{add:s}:{remove:s},a,o,r):i.apply(this,arguments):t.effects.animateClass.call(this,{toggle:s},n,a,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,a){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,a)}})}(),function(){function s(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function n(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}t.extend(t.effects,{version:"1.10.4",save:function(t,e){for(var s=0;e.length>s;s++)null!==e[s]&&t.data(i+e[s],t[0].style[e[s]])},restore:function(t,s){var n,a;for(a=0;s.length>a;a++)null!==s[a]&&(n=t.data(i+s[a]),n===e&&(n=""),t.css(s[a],n))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},a=document.activeElement;try{a.id}catch(o){a=document.body}return e.wrap(s),(e[0]===a||t.contains(e[0],a))&&t(a).focus(),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).focus()),e},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var a=e.cssUnit(i);a[0]>0&&(n[i]=a[0]*s+a[1])}),n}}),t.fn.extend({effect:function(){function e(e){function s(){t.isFunction(a)&&a.call(n[0]),t.isFunction(e)&&e()}var n=t(this),a=i.complete,r=i.mode;(n.is(":hidden")?"hide"===r:"show"===r)?(n[r](),s()):o.call(n[0],i,s)}var i=s.apply(this,arguments),n=i.mode,a=i.queue,o=t.effects.effect[i.effect];return t.fx.off||!o?n?this[n](i.duration,i.complete):this.each(function(){i.complete&&i.complete.call(this)}):a===!1?this.each(e):this.queue(a||"fx",e)},show:function(t){return function(e){if(n(e))return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="show",this.effect.call(this,i)}}(t.fn.show),hide:function(t){return function(e){if(n(e))return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="hide",this.effect.call(this,i)}}(t.fn.hide),toggle:function(t){return function(e){if(n(e)||"boolean"==typeof e)return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="toggle",this.effect.call(this,i)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s}})}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}()})(jQuery);(function(t){var e=/up|down|vertical/,i=/up|left|vertical|horizontal/;t.effects.effect.blind=function(s,n){var a,o,r,l=t(this),h=["position","top","bottom","left","right","height","width"],c=t.effects.setMode(l,s.mode||"hide"),u=s.direction||"up",d=e.test(u),p=d?"height":"width",f=d?"top":"left",g=i.test(u),m={},v="show"===c;l.parent().is(".ui-effects-wrapper")?t.effects.save(l.parent(),h):t.effects.save(l,h),l.show(),a=t.effects.createWrapper(l).css({overflow:"hidden"}),o=a[p](),r=parseFloat(a.css(f))||0,m[p]=v?o:0,g||(l.css(d?"bottom":"right",0).css(d?"top":"left","auto").css({position:"absolute"}),m[f]=v?r:o+r),v&&(a.css(p,0),g||a.css(f,r+o)),a.animate(m,{duration:s.duration,easing:s.easing,queue:!1,complete:function(){"hide"===c&&l.hide(),t.effects.restore(l,h),t.effects.removeWrapper(l),n()}})}})(jQuery);(function(t){t.effects.effect.bounce=function(e,i){var s,n,a,o=t(this),r=["position","top","bottom","left","right","height","width"],l=t.effects.setMode(o,e.mode||"effect"),h="hide"===l,c="show"===l,u=e.direction||"up",d=e.distance,p=e.times||5,f=2*p+(c||h?1:0),g=e.duration/f,m=e.easing,v="up"===u||"down"===u?"top":"left",_="up"===u||"left"===u,b=o.queue(),y=b.length;for((c||h)&&r.push("opacity"),t.effects.save(o,r),o.show(),t.effects.createWrapper(o),d||(d=o["top"===v?"outerHeight":"outerWidth"]()/3),c&&(a={opacity:1},a[v]=0,o.css("opacity",0).css(v,_?2*-d:2*d).animate(a,g,m)),h&&(d/=Math.pow(2,p-1)),a={},a[v]=0,s=0;p>s;s++)n={},n[v]=(_?"-=":"+=")+d,o.animate(n,g,m).animate(a,g,m),d=h?2*d:d/2;h&&(n={opacity:0},n[v]=(_?"-=":"+=")+d,o.animate(n,g,m)),o.queue(function(){h&&o.hide(),t.effects.restore(o,r),t.effects.removeWrapper(o),i()}),y>1&&b.splice.apply(b,[1,0].concat(b.splice(y,f+1))),o.dequeue()}})(jQuery);(function(t){t.effects.effect.clip=function(e,i){var s,n,a,o=t(this),r=["position","top","bottom","left","right","height","width"],l=t.effects.setMode(o,e.mode||"hide"),h="show"===l,c=e.direction||"vertical",u="vertical"===c,d=u?"height":"width",p=u?"top":"left",f={};t.effects.save(o,r),o.show(),s=t.effects.createWrapper(o).css({overflow:"hidden"}),n="IMG"===o[0].tagName?s:o,a=n[d](),h&&(n.css(d,0),n.css(p,a/2)),f[d]=h?a:0,f[p]=h?0:a/2,n.animate(f,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){h||o.hide(),t.effects.restore(o,r),t.effects.removeWrapper(o),i()}})}})(jQuery);(function(t){t.effects.effect.drop=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","opacity","height","width"],o=t.effects.setMode(n,e.mode||"hide"),r="show"===o,l=e.direction||"left",h="up"===l||"down"===l?"top":"left",c="up"===l||"left"===l?"pos":"neg",u={opacity:r?1:0};t.effects.save(n,a),n.show(),t.effects.createWrapper(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,r&&n.css("opacity",0).css(h,"pos"===c?-s:s),u[h]=(r?"pos"===c?"+=":"-=":"pos"===c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}})}})(jQuery);(function(t){t.effects.effect.explode=function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),g||p.hide(),i()}var a,o,r,l,h,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=t.effects.setMode(p,e.mode||"hide"),g="show"===f,m=p.show().css("visibility","hidden").offset(),v=Math.ceil(p.outerWidth()/d),_=Math.ceil(p.outerHeight()/u),b=[];for(a=0;u>a;a++)for(l=m.top+a*_,c=a-(u-1)/2,o=0;d>o;o++)r=m.left+o*v,h=o-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-o*v,top:-a*_}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:v,height:_,left:r+(g?h*v:0),top:l+(g?c*_:0),opacity:g?0:1}).animate({left:r+(g?0:h*v),top:l+(g?0:c*_),opacity:g?1:0},e.duration||500,e.easing,s)}})(jQuery);(function(t){t.effects.effect.fade=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"toggle");s.animate({opacity:n},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}})(jQuery);(function(t){t.effects.effect.fold=function(e,i){var s,n,a=t(this),o=["position","top","bottom","left","right","height","width"],r=t.effects.setMode(a,e.mode||"hide"),l="show"===r,h="hide"===r,c=e.size||15,u=/([0-9]+)%/.exec(c),d=!!e.horizFirst,p=l!==d,f=p?["width","height"]:["height","width"],g=e.duration/2,m={},v={};t.effects.save(a,o),a.show(),s=t.effects.createWrapper(a).css({overflow:"hidden"}),n=p?[s.width(),s.height()]:[s.height(),s.width()],u&&(c=parseInt(u[1],10)/100*n[h?0:1]),l&&s.css(d?{height:0,width:c}:{height:c,width:0}),m[f[0]]=l?n[0]:c,v[f[1]]=l?n[1]:0,s.animate(m,g,e.easing).animate(v,g,e.easing,function(){h&&a.hide(),t.effects.restore(a,o),t.effects.removeWrapper(a),i()})}})(jQuery);(function(t){t.effects.effect.highlight=function(e,i){var s=t(this),n=["backgroundImage","backgroundColor","opacity"],a=t.effects.setMode(s,e.mode||"show"),o={backgroundColor:s.css("backgroundColor")};"hide"===a&&(o.opacity=0),t.effects.save(s,n),s.show().css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(o,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===a&&s.hide(),t.effects.restore(s,n),i()}})}})(jQuery);(function(t){t.effects.effect.pulsate=function(e,i){var s,n=t(this),a=t.effects.setMode(n,e.mode||"show"),o="show"===a,r="hide"===a,l=o||"hide"===a,h=2*(e.times||5)+(l?1:0),c=e.duration/h,u=0,d=n.queue(),p=d.length;for((o||!n.is(":visible"))&&(n.css("opacity",0).show(),u=1),s=1;h>s;s++)n.animate({opacity:u},c,e.easing),u=1-u;n.animate({opacity:u},c,e.easing),n.queue(function(){r&&n.hide(),i()}),p>1&&d.splice.apply(d,[1,0].concat(d.splice(p,h+1))),n.dequeue()}})(jQuery);(function(t){t.effects.effect.puff=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"hide"),a="hide"===n,o=parseInt(e.percent,10)||150,r=o/100,l={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()};t.extend(e,{effect:"scale",queue:!1,fade:!0,mode:n,complete:i,percent:a?o:100,from:a?l:{height:l.height*r,width:l.width*r,outerHeight:l.outerHeight*r,outerWidth:l.outerWidth*r}}),s.effect(e)},t.effects.effect.scale=function(e,i){var s=t(this),n=t.extend(!0,{},e),a=t.effects.setMode(s,e.mode||"effect"),o=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"hide"===a?0:100),r=e.direction||"both",l=e.origin,h={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()},c={y:"horizontal"!==r?o/100:1,x:"vertical"!==r?o/100:1};n.effect="size",n.queue=!1,n.complete=i,"effect"!==a&&(n.origin=l||["middle","center"],n.restore=!0),n.from=e.from||("show"===a?{height:0,width:0,outerHeight:0,outerWidth:0}:h),n.to={height:h.height*c.y,width:h.width*c.x,outerHeight:h.outerHeight*c.y,outerWidth:h.outerWidth*c.x},n.fade&&("show"===a&&(n.from.opacity=0,n.to.opacity=1),"hide"===a&&(n.from.opacity=1,n.to.opacity=0)),s.effect(n)},t.effects.effect.size=function(e,i){var s,n,a,o=t(this),r=["position","top","bottom","left","right","width","height","overflow","opacity"],l=["position","top","bottom","left","right","overflow","opacity"],h=["width","height","overflow"],c=["fontSize"],u=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],d=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=t.effects.setMode(o,e.mode||"effect"),f=e.restore||"effect"!==p,g=e.scale||"both",m=e.origin||["middle","center"],v=o.css("position"),_=f?r:l,b={height:0,width:0,outerHeight:0,outerWidth:0};"show"===p&&o.show(),s={height:o.height(),width:o.width(),outerHeight:o.outerHeight(),outerWidth:o.outerWidth()},"toggle"===e.mode&&"show"===p?(o.from=e.to||b,o.to=e.from||s):(o.from=e.from||("show"===p?b:s),o.to=e.to||("hide"===p?b:s)),a={from:{y:o.from.height/s.height,x:o.from.width/s.width},to:{y:o.to.height/s.height,x:o.to.width/s.width}},("box"===g||"both"===g)&&(a.from.y!==a.to.y&&(_=_.concat(u),o.from=t.effects.setTransition(o,u,a.from.y,o.from),o.to=t.effects.setTransition(o,u,a.to.y,o.to)),a.from.x!==a.to.x&&(_=_.concat(d),o.from=t.effects.setTransition(o,d,a.from.x,o.from),o.to=t.effects.setTransition(o,d,a.to.x,o.to))),("content"===g||"both"===g)&&a.from.y!==a.to.y&&(_=_.concat(c).concat(h),o.from=t.effects.setTransition(o,c,a.from.y,o.from),o.to=t.effects.setTransition(o,c,a.to.y,o.to)),t.effects.save(o,_),o.show(),t.effects.createWrapper(o),o.css("overflow","hidden").css(o.from),m&&(n=t.effects.getBaseline(m,s),o.from.top=(s.outerHeight-o.outerHeight())*n.y,o.from.left=(s.outerWidth-o.outerWidth())*n.x,o.to.top=(s.outerHeight-o.to.outerHeight)*n.y,o.to.left=(s.outerWidth-o.to.outerWidth)*n.x),o.css(o.from),("content"===g||"both"===g)&&(u=u.concat(["marginTop","marginBottom"]).concat(c),d=d.concat(["marginLeft","marginRight"]),h=r.concat(u).concat(d),o.find("*[width]").each(function(){var i=t(this),s={height:i.height(),width:i.width(),outerHeight:i.outerHeight(),outerWidth:i.outerWidth()};f&&t.effects.save(i,h),i.from={height:s.height*a.from.y,width:s.width*a.from.x,outerHeight:s.outerHeight*a.from.y,outerWidth:s.outerWidth*a.from.x},i.to={height:s.height*a.to.y,width:s.width*a.to.x,outerHeight:s.height*a.to.y,outerWidth:s.width*a.to.x},a.from.y!==a.to.y&&(i.from=t.effects.setTransition(i,u,a.from.y,i.from),i.to=t.effects.setTransition(i,u,a.to.y,i.to)),a.from.x!==a.to.x&&(i.from=t.effects.setTransition(i,d,a.from.x,i.from),i.to=t.effects.setTransition(i,d,a.to.x,i.to)),i.css(i.from),i.animate(i.to,e.duration,e.easing,function(){f&&t.effects.restore(i,h)})})),o.animate(o.to,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){0===o.to.opacity&&o.css("opacity",o.from.opacity),"hide"===p&&o.hide(),t.effects.restore(o,_),f||("static"===v?o.css({position:"relative",top:o.to.top,left:o.to.left}):t.each(["top","left"],function(t,e){o.css(e,function(e,i){var s=parseInt(i,10),n=t?o.to.left:o.to.top;return"auto"===i?n+"px":s+n+"px"})})),t.effects.removeWrapper(o),i()}})}})(jQuery);(function(t){t.effects.effect.shake=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","height","width"],o=t.effects.setMode(n,e.mode||"effect"),r=e.direction||"left",l=e.distance||20,h=e.times||3,c=2*h+1,u=Math.round(e.duration/c),d="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},g={},m={},v=n.queue(),_=v.length;for(t.effects.save(n,a),n.show(),t.effects.createWrapper(n),f[d]=(p?"-=":"+=")+l,g[d]=(p?"+=":"-=")+2*l,m[d]=(p?"-=":"+=")+2*l,n.animate(f,u,e.easing),s=1;h>s;s++)n.animate(g,u,e.easing).animate(m,u,e.easing);n.animate(g,u,e.easing).animate(f,u/2,e.easing).queue(function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}),_>1&&v.splice.apply(v,[1,0].concat(v.splice(_,c+1))),n.dequeue()}})(jQuery);(function(t){t.effects.effect.slide=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","width","height"],o=t.effects.setMode(n,e.mode||"show"),r="show"===o,l=e.direction||"left",h="up"===l||"down"===l?"top":"left",c="up"===l||"left"===l,u={};t.effects.save(n,a),n.show(),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0),t.effects.createWrapper(n).css({overflow:"hidden"}),r&&n.css(h,c?isNaN(s)?"-"+s:-s:s),u[h]=(r?c?"+=":"-=":c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}})}})(jQuery);(function(t){t.effects.effect.transfer=function(e,i){var s=t(this),n=t(e.to),a="fixed"===n.css("position"),o=t("body"),r=a?o.scrollTop():0,l=a?o.scrollLeft():0,h=n.offset(),c={top:h.top-r,left:h.left-l,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo(document.body).addClass(e.className).css({top:u.top-r,left:u.left-l,height:s.innerHeight(),width:s.innerWidth(),position:a?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),i()})}})(jQuery);
/*! jQuery UI - v1.10.4 - 2014-04-02
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.jaccordion.js
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */


(function( $, undefined ) {

var uuid = 0,
	runiqueId = /^ui-id-\d+$/;

// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};

$.extend( $.ui, {
	version: "1.10.4",

	keyCode: {
		BACKSPACE: 8,
		COMMA: 188,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
});

// plugins
$.fn.extend({
	focus: (function( orig ) {
		return function( delay, fn ) {
			return typeof delay === "number" ?
				this.each(function() {
					var elem = this;
					setTimeout(function() {
						$( elem ).focus();
						if ( fn ) {
							fn.call( elem );
						}
					}, delay );
				}) :
				orig.apply( this, arguments );
		};
	})( $.fn.focus ),

	scrollParent: function() {
		var scrollParent;
		if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
			}).eq(0);
		}

		return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	},

	uniqueId: function() {
		return this.each(function() {
			if ( !this.id ) {
				this.id = "ui-id-" + (++uuid);
			}
		});
	},

	removeUniqueId: function() {
		return this.each(function() {
			if ( runiqueId.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		});
	}
});

// selectors
function focusable( element, isTabIndexNotNaN ) {
	var map, mapName, img,
		nodeName = element.nodeName.toLowerCase();
	if ( "area" === nodeName ) {
		map = element.parentNode;
		mapName = map.name;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap=#" + mapName + "]" )[0];
		return !!img && visible( img );
	}
	return ( /input|select|textarea|button|object/.test( nodeName ) ?
		!element.disabled :
		"a" === nodeName ?
			element.href || isTabIndexNotNaN :
			isTabIndexNotNaN) &&
		// the element and all of its ancestors must be visible
		visible( element );
}

function visible( element ) {
	return $.expr.filters.visible( element ) &&
		!$( element ).parents().addBack().filter(function() {
			return $.css( this, "visibility" ) === "hidden";
		}).length;
}

$.extend( $.expr[ ":" ], {
	data: $.expr.createPseudo ?
		$.expr.createPseudo(function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		}) :
		// support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		},

	focusable: function( element ) {
		return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			isTabIndexNaN = isNaN( tabIndex );
		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
	}
});

// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
	$.each( [ "Width", "Height" ], function( i, name ) {
		var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
			type = name.toLowerCase(),
			orig = {
				innerWidth: $.fn.innerWidth,
				innerHeight: $.fn.innerHeight,
				outerWidth: $.fn.outerWidth,
				outerHeight: $.fn.outerHeight
			};

		function reduce( elem, size, border, margin ) {
			$.each( side, function() {
				size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
				if ( border ) {
					size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
				}
				if ( margin ) {
					size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
				}
			});
			return size;
		}

		$.fn[ "inner" + name ] = function( size ) {
			if ( size === undefined ) {
				return orig[ "inner" + name ].call( this );
			}

			return this.each(function() {
				$( this ).css( type, reduce( this, size ) + "px" );
			});
		};

		$.fn[ "outer" + name] = function( size, margin ) {
			if ( typeof size !== "number" ) {
				return orig[ "outer" + name ].call( this, size );
			}

			return this.each(function() {
				$( this).css( type, reduce( this, size, true, margin ) + "px" );
			});
		};
	});
}

// support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
	$.fn.removeData = (function( removeData ) {
		return function( key ) {
			if ( arguments.length ) {
				return removeData.call( this, $.camelCase( key ) );
			} else {
				return removeData.call( this );
			}
		};
	})( $.fn.removeData );
}





// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

$.support.selectstart = "onselectstart" in document.createElement( "div" );
$.fn.extend({
	disableSelection: function() {
		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
			".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
	},

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	}
});

$.extend( $.ui, {
	// $.ui.plugin is deprecated. Use $.widget() extensions instead.
	plugin: {
		add: function( module, option, set ) {
			var i,
				proto = $.ui[ module ].prototype;
			for ( i in set ) {
				proto.plugins[ i ] = proto.plugins[ i ] || [];
				proto.plugins[ i ].push( [ option, set[ i ] ] );
			}
		},
		call: function( instance, name, args ) {
			var i,
				set = instance.plugins[ name ];
			if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
				return;
			}

			for ( i = 0; i < set.length; i++ ) {
				if ( instance.options[ set[ i ][ 0 ] ] ) {
					set[ i ][ 1 ].apply( instance.element, args );
				}
			}
		}
	},

	// only used by resizable
	hasScroll: function( el, a ) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	}
});

})( jQuery );
(function( $, undefined ) {

var uuid = 0,
	slice = Array.prototype.slice,
	_cleanData = $.cleanData;
$.cleanData = function( elems ) {
	for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
		try {
			$( elem ).triggerHandler( "remove" );
		// http://bugs.jquery.com/ticket/8235
		} catch( e ) {}
	}
	_cleanData( elems );
};

$.widget = function( name, base, prototype ) {
	var fullName, existingConstructor, constructor, basePrototype,
		// proxiedPrototype allows the provided prototype to remain unmodified
		// so that it can be used as a mixin for multiple widgets (#8876)
		proxiedPrototype = {},
		namespace = name.split( "." )[ 0 ];

	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};
	// extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,
		// copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),
		// track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	});

	basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = (function() {
			var _super = function() {
					return base.prototype[ prop ].apply( this, arguments );
				},
				_superApply = function( args ) {
					return base.prototype[ prop ].apply( this, args );
				};
			return function() {
				var __super = this._super,
					__superApply = this._superApply,
					returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		})();
	});
	constructor.prototype = $.widget.extend( basePrototype, {
		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	});

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
		});
		// remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );
};

$.widget.extend = function( target ) {
	var input = slice.call( arguments, 1 ),
		inputIndex = 0,
		inputLength = input.length,
		key,
		value;
	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :
						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );
				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.widget.extend.apply( null, [ options ].concat(args) ) :
			options;

		if ( isMethodCall ) {
			this.each(function() {
				var methodValue,
					instance = $.data( this, fullName );
				if ( !instance ) {
					return $.error( "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'" );
				}
				if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
					return $.error( "no such method '" + options + "' for " + name + " widget instance" );
				}
				methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue && methodValue.jquery ?
						returnValue.pushStack( methodValue.get() ) :
						methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} )._init();
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",
	options: {
		disabled: false,

		// callbacks
		create: null
	},
	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = uuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;
		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			});
			this.document = $( element.style ?
				// element within the document
				element.ownerDocument :
				// element is window or document
				element.document || element );
			this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
		}

		this._create();
		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},
	_getCreateOptions: $.noop,
	_getCreateEventData: $.noop,
	_create: $.noop,
	_init: $.noop,

	destroy: function() {
		this._destroy();
		// we can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.unbind( this.eventNamespace )
			// 1.9 BC for #7810
			// TODO remove dual storage
			.removeData( this.widgetName )
			.removeData( this.widgetFullName )
			// support: jquery <1.6.3
			// http://bugs.jquery.com/ticket/9413
			.removeData( $.camelCase( this.widgetFullName ) );
		this.widget()
			.unbind( this.eventNamespace )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetFullName + "-disabled " +
				"ui-state-disabled" );

		// clean up events and states
		this.bindings.unbind( this.eventNamespace );
		this.hoverable.removeClass( "ui-state-hover" );
		this.focusable.removeClass( "ui-state-focus" );
	},
	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key,
			parts,
			curOption,
			i;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {
			// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
			this.hoverable.removeClass( "ui-state-hover" );
			this.focusable.removeClass( "ui-state-focus" );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement,
			instance = this;

		// no suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// no element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			// accept selectors, DOM elements
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {
				// allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
							$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^(\w+)\s*(.*)$/ ),
				eventName = match[1] + instance.eventNamespace,
				selector = match[2];
			if ( selector ) {
				delegateElement.delegate( selector, eventName, handlerProxy );
			} else {
				element.bind( eventName, handlerProxy );
			}
		});
	},

	_off: function( element, eventName ) {
		eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
		element.unbind( eventName ).undelegate( eventName );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				$( event.currentTarget ).addClass( "ui-state-hover" );
			},
			mouseleave: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-hover" );
			}
		});
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				$( event.currentTarget ).addClass( "ui-state-focus" );
			},
			focusout: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-focus" );
			}
		});
	},

	_trigger: function( type, event, data ) {
		var prop, orig,
			callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		// the original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}
		var hasOptions,
			effectName = !options ?
				method :
				options === true || typeof options === "number" ?
					defaultEffect :
					options.effect || defaultEffect;
		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}
		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;
		if ( options.delay ) {
			element.delay( options.delay );
		}
		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue(function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			});
		}
	};
});

})( jQuery );
(function( $, undefined ) {

var uid = 0,
	hideProps = {},
	showProps = {};

hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
	hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
showProps.height = showProps.paddingTop = showProps.paddingBottom =
	showProps.borderTopWidth = showProps.borderBottomWidth = "show";

$.widget( "ui.jaccordion", {
	version: "1.10.4",
	options: {
		active: 0,
		animate: {},
		collapsible: false,
		event: "click",
		header: "> li > :first-child,> :not(li):even",
		heightStyle: "auto",
		icons: {
			activeHeader: "ui-icon-triangle-1-s",
			header: "ui-icon-triangle-1-e"
		},

		// callbacks
		activate: null,
		beforeActivate: null
	},

	_create: function() {
		var options = this.options;
		this.prevShow = this.prevHide = $();
		this.element.addClass( "ui-jaccordion ui-widget ui-helper-reset" )
			// ARIA
			.attr( "role", "tablist" );

		// don't allow collapsible: false and active: false / null
		if ( !options.collapsible && (options.active === false || options.active == null) ) {
			options.active = 0;
		}

		this._processPanels();
		// handle negative values
		if ( options.active < 0 ) {
			options.active += this.headers.length;
		}
		this._refresh();
	},

	_getCreateEventData: function() {
		return {
			header: this.active,
			panel: !this.active.length ? $() : this.active.next(),
			content: !this.active.length ? $() : this.active.next()
		};
	},

	_createIcons: function() {
		var icons = this.options.icons;
		if ( icons ) {
			$( "<span>" )
				.addClass( "ui-jaccordion-header-icon ui-icon " + icons.header )
				.prependTo( this.headers );
			this.active.children( ".ui-jaccordion-header-icon" )
				.removeClass( icons.header )
				.addClass( icons.activeHeader );
			this.headers.addClass( "ui-jaccordion-icons" );
		}
	},

	_destroyIcons: function() {
		this.headers
			.removeClass( "ui-jaccordion-icons" )
			.children( ".ui-jaccordion-header-icon" )
				.remove();
	},

	_destroy: function() {
		var contents;

		// clean up main element
		this.element
			.removeClass( "ui-jaccordion ui-widget ui-helper-reset" )
			.removeAttr( "role" );

		// clean up headers
		this.headers
			.removeClass( "ui-jaccordion-header ui-jaccordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
			.removeAttr( "role" )
			.removeAttr( "aria-expanded" )
			.removeAttr( "aria-selected" )
			.removeAttr( "aria-controls" )
			.removeAttr( "tabIndex" )
			.each(function() {
				if ( /^ui-jaccordion/.test( this.id ) ) {
					this.removeAttribute( "id" );
				}
			});
		this._destroyIcons();

		// clean up content panels
		contents = this.headers.next()
			.css( "display", "" )
			.removeAttr( "role" )
			.removeAttr( "aria-hidden" )
			.removeAttr( "aria-labelledby" )
			.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-jaccordion-content ui-jaccordion-content-active ui-state-disabled" )
			.each(function() {
				if ( /^ui-jaccordion/.test( this.id ) ) {
					this.removeAttribute( "id" );
				}
			});
		if ( this.options.heightStyle !== "content" ) {
			contents.css( "height", "" );
		}
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {
			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		if ( key === "event" ) {
			if ( this.options.event ) {
				this._off( this.headers, this.options.event );
			}
			this._setupEvents( value );
		}

		this._super( key, value );

		// setting collapsible: false while collapsed; open first panel
		if ( key === "collapsible" && !value && this.options.active === false ) {
			this._activate( 0 );
		}

		if ( key === "icons" ) {
			this._destroyIcons();
			if ( value ) {
				this._createIcons();
			}
		}

		// #5332 - opacity doesn't cascade to positioned elements in IE
		// so we need to add the disabled class to the headers and panels
		if ( key === "disabled" ) {
			this.headers.add( this.headers.next() )
				.toggleClass( "ui-state-disabled", !!value );
		}
	},

	_keydown: function( event ) {
		if ( event.altKey || event.ctrlKey ) {
			return;
		}

		var keyCode = $.ui.keyCode,
			length = this.headers.length,
			currentIndex = this.headers.index( event.target ),
			toFocus = false;

		switch ( event.keyCode ) {
			case keyCode.RIGHT:
			case keyCode.DOWN:
				toFocus = this.headers[ ( currentIndex + 1 ) % length ];
				break;
			case keyCode.LEFT:
			case keyCode.UP:
				toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
				break;
			case keyCode.SPACE:
			case keyCode.ENTER:
				this._eventHandler( event );
				break;
			case keyCode.HOME:
				toFocus = this.headers[ 0 ];
				break;
			case keyCode.END:
				toFocus = this.headers[ length - 1 ];
				break;
		}

		if ( toFocus ) {
			$( event.target ).attr( "tabIndex", -1 );
			$( toFocus ).attr( "tabIndex", 0 );
			toFocus.focus();
			event.preventDefault();
		}
	},

	_panelKeyDown : function( event ) {
		if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
			$( event.currentTarget ).prev().focus();
		}
	},

	refresh: function() {
		var options = this.options;
		this._processPanels();

		// was collapsed or no panel
		if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
			options.active = false;
			this.active = $();
		// active false only when collapsible is true
		} else if ( options.active === false ) {
			this._activate( 0 );
		// was active, but active panel is gone
		} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			// all remaining panel are disabled
			if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
				options.active = false;
				this.active = $();
			// activate previous panel
			} else {
				this._activate( Math.max( 0, options.active - 1 ) );
			}
		// was active, active panel still exists
		} else {
			// make sure active index is correct
			options.active = this.headers.index( this.active );
		}

		this._destroyIcons();

		this._refresh();
	},

	_processPanels: function() {
		this.headers = this.element.find( this.options.header )
			.addClass( "ui-jaccordion-header ui-helper-reset ui-state-default ui-corner-all" );

		this.headers.next()
			.addClass( "ui-jaccordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
			.filter(":not(.ui-jaccordion-content-active)")
			.hide();
	},

	_refresh: function() {
		var maxHeight,
			options = this.options,
			heightStyle = options.heightStyle,
			parent = this.element.parent(),
			jaccordionId = this.jaccordionId = "ui-jaccordion-" +
				(this.element.attr( "id" ) || ++uid);

		this.active = this._findActive( options.active )
			.addClass( "ui-jaccordion-header-active ui-state-active ui-corner-top" )
			.removeClass( "ui-corner-all" );
		this.active.next()
			.addClass( "ui-jaccordion-content-active" )
			.show();

		this.headers
			.attr( "role", "tab" )
			.each(function( i ) {
				var header = $( this ),
					headerId = header.attr( "id" ),
					panel = header.next(),
					panelId = panel.attr( "id" );
				if ( !headerId ) {
					headerId = jaccordionId + "-header-" + i;
					header.attr( "id", headerId );
				}
				if ( !panelId ) {
					panelId = jaccordionId + "-panel-" + i;
					panel.attr( "id", panelId );
				}
				header.attr( "aria-controls", panelId );
				panel.attr( "aria-labelledby", headerId );
			})
			.next()
				.attr( "role", "tabpanel" );

		this.headers
			.not( this.active )
			.attr({
				"aria-selected": "false",
				"aria-expanded": "false",
				tabIndex: -1
			})
			.next()
				.attr({
					"aria-hidden": "true"
				})
				.hide();

		// make sure at least one header is in the tab order
		if ( !this.active.length ) {
			this.headers.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active.attr({
				"aria-selected": "true",
				"aria-expanded": "true",
				tabIndex: 0
			})
			.next()
				.attr({
					"aria-hidden": "false"
				});
		}

		this._createIcons();

		this._setupEvents( options.event );

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			this.element.siblings( ":visible" ).each(function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			});

			this.headers.each(function() {
				maxHeight -= $( this ).outerHeight( true );
			});

			this.headers.next()
				.each(function() {
					$( this ).height( Math.max( 0, maxHeight -
						$( this ).innerHeight() + $( this ).height() ) );
				})
				.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.headers.next()
				.each(function() {
					maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
				})
				.height( maxHeight );
		}
	},

	_activate: function( index ) {
		var active = this._findActive( index )[ 0 ];

		// trying to activate the already active panel
		if ( active === this.active[ 0 ] ) {
			return;
		}

		// trying to collapse, simulate a click on the currently active header
		active = active || this.active[ 0 ];

		this._eventHandler({
			target: active,
			currentTarget: active,
			preventDefault: $.noop
		});
	},

	_findActive: function( selector ) {
		return typeof selector === "number" ? this.headers.eq( selector ) : $();
	},

	_setupEvents: function( event ) {
		var events = {
			keydown: "_keydown"
		};
		if ( event ) {
			$.each( event.split(" "), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			});
		}

		this._off( this.headers.add( this.headers.next() ) );
		this._on( this.headers, events );
		this._on( this.headers.next(), { keydown: "_panelKeyDown" });
		this._hoverable( this.headers );
		this._focusable( this.headers );
	},

	_eventHandler: function( event ) {
		var options = this.options,
			active = this.active,
			clicked = $( event.currentTarget ),
			clickedIsActive = clicked[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : clicked.next(),
			toHide = active.next(),
			eventData = {
				oldHeader: active,
				oldPanel: toHide,
				newHeader: collapsing ? $() : clicked,
				newPanel: toShow
			};

		event.preventDefault();

		if (
				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||
				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.headers.index( clicked );

		// when the call to ._toggle() comes after the class changes
		// it causes a very odd bug in IE 8 (see #6720)
		this.active = clickedIsActive ? $() : clicked;
		this._toggle( eventData );

		// switch classes
		// corner classes on the previously active header stay after the animation
		active.removeClass( "ui-jaccordion-header-active ui-state-active" );
		if ( options.icons ) {
			active.children( ".ui-jaccordion-header-icon" )
				.removeClass( options.icons.activeHeader )
				.addClass( options.icons.header );
		}

		if ( !clickedIsActive ) {
			clicked
				.removeClass( "ui-corner-all" )
				.addClass( "ui-jaccordion-header-active ui-state-active ui-corner-top" );
			if ( options.icons ) {
				clicked.children( ".ui-jaccordion-header-icon" )
					.removeClass( options.icons.header )
					.addClass( options.icons.activeHeader );
			}

			clicked
				.next()
				.addClass( "ui-jaccordion-content-active" );
		}
	},

	_toggle: function( data ) {
		var toShow = data.newPanel,
			toHide = this.prevShow.length ? this.prevShow : data.oldPanel;

		// handle activating a panel during the animation for another activation
		this.prevShow.add( this.prevHide ).stop( true, true );
		this.prevShow = toShow;
		this.prevHide = toHide;

		if ( this.options.animate ) {
			this._animate( toShow, toHide, data );
		} else {
			toHide.hide();
			toShow.show();
			this._toggleComplete( data );
		}

		toHide.attr({
			"aria-hidden": "true"
		});
		toHide.prev().attr( "aria-selected", "false" );
		// if we're switching panels, remove the old header from the tab order
		// if we're opening from collapsed state, remove the previous header from the tab order
		// if we're collapsing, then keep the collapsing header in the tab order
		if ( toShow.length && toHide.length ) {
			toHide.prev().attr({
				"tabIndex": -1,
				"aria-expanded": "false"
			});
		} else if ( toShow.length ) {
			this.headers.filter(function() {
				return $( this ).attr( "tabIndex" ) === 0;
			})
			.attr( "tabIndex", -1 );
		}

		toShow
			.attr( "aria-hidden", "false" )
			.prev()
				.attr({
					"aria-selected": "true",
					tabIndex: 0,
					"aria-expanded": "true"
				});
	},

	_animate: function( toShow, toHide, data ) {
		var total, easing, duration,
			that = this,
			adjust = 0,
			down = toShow.length &&
				( !toHide.length || ( toShow.index() < toHide.index() ) ),
			animate = this.options.animate || {},
			options = down && animate.down || animate,
			complete = function() {
				that._toggleComplete( data );
			};

		if ( typeof options === "number" ) {
			duration = options;
		}
		if ( typeof options === "string" ) {
			easing = options;
		}
		// fall back from options to animation in case of partial down settings
		easing = easing || options.easing || animate.easing;
		duration = duration || options.duration || animate.duration;

		if ( !toHide.length ) {
			return toShow.animate( showProps, duration, easing, complete );
		}
		if ( !toShow.length ) {
			return toHide.animate( hideProps, duration, easing, complete );
		}

		total = toShow.show().outerHeight();
		toHide.animate( hideProps, {
			duration: duration,
			easing: easing,
			step: function( now, fx ) {
				fx.now = Math.round( now );
			}
		});
		toShow
			.hide()
			.animate( showProps, {
				duration: duration,
				easing: easing,
				complete: complete,
				step: function( now, fx ) {
					fx.now = Math.round( now );
					if ( fx.prop !== "height" ) {
						adjust += fx.now;
					} else if ( that.options.heightStyle !== "content" ) {
						fx.now = Math.round( total - toHide.outerHeight() - adjust );
						adjust = 0;
					}
				}
			});
	},

	_toggleComplete: function( data ) {
		var toHide = data.oldPanel;

		toHide
			.removeClass( "ui-jaccordion-content-active" )
			.prev()
				.removeClass( "ui-corner-top" )
				.addClass( "ui-corner-all" );

		// Work around for rendering bug in IE (#5421)
		if ( toHide.length ) {
			toHide.parent()[0].className = toHide.parent()[0].className;
		}
		this._trigger( "activate", null, data );
	}
});

})( jQuery );
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (MIT_LICENSE.txt)
 * and GPL Version 2 (GPL_LICENSE.txt) licenses.
 *
 * Version: 1.1.1
 * Requires jQuery 1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */


(function($) {

$.extend($.fn, {
	livequery: function(type, fn, fn2) {
		var self = this, q;

		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;

		// See if Live Query already exists
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
		});

		// Create new Live Query if it wasn't found
		q = q || new $.livequery(this.selector, this.context, type, fn, fn2);

		// Make sure it is running
		q.stopped = false;

		// Run it immediately for the first time
		q.run();

		// Contnue the chain
		return this;
	},

	expire: function(type, fn, fn2) {
		var self = this;

		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;

		// Find the Live Query based on arguments and stop it
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
		});

		// Continue the chain
		return this;
	}
});

$.livequery = function(selector, context, type, fn, fn2) {
	this.selector = selector;
	this.context  = context;
	this.type     = type;
	this.fn       = fn;
	this.fn2      = fn2;
	this.elements = [];
	this.stopped  = false;

	// The id is the index of the Live Query in $.livequery.queries
	this.id = $.livequery.queries.push(this)-1;

	// Mark the functions for matching later on
	fn.$lqguid = fn.$lqguid || $.livequery.guid++;
	if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;

	// Return the Live Query
	return this;
};

$.livequery.prototype = {
	stop: function() {
		var query = this;

		if ( this.type )
			// Unbind all bound events
			this.elements.unbind(this.type, this.fn);
		else if (this.fn2)
			// Call the second function for all matched elements
			this.elements.each(function(i, el) {
				query.fn2.apply(el);
			});

		// Clear out matched elements
		this.elements = [];

		// Stop the Live Query from running until restarted
		this.stopped = true;
	},

	run: function() {
		// Short-circuit if stopped
		if ( this.stopped ) return;
		var query = this;

		var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);

		// Set elements to the latest set of matched elements
		this.elements = els;

		if (this.type) {
			// Bind events to newly matched elements
			nEls.bind(this.type, this.fn);

			// Unbind events to elements no longer matched
			if (oEls.length > 0)
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						$.event.remove(el, query.type, query.fn);
				});
		}
		else {
			// Call the first function for newly matched elements
			nEls.each(function() {
				query.fn.apply(this);
			});

			// Call the second function for elements no longer matched
			if ( this.fn2 && oEls.length > 0 )
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						query.fn2.apply(el);
				});
		}
	}
};

$.extend($.livequery, {
	guid: 0,
	queries: [],
	queue: [],
	running: false,
	timeout: null,

	checkQueue: function() {
		if ( $.livequery.running && $.livequery.queue.length ) {
			var length = $.livequery.queue.length;
			// Run each Live Query currently in the queue
			while ( length-- )
				$.livequery.queries[ $.livequery.queue.shift() ].run();
		}
	},

	pause: function() {
		// Don't run anymore Live Queries until restarted
		$.livequery.running = false;
	},

	play: function() {
		// Restart Live Queries
		$.livequery.running = true;
		// Request a run of the Live Queries
		$.livequery.run();
	},

	registerPlugin: function() {
		$.each( arguments, function(i,n) {
			// Short-circuit if the method doesn't exist
			if (!$.fn[n]) return;

			// Save a reference to the original method
			var old = $.fn[n];

			// Create a new method
			$.fn[n] = function() {
				// Call the original method
				var r = old.apply(this, arguments);

				// Request a run of the Live Queries
				$.livequery.run();

				// Return the original methods result
				return r;
			}
		});
	},

	run: function(id) {
		if (id != undefined) {
			// Put the particular Live Query in the queue if it doesn't already exist
			if ( $.inArray(id, $.livequery.queue) < 0 )
				$.livequery.queue.push( id );
		}
		else
			// Put each Live Query in the queue if it doesn't already exist
			$.each( $.livequery.queries, function(id) {
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			});

		// Clear timeout if it already exists
		if ($.livequery.timeout) clearTimeout($.livequery.timeout);
		// Create a timeout to check the queue and actually run the Live Queries
		$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
	},

	stop: function(id) {
		if (id != undefined)
			// Stop are particular Live Query
			$.livequery.queries[ id ].stop();
		else
			// Stop all Live Queries
			$.each( $.livequery.queries, function(id) {
				$.livequery.queries[ id ].stop();
			});
	}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove', 'html');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });

})(jQuery);
/**
 * jQuery Masonry v2.0.110927
 * A dynamic layout plugin for jQuery
 * The flip-side of CSS Floats
 * http://masonry.desandro.com
 *
 * Licensed under the MIT license.
 * Copyright 2011 David DeSandro
 */

 
(function( window, $, undefined ){

  /*
   * smartresize: debounced resize event for jQuery
   *
   * latest version and complete README available on Github:
   * https://github.com/louisremi/jquery.smartresize.js
   *
   * Copyright 2011 @louis_remi
   * Licensed under the MIT license.
   */

  var $event = $.event,
      resizeTimeout;

  $event.special.smartresize = {
    setup: function() {
      $j(this).bind( "resize", $event.special.smartresize.handler );
    },
    teardown: function() {
      $j(this).unbind( "resize", $event.special.smartresize.handler );
    },
    handler: function( event, execAsap ) {
      // Save the context
      var context = this,
          args = arguments;

      // set correct event type
      event.type = "smartresize";

      if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
      resizeTimeout = setTimeout(function() {
        jQuery.event.handle.apply( context, args );
      }, execAsap === "execAsap"? 0 : 100 );
    }
  };

  $.fn.smartresize = function( fn ) {
    return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
  };



// ========================= Masonry ===============================


  // our "Widget" object constructor
  $.Mason = function( options, element ){
    this.element = $j( element );

    this._create( options );
    this._init();
  };
  
  // styles of container element we want to keep track of
  var masonryContainerStyles = [ 'position', 'height' ];
  
  $.Mason.settings = {
    isResizable: true,
    isAnimated: false,
    animationOptions: {
      queue: false,
      duration: 500
    },
    gutterWidth: 0,
    isRTL: false,
    isFitWidth: false
  };

  $.Mason.prototype = {

    _filterFindBricks: function( $elems ) {
      var selector = this.options.itemSelector;
      // if there is a selector
      // filter/find appropriate item elements
      return !selector ? $elems : $elems.filter( selector ).add( $elems.find( selector ) );
    },

    _getBricks: function( $elems ) {
      var $bricks = this._filterFindBricks( $elems )
        .css({ position: 'absolute' })
        .addClass('masonry-brick');
      return $bricks;
    },
    
    // sets up widget
    _create : function( options ) {
      
      this.options = $.extend( true, {}, $.Mason.settings, options );
      
      this.styleQueue = [];
      // need to get bricks
      this.reloadItems();


      // get original styles in case we re-apply them in .destroy()
      var elemStyle = this.element[0].style;
      this.originalStyle = {};
      for ( var i=0, len = masonryContainerStyles.length; i < len; i++ ) {
        var prop = masonryContainerStyles[i];
        this.originalStyle[ prop ] = elemStyle[ prop ] || '';
      }

      this.element.css({
        position : 'relative'
      });
      
      this.horizontalDirection = this.options.isRTL ? 'right' : 'left';
      this.offset = {};
      
      // get top left position of where the bricks should be
      var $cursor = $j( document.createElement('div') );
      this.element.prepend( $cursor );
      this.offset.y = Math.round( $cursor.position().top );
      // get horizontal offset
      if ( !this.options.isRTL ) {
        this.offset.x = Math.round( $cursor.position().left );
      } else {
        $cursor.css({ 'float': 'right', display: 'inline-block'});
        this.offset.x = Math.round( this.element.outerWidth() - $cursor.position().left );
      }
      $cursor.remove();

      // add masonry class first time around
      var instance = this;
      setTimeout( function() {
        instance.element.addClass('masonry');
      }, 0 );
      
      // bind resize method
      if ( this.options.isResizable ) {
        $j(window).bind( 'smartresize.masonry', function() { 
          instance.resize();
        });
      }
      
    },
  
    // _init fires when instance is first created
    // and when instance is triggered again -> $el.masonry();
    _init : function( callback ) {
      this._getColumns('masonry');
      this._reLayout( callback );
    },

    option: function( key, value ){
      // set options AFTER initialization:
      // signature: $j('#foo').bar({ cool:false });
      if ( $.isPlainObject( key ) ){
        this.options = $.extend(true, this.options, key);
      } 
    },
    
    // ====================== General Layout ======================

    // used on collection of atoms (should be filtered, and sorted before )
    // accepts atoms-to-be-laid-out to start with
    layout : function( $bricks, callback ) {

      // layout logic
      var $brick, colSpan, groupCount, groupY, groupColY, j;
      
      for (var i=0, len = $bricks.length; i < len; i++) {
        $brick = $j( $bricks[i] );
        //how many columns does this brick span
        colSpan = Math.ceil( $brick.outerWidth(true) / this.columnWidth );
        colSpan = Math.min( colSpan, this.cols );

        if ( colSpan === 1 ) {
          // if brick spans only one column, just like singleMode
          this._placeBrick( $brick, this.colYs );
        } else {
          // brick spans more than one column
          // how many different places could this brick fit horizontally
          groupCount = this.cols + 1 - colSpan;
          groupY = [];

          // for each group potential horizontal position
          for ( j=0; j < groupCount; j++ ) {
            // make an array of colY values for that one group
            groupColY = this.colYs.slice( j, j+colSpan );
            // and get the max value of the array
            groupY[j] = Math.max.apply( Math, groupColY );
          }
        
          this._placeBrick( $brick, groupY );
        }
      }
      
      // set the size of the container
      var containerSize = {};
      containerSize.height = Math.max.apply( Math, this.colYs ) - this.offset.y;
      if ( this.options.isFitWidth ) {
        var unusedCols = 0,
            i = this.cols;
        // count unused columns
        while ( --i ) {
          if ( this.colYs[i] !== this.offset.y ) {
            break;
          }
          unusedCols++;
        }
        // fit container to columns that have been used;
        containerSize.width = (this.cols - unusedCols) * this.columnWidth - this.options.gutterWidth;
      }
      this.styleQueue.push({ $el: this.element, style: containerSize });

      // are we animating the layout arrangement?
      // use plugin-ish syntax for css or animate
      var styleFn = !this.isLaidOut ? 'css' : (
            this.options.isAnimated ? 'animate' : 'css'
          ),
          animOpts = this.options.animationOptions;

      // process styleQueue
      var obj;
      for (i=0, len = this.styleQueue.length; i < len; i++) {
        obj = this.styleQueue[i];
        obj.$el[ styleFn ]( obj.style, animOpts );
      }

      // clear out queue for next time
      this.styleQueue = [];

      // provide $elems as context for the callback
      if ( callback ) {
        callback.call( $bricks );
      }
      
      this.isLaidOut = true;
    },
    
    // calculates number of columns
    // i.e. this.columnWidth = 200
    _getColumns : function() {
      var container = this.options.isFitWidth ? this.element.parent() : this.element,
          containerWidth = container.width();
      
      this.columnWidth = this.options.columnWidth ||
                    // or use the size of the first item
                    this.$bricks.outerWidth(true) ||
                    // if there's no items, use size of container
                    containerWidth;

      this.columnWidth += this.options.gutterWidth;

      this.cols = Math.floor( ( containerWidth + this.options.gutterWidth ) / this.columnWidth );
      this.cols = Math.max( this.cols, 1 );

    },

    _placeBrick : function( $brick, setY ) {
      // get the minimum Y value from the columns
      var minimumY = Math.min.apply( Math, setY ),
          shortCol = 0;
      
      // Find index of short column, the first from the left
      for (var i=0, len = setY.length; i < len; i++) {
        if ( setY[i] === minimumY ) {
          shortCol = i;
          break;
        }
      }

      // position the brick
      var position = {
        top : minimumY
      };
      // position.left or position.right
      position[ this.horizontalDirection ] = this.columnWidth * shortCol + this.offset.x;
      this.styleQueue.push({ $el: $brick, style: position });

      // apply setHeight to necessary columns
      var setHeight = minimumY + $brick.outerHeight(true),
          setSpan = this.cols + 1 - len;
      for ( i=0; i < setSpan; i++ ) {
        this.colYs[ shortCol + i ] = setHeight;
      }

    },
    
    
    resize : function() {
      var prevColCount = this.cols;
      // get updated colCount
      this._getColumns('masonry');
      if ( this.cols !== prevColCount ) {
        // if column count has changed, trigger new layout
        this._reLayout();
      }
    },
    
    
    _reLayout : function( callback ) {
      // reset columns
      var i = this.cols;
      this.colYs = [];
      while (i--) {
        this.colYs.push( this.offset.y );
      }
      // apply layout logic to all bricks
      this.layout( this.$bricks, callback );
    },
    
    // ====================== Convenience methods ======================
    
    // goes through all children again and gets bricks in proper order
    reloadItems : function() {
      this.$bricks = this._getBricks( this.element.children() );
    },
    
    
    reload : function( callback ) {
      this.reloadItems();
      this._init( callback );
    },
    

    // convienence method for working with Infinite Scroll
    appended : function( $content, isAnimatedFromBottom, callback ) {
      if ( isAnimatedFromBottom ) {
        // set new stuff to the bottom
        this._filterFindBricks( $content ).css({ top: this.element.height() });
        var instance = this;
        setTimeout( function(){
          instance._appended( $content, callback );
        }, 1 );
      } else {
        this._appended( $content, callback );
      }
    },
    
    _appended : function( $content, callback ) {
      var $newBricks = this._getBricks( $content );
      // add new bricks to brick pool
      this.$bricks = this.$bricks.add( $newBricks );
      this.layout( $newBricks, callback );
    },
    
    // removes elements from Masonry widget
    remove : function( $content ) {
      this.$bricks = this.$bricks.not( $content );
      $content.remove();
    },
    
    // destroys widget, returns elements and container back (close) to original style
    destroy : function() {

      this.$bricks
        .removeClass('masonry-brick')
        .each(function(){
          this.style.position = '';
          this.style.top = '';
          this.style.left = '';
        });
      
      // re-apply saved container styles
      var elemStyle = this.element[0].style;
      for ( var i=0, len = masonryContainerStyles.length; i < len; i++ ) {
        var prop = masonryContainerStyles[i];
        elemStyle[ prop ] = this.originalStyle[ prop ];
      }
      
      this.element
        .unbind('.masonry')
        .removeClass('masonry')
        .removeData('masonry');
      
      $j(window).unbind('.masonry');

    }
    
  };
  
  
  // ======================= imagesLoaded Plugin ===============================
  /*!
   * jQuery imagesLoaded plugin v1.0.3
   * http://github.com/desandro/imagesloaded
   *
   * MIT License. by Paul Irish et al.
   */


  // $j('#my-container').imagesLoaded(myFunction)
  // or
  // $j('img').imagesLoaded(myFunction)

  // execute a callback when all images have loaded.
  // needed because .load() doesn't work on cached images

  // callback function gets image collection as argument
  //  `this` is the container

  $.fn.imagesLoaded = function( callback ) {
    var $this = this,
        $images = $this.find('img').add( $this.filter('img') ),
        len = $images.length,
        blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

    function triggerCallback() {
      callback.call( $this, $images );
    }

    function imgLoaded() {
      if ( --len <= 0 && this.src !== blank ){
        setTimeout( triggerCallback );
        $images.unbind( 'load error', imgLoaded );
      }
    }

    if ( !len ) {
      triggerCallback();
    }

    $images.bind( 'load error',  imgLoaded ).each( function() {
      // cached images don't fire load sometimes, so we reset src.
      if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
      }
    });

    return $this;
  };


  // helper function for logging errors
  // $.error breaks jQuery chaining
  var logError = function( message ) {
    if ( this.console ) {
      console.error( message );
    }
  };
  
  // =======================  Plugin bridge  ===============================
  // leverages data method to either create or return $.Mason constructor
  // A bit from jQuery UI
  //   https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js
  // A bit from jcarousel 
  //   https://github.com/jsor/jcarousel/blob/master/lib/jquery.jcarousel.js

  $.fn.masonry = function( options ) {
    if ( typeof options === 'string' ) {
      // call method
      var args = Array.prototype.slice.call( arguments, 1 );

      this.each(function(){
        var instance = $.data( this, 'masonry' );
        if ( !instance ) {
          logError( "cannot call methods on masonry prior to initialization; " +
            "attempted to call method '" + options + "'" );
          return;
        }
        if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
          logError( "no such method '" + options + "' for masonry instance" );
          return;
        }
        // apply method
        instance[ options ].apply( instance, args );
      });
    } else {
      this.each(function() {
        var instance = $.data( this, 'masonry' );
        if ( instance ) {
          // apply options & init
          instance.option( options || {} );
          instance._init();
        } else {
          // initialize new instance
          $.data( this, 'masonry', new $.Mason( options, this ) );
        }
      });
    }
    return this;
  };

})( window, jQuery );
(function($, undefined) {

/**
 * Unobtrusive scripting adapter for jQuery
 * https://github.com/rails/jquery-ujs
 *
 * Requires jQuery 1.8.0 or later.
 *
 * Released under the MIT license
 *
 */

  // Cut down on the number of issues from people inadvertently including jquery_ujs twice
  // by detecting and raising an error when it happens.
  'use strict';

  if ( $.rails !== undefined ) {
    $.error('jquery-ujs has already been loaded!');
  }

  // Shorthand to make it a little easier to call public rails functions from within rails.js
  var rails;
  var $document = $(document);

  $.rails = rails = {
    // Link elements bound by jquery-ujs
    linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]',

    // Button elements bound by jquery-ujs
    buttonClickSelector: 'button[data-remote]:not([form]):not(form button), button[data-confirm]:not([form]):not(form button)',

    // Select elements bound by jquery-ujs
    inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',

    // Form elements bound by jquery-ujs
    formSubmitSelector: 'form',

    // Form input elements bound by jquery-ujs
    formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',

    // Form input elements disabled during form submission
    disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',

    // Form input elements re-enabled after form submission
    enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',

    // Form required input elements
    requiredInputSelector: 'input[name][required]:not([disabled]), textarea[name][required]:not([disabled])',

    // Form file input elements
    fileInputSelector: 'input[name][type=file]:not([disabled])',

    // Link onClick disable selector with possible reenable after remote submission
    linkDisableSelector: 'a[data-disable-with], a[data-disable]',

    // Button onClick disable selector with possible reenable after remote submission
    buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]',

    // Up-to-date Cross-Site Request Forgery token
    csrfToken: function() {
     return $('meta[name=csrf-token]').attr('content');
    },

    // URL param that must contain the CSRF token
    csrfParam: function() {
     return $('meta[name=csrf-param]').attr('content');
    },

    // Make sure that every Ajax request sends the CSRF token
    CSRFProtection: function(xhr) {
      var token = rails.csrfToken();
      if (token) xhr.setRequestHeader('X-CSRF-Token', token);
    },

    // Make sure that all forms have actual up-to-date tokens (cached forms contain old ones)
    refreshCSRFTokens: function(){
      $('form input[name="' + rails.csrfParam() + '"]').val(rails.csrfToken());
    },

    // Triggers an event on an element and returns false if the event result is false
    fire: function(obj, name, data) {
      var event = $.Event(name);
      obj.trigger(event, data);
      return event.result !== false;
    },

    // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm
    confirm: function(message) {
      return confirm(message);
    },

    // Default ajax function, may be overridden with custom function in $.rails.ajax
    ajax: function(options) {
      return $.ajax(options);
    },

    // Default way to get an element's href. May be overridden at $.rails.href.
    href: function(element) {
      return element[0].href;
    },

    // Checks "data-remote" if true to handle the request through a XHR request.
    isRemote: function(element) {
      return element.data('remote') !== undefined && element.data('remote') !== false;
    },

    // Submits "remote" forms and links with ajax
    handleRemote: function(element) {
      var method, url, data, withCredentials, dataType, options;

      if (rails.fire(element, 'ajax:before')) {
        withCredentials = element.data('with-credentials') || null;
        dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType);

        if (element.is('form')) {
          method = element.data('ujs:submit-button-formmethod') || element.attr('method');
          url = element.data('ujs:submit-button-formaction') || element.attr('action');
          data = $(element[0]).serializeArray();
          // memoized value from clicked submit button
          var button = element.data('ujs:submit-button');
          if (button) {
            data.push(button);
            element.data('ujs:submit-button', null);
          }
          element.data('ujs:submit-button-formmethod', null);
          element.data('ujs:submit-button-formaction', null);
        } else if (element.is(rails.inputChangeSelector)) {
          method = element.data('method');
          url = element.data('url');
          data = element.serialize();
          if (element.data('params')) data = data + '&' + element.data('params');
        } else if (element.is(rails.buttonClickSelector)) {
          method = element.data('method') || 'get';
          url = element.data('url');
          data = element.serialize();
          if (element.data('params')) data = data + '&' + element.data('params');
        } else {
          method = element.data('method');
          url = rails.href(element);
          data = element.data('params') || null;
        }

        options = {
          type: method || 'GET', data: data, dataType: dataType,
          // stopping the "ajax:beforeSend" event will cancel the ajax request
          beforeSend: function(xhr, settings) {
            if (settings.dataType === undefined) {
              xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
            }
            if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) {
              element.trigger('ajax:send', xhr);
            } else {
              return false;
            }
          },
          success: function(data, status, xhr) {
            element.trigger('ajax:success', [data, status, xhr]);
          },
          complete: function(xhr, status) {
            element.trigger('ajax:complete', [xhr, status]);
          },
          error: function(xhr, status, error) {
            element.trigger('ajax:error', [xhr, status, error]);
          },
          crossDomain: rails.isCrossDomain(url)
        };

        // There is no withCredentials for IE6-8 when
        // "Enable native XMLHTTP support" is disabled
        if (withCredentials) {
          options.xhrFields = {
            withCredentials: withCredentials
          };
        }

        // Only pass url to `ajax` options if not blank
        if (url) { options.url = url; }

        return rails.ajax(options);
      } else {
        return false;
      }
    },

    // Determines if the request is a cross domain request.
    isCrossDomain: function(url) {
      var originAnchor = document.createElement('a');
      originAnchor.href = location.href;
      var urlAnchor = document.createElement('a');

      try {
        urlAnchor.href = url;
        // This is a workaround to a IE bug.
        urlAnchor.href = urlAnchor.href;

        // If URL protocol is false or is a string containing a single colon
        // *and* host are false, assume it is not a cross-domain request
        // (should only be the case for IE7 and IE compatibility mode).
        // Otherwise, evaluate protocol and host of the URL against the origin
        // protocol and host.
        return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) ||
          (originAnchor.protocol + '//' + originAnchor.host ===
            urlAnchor.protocol + '//' + urlAnchor.host));
      } catch (e) {
        // If there is an error parsing the URL, assume it is crossDomain.
        return true;
      }
    },

    // Handles "data-method" on links such as:
    // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
    handleMethod: function(link) {
      var href = rails.href(link),
        method = link.data('method'),
        target = link.attr('target'),
        csrfToken = rails.csrfToken(),
        csrfParam = rails.csrfParam(),
        form = $('<form method="post" action="' + href + '"></form>'),
        metadataInput = '<input name="_method" value="' + method + '" type="hidden" />';

      if (csrfParam !== undefined && csrfToken !== undefined && !rails.isCrossDomain(href)) {
        metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
      }

      if (target) { form.attr('target', target); }

      form.hide().append(metadataInput).appendTo('body');
      form.submit();
    },

    // Helper function that returns form elements that match the specified CSS selector
    // If form is actually a "form" element this will return associated elements outside the from that have
    // the html form attribute set
    formElements: function(form, selector) {
      return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector);
    },

    /* Disables form elements:
      - Caches element value in 'ujs:enable-with' data store
      - Replaces element text with value of 'data-disable-with' attribute
      - Sets disabled property to true
    */
    disableFormElements: function(form) {
      rails.formElements(form, rails.disableSelector).each(function() {
        rails.disableFormElement($(this));
      });
    },

    disableFormElement: function(element) {
      var method, replacement;

      method = element.is('button') ? 'html' : 'val';
      replacement = element.data('disable-with');

      if (replacement !== undefined) {
        element.data('ujs:enable-with', element[method]());
        element[method](replacement);
      }

      element.prop('disabled', true);
      element.data('ujs:disabled', true);
    },

    /* Re-enables disabled form elements:
      - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
      - Sets disabled property to false
    */
    enableFormElements: function(form) {
      rails.formElements(form, rails.enableSelector).each(function() {
        rails.enableFormElement($(this));
      });
    },

    enableFormElement: function(element) {
      var method = element.is('button') ? 'html' : 'val';
      if (element.data('ujs:enable-with') !== undefined) {
        element[method](element.data('ujs:enable-with'));
        element.removeData('ujs:enable-with'); // clean up cache
      }
      element.prop('disabled', false);
      element.removeData('ujs:disabled');
    },

   /* For 'data-confirm' attribute:
      - Fires `confirm` event
      - Shows the confirmation dialog
      - Fires the `confirm:complete` event

      Returns `true` if no function stops the chain and user chose yes; `false` otherwise.
      Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog.
      Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function
      return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog.
   */
    allowAction: function(element) {
      var message = element.data('confirm'),
          answer = false, callback;
      if (!message) { return true; }

      if (rails.fire(element, 'confirm')) {
        try {
          answer = rails.confirm(message);
        } catch (e) {
          (console.error || console.log).call(console, e.stack || e);
        }
        callback = rails.fire(element, 'confirm:complete', [answer]);
      }
      return answer && callback;
    },

    // Helper function which checks for blank inputs in a form that match the specified CSS selector
    blankInputs: function(form, specifiedSelector, nonBlank) {
      var foundInputs = $(),
        input,
        valueToCheck,
        radiosForNameWithNoneSelected,
        radioName,
        selector = specifiedSelector || 'input,textarea',
        requiredInputs = form.find(selector),
        checkedRadioButtonNames = {};

      requiredInputs.each(function() {
        input = $(this);
        if (input.is('input[type=radio]')) {

          // Don't count unchecked required radio as blank if other radio with same name is checked,
          // regardless of whether same-name radio input has required attribute or not. The spec
          // states https://www.w3.org/TR/html5/forms.html#the-required-attribute
          radioName = input.attr('name');

          // Skip if we've already seen the radio with this name.
          if (!checkedRadioButtonNames[radioName]) {

            // If none checked
            if (form.find('input[type=radio]:checked[name="' + radioName + '"]').length === 0) {
              radiosForNameWithNoneSelected = form.find(
                'input[type=radio][name="' + radioName + '"]');
              foundInputs = foundInputs.add(radiosForNameWithNoneSelected);
            }

            // We only need to check each name once.
            checkedRadioButtonNames[radioName] = radioName;
          }
        } else {
          valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : !!input.val();
          if (valueToCheck === nonBlank) {
            foundInputs = foundInputs.add(input);
          }
        }
      });
      return foundInputs.length ? foundInputs : false;
    },

    // Helper function which checks for non-blank inputs in a form that match the specified CSS selector
    nonBlankInputs: function(form, specifiedSelector) {
      return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank
    },

    // Helper function, needed to provide consistent behavior in IE
    stopEverything: function(e) {
      $(e.target).trigger('ujs:everythingStopped');
      e.stopImmediatePropagation();
      return false;
    },

    //  Replace element's html with the 'data-disable-with' after storing original html
    //  and prevent clicking on it
    disableElement: function(element) {
      var replacement = element.data('disable-with');

      if (replacement !== undefined) {
        element.data('ujs:enable-with', element.html()); // store enabled state
        element.html(replacement);
      }

      element.bind('click.railsDisable', function(e) { // prevent further clicking
        return rails.stopEverything(e);
      });
      element.data('ujs:disabled', true);
    },

    // Restore element to its original state which was disabled by 'disableElement' above
    enableElement: function(element) {
      if (element.data('ujs:enable-with') !== undefined) {
        element.html(element.data('ujs:enable-with')); // set to old enabled state
        element.removeData('ujs:enable-with'); // clean up cache
      }
      element.unbind('click.railsDisable'); // enable element
      element.removeData('ujs:disabled');
    }
  };

  if (rails.fire($document, 'rails:attachBindings')) {

    $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }});

    // This event works the same as the load event, except that it fires every
    // time the page is loaded.
    //
    // See https://github.com/rails/jquery-ujs/issues/357
    // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching
    $(window).on('pageshow.rails', function () {
      $($.rails.enableSelector).each(function () {
        var element = $(this);

        if (element.data('ujs:disabled')) {
          $.rails.enableFormElement(element);
        }
      });

      $($.rails.linkDisableSelector).each(function () {
        var element = $(this);

        if (element.data('ujs:disabled')) {
          $.rails.enableElement(element);
        }
      });
    });

    $document.on('ajax:complete', rails.linkDisableSelector, function() {
        rails.enableElement($(this));
    });

    $document.on('ajax:complete', rails.buttonDisableSelector, function() {
        rails.enableFormElement($(this));
    });

    $document.on('click.rails', rails.linkClickSelector, function(e) {
      var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey;
      if (!rails.allowAction(link)) return rails.stopEverything(e);

      if (!metaClick && link.is(rails.linkDisableSelector)) rails.disableElement(link);

      if (rails.isRemote(link)) {
        if (metaClick && (!method || method === 'GET') && !data) { return true; }

        var handleRemote = rails.handleRemote(link);
        // Response from rails.handleRemote() will either be false or a deferred object promise.
        if (handleRemote === false) {
          rails.enableElement(link);
        } else {
          handleRemote.fail( function() { rails.enableElement(link); } );
        }
        return false;

      } else if (method) {
        rails.handleMethod(link);
        return false;
      }
    });

    $document.on('click.rails', rails.buttonClickSelector, function(e) {
      var button = $(this);

      if (!rails.allowAction(button) || !rails.isRemote(button)) return rails.stopEverything(e);

      if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button);

      var handleRemote = rails.handleRemote(button);
      // Response from rails.handleRemote() will either be false or a deferred object promise.
      if (handleRemote === false) {
        rails.enableFormElement(button);
      } else {
        handleRemote.fail( function() { rails.enableFormElement(button); } );
      }
      return false;
    });

    $document.on('change.rails', rails.inputChangeSelector, function(e) {
      var link = $(this);
      if (!rails.allowAction(link) || !rails.isRemote(link)) return rails.stopEverything(e);

      rails.handleRemote(link);
      return false;
    });

    $document.on('submit.rails', rails.formSubmitSelector, function(e) {
      var form = $(this),
        remote = rails.isRemote(form),
        blankRequiredInputs,
        nonBlankFileInputs;

      if (!rails.allowAction(form)) return rails.stopEverything(e);

      // Skip other logic when required values are missing or file upload is present
      if (form.attr('novalidate') === undefined) {
        if (form.data('ujs:formnovalidate-button') === undefined) {
          blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector, false);
          if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
            return rails.stopEverything(e);
          }
        } else {
          // Clear the formnovalidate in case the next button click is not on a formnovalidate button
          // Not strictly necessary to do here, since it is also reset on each button click, but just to be certain
          form.data('ujs:formnovalidate-button', undefined);
        }
      }

      if (remote) {
        nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
        if (nonBlankFileInputs) {
          // Slight timeout so that the submit button gets properly serialized
          // (make it easy for event handler to serialize form without disabled values)
          setTimeout(function(){ rails.disableFormElements(form); }, 13);
          var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);

          // Re-enable form elements if event bindings return false (canceling normal form submission)
          if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); }

          return aborted;
        }

        rails.handleRemote(form);
        return false;

      } else {
        // Slight timeout so that the submit button gets properly serialized
        setTimeout(function(){ rails.disableFormElements(form); }, 13);
      }
    });

    $document.on('click.rails', rails.formInputClickSelector, function(event) {
      var button = $(this);

      if (!rails.allowAction(button)) return rails.stopEverything(event);

      // Register the pressed submit button
      var name = button.attr('name'),
        data = name ? {name:name, value:button.val()} : null;

      var form = button.closest('form');
      if (form.length === 0) {
        form = $('#' + button.attr('form'));
      }
      form.data('ujs:submit-button', data);

      // Save attributes from button
      form.data('ujs:formnovalidate-button', button.attr('formnovalidate'));
      form.data('ujs:submit-button-formaction', button.attr('formaction'));
      form.data('ujs:submit-button-formmethod', button.attr('formmethod'));
    });

    $document.on('ajax:send.rails', rails.formSubmitSelector, function(event) {
      if (this === event.target) rails.disableFormElements($(this));
    });

    $document.on('ajax:complete.rails', rails.formSubmitSelector, function(event) {
      if (this === event.target) rails.enableFormElements($(this));
    });

    $(function(){
      rails.refreshCSRFTokens();
    });
  }

})( jQuery );
/*!
 * Spinners 3.0.0
 * (c) 2010-2012 Nick Stakenburg - http://www.nickstakenburg.com
 *
 * Spinners is freely distributable under the terms of an MIT-style license.
 *
 * GitHub: http://github.com/staaky/spinners
 */

;var Spinners={version:"3.0.0"};(function(a){function b(a){return a*Math.PI/180}function c(a){this.element=a}function d(b,c){b&&(this.element=b,h.remove(b),h.removeDetached(),this._position=0,this._state="stopped",this.setOptions(a.extend({color:"#000",dashes:12,radius:5,height:5,width:1.8,opacity:1,padding:3,rotation:700},c||{})),this.drawPosition(0),h.add(this))}var e={scroll:function(a,b){if(!b)return a;var c=a.slice(0,b);return a.slice(b,a.length).concat(c)},isElement:function(a){return a&&1==a.nodeType},element:{isAttached:function(){return function(a){for(;a&&a.parentNode;)a=a.parentNode;return!!a&&!!a.body}}()}},f={drawRoundedRectangle:function(c,d){var e=a.extend({top:0,left:0,width:0,height:0,radius:0},d||{}),f=e.left,g=e.top,h=e.width,i=e.height,e=e.radius;c.beginPath(),c.moveTo(f+e,g),c.arc(f+h-e,g+e,e,b(-90),b(0),!1),c.arc(f+h-e,g+i-e,e,b(0),b(90),!1),c.arc(f+e,g+i-e,e,b(90),b(180),!1),c.arc(f+e,g+e,e,b(-180),b(-90),!1),c.closePath(),c.fill()}},g=function(){function a(a){var c=[];0==a.indexOf("#")&&(a=a.substring(1)),a=a.toLowerCase();if(""!=a.replace(b,""))return null;3==a.length?(c[0]=a.charAt(0)+a.charAt(0),c[1]=a.charAt(1)+a.charAt(1),c[2]=a.charAt(2)+a.charAt(2)):(c[0]=a.substring(0,2),c[1]=a.substring(2,4),c[2]=a.substring(4));for(a=0;a<c.length;a++)c[a]=parseInt(c[a],16);return c.red=c[0],c.green=c[1],c.blue=c[2],c}var b=RegExp("[0123456789abcdef]","g"),c=function(){function a(a,b,c){return a=a.toString(c||10),Array(b-a.length).join("0")+a}return function(b,c,d){return"#"+a(b,2,16)+a(c,2,16)+a(d,2,16)}}();return{hex2rgb:a,hex2fill:function(b,c){"undefined"==typeof c&&(c=1);var d=c,e=a(b);return e[3]=d,e.opacity=d,"rgba("+e.join()+")"},rgb2hex:c}}();a.extend(Spinners,{enabled:!1,support:{canvas:function(){var b=a("<canvas>")[0];return!!b.getContext&&!!b.getContext("2d")}()},init:function(){if(this.support.canvas||window.G_vmlCanvasManager&&window.attachEvent&&-1===navigator.userAgent.indexOf("Opera"))window.G_vmlCanvasManager&&window.G_vmlCanvasManager.init_(document),this.enabled=!0},create:function(a,b){return c.create(a,b),this.get(a)},get:function(a){return new c(a)},play:function(a){return this.get(a).play(),this},pause:function(a){return this.get(a).pause(),this},toggle:function(a){return this.get(a).toggle(),this},stop:function(a){return this.get(a).stop(),this},remove:function(a){return this.get(a).remove(),this},removeDetached:function(){return h.removeDetached(),this},center:function(a){return this.get(a).center(),this},setOptions:function(a,b){return this.get(a).setOptions(b),this},getDimensions:function(a){return a=2*h.get(a)[0].getLayout().workspace.radius,{width:a,height:a}}});var h={spinners:[],get:function(b){if(b){var c=[];return a.each(this.spinners,function(d,f){f&&(e.isElement(b)?f.element==b:a(f.element).is(b))&&c.push(f)}),c}},add:function(a){this.spinners.push(a)},remove:function(b){a(a.map(this.spinners,function(c){if(e.isElement(b)?c.element==b:a(c.element).is(b))return c.element})).each(a.proxy(function(a,b){this.removeByElement(b)},this))},removeByElement:function(b){var c=this.get(b)[0];c&&(c.remove(),this.spinners=a.grep(this.spinners,function(a){return a.element!=b}))},removeDetached:function(){a.each(this.spinners,a.proxy(function(a,b){b&&b.element&&!e.element.isAttached(b.element)&&this.remove(b.element)},this))}};a.extend(c,{create:function(b,c){if(b){var f=c||{},g=[];return e.isElement(b)?g.push(new d(b,f)):a(b).each(function(a,b){g.push(new d(b,f))}),g}}}),a.extend(c.prototype,{items:function(){return h.get(this.element)},play:function(){return a.each(this.items(),function(a,b){b.play()}),this},stop:function(){return a.each(this.items(),function(a,b){b.stop()}),this},pause:function(){return a.each(this.items(),function(a,b){b.pause()}),this},toggle:function(){return a.each(this.items(),function(a,b){b.toggle()}),this},center:function(){return a.each(this.items(),function(a,b){b.center()}),this},setOptions:function(b){return a.each(this.items(),function(a,c){c.setOptions(b)}),this},remove:function(){return h.remove(this.element),this}}),a.extend(d.prototype,{setOptions:function(b){this.options=a.extend({},this.options,b||{}),this.options.radii&&(b=this.options.radii,this.options.radius=Math.min(b[0],b[1]),this.options.height=Math.max(b[0],b[1])-this.options.radius),this.options.dashWidth&&(this.options.width=this.options.dashWidth),this.options.speed&&(this.options.duration=1e3*this.options.speed);var b=this._state,c=this._position;this._layout=null,this.build(),c&&c>=this.options.dashes-1&&(this._position=this.options.dashes-1);switch(b){case"playing":this.play();break;case"paused":case"stopped":this.drawPosition(this._position)}this._centered&&this.center()},remove:function(){this.canvas&&(this.pause(),a(this.canvas).remove(),this.ctx=this.canvas=null)},build:function(){this.remove();var b=this.getLayout().workspace.radius;return a(document.body).append(this.canvas=a("<canvas>").attr({width:2*b,height:2*b}).css({zoom:1})),window.G_vmlCanvasManager&&G_vmlCanvasManager.initElement(this.canvas[0]),this.ctx=this.canvas[0].getContext("2d"),this.ctx.globalAlpha=this.options.opacity,a(this.element).append(this.canvas),this.ctx.translate(b,b),this},drawPosition:function(a){var c=this.getLayout().workspace,a=e.scroll(c.opacities,-1*a),d=c.radius,c=this.options.dashes,f=b(360/c);this.ctx.clearRect(-1*d,-1*d,2*d,2*d);for(d=0;d<c;d++)this.drawDash(a[d],this.options.color),this.ctx.rotate(f)},drawDash:function(a,b){this.ctx.fillStyle=g.hex2fill(b,a);var c=this.getLayout(),d=c.workspace.radius,e=c.dash.position,c=c.dash.dimensions;f.drawRoundedRectangle(this.ctx,{top:e.top-d,left:e.left-d,width:c.width,height:c.height,radius:Math.min(c.height,c.width)/2})},_nextPosition:function(){var b=this.options.rotation/this.options.dashes;this.nextPosition(),this._playTimer=window.setTimeout(a.proxy(this._nextPosition,this),b)},nextPosition:function(){this._position==this.options.dashes-1&&(this._position=-1),this._position++,this.drawPosition(this._position)},play:function(){if("playing"!=this._state){this._state="playing";var b=this.options.rotation/this.options.dashes;return this._playTimer=window.setTimeout(a.proxy(this._nextPosition,this),b),this}},pause:function(){if("paused"!=this._state)return this._pause(),this._state="paused",this},_pause:function(){this._playTimer&&(window.clearTimeout(this._playTimer),this._playTimer=null)},stop:function(){if("stopped"!=this._state)return this._pause(),this._position=0,this.drawPosition(0),this._state="stopped",this},toggle:function(){return this["playing"==this._state?"pause":"play"](),this},getLayout:function(){if(this._layout)return this._layout;for(var a=this.options,b=a.dashes,c=a.width,d=a.radius,e=a.radius+a.height,f=Math.max(c,e),f=Math.ceil(Math.max(f,Math.sqrt(e*e+c/2*(c/2)))),a=f+=a.padding,g=1/b,h=[],i=0;i<b;i++)h.push((i+1)*g);return this._layout=b={workspace:{radius:a,opacities:h},dash:{position:{top:f-e,left:f-c/2},dimensions:{width:c,height:e-d}}}},center:function(){var b=2*this.getLayout().workspace.radius;a(this.element.parentNode).css({position:"relative"}),a(this.element).css({position:"absolute",height:b+"px",width:b+"px",top:"50%",left:"50%",marginLeft:-0.5*b+"px",marginTop:-0.5*b+"px"}),this._centered=!0}}),Spinners.init(),Spinners.enabled||(c.create=function(){return[]})})(jQuery);
/*!
 * Tipped - The jQuery Tooltip - v2.5.6
 * (c) 2010-2012 Nick Stakenburg
 *
 * http://projects.nickstakenburg.com/tipped
 *
 * License: http://projects.nickstakenburg.com/tipped/license
 */

;var Tipped = { version: '2.5.6' };

Tipped.Skins = {
  // base skin, don't modify! (create custom skins in a seperate file)
  'base': {
    afterUpdate: false,
    ajax: {
      cache: true,
      type: 'get'
    },
    background: {
      color: '#f2f2f2',
      opacity: 1
    },
    border: {
      size: 1,
      color: '#000',
      opacity: 1
    },
    closeButtonSkin: 'default',
    containment: {
      selector: 'viewport'
    },
    fadeIn: 180,
    fadeOut: 220,
    showDelay: 75,
    hideDelay: 25,
    radius: {
      size: 3,
      position: 'background'
    },
    hideAfter: false,
    hideOn: {
      element: 'self',
      event: 'mouseleave'
    },
    hideOthers: false,
    hook: 'topleft',
    inline: false,
    offset: {
      x: 0, y: 0,
      mouse: { x: -12, y: -12 } // only defined in the base class
    },
    onHide: false,
    onShow: false,
    shadow: {
      blur: 2,
      color: '#000',
      offset: { x: 0, y: 0 },
      opacity: .15
    },
    showOn: 'mousemove',
    spinner: true,
    stem: {
      height: 6,
      width: 11,
      offset: { x: 5, y: 5 },
      spacing: 2
    },
    target: 'self'
  },

  // Every other skin inherits from this one
  'reset': {
    ajax: false,
    closeButton: false,
    hideOn: [{
      element: 'self',
      event: 'mouseleave'
    }, {
      element: 'tooltip',
      event: 'mouseleave'
    }],
    hook: 'topmiddle',
    stem: true
  },

  // Custom skins start here
  'black': {
     background: { color: '#232323', opacity: .9 },
     border: { size: 1, color: "#232323" },
     spinner: { color: '#fff' }
  },

  'cloud': {
    border: {
      size: 1,
      color: [
        { position: 0, color: '#bec6d5'},
        { position: 1, color: '#b1c2e3' }
      ]
    },
    closeButtonSkin: 'light',
    background: {
      color: [
        { position: 0, color: '#f6fbfd'},
        { position: 0.1, color: '#fff' },
        { position: .48, color: '#fff'},
        { position: .5, color: '#fefffe'},
        { position: .52, color: '#f7fbf9'},
        { position: .8, color: '#edeff0' },
        { position: 1, color: '#e2edf4' }
      ]
    },
    shadow: { opacity: .1 }
  },

  'dark': {
    border: { size: 1, color: '#1f1f1f', opacity: .95 },
    background: {
      color: [
        { position: .0, color: '#686766' },
        { position: .48, color: '#3a3939' },
        { position: .52, color: '#2e2d2d' },
        { position: .54, color: '#2c2b2b' },
        { position: 0.95, color: '#222' },
        { position: 1, color: '#202020' }
      ],
      opacity: .9
    },
    radius: { size: 4 },
    shadow: { offset: { x: 0, y: 1 } },
    spinner: { color: '#ffffff' }
  },

  'facebook': {
    background: { color: '#282828' },
    border: 0,
    fadeIn: 0,
    fadeOut: 0,
    radius: 0,
    stem: {
      width: 7,
      height: 4,
      offset: { x: 6, y: 6 }
    },
    shadow: false
  },

  'lavender': {
    background: {
      color: [
        { position: .0, color: '#b2b6c5' },
        { position: .5, color: '#9da2b4' },
        { position: 1, color: '#7f85a0' }
      ]
    },
    border: {
      color: [
        { position: 0, color: '#a2a9be' },
        { position: 1, color: '#6b7290' }
      ],
      size: 1
    },
    radius: 1,
    shadow: { opacity: .1 }
  },

  'light': {
    border: { size: 0, color: '#afafaf' },
    background: {
      color: [
        { position: 0, color: '#fefefe' },
        { position: 1, color: '#f7f7f7' }
      ]
    },
    closeButtonSkin: 'light',
    radius: 1,
    stem: {
      height: 7,
      width: 13,
      offset: { x: 7, y: 7 }
    },
    shadow: { opacity: .32, blur: 2 }
  },

  'lime': {
    border: {
      size: 1,
      color: [
        { position: 0,   color: '#5a785f' },
        { position: .05, color: '#0c7908' },
        { position: 1, color: '#587d3c' }
      ]
    },
    background: {
      color: [
        { position: 0,   color: '#a5e07f' },
        { position: .02, color: '#cef8be' },
        { position: .09, color: '#7bc83f' },
        { position: .35, color: '#77d228' },
        { position: .65, color: '#85d219' },
        { position: .8,  color: '#abe041' },
        { position: 1,   color: '#c4f087' }
      ]
    }
  },

  'liquid' : {
    border: {
      size: 1,
      color: [
        { position: 0, color: '#454545' },
        { position: 1, color: '#101010' }
      ]
    },
    background: {
      color: [
        { position: 0, color: '#515562'},
        { position: .3, color: '#252e43'},
        { position: .48, color: '#111c34'},
        { position: .52, color: '#161e32'},
        { position: .54, color: '#0c162e'},
        { position: 1, color: '#010c28'}
      ],
      opacity: .8
    },
    radius: { size: 4 },
    shadow: { offset: { x: 0, y: 1 } },
    spinner: { color: '#ffffff' }
  },

  'blue': {
    border: {
      color: [
        { position: 0, color: '#113d71'},
        { position: 1, color: '#1e5290' }
      ]
    },
    background: {
      color: [
        { position: 0, color: '#3a7ab8'},
        { position: .48, color: '#346daa'},
        { position: .52, color: '#326aa6'},
        { position: 1, color: '#2d609b' }
      ]
    },
    spinner: { color: '#f2f6f9' },
    shadow: { opacity: .2 }
  },

  'salmon' : {
    background: {
      color: [
        { position: 0, color: '#fbd0b7' },
        { position: .5, color: '#fab993' },
        { position: 1, color: '#f8b38b' }
      ]
    },
    border: {
      color: [
        { position: 0, color: '#eda67b' },
        { position: 1, color: '#df946f' }
      ],
      size: 1
    },
    radius: 1,
    shadow: { opacity: .1 }
  },

  'yellow': {
    border: { size: 1, color: '#f7c735' },
    background: '#ffffaa',
    radius: 1,
    shadow: { opacity: .1 }
  }
};

Tipped.Skins.CloseButtons = {
  'base': {
    diameter: 17,
    border: 2,
    x: { diameter: 10, size: 2, opacity: 1 },
    states: {
      'default': {
        background: {
          color: [
            { position: 0, color: '#1a1a1a' },
            { position: 0.46, color: '#171717' },
            { position: 0.53, color: '#121212' },
            { position: 0.54, color: '#101010' },
            { position: 1, color: '#000' }
          ],
          opacity: 1
        },
        x: { color: '#fafafa', opacity: 1 },
        border: { color: '#fff', opacity: 1 }
      },
      'hover': {
        background: {
          color: '#333',
          opacity: 1
        },
        x: { color: '#e6e6e6', opacity: 1 },
        border: { color: '#fff', opacity: 1 }
      }
    },
    shadow: {
      blur: 2,
      color: '#000',
      offset: { x: 0, y: 0 },
      opacity: .3
    }
  },

  'reset': {},

  'default': {},

  'light': {
    diameter: 17,
    border: 2,
    x: { diameter: 10, size: 2, opacity: 1 },
    states: {
      'default': {
        background: {
          color: [
            { position: 0, color: '#797979' },
            { position: 0.48, color: '#717171' },
            { position: 0.52, color: '#666' },
            { position: 1, color: '#666' }
          ],
          opacity: 1
        },
        x: { color: '#fff', opacity: .95 },
        border: { color: '#676767', opacity: 1 }
      },
      'hover': {
        background: {
          color: [
            { position: 0, color: '#868686' },
            { position: 0.48, color: '#7f7f7f' },
            { position: 0.52, color: '#757575' },
            { position: 1, color: '#757575' }
          ],
          opacity: 1
        },
        x: { color: '#fff', opacity: 1 },
        border: { color: '#767676', opacity: 1 }
      }
    }
  }
};

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(13(e){13 n(e,t){1b n=[e,t];1c n.15=e,n.17=t,n}13 r(e){12.1j=e}13 i(e){1b t={},n;21(n 5g e)t[n]=e[n]+"2t";1c t}13 s(e){1c 2C*e/1d.2Z}13 o(e){1c e*1d.2Z/2C}13 u(t){1h(t){12.1j=t,A.1D(t);1b n=12.2c();12.1a=e.1m({},n.1a),12.2u=1,12.1r={},12.1R=e(t).20("2o-1R"),A.30(12),12.22=12.1a.1s.1x,12.7V=12.1a.1o&&12.22,12.1O()}}13 a(t,n,r){(12.1j=t)&&n&&(12.1a=e.1m({31:3,1F:{x:0,y:0},1P:"#4o",1K:.5,2L:1},r||{}),12.2u=12.1a.2L,12.1r={},12.1R=e(t).20("2o-1R"),O.30(12),12.1O())}13 f(t,n){1h(12.1j=t)12.1a=e.1m({31:5,1F:{x:0,y:0},1P:"#4o",1K:.5,2L:1},n||{}),12.2u=12.1a.2L,12.1R=e(t).20("2o-1R"),M.30(12),12.1O()}13 l(t,n){21(1b r 5g n)n[r]&&n[r].3x&&n[r].3x===5h?(t[r]=e.1m({},t[r])||{},l(t[r],n[r])):t[r]=n[r];1c t}13 c(t,n,r){1h(12.1j=t){1b i=e(t).20("2o-1R");i&&I.1D(t),i=b(),e(t).20("2o-1R",i),12.1R=i,"7W"==e.1t(n)&&!p.2k(n)?(r=n,n=1C):r=r||{},12.1a=I.6b(r),r=t.6c("5i"),n||((i=t.6c("20-2o"))?n=i:r&&(n=r)),r&&(e(t).20("5j",r),t.7X("5i","")),12.2M=n,12.2j=12.1a.2j||+I.1a.4p,12.1r={3a:{14:1,19:1},5k:[],3b:[],2p:{4q:!1,2v:!1,1M:!1,3k:!1,1O:!1,4r:!1,5l:!1,3y:!1},5m:""},t=12.1a.1E,12.1E="2N"==t?"2N":"4s"==t||!t?12.1j:t&&1y.6d(t)||12.1j,12.6e(),I.30(12)}}1b t,h=6f.3z.7Y,p={7Z:13(t,n){1c 13(){1b r=[e.1w(t,12)].6g(h.5n(5o));1c n.5p(12,r)}},2k:13(e){1c e&&1==e.80},4t:13(e,t){1b n=h.5n(5o,2);1c 81(13(){1c e.5p(e,n)},t)},3T:13(e){1c p.4t.5p(12,[e,1].6g(h.5n(5o,1)))},5q:13(e){1c{x:e.5r,y:e.6h}},1j:{4u:13(e){1b t=0,r=0;82 t+=e.4v||0,r+=e.4w||0,e=e.4x;83(e);1c n(r,t)},4y:13(t){1b r=e(t).1F(),t=p.1j.4u(t),i=e(1S).4v(),s=e(1S).4w();1c r.15+=t.15-s,r.17+=t.17-i,n(r.15,r.17)},5s:13(e){21(;e&&e.4x;)e=e.4x;1c!!e&&!!e.3c}}},d=84.85,v=13(e){1c(e=6i(e+"([\\\\d.]+)").86(d))?6j(e[1]):!0};t=!!1S.87&&-1===d.3l("6k")&&v("88 "),-1<d.3l("6k")&&1S.5t&&5t.6l&&6j(5t.6l()),-1<d.3l("6m/")&&v("6m/"),-1<d.3l("89")&&-1===d.3l("8a")&&v("8b:"),d.3d(/8c.*8d.*8e/),-1<d.3l("6n")&&v("6n/");1b m=13(e){21(1b t=(e=e.3d(g))&&e[1]&&e[1].2O(".")||[],n=0,r=0,i=t.23;r<i;r++)n+=2P(t[r]*1d.4z(10,6-2*r));1c e&&e[3]?n-1:n},g=/^(\\d+(\\.?\\d+){0,3})([A-6o-8f-]+[A-6o-8g-9]+)?/,y={32:{3U:{5u:"1.4.4",5v:1S.3U&&3U.8h.8i}},6p:13(e){!12.32[e].6q&&(12.32[e].6q=!0,!12.32[e].5v||m(12.32[e].5v)<m(12.32[e].5u)&&!12.32[e].6r)&&((12.32[e].6r=!0,e="1V 6s "+e+" >= "+12.32[e].5u,1S.5w)?5w[5w.6t?"6t":"8j"](e):6u(e))}},b,w=0;b=13(e){e=e||"8k";21(w++;1y.6d(e+w);)w++;1c e+w},e.1m(1V,{33:{3e:13(){1b e=1y.24("3e");1c!!e.3A&&!!e.3A("2d")}(),4A:13(){6v{1c!!("8l"5g 1S||1S.6w&&1y 8m 6w)}6x(e){1c!1}}(),3V:13(){1b t=!1;1c e.1z(["8n","8o","8p"],13(e,n){6v{1y.8q(n),t=!0}6x(r){}}),t}()},3m:13(){1h(!12.33.3e&&!1S.3W){1h(!t)1c;6u("1V 6s 8r (8s.8t)")}y.6p("3U"),e(1y).6y(13(){I.6z()})},4B:13(e,t,n){1c r.4B(e,t,n),12.1v(e)},1v:13(e){1c 3n r(e)},5x:13(e){1c I.5x(e)},1T:13(e){1c 12.1v(e).1T(),12},1J:13(e){1c 12.1v(e).1J(),12},34:13(e){1c 12.1v(e).34(),12},2Q:13(e){1c 12.1v(e).2Q(),12},1D:13(e){1c 12.1v(e).1D(),12},4C:13(){1c I.4C(),12},5y:13(e){1c I.5y(e),12},5z:13(e){1c I.5z(e),12},1M:13(t){1h(p.2k(t))1c I.5A(t);1h("5B"!=e.1t(t)){1b t=e(t),n=0;1c e.1z(t,13(e,t){I.5A(t)&&n++}),n}1c I.3B().23}}),e.1m(r,{4B:13(t,n,r){1h(t){1b i=r||{},s=[];1c I.6A(),p.2k(t)?s.2R(3n c(t,n,i)):e(t).1z(13(e,t){s.2R(3n c(t,n,i))}),s}}}),e.1m(r.3z,{3X:13(){1c I.2w.4D={x:0,y:0},I.1v(12.1j)},1T:13(){1c e.1z(12.3X(),13(e,t){t.1T()}),12},1J:13(){1c e.1z(12.3X(),13(e,t){t.1J()}),12},34:13(){1c e.1z(12.3X(),13(e,t){t.34()}),12},2Q:13(){1c e.1z(12.3X(),13(e,t){t.2Q()}),12},1D:13(){1c I.1D(12.1j),12}}),v=1S.3W&&!1V.33.3e&&t?13(e){3W.8u(e)}:13(){};1b E={3m:v,6B:13(t,n){1b r=e.1m({17:0,15:0,14:0,19:0,1p:0},n||{}),i=r.15,s=r.17,u=r.14,a=r.19;(r=r.1p)?(t.2e(),t.3o(i+r,s),t.29(i+u-r,s+r,r,o(-90),o(0),!1),t.29(i+u-r,s+a-r,r,o(0),o(90),!1),t.29(i+r,s+a-r,r,o(90),o(2C),!1),t.29(i+r,s+r,r,o(-2C),o(-90),!1),t.2f(),t.35()):t.6C(i,s,u,a)},8v:13(t,n,r){21(1b r=e.1m({x:0,y:0,1P:"#4o"},r||{}),i=0,s=n.23;i<s;i++)21(1b o=0,u=n[i].23;o<u;o++){1b a=2P(n[i].3p(o))*(1/9);t.2S=N.2T(r.1P,a),a&&t.6C(r.x+o,r.y+i,1,1)}},3Y:13(t,n,r){1b i;1c"2q"==e.1t(n)?i=N.2T(n):"2q"==e.1t(n.1P)?i=N.2T(n.1P,"2x"==e.1t(n.1K)?n.1K:1):e.6D(n.1P)&&(r=e.1m({3C:0,3D:0,3E:0,3F:0},r||{}),i=E.6E.6F(t.8w(r.3C,r.3D,r.3E,r.3F),n.1P,n.1K)),i},6E:{6F:13(t,n,r){21(1b r="2x"==e.1t(r)?r:1,i=0,s=n.23;i<s;i++){1b o=n[i];1h("5B"==e.1t(o.1K)||"2x"!=e.1t(o.1K))o.1K=1;t.8x(o.1e,N.2T(o.1P,o.1K*r))}1c t}}},S={17:"19",15:"14",1W:"19",1X:"14"},x={3Z:"3G 40 3H 3I 41 42 43 44 46 47 48 3J".2O(" "),49:{6G:/^(17|15|1W|1X)(17|15|1W|1X|2U|2V)$/,1U:/^(17|1W)/,36:/(2U|2V)/,6H:/^(17|1W|15|1X)/},6I:13(e){1c S[e]},36:13(e){1c!!e.3q().3d(12.49.36)},6J:13(e){1c!12.36(e)},2D:13(e){1c e.3q().3d(12.49.1U)?"1U":"2E"},5C:13(e){1b t=1C;1c(e=e.3q().3d(12.49.6H))&&e[1]&&(t=e[1]),t},2O:13(e){1c e.3q().3d(12.49.6G)}},T={5D:13(e){1c e=e.1a.1o,{14:e.14,19:e.19}},4a:13(t,n,r){1c r=e.1m({3K:"1G"},r||{}),t=t.1a.1o,n=12.4E(t.14,t.19,n),r.3K&&(n.14=1d[r.3K](n.14),n.19=1d[r.3K](n.19)),{14:n.14,19:n.19}},4E:13(e,t,n){1b r=2C-s(1d.6K(.5*(t/e))),n=1d.4F(o(r-90))*n,n=e+2*n;1c{14:n,19:n*t/e}},3L:13(e,t){1b n=12.4a(e,t),r=12.5D(e);x.36(e.22);1b i=1d.1G(n.19+t);1c{3f:{1g:{14:1d.1G(n.14),19:1d.1G(i)}},1l:{1g:n},1o:{1g:{14:r.14,19:r.19}}}},5E:13(t,n,r){1b i=t.1a,s={17:0,15:0},o={17:0,15:0},u=e.1m({},n),a=t.1l,f=f||12.3L(t,t.1l),l=f.3f.1g;r&&(l.19=r,a=0);1h(t.1a.1o){1b c=x.5C(t.22);"17"==c?s.17=l.19-a:"15"==c&&(s.15=l.19-a);1b r=x.2O(t.22),h=x.2D(t.22);1h("1U"==h){1Q(r[2]){1i"2U":1i"2V":o.15=.5*u.14;1B;1i"1X":o.15=u.14}"1W"==r[1]&&(o.17=u.19-a+l.19)}26{1Q(r[2]){1i"2U":1i"2V":o.17=.5*u.19;1B;1i"1W":o.17=u.19}"1X"==r[1]&&(o.15=u.14-a+l.19)}u[x.6I(c)]+=l.19-a}26 1h(r=x.2O(t.22),h=x.2D(t.22),"1U"==h){1Q(r[2]){1i"2U":1i"2V":o.15=.5*u.14;1B;1i"1X":o.15=u.14}"1W"==r[1]&&(o.17=u.19)}26{1Q(r[2]){1i"2U":1i"2V":o.17=.5*u.19;1B;1i"1W":o.17=u.19}"1X"==r[1]&&(o.15=u.14)}c=i.1p&&i.1p.2y||0,a=i.1l&&i.1l.2y||0;1h(t.1a.1o){1b p=i.1o&&i.1o.1F||{x:0,y:0},t=c&&"1n"==i.1p.1e?c:0,c=c&&"1l"==i.1p.1e?c:c+a,d=a+t+.5*f.1o.1g.14-.5*f.1l.1g.14,f=1d.1G(a+t+.5*f.1o.1g.14+(c>d?c-d:0));1h("1U"==h)1Q(r[2]){1i"15":o.15+=f;1B;1i"1X":o.15-=f}26 1Q(r[2]){1i"17":o.17+=f;1B;1i"1W":o.17-=f}}1h(i.1o&&(p=i.1o.1F))1h("1U"==h)1Q(r[2]){1i"15":o.15+=p.x;1B;1i"1X":o.15-=p.x}26 1Q(r[2]){1i"17":o.17+=p.y;1B;1i"1W":o.17-=p.y}1b v;1h(i.1o&&(v=i.1o.8y))1h("1U"==h)1Q(r[1]){1i"17":o.17-=v;1B;1i"1W":o.17+=v}26 1Q(r[1]){1i"15":o.15-=v;1B;1i"1X":o.15+=v}1c{1g:u,1e:{17:0,15:0},1n:{1e:s,1g:n},1o:{1g:l},2l:o}}},N,C=13(e){1c e.6L=e[0],e.6M=e[1],e.6N=e[2],e},k=13(e){1b t=6f(3);0==e.3l("#")&&(e=e.4G(1)),e=e.3q();1h(""!=e.8z(L,""))1c 1C;3==e.23?(t[0]=e.3p(0)+e.3p(0),t[1]=e.3p(1)+e.3p(1),t[2]=e.3p(2)+e.3p(2)):(t[0]=e.4G(0,2),t[1]=e.4G(2,4),t[2]=e.4G(4));21(e=0;e<t.23;e++)t[e]=2P(t[e],16);1c C(t)},L=6i("[8A]","g");N={8B:k,2T:13(t,n){"5B"==e.1t(n)&&(n=1);1b r=n,i=k(t);1c i[3]=r,i.1K=r,"8C("+i.8D()+")"},8E:13(e){1b e=k(e),e=C(e),t=e.6L,n=e.6M,r=e.6N,i,s=t>n?t:n;r>s&&(s=r);1b o=t<n?t:n;r<o&&(o=r),i=s/8F,e=0!=s?(s-o)/s:0;1h(0==e)t=0;26{1b u=(s-t)/(s-o),a=(s-n)/(s-o),r=(s-r)/(s-o),t=(t==s?r-a:n==s?2+u-r:4+a-u)/6;0>t&&(t+=1)}1c t=1d.27(6O*t),e=1d.27(5F*e),i=1d.27(5F*i),n=[],n[0]=t,n[1]=e,n[2]=i,n.8G=t,n.8H=e,n.8I=i,"#"+(50<n[2]?"4o":"8J")}};1b A={4H:{},1v:13(t){1h(!t)1c 1C;1b n=1C;1c(t=e(t).20("2o-1R"))&&(n=12.4H[t]),n},30:13(e){12.4H[e.1R]=e},1D:13(e){1h(e=12.1v(e))4b 12.4H[e.1R],e.1D()}};e.1m(u.3z,{4I:13(){1b e=12.2c();12.3a=e.1r.3a,e=e.1a,12.1p=e.1p&&e.1p.2y||0,12.1l=e.1l&&e.1l.2y||0,12.2m=e.2m,e=1d.5G(12.3a.19,12.3a.14),12.1p>e/2&&(12.1p=1d.5H(e/2)),"1l"==12.1a.1p.1e&&12.1p>12.1l&&(12.1l=12.1p),12.1r={1a:{1p:12.1p,1l:12.1l,2m:12.2m}}},6P:13(){12.1r.1s={};1b t=12.22;e.1z(x.3Z,e.1w(13(t,n){1b r,i=12.1r.1s[n]={};12.22=n,r=12.2n(),i.2l=r.2l,i.1H={1g:r.1H.1g,1e:{17:r.1H.1e.17,15:r.1H.1e.15}},i.1x={1g:r.2a.1g};1h(12.1u){r=12.1u.2n();1b s=r.2a.1e,o=i.1H.1e;e.1m(!0,i,{2l:r.2l,1H:{1e:{17:o.17+s.17,15:o.15+s.15}},1x:{1g:r.1x.1g}})}},12)),12.22=t},1O:13(){12.37(),1S.3W&&1S.3W.8K(1y);1b n=12.2c(),r=12.1a;12.1H=e("<2g>").1Y("8L")[0],e(n.4J).1Z(12.1H),12.4I(),12.6Q(n),r.1A&&(12.6R(n),r.1A.1u&&(12.2W?(12.2W.1a=r.1A.1u,12.2W.1O()):12.2W=3n f(12.1j,e.1m({2L:12.2u},r.1A.1u)))),t&&7>t&&e(n.1k).5I(12.2X=e("<8M>").1Y("8N").2F({8O:0,4c:"8P:\'\';"})),12.4K(),r.1u&&(12.1u?(12.1u.1a=r.1u,12.1u.1O()):12.1u=3n a(12.1j,12,e.1m({2L:12.2u},r.1u))),12.6P()},1D:13(){12.37(),12.1a.1u&&(O.1D(12.1j),12.1a.1A&&12.1a.1A.1u&&M.1D(12.1j)),12.2X&&(12.2X.1D(),12.2X=1C),12.1k&&(e(12.1k).1D(),12.1k=1C)},37:13(){12.1H&&(12.1A&&(e(12.1A).1D(),12.5J=12.5K=12.1A=1C),e(12.1H).1D(),12.1H=12.1n=12.1o=1C,12.1r={})},2c:13(){1c I.1v(12.1j)[0]},2Q:13(){1b t=12.2c(),n=e(t.1k),r=e(t.1k).5L(".6S").6T()[0];1h(r){e(r).1q({14:"5M",19:"5M"});1b i=2P(n.1q("17")),s=2P(n.1q("15")),o=2P(n.1q("14"));n.1q({15:"-6U",17:"-6U",14:"8Q",19:"5M"}),t.1I("1M")||e(t.1k).1T();1b u=I.4L.5N(r);t.1a.3g&&"2x"==e.1t(t.1a.3g)&&u.14>t.1a.3g&&(e(r).1q({14:t.1a.3g+"2t"}),u=I.4L.5N(r)),t.1I("1M")||e(t.1k).1J(),t.1r.3a=u,n.1q({15:s+"2t",17:i+"2t",14:o+"2t"}),12.1O()}},4d:13(e){12.22!=e&&(12.22=e,12.1O())},6R:13(t){1b n=t.1a.1A,n={14:n.3r+2*n.1l,19:n.3r+2*n.1l};e(t.1k).1Z(e(12.1A=1y.24("2g")).1Y("6V").1q(i(n)).1Z(e(12.6W=1y.24("2g")).1Y("8R").1q(i(n)))),12.5O(t,"5P"),12.5O(t,"5Q"),1V.33.4A||e(12.1A).3M("4e",e.1w(12.6X,12)).3M("4M",e.1w(12.6Y,12))},5O:13(t,n){1b r=t.1a.1A,s=r.3r,u=r.1l||0,a=r.x.3r,f=r.x.2y,l=r.2p[n||"5P"],c={14:s+2*u,19:s+2*u};a>=s&&(a=s-2);1b h;e(12.6W).1Z(e(12[n+"6Z"]=1y.24("2g")).1Y("8S").1q(e.1m(i(c),{15:("5Q"==n?c.14:0)+"2t"}))),e(1y.3c).1Z(e(h=1y.24("3e")).2F(c)),E.3m(h),r=h.3A("2d"),r.2L=12.2u,e(12[n+"6Z"]).1Z(h),r.8T(c.14/2,c.19/2),r.2S=E.3Y(r,l.1n,{3C:0,3D:0-s/2,3E:0,3F:0+s/2}),r.2e(),r.29(0,0,s/2,0,2*1d.2Z,!0),r.2f(),r.35(),u&&(r.2S=E.3Y(r,l.1l,{3C:0,3D:0-s/2-u,3E:0,3F:0+s/2+u}),r.2e(),r.29(0,0,s/2,1d.2Z,0,!1),r.1f((s+u)/2,0),r.29(0,0,s/2+u,0,1d.2Z,!0),r.29(0,0,s/2+u,1d.2Z,0,!0),r.1f(s/2,0),r.29(0,0,s/2,0,1d.2Z,!1),r.2f(),r.35()),s=a/2,f/=2,f>s&&(u=f,f=s,s=u),r.2S=N.2T(l.x.1P||l.x,l.x.1K||1),r.4N(o(45)),r.2e(),r.3o(0,0),r.1f(0,s);21(l=0;4>l;l++)r.1f(0,s),r.1f(f,s),r.1f(f,s-(s-f)),r.1f(s,f),r.1f(s,0),r.4N(o(90));r.2f(),r.35()},6Q:13(t){1b n=12.2n(),r=12.1a.1o&&12.4f(),i=12.22&&12.22.3q(),s=12.1p,o=12.1l,t=t.1a.1o&&t.1a.1o.1F||{x:0,y:0},u=0,a=0;s&&(u="1n"==12.1a.1p.1e?s:0,a="1l"==12.1a.1p.1e?s:u+o),e(1y.3c).1Z(12.38=1y.24("3e")),e(12.38).2F(n.1H.1g),E.3m(12.38),s=12.38.3A("2d"),s.2L=12.2u,e(12.1H).1Z(12.38),s.2S=E.3Y(s,12.1a.1n,{3C:0,3D:n.1n.1e.17+o,3E:0,3F:n.1n.1e.17+n.1n.1g.19-o}),s.8U=0,12.5R(s,{2e:!0,2f:!0,1l:o,1p:u,4O:a,3s:n,3t:r,1o:12.1a.1o,3u:i,3v:t}),s.35();1h(o){1b f=E.3Y(s,12.1a.1l,{3C:0,3D:n.1n.1e.17,3E:0,3F:n.1n.1e.17+n.1n.1g.19});s.2S=f,12.5R(s,{2e:!0,2f:!1,1l:o,1p:u,4O:a,3s:n,3t:r,1o:12.1a.1o,3u:i,3v:t}),12.70(s,{2e:!1,2f:!0,1l:o,71:u,1p:{2y:a,1e:12.1a.1p.1e},3s:n,3t:r,1o:12.1a.1o,3u:i,3v:t}),s.35()}},5R:13(t,n){1b r=e.1m({1o:!1,3u:1C,2e:!1,2f:!1,3s:1C,3t:1C,1p:0,1l:0,4O:0,3v:{x:0,y:0}},n||{}),i=r.3s,s=r.3t,u=r.3v,a=r.1l,f=r.1p,l=r.3u,c=i.1n.1e,i=i.1n.1g,h,p,d;s&&(h=s.1o.1g,p=s.3f.1g,d=r.4O,s=a+f+.5*h.14-.5*s.1l.1g.14,d=1d.1G(d>s?d-s:0));1b v,s=f?c.15+a+f:c.15+a;v=c.17+a,u&&u.x&&/^(3G|3J)$/.4P(l)&&(s+=u.x),r.2e&&t.2e(),t.3o(s,v);1h(r.1o)1Q(l){1i"3G":s=c.15+a,f&&(s+=f),s+=1d.1N(d,u.x||0),t.1f(s,v),v-=h.19,s+=.5*h.14,t.1f(s,v),v+=h.19,s+=.5*h.14,t.1f(s,v);1B;1i"40":1i"4Q":s=c.15+.5*i.14-.5*h.14,t.1f(s,v),v-=h.19,s+=.5*h.14,t.1f(s,v),v+=h.19,s+=.5*h.14,t.1f(s,v),s=c.15+.5*i.14-.5*p.14,t.1f(s,v);1B;1i"3H":s=c.15+i.14-a-h.14,f&&(s-=f),s-=1d.1N(d,u.x||0),t.1f(s,v),v-=h.19,s+=.5*h.14,t.1f(s,v),v+=h.19,s+=.5*h.14,t.1f(s,v)}f?f&&(t.29(c.15+i.14-a-f,c.17+a+f,f,o(-90),o(0),!1),s=c.15+i.14-a,v=c.17+a+f):(s=c.15+i.14-a,v=c.17+a,t.1f(s,v));1h(r.1o)1Q(l){1i"3I":v=c.17+a,f&&(v+=f),v+=1d.1N(d,u.y||0),t.1f(s,v),s+=h.19,v+=.5*h.14,t.1f(s,v),s-=h.19,v+=.5*h.14,t.1f(s,v);1B;1i"41":1i"4R":v=c.17+.5*i.19-.5*h.14,t.1f(s,v),s+=h.19,v+=.5*h.14,t.1f(s,v),s-=h.19,v+=.5*h.14,t.1f(s,v);1B;1i"42":v=c.17+i.19-a,f&&(v-=f),v-=h.14,v-=1d.1N(d,u.y||0),t.1f(s,v),s+=h.19,v+=.5*h.14,t.1f(s,v),s-=h.19,v+=.5*h.14,t.1f(s,v)}f?f&&(t.29(c.15+i.14-a-f,c.17+i.19-a-f,f,o(0),o(90),!1),s=c.15+i.14-a-f,v=c.17+i.19-a):(s=c.15+i.14-a,v=c.17+i.19-a,t.1f(s,v));1h(r.1o)1Q(l){1i"43":s=c.15+i.14-a,f&&(s-=f),s-=1d.1N(d,u.x||0),t.1f(s,v),s-=.5*h.14,v+=h.19,t.1f(s,v),s-=.5*h.14,v-=h.19,t.1f(s,v);1B;1i"44":1i"4S":s=c.15+.5*i.14+.5*h.14,t.1f(s,v),s-=.5*h.14,v+=h.19,t.1f(s,v),s-=.5*h.14,v-=h.19,t.1f(s,v);1B;1i"46":s=c.15+a+h.14,f&&(s+=f),s+=1d.1N(d,u.x||0),t.1f(s,v),s-=.5*h.14,v+=h.19,t.1f(s,v),s-=.5*h.14,v-=h.19,t.1f(s,v)}f?f&&(t.29(c.15+a+f,c.17+i.19-a-f,f,o(90),o(2C),!1),s=c.15+a,v=c.17+i.19-a-f):(s=c.15+a,v=c.17+i.19-a,t.1f(s,v));1h(r.1o)1Q(l){1i"47":v=c.17+i.19-a,f&&(v-=f),v-=1d.1N(d,u.y||0),t.1f(s,v),s-=h.19,v-=.5*h.14,t.1f(s,v),s+=h.19,v-=.5*h.14,t.1f(s,v);1B;1i"48":1i"4T":v=c.17+.5*i.19+.5*h.14,t.1f(s,v),s-=h.19,v-=.5*h.14,t.1f(s,v),s+=h.19,v-=.5*h.14,t.1f(s,v);1B;1i"3J":v=c.17+a+h.14,f&&(v+=f),v+=1d.1N(d,u.y||0),t.1f(s,v),s-=h.19,v-=.5*h.14,t.1f(s,v),s+=h.19,v-=.5*h.14,t.1f(s,v)}1c f?f&&(t.29(c.15+a+f,c.17+a+f,f,o(-2C),o(-90),!1),s=c.15+a+f,v=c.17+a,s+=1,t.1f(s,v)):(s=c.15+a,v=c.17+a,t.1f(s,v)),r.2f&&t.2f(),{x:s,y:v}},70:13(t,n){1b r=e.1m({1o:!1,3u:1C,2e:!1,2f:!1,3s:1C,3t:1C,1p:0,1l:0,8V:0,3v:{x:0,y:0}},n||{}),i=r.3s,s=r.3t,u=r.3v,a=r.1l,f=r.1p&&r.1p.2y||0,l=r.71,c=r.3u,h=i.1n.1e,i=i.1n.1g,p,d,v;s&&(p=s.1o.1g,d=s.1l.1g,v=a+l+.5*p.14-.5*d.14,v=1d.1G(f>v?f-v:0));1b s=h.15+a+l,m=h.17+a;l&&(s+=1),e.1m({},{x:s,y:m}),r.2e&&t.2e();1b g=e.1m({},{x:s,y:m}),m=m-a;t.1f(s,m),f?f&&(t.29(h.15+f,h.17+f,f,o(-90),o(-2C),!0),s=h.15,m=h.17+f):(s=h.15,m=h.17,t.1f(s,m));1h(r.1o)1Q(c){1i"3J":m=h.17+a,l&&(m+=l),m-=.5*d.14,m+=.5*p.14,m+=1d.1N(v,u.y||0),t.1f(s,m),s-=d.19,m+=.5*d.14,t.1f(s,m),s+=d.19,m+=.5*d.14,t.1f(s,m);1B;1i"48":1i"4T":m=h.17+.5*i.19-.5*d.14,t.1f(s,m),s-=d.19,m+=.5*d.14,t.1f(s,m),s+=d.19,m+=.5*d.14,t.1f(s,m);1B;1i"47":m=h.17+i.19-a-d.14,l&&(m-=l),m+=.5*d.14,m-=.5*p.14,m-=1d.1N(v,u.y||0),t.1f(s,m),s-=d.19,m+=.5*d.14,t.1f(s,m),s+=d.19,m+=.5*d.14,t.1f(s,m)}f?f&&(t.29(h.15+f,h.17+i.19-f,f,o(-2C),o(-8W),!0),s=h.15+f,m=h.17+i.19):(s=h.15,m=h.17+i.19,t.1f(s,m));1h(r.1o)1Q(c){1i"46":s=h.15+a,l&&(s+=l),s-=.5*d.14,s+=.5*p.14,s+=1d.1N(v,u.x||0),t.1f(s,m),m+=d.19,s+=.5*d.14,t.1f(s,m),m-=d.19,s+=.5*d.14,t.1f(s,m);1B;1i"44":1i"4S":s=h.15+.5*i.14-.5*d.14,t.1f(s,m),m+=d.19,s+=.5*d.14,t.1f(s,m),m-=d.19,s+=.5*d.14,t.1f(s,m),s=h.15+.5*i.14+d.14,t.1f(s,m);1B;1i"43":s=h.15+i.14-a-d.14,l&&(s-=l),s+=.5*d.14,s-=.5*p.14,s-=1d.1N(v,u.x||0),t.1f(s,m),m+=d.19,s+=.5*d.14,t.1f(s,m),m-=d.19,s+=.5*d.14,t.1f(s,m)}f?f&&(t.29(h.15+i.14-f,h.17+i.19-f,f,o(90),o(0),!0),s=h.15+i.14,m=h.17+i.14+f):(s=h.15+i.14,m=h.17+i.19,t.1f(s,m));1h(r.1o)1Q(c){1i"42":m=h.17+i.19-a,m+=.5*d.14,m-=.5*p.14,l&&(m-=l),m-=1d.1N(v,u.y||0),t.1f(s,m),s+=d.19,m-=.5*d.14,t.1f(s,m),s-=d.19,m-=.5*d.14,t.1f(s,m);1B;1i"41":1i"4R":m=h.17+.5*i.19+.5*d.14,t.1f(s,m),s+=d.19,m-=.5*d.14,t.1f(s,m),s-=d.19,m-=.5*d.14,t.1f(s,m);1B;1i"3I":m=h.17+a,l&&(m+=l),m+=d.14,m-=.5*d.14-.5*p.14,m+=1d.1N(v,u.y||0),t.1f(s,m),s+=d.19,m-=.5*d.14,t.1f(s,m),s-=d.19,m-=.5*d.14,t.1f(s,m)}f?f&&(t.29(h.15+i.14-f,h.17+f,f,o(0),o(-90),!0),m=h.17):(s=h.15+i.14,m=h.17,t.1f(s,m));1h(r.1o)1Q(c){1i"3H":s=h.15+i.14-a,s+=.5*d.14-.5*p.14,l&&(s-=l),s-=1d.1N(v,u.x||0),t.1f(s,m),m-=d.19,s-=.5*d.14,t.1f(s,m),m+=d.19,s-=.5*d.14,t.1f(s,m);1B;1i"40":1i"4Q":s=h.15+.5*i.14+.5*d.14,t.1f(s,m),m-=d.19,s-=.5*d.14,t.1f(s,m),m+=d.19,s-=.5*d.14,t.1f(s,m),s=h.15+.5*i.14-d.14,t.1f(s,m),t.1f(s,m);1B;1i"3G":s=h.15+a+d.14,s-=.5*d.14,s+=.5*p.14,l&&(s+=l),s+=1d.1N(v,u.x||0),t.1f(s,m),m-=d.19,s-=.5*d.14,t.1f(s,m),m+=d.19,s-=.5*d.14,t.1f(s,m)}t.1f(g.x,g.y-a),t.1f(g.x,g.y),r.2f&&t.2f()},6X:13(){1b t=12.2c().1a.1A,t=t.3r+2*t.1l;e(12.5K).1q({15:-1*t+"2t"}),e(12.5J).1q({15:0})},6Y:13(){1b t=12.2c().1a.1A,t=t.3r+2*t.1l;e(12.5K).1q({15:0}),e(12.5J).1q({15:t+"2t"})},4f:13(){1c T.3L(12,12.1l)},2n:13(){1b e,t,n,r,i,s,u=12.2c(),a=12.3a,f=u.1a,l=12.1p,c=12.1l,u=12.2m,a={14:2*c+2*u+a.14,19:2*c+2*u+a.19};12.1a.1o&&12.4f();1b h=T.5E(12,a),u=h.1g,p=h.1e,a=h.1n.1g,d=h.1n.1e,v=0,m=0,g=u.14,y=u.19;1c f.1A&&(i=l,"1n"==f.1p.1e&&(i+=c),v=i-1d.8X(o(45))*i,c="1X",12.22.3q().3d(/^(3H|3I)$/)&&(c="15"),s=i=f=f.1A.3r+2*f.1A.1l,m=d.15-f/2+("15"==c?v:a.14-v),v=d.17-f/2+v,"15"==c?0>m&&(f=1d.2z(m),g+=f,p.15+=f,m=0):(f=m+f-g,0<f&&(g+=f)),0>v&&(f=1d.2z(v),y+=f,p.17+=f,v=0),12.1a.1A.1u)&&(e=12.1a.1A.1u,t=e.31,f=e.1F,n=i+2*t,r=s+2*t,e=v-t+f.y,t=m-t+f.x,"15"==c?0>t&&(f=1d.2z(t),g+=f,p.15+=f,m+=f,t=0):(f=t+n-g,0<f&&(g+=f)),0>e)&&(f=1d.2z(e),y+=f,p.17+=f,v+=f,e=0),h=h.2l,h.17+=p.17,h.15+=p.15,c={15:1d.1G(p.15+d.15+12.1l+12.1a.2m),17:1d.1G(p.17+d.17+12.1l+12.1a.2m)},a={1x:{1g:{14:1d.1G(g),19:1d.1G(y)}},2a:{1g:{14:1d.1G(g),19:1d.1G(y)}},1H:{1g:u,1e:{17:1d.27(p.17),15:1d.27(p.15)}},1n:{1g:{14:1d.1G(a.14),19:1d.1G(a.19)},1e:{17:1d.27(d.17),15:1d.27(d.15)}},2l:{17:1d.27(h.17),15:1d.27(h.15)},2M:{1e:c}},12.1a.1A&&(a.1A={1g:{14:1d.1G(i),19:1d.1G(s)},1e:{17:1d.27(v),15:1d.27(m)}},12.1a.1A.1u&&(a.2W={1g:{14:1d.1G(n),19:1d.1G(r)},1e:{17:1d.27(e),15:1d.27(t)}})),a},4K:13(){1b t=12.2n(),n=12.2c();e(n.1k).1q(i(t.1x.1g)),e(n.4J).1q(i(t.2a.1g)),12.2X&&12.2X.1q(i(t.1x.1g)),e(12.1H).1q(e.1m(i(t.1H.1g),i(t.1H.1e))),12.1A&&(e(12.1A).1q(i(t.1A.1e)),t.2W&&e(12.2W.1k).1q(i(t.2W.1e))),e(n.3h).1q(i(t.2M.1e))},72:13(e){12.2u=e||0,12.1u&&(12.1u.2u=12.2u)},8Y:13(e){12.72(e),12.1O()}});1b O={3i:{},1v:13(t){1h(!t)1c 1C;1b n=1C;1c(t=e(t).20("2o-1R"))&&(n=12.3i[t]),n},30:13(e){12.3i[e.1R]=e},1D:13(e){1h(e=12.1v(e))4b 12.3i[e.1R],e.1D()},4g:13(e){1c 1d.2Z/2-1d.4z(e,1d.4F(e)*1d.2Z)},4h:{4a:13(e,t){1b n=A.1v(e.1j).4f().1l.1g,n=12.4E(n.14,n.19,t,{3K:!1});1c{14:n.14,19:n.19}},8Z:13(e,t,n){1b r=.5*e,i=2C-s(1d.91(r/1d.73(r*r+t*t)))-90,i=o(i),n=1/1d.4F(i)*n,r=2*(r+n);1c{14:r,19:r/e*t}},4E:13(e,t,n){1b r=2C-s(1d.6K(.5*(t/e))),n=1d.4F(o(r-90))*n,n=e+2*n;1c{14:n,19:n*t/e}},3L:13(t){1b n=A.1v(t.1j),r=t.1a.31,i=x.6J(n.22);x.2D(n.22),n=O.4h.4a(t,r),n={3f:{1g:{14:1d.1G(n.14),19:1d.1G(n.19)},1e:{17:0,15:0}}};1h(r){n.2Y=[];21(1b s=0;s<=r;s++){1b o=O.4h.4a(t,s,{3K:!1});n.2Y.2R({1e:{17:n.3f.1g.19-o.19,15:i?r-s:(n.3f.1g.14-o.14)/2},1g:o})}}26 n.2Y=[e.1m({},n.3f)];1c n},4N:13(e,t,n){T.4N(e,t.3j(),n)}}};e.1m(a.3z,{4I:13(){},1D:13(){12.37()},37:13(){12.1k&&(e(12.1k).1D(),12.1k=12.1H=12.1n=12.1o=1C,12.1r={})},1O:13(){12.37(),12.4I();1b t=12.2c(),n=12.3j();12.1k=e("<2g>").1Y("92")[0],e(t.1k).5I(12.1k),n.2X&&e(t.1k).5I(n.2X),n.2n(),e(12.1k).1q({17:0,15:0}),12.74(),12.4K()},2c:13(){1c I.1v(12.1j)[0]},3j:13(){1c A.1v(12.1j)},2n:13(){1b t=12.3j(),n=t.2n();12.2c();1b r=12.1a.31,i=e.1m({},n.1n.1g);i.14+=2*r,i.19+=2*r;1b s;t.1a.1o&&(s=O.4h.3L(12).3f.1g,s=s.19);1b o=T.5E(t,i,s);s=o.1g;1b u=o.1e,i=o.1n.1g,o=o.1n.1e,a=n.1H.1e,f=n.1n.1e,r={17:a.17+f.17-(o.17+r)+12.1a.1F.y,15:a.15+f.15-(o.15+r)+12.1a.1F.x},a=n.2l,f=n.2a.1g,l={17:0,15:0};1h(0>r.17){1b c=1d.2z(r.17);l.17+=c,r.17=0,a.17+=c}1c 0>r.15&&(c=1d.2z(r.15),l.15+=c,r.15=0,a.15+=c),c={19:1d.1N(s.19+r.17,f.19+l.17),14:1d.1N(s.14+r.15,f.14+l.15)},t={15:1d.1G(l.15+n.1H.1e.15+n.1n.1e.15+t.1l+t.2m),17:1d.1G(l.17+n.1H.1e.17+n.1n.1e.17+t.1l+t.2m)},{1x:{1g:c},2a:{1g:f,1e:l},1k:{1g:s,1e:r},1H:{1g:s,1e:{17:1d.27(u.17),15:1d.27(u.15)}},1n:{1g:{14:1d.1G(i.14),19:1d.1G(i.19)},1e:{17:1d.27(o.17),15:1d.27(o.15)}},2l:a,2M:{1e:t}}},75:13(){1c 12.1a.1K/(12.1a.31+1)},74:13(){1b t=12.3j(),n=t.2n(),r=12.2c(),s=12.2n(),o=12.1a.31,u=O.4h.3L(12),a=t.22,f=x.5C(a),l=o,c=o;1h(r.1a.1o){1b h=u.2Y[u.2Y.23-1];"15"==f&&(c+=1d.1G(h.1g.19)),"17"==f&&(l+=1d.1G(h.1g.19))}1b p=t.1r.1a,h=p.1p,p=p.1l;"1n"==r.1a.1p.1e&&h&&(h+=p),r=s.1H.1g,e(12.1k).1Z(e(12.1H=1y.24("2g")).1Y("93").1q(i(r))).1q(i(r)),e(1y.3c).1Z(e(12.38=1y.24("3e")).2F(s.1H.1g)),E.3m(12.38),s=12.38.3A("2d"),s.2L=12.2u,e(12.1H).1Z(12.38);21(1b r=o+1,d=0;d<=o;d++)s.2S=N.2T(12.1a.1P,O.4g(d*(1/r))*(12.1a.1K/r)),E.6B(s,{14:n.1n.1g.14+2*d,19:n.1n.1g.19+2*d,17:l-d,15:c-d,1p:h+d});1h(t.1a.1o){1b d=u.2Y[0].1g,v=t.1a.1o,o=p+.5*v.14,m=t.1a.1p&&"1n"==t.1a.1p.1e?t.1a.1p.2y||0:0;m&&(o+=m),p=p+m+.5*v.14-.5*d.14,h=1d.1G(h>p?h-p:0),o+=1d.1N(h,t.1a.1o.1F&&t.1a.1o.1F[f&&/^(15|1X)$/.4P(f)?"y":"x"]||0);1h("17"==f||"1W"==f){1Q(a){1i"3G":1i"46":c+=o;1B;1i"40":1i"4Q":1i"44":1i"4S":c+=.5*n.1n.1g.14;1B;1i"3H":1i"43":c+=n.1n.1g.14-o}"1W"==f&&(l+=n.1n.1g.19),d=0;21(t=u.2Y.23;d<t;d++)s.2S=N.2T(12.1a.1P,O.4g(d*(1/r))*(12.1a.1K/r)),o=u.2Y[d],s.2e(),"17"==f?(s.3o(c,l-d),s.1f(c-.5*o.1g.14,l-d),s.1f(c,l-d-o.1g.19),s.1f(c+.5*o.1g.14,l-d)):(s.3o(c,l+d),s.1f(c-.5*o.1g.14,l+d),s.1f(c,l+d+o.1g.19),s.1f(c+.5*o.1g.14,l+d)),s.2f(),s.35()}26{1Q(a){1i"3J":1i"3I":l+=o;1B;1i"48":1i"4T":1i"41":1i"4R":l+=.5*n.1n.1g.19;1B;1i"47":1i"42":l+=n.1n.1g.19-o}"1X"==f&&(c+=n.1n.1g.14),d=0;21(t=u.2Y.23;d<t;d++)s.2S=N.2T(12.1a.1P,O.4g(d*(1/r))*(12.1a.1K/r)),o=u.2Y[d],s.2e(),"15"==f?(s.3o(c-d,l),s.1f(c-d,l-.5*o.1g.14),s.1f(c-d-o.1g.19,l),s.1f(c-d,l+.5*o.1g.14)):(s.3o(c+d,l),s.1f(c+d,l-.5*o.1g.14),s.1f(c+d+o.1g.19,l),s.1f(c+d,l+.5*o.1g.14)),s.2f(),s.35()}}},4K:13(){1b t=12.2n(),n=12.3j(),r=12.2c();e(r.1k).1q(i(t.1x.1g)),e(r.4J).1q(e.1m(i(t.2a.1e),i(t.2a.1g))),n.2X&&n.2X.1q(i(t.1x.1g));1h(r.1a.1A){1b s=n.2n(),o=t.2a.1e,u=s.1A.1e;e(n.1A).1q(i({17:o.17+u.17,15:o.15+u.15})),r.1a.1A.1u&&(s=s.2W.1e,e(n.2W.1k).1q(i({17:o.17+s.17,15:o.15+s.15})))}e(12.1k).1q(e.1m(i(t.1k.1g),i(t.1k.1e))),e(12.1H).1q(i(t.1H.1g)),e(r.3h).1q(i(t.2M.1e))}});1b M={3i:{},1v:13(t){1c t?(t=e(t).20("2o-1R"))?12.3i[t]:1C:1C},30:13(e){12.3i[e.1R]=e},1D:13(e){1h(e=12.1v(e))4b 12.3i[e.1R],e.1D()}};e.1m(f.3z,{1O:13(){12.37(),12.2c();1b t=12.3j(),n=t.2n().1A.1g,r=e.1m({},n),i=12.1a.31;r.14+=2*i,r.19+=2*i,e(t.1A).5S(e(12.1k=1y.24("2g")).1Y("94")),e(1y.3c).1Z(e(12.4U=1y.24("3e")).2F(r)),E.3m(12.4U),t=12.4U.3A("2d"),t.2L=12.2u,e(12.1k).1Z(12.4U);21(1b s=r.14/2,r=r.19/2,n=n.19/2,u=i+1,a=0;a<=i;a++)t.2S=N.2T(12.1a.1P,O.4g(a*(1/u))*(12.1a.1K/u)),t.2e(),t.29(s,r,n+a,o(0),o(6O),!0),t.2f(),t.35()},1D:13(){12.37()},37:13(){12.1k&&(e(12.1k).1D(),12.1k=1C)},2c:13(){1c I.1v(12.1j)[0]},3j:13(){1c A.1v(12.1j)},75:13(){1c 12.1a.1K/(12.1a.31+1)}});1b 5T=13(t){1c"2q"==e.1t(t)?{1j:B.28&&B.28.1j||H.28.1j,2r:t}:l(e.1m({},H.28),t)},D=13(t){1c H=1V.2G.76,B=l(e.1m({},H),1V.2G.5U),j=1V.2G.5V.76,F=l(e.1m({},j),1V.2G.5V.5U),D=P,P(t)},P=13(t){t.2a=t.2a||(1V.2G[I.1a.3N]?I.1a.3N:"5W");1b n=t.2a?e.1m({},1V.2G[t.2a]||1V.2G[I.1a.3N]):{},n=l(e.1m({},B),n),n=l(e.1m({},n),t);1h(n.2h){1b r=B.2h||{},i=H.2h;"4i"==e.1t(n.2h)&&(n.2h={4j:r.4j||i.4j,1t:r.1t||i.1t}),n.2h=l(e.1m({},i),n.2h)}n.1n&&"2q"==e.1t(n.1n)&&(n.1n={1P:n.1n,1K:1}),n.1l&&(r=B.1l||{},i=H.1l,r="2x"==e.1t(n.1l)?{2y:n.1l,1P:r.1P||i.1P,1K:r.1K||i.1K}:l(e.1m({},i),n.1l),n.1l=0===r.2y?!1:r),n.1p&&(r="2x"==e.1t(n.1p)?{2y:n.1p,1e:B.1p&&B.1p.1e||H.1p.1e}:l(e.1m({},H.1p),n.1p),n.1p=0===r.2y?!1:r),r=r=n.1s&&n.1s.1E||"2q"==e.1t(n.1s)&&n.1s||B.1s&&B.1s.1E||"2q"==e.1t(B.1s)&&B.1s||H.1s&&H.1s.1E||H.1s,i=n.1s&&n.1s.1x||B.1s&&B.1s.1x||H.1s&&H.1s.1x||I.2w.77(r);1h(n.1s){1h("2q"==e.1t(n.1s))r={1E:n.1s,1x:I.2w.78(n.1s)};26 1h(r={1x:i,1E:r},n.1s.1x&&(r.1x=n.1s.1x),n.1s.1E)r.1E=n.1s.1E}26 r={1x:i,1E:r};n.1s=r,"2N"==n.1E?(i=e.1m({},H.1F.2N),e.1m(i,1V.2G.5U.1F||{}),t.2a&&e.1m(i,(1V.2G[t.2a]||1V.2G[I.1a.3N]).1F||{}),i=I.2w.79(H.1F.2N,H.1s,r.1E),t.1F&&(i=e.1m(i,t.1F||{})),n.3O=0):i={x:n.1F.x,y:n.1F.y},n.1F=i;1h(n.1A&&n.7a){1b t=e.1m({},1V.2G.5V[n.7a]),s=l(e.1m({},F),t);s.2p&&e.1z(["5P","5Q"],13(t,n){1b r=s.2p[n],i=F.2p&&F.2p[n];1h(r.1n){1b o=i&&i.1n;e.1t(r.1n)=="2x"?r.1n={1P:o&&o.1P||j.2p[n].1n.1P,1K:r.1n}:e.1t(r.1n)=="2q"?(o=o&&e.1t(o.1K)=="2x"&&o.1K||j.2p[n].1n.1K,r.1n={1P:r.1n,1K:o}):r.1n=l(e.1m({},j.2p[n].1n),r.1n)}r.1l&&(i=i&&i.1l,r.1l=e.1t(r.1l)=="2x"?{1P:i&&i.1P||j.2p[n].1l.1P,1K:r.1l}:l(e.1m({},j.2p[n].1l),r.1l))}),s.1u&&(t=F.1u&&F.1u.3x&&F.1u.3x==5h?F.1u:j.1u,s.1u.3x&&s.1u.3x==5h&&(t=l(t,s.1u)),s.1u=t),n.1A=s}n.1u&&(t="4i"==e.1t(n.1u)?B.1u&&"4i"==e.1t(B.1u)?H.1u:B.1u?B.1u:H.1u:l(e.1m({},H.1u),n.1u||{}),"2x"==e.1t(t.1F)&&(t.1F={x:t.1F,y:t.1F}),n.1u=t),n.1o&&(t={},t="4i"==e.1t(n.1o)?l({},H.1o):l(l({},H.1o),e.1m({},n.1o)),"2x"==e.1t(t.1F)&&(t.1F={x:t.1F,y:t.1F}),n.1o=t),n.2s&&("2q"==e.1t(n.2s)?n.2s={4V:n.2s,7b:!0}:"4i"==e.1t(n.2s)&&(n.2s=n.2s?{4V:"7c",7b:!0}:!1)),n.28&&"2A-95"==n.28&&(n.7d=!0,n.28=!1);1h(n.28)1h(e.6D(n.28)){1b o=[];e.1z(n.28,13(e,t){o.2R(5T(t))}),n.28=o}26 n.28=[5T(n.28)];1c n.2H&&"2q"==e.1t(n.2H)&&(n.2H=[""+n.2H]),n.2m=0,n.1L&&!1S.5X&&(n.1L=!1),n},H,B,j,F,I={2I:{},1a:{3N:"5W",4p:96},6z:13(){1b t=["2A"];1V.33.4A&&(t.2R("97"),e(1y.3c).3M("2A",13(){})),e.1z(t,13(t,n){e(1y.7e).98(".3w .6V, .3w .99-1x",n,13(t){t.9a(),t.9b(),I.5Y(e(t.1E).4W(".3w")[0]).1J()})}),e(1S).3M("9c",e.1w(12.7f,12))},7f:13(){12.4X&&(1S.5Z(12.4X),12.4X=1C),12.4X=p.4t(e.1w(13(){1b t=12.3B();e.1z(t,13(e,t){t.1e()})},12),9d)},4Y:13(t){1b n=e(t).20("2o-1R"),r;n||(t=12.5Y(e(t).4W(".3w")[0]))&&t.1j&&(n=e(t.1j).20("2o-1R"));1h(n&&(r=12.2I[n]))1c r},5x:13(e){1b t;1c p.2k(e)&&(t=12.4Y(e)),t&&t.1j},1v:13(t){1b n=[];1h(p.2k(t)){1b r=12.4Y(t);r&&(n=[r])}26 e.1z(12.2I,13(r,i){i.1j&&e(i.1j).7g(t)&&n.2R(i)});1c n},5Y:13(t){1h(!t)1c 1C;1b n=1C;1c e.1z(12.2I,13(e,r){r.1I("1O")&&r.1k===t&&(n=r)}),n},9e:13(t){1b n=[];1c e.1z(12.2I,13(r,i){i.1j&&e(i.1j).7g(t)&&n.2R(i)}),n},1T:13(t){p.2k(t)?(t=12.1v(t)[0])&&t.1T():e(t).1z(e.1w(13(e,t){1b n=12.1v(t)[0];n&&n.1T()},12))},1J:13(t){p.2k(t)?(t=12.1v(t)[0])&&t.1J():e(t).1z(e.1w(13(e,t){1b n=12.1v(t)[0];n&&n.1J()},12))},34:13(t){p.2k(t)?(t=12.1v(t)[0])&&t.34():e(t).1z(e.1w(13(e,t){1b n=12.1v(t)[0];n&&n.34()},12))},4C:13(){e.1z(12.3B(),13(e,t){t.1J()})},2Q:13(t){p.2k(t)?(t=12.1v(t)[0])&&t.2Q():e(t).1z(e.1w(13(e,t){1b n=12.1v(t)[0];n&&n.2Q()},12))},3B:13(){1b t=[];1c e.1z(12.2I,13(e,n){n.1M()&&t.2R(n)}),t},5A:13(t){1b n=!1;1c p.2k(t)&&e.1z(12.3B()||[],13(e,r){1h(r.1j==t)1c n=!0,!1}),n},7h:13(){1b t=0,n;1c e.1z(12.2I,13(e,r){r.2j>t&&(t=r.2j,n=r)}),n},7i:13(){1>=12.3B().23&&e.1z(12.2I,13(t,n){n.1I("1O")&&!n.1a.2j&&e(n.1k).1q({2j:n.2j=+I.1a.4p})})},30:13(e){12.2I[e.1R]=e},4Z:13(t){1h(t=12.4Y(t)){1b n=e(t.1j).20("2o-1R");4b 12.2I[n],t.1J(),t.1D()}},1D:13(t){p.2k(t)?12.4Z(t):e(t).1z(e.1w(13(e,t){12.4Z(t)},12))},6A:13(){e.1z(12.2I,e.1w(13(e,t){t.1j&&!p.1j.5s(t.1j)&&12.4Z(t.1j)},12))},5y:13(e){12.1a.3N=e||"5W"},5z:13(e){12.1a.4p=e||0},6b:D},q=13(t,n){1b r=x.2O(t),i=r[1],r=r[2],s=x.2D(t),o=e.1m({1U:!0,2E:!0},n||{});1c"1U"==s?(o.2E&&(i=K[i]),o.1U&&(r=K[r])):(o.2E&&(r=K[r]),o.1U&&(i=K[i])),i+r},R=13(t,n){1h(t.1a.2s){1b r=n,i=J(t),s=i.1g,i=i.1e,o=A.1v(t.1j).1r.1s[r.1s.1x].1x.1g,u=r.1e;i.15>u.15&&(r.1e.15=i.15),i.17>u.17&&(r.1e.17=i.17),i.15+s.14<u.15+o.14&&(r.1e.15=i.15+s.14-o.14),i.17+s.19<u.17+o.19&&(r.1e.17=i.17+s.19-o.19),n=r}t.4d(n.1s.1x),r=n.1e,e(t.1k).1q({17:r.17+"2t",15:r.15+"2t"})},U=13(e){1c e&&(/^2N|2A|4A$/.4P("2q"==7j e.1t&&e.1t||"")||0<=e.5r)},z=13(e,t,n,r){1b i=e>=n&&e<=r,s=t>=n&&t<=r;1c i&&s?t-e:i&&!s?r-e:!i&&s?t-n:(i=n>=e&&n<=t,s=r>=e&&r<=t,i&&s?r-n:i&&!s?t-n:!i&&s?r-e:0)},W=13(e,t){1b n=e.1g.14*e.1g.19;1c n?z(e.1e.15,e.1e.15+e.1g.14,t.1e.15,t.1e.15+t.1g.14)*z(e.1e.17,e.1e.17+e.1g.19,t.1e.17,t.1e.17+t.1g.19)/n:0},X=13(e,t){1b n=x.2O(t),r={15:0,17:0};1h("1U"==x.2D(t)){1Q(n[2]){1i"2U":1i"2V":r.15=.5*e.14;1B;1i"1X":r.15=e.14}"1W"==n[1]&&(r.17=e.19)}26{1Q(n[2]){1i"2U":1i"2V":r.17=.5*e.19;1B;1i"1W":r.17=e.19}"1X"==n[1]&&(r.15=e.14)}1c r},V=13(t){1b n=p.1j.4y(t),t=p.1j.4u(t),r=e(1S).4v(),i=e(1S).4w();1c n.15+=-1*(t.15-i),n.17+=-1*(t.17-r),n},$=13(t,n,r,i){1b s,o,u=A.1v(t.1j),a=u.1a,f=a.1F,l=U(r);l||!r?(o={14:1,19:1},l?(s=p.5q(r),s={17:s.y,15:s.x}):(s=t.1r.2r,s={17:s?s.y:0,15:s?s.x:0}),t.1r.2r={x:s.15,y:s.17}):(s=V(r),o={14:e(r).7k(),19:e(r).7l()});1h(a.1o&&"2N"!=a.1E){1b r=x.2O(i),c=x.2O(n),h=x.2D(i),d=u.1r.1a,u=u.4f().1l.1g,v=d.1p,d=d.1l,m=v&&"1n"==a.1p.1e?v:0,v=v&&"1l"==a.1p.1e?v:v+d,u=d+m+.5*a.1o.14-.5*u.14;4k=1d.1G(d+m+.5*a.1o.14+(v>u?v-u:0)+a.1o.1F["1U"==h?"x":"y"]);1h("1U"==h&&"15"==r[2]&&"15"==c[2]||"1X"==r[2]&&"1X"==c[2])o.14-=2*4k,s.15+=4k;26 1h("2E"==h&&"17"==r[2]&&"17"==c[2]||"1W"==r[2]&&"1W"==c[2])o.19-=2*4k,s.17+=4k}r=e.1m({},s),a=l?q(a.1s.1x):a.1s.1E,X(o,a),l=X(o,i),s={15:s.15+l.15,17:s.17+l.17},f=e.1m({},f),f=Q(f,a,i),s.17+=f.y,s.15+=f.x,u=A.1v(t.1j),f=u.1r.1s,a=e.1m({},f[n]),s={17:s.17-a.2l.17,15:s.15-a.2l.15},a.1x.1e=s,a={1U:!0,2E:!0};1h(t.1a.2s){1h(l=J(t),t=(t.1a.1u?O.1v(t.1j):u).2n().1x.1g,a.2J=W({1g:t,1e:s},l),1>a.2J){1h(s.15<l.1e.15||s.15+t.14>l.1e.15+l.1g.14)a.1U=!1;1h(s.17<l.1e.17||s.17+t.19>l.1e.17+l.1g.19)a.2E=!1}}26 a.2J=1;1c t=f[n].1H,o=W({1g:o,1e:r},{1g:t.1g,1e:{17:s.17+t.1e.17,15:s.15+t.1e.15}}),{1e:s,2J:{1E:o},3P:a,1s:{1x:n,1E:i}}},J=13(t){1b n={17:e(1S).4v(),15:e(1S).4w()},r=t.1a,i=r.1E;1h("2N"==i||"4s"==i)i=t.1j;1c t=e(i).4W(r.2s.4V).6T()[0],!t||"7c"==r.2s.4V?{1g:{14:e(1S).14(),19:e(1S).19()},1e:n}:(r=p.1j.4y(t),i=p.1j.4u(t),r.15+=-1*(i.15-n.15),r.17+=-1*(i.17-n.17),{1g:{14:e(t).7m(),19:e(t).7n()},1e:r})},K={15:"1X",1X:"15",17:"1W",1W:"17",2U:"2U",2V:"2V"},Q,G=[[-1,-1],[0,-1],[1,-1],[-1,0],[0,0],[1,0],[-1,1],[0,1],[1,1]],Y={3J:0,3G:0,40:1,4Q:1,3H:2,3I:2,41:5,4R:5,42:8,43:8,44:7,4S:7,46:6,47:6,48:3,4T:3};Q=13(e,t,n){1b r=G[Y[t]],i=G[Y[n]],r=[1d.5H(.5*1d.2z(r[0]-i[0]))?-1:1,1d.5H(.5*1d.2z(r[1]-i[1]))?-1:1];1c!x.36(t)&&x.36(n)&&("1U"==x.2D(n)?r[0]=0:r[1]=0),{x:r[0]*e.x,y:r[1]*e.y}},I.2w={1v:$,7o:13(e,t,n,r){1b i=$(e,t,n,r);/9f$/.4P(n&&"2q"==7j n.1t?n.1t:"");1h(1===i.3P.2J)R(e,i);26{1b s=t,o=r,o={1U:!i.3P.1U,2E:!i.3P.2E};1h(!x.36(t))1c s=q(t,o),o=q(r,o),i=$(e,s,n,o),R(e,i),i;1h("1U"==x.2D(t)&&o.2E||"2E"==x.2D(t)&&o.1U)1h(s=q(t,o),o=q(r,o),i=$(e,s,n,o),1===i.3P.2J)1c R(e,i),i;t=[],r=x.3Z,s=0;21(o=r.23;s<o;s++)21(1b u=r[s],a=0,f=x.3Z.23;a<f;a++)t.2R($(e,x.3Z[a],n,u));21(1b n=i,l=A.1v(e.1j).1r.1s,s=l[n.1s.1x],r=0,c=n.1e.15+s.2l.15,h=n.1e.17+s.2l.17,p=0,d=1,v={1g:s.1x.1g,1e:n.1e},m=0,s=1,u=o=0,a=t.23;u<a;u++){f=t[u],f.2K={},f.2K.2s=f.3P.2J;1b g=l[f.1s.1x].2l,g=1d.73(1d.4z(1d.2z(f.1e.15+g.15-c),2)+1d.4z(1d.2z(f.1e.17+g.17-h),2)),r=1d.1N(r,g);f.2K.7p=g,g=f.2J.1E,d=1d.5G(d,g),p=1d.1N(p,g),f.2K.7q=g,g=W(v,{1g:l[f.1s.1x].1x.1g,1e:f.1e}),s=1d.5G(s,g),m=1d.1N(m,g),f.2K.7r=g,g="1U"==x.2D(n.1s.1E)?"17":"15",g=1d.2z(n.1e[g]-f.1e[g]),o=1d.1N(o,g),f.2K.7s=g}21(1b l=0,y,p=1d.1N(n.2J.1E-d,p-n.2J.1E),d=m-s,u=0,a=t.23;u<a;u++)f=t[u],m=51*f.2K.2s,m+=18*(1-f.2K.7p/r)||9,c=1d.2z(n.2J.1E-f.2K.7q)||0,m+=4*(1-(c/p||1)),m+=11*((f.2K.7r-s)/d||0),m+=x.36(f.1s.1x)?0:25*(1-f.2K.7s/(o||1)),l=1d.1N(l,m),m==l&&(y=u);R(e,t[y])}1c i},77:q,78:13(e){1c e=x.2O(e),q(e[1]+K[e[2]])},7t:V,79:Q,60:U},I.2w.4D={x:0,y:0},e(1y).6y(13(){1b t=I.2w;e(1y).3M("52",13(e){t.4D={x:e.5r,y:e.6h}})});1b Z=13(t){1c{14:e(t).7m(),19:e(t).7n()}},53=13(t){1b n=Z(t),r=t.4x;1c r&&e(r).1q({14:n.14+"2t"})&&Z(t).19>n.19&&n.14++,e(r).1q({14:"5F%"}),n};I.4L={1O:13(){e(1y.3c).1Z(e(1y.24("2g")).1Y("9g").1Z(e(1y.24("2g")).1Y("3w").1Z(e(12.1k=1y.24("2g")).1Y("7u"))))},3Q:13(t,n,r,i){12.1k||12.1O();1b s=t.1a,i=e.1m({1L:!1},i||{});(s.7v||p.2k(n))&&!e(n).20("7w")&&(s.7v&&"2q"==e.1t(n)&&(t.39=e("#"+n)[0],n=t.39),!t.3R&&n&&p.1j.5s(n))&&(e(t.39).20("7x",e(t.39).1q("7y")),t.3R=1y.24("2g"),e(t.39).5S(e(t.3R).1J()));1b o=1y.24("2g");e(12.1k).1Z(e(o).1Y("6S 9h").1Z(n)),p.2k(n)&&e(n).1T(),s.2a&&e(o).1Y("9i"+t.1a.2a);1b u=e(o).5L("7z[4c]").9j(13(){1c!e(12).2F("19")||!e(12).2F("14")});1h(0<u.23&&!t.1I("3y")){t.2b("3y",!0),s.1L&&(!i.1L&&!t.1L&&(t.1L=t.61(s.1L)),t.1I("1M")&&(t.1e(),e(t.1k).1T()),t.1L.62());1b a=0,n=1d.1N(9k,9l*(u.23||0));t.2i("3y"),t.3S("3y",e.1w(13(){u.1z(13(){12.63=13(){}}),a>=u.23||(12.54(t,o),r&&r())},12),n),e.1z(u,e.1w(13(n,i){1b s=3n 9m;s.63=e.1w(13(){s.63=13(){};1b n=s.14,f=s.19,l=e(i).2F("14"),c=e(i).2F("19");1h(!l||!c)!l&&c?(n=1d.27(c*n/f),f=c):!c&&l&&(f=1d.27(l*f/n),n=l),e(i).2F({14:n,19:f}),a++;a==u.23&&(t.2i("3y"),t.1L&&(t.1L.1D(),t.1L=1C),t.1I("1M")&&e(t.1k).1J(),12.54(t,o),r&&r())},12),s.4c=i.4c},12))}26 12.54(t,o),r&&r()},54:13(t,n){1b r=53(n),i=r.14-(2P(e(n).1q("2m-15"))||0)-(2P(e(n).1q("2m-1X"))||0);2P(e(n).1q("2m-17")),2P(e(n).1q("2m-1W")),t.1a.3g&&"2x"==e.1t(t.1a.3g)&&i>t.1a.3g&&(e(n).1q({14:t.1a.3g+"2t"}),r=53(n)),t.1r.3a=r,e(t.3h).7A(n)},5N:53},e.1m(c.3z,{1O:13(){12.1I("1O")||(e(1y.3c).1Z(e(12.1k).1q({15:"-55",17:"-55",2j:12.2j}).1Z(e(12.4J=1y.24("2g")).1Y("9n")).1Z(e(12.3h=1y.24("2g")).1Y("7u"))),e(12.1k).1Y("9o"+12.1a.2a),12.1a.7d&&(e(12.1j).1Y("7B"),12.2B(1y.7e,"2A",e.1w(13(t){12.1M()&&(t=e(t.1E).4W(".3w, .7B")[0],(!t||t&&t!=12.1k&&t!=12.1j)&&12.1J())},12))),1V.33.3V&&(12.1a.4l||12.1a.3O)&&(12.56(12.1a.4l),e(12.1k).1Y("64")),12.7C(),12.2b("1O",!0),I.30(12))},6e:13(){e(12.1k=1y.24("2g")).1Y("3w"),12.7D()},7E:13(){12.1O();1b e=A.1v(12.1j);e?e.1O():(3n u(12.1j),12.2b("4r",!0))},7D:13(){12.2B(12.1j,"4e",12.57),12.2B(12.1j,"4M",e.1w(13(e){12.65(e)},12)),12.1a.2H&&e.1z(12.1a.2H,e.1w(13(t,n){1b r=!1;"2A"==n&&(12.1a.28&&e.1z(12.1a.28,13(e,t){1h("4s"==t.1j&&"2A"==t.2r)1c r=!0,!1}),12.2b("5l",r)),12.2B(12.1j,n,"2A"==n?r?12.34:12.1T:e.1w(13(){12.7F()},12))},12)),12.1a.28?e.1z(12.1a.28,e.1w(13(t,n){1b r;1Q(n.1j){1i"4s":1h(12.1I("5l")&&"2A"==n.2r)1c;r=12.1j;1B;1i"1E":r=12.1E}r&&12.2B(r,n.2r,"2A"==n.2r?12.1J:e.1w(13(){12.66()},12))},12)):12.1a.7G&&12.1a.2H&&-1<!e.67("2A",12.1a.2H)&&12.2B(12.1j,"4M",e.1w(13(){12.2i("1T")},12));1b t=!1;!12.1a.9p&&12.1a.2H&&((t=-1<e.67("52",12.1a.2H))||-1<e.67("7H",12.1a.2H))&&"2N"==12.1E&&12.2B(12.1j,t?"52":"7H",13(e){12.1I("4r")&&12.1e(e)})},7C:13(){12.2B(12.1k,"4e",12.57),12.2B(12.1k,"4M",12.65),12.2B(12.1k,"4e",e.1w(13(){12.58("4m")||12.1T()},12)),12.1a.28&&e.1z(12.1a.28,e.1w(13(t,n){1b r;1Q(n.1j){1i"1x":r=12.1k}r&&12.2B(r,n.2r,n.2r.3d(/^(2A|52|4e)$/)?12.1J:e.1w(13(){12.66()},12))},12))},1T:13(t){12.2i("1J"),12.2i("4m");1h(!12.1M()){1h("13"==e.1t(12.2M)||"13"==e.1t(12.1r.59)){"13"!=e.1t(12.1r.59)&&(12.1r.59=12.2M);1b n=12.1r.59(12.1j)||!1;n!=12.1r.5m&&(12.1r.5m=n,12.2b("3k",!1),12.68()),12.2M=n;1h(!n)1c}12.1a.9q&&I.4C(),12.2b("1M",!0),12.1a.2h?12.7I(t):12.1I("3k")||12.3Q(12.2M),12.1I("4r")&&12.1e(t),12.5a(),12.1a.5b&&p.3T(e.1w(13(){12.57()},12)),"13"==e.1t(12.1a.5c)&&(!12.1a.2h||12.1a.2h&&12.1a.2h.4j&&12.1I("3k"))&&12.1a.5c(12.3h.5d,12.1j),1V.33.3V&&(12.1a.4l||12.1a.3O)&&(12.56(12.1a.4l),e(12.1k).1Y("7J").7K("64")),e(12.1k).1T()}},1J:13(){12.2i("1T"),12.1I("1M")&&(12.2b("1M",!1),1V.33.3V&&(12.1a.4l||12.1a.3O)?(12.56(12.1a.3O),e(12.1k).7K("7J").1Y("64"),12.3S("4m",e.1w(12.69,12),12.1a.3O)):12.69(),12.1r.2v)&&(12.1r.2v.7L(),12.1r.2v=1C,12.2b("2v",!1))},69:13(){12.1I("1O")&&(e(12.1k).1q({15:"-55",17:"-55"}),I.7i(),12.7M(),"13"==e.1t(12.1a.7N)&&!12.1L)&&12.1a.7N(12.3h.5d,12.1j)},34:13(e){12[12.1M()?"1J":"1T"](e)},1M:13(){1c 12.1I("1M")},7F:13(t){12.2i("1J"),12.2i("4m"),!12.1I("1M")&&!12.58("1T")&&12.3S("1T",e.1w(13(){12.2i("1T"),12.1T(t)},12),12.1a.7G||1)},66:13(){12.2i("1T"),!12.58("1J")&&12.1I("1M")&&12.3S("1J",e.1w(13(){12.2i("1J"),12.2i("4m"),12.1J()},12),12.1a.9r||1)},56:13(e){1h(1V.33.3V){1b e=e||0,t=12.1k.9s;t.9t=e+"5e",t.9u=e+"5e",t.9v=e+"5e",t.9w=e+"5e"}},2b:13(e,t){12.1r.2p[e]=t},1I:13(e){1c 12.1r.2p[e]},57:13(){12.2b("4q",!0),12.1I("1M")&&12.5a(),12.1a.5b&&12.2i("6a")},65:13(){12.2b("4q",!1),12.1a.5b&&12.3S("6a",e.1w(13(){12.2i("6a"),12.1I("4q")||12.1J()},12),12.1a.5b)},58:13(e){1c 12.1r.3b[e]},3S:13(e,t,n){12.1r.3b[e]=p.4t(t,n)},2i:13(e){12.1r.3b[e]&&(1S.5Z(12.1r.3b[e]),4b 12.1r.3b[e])},7O:13(){e.1z(12.1r.3b,13(e,t){1S.5Z(t)}),12.1r.3b=[]},2B:13(t,n,r,i){r=e.1w(r,i||12),12.1r.5k.2R({1j:t,7P:n,7Q:r}),e(t).3M(n,r)},7R:13(){e.1z(12.1r.5k,13(t,n){e(n.1j).7S(n.7P,n.7Q)})},4d:13(e){1b t=A.1v(12.1j);t&&t.4d(e)},7M:13(){12.4d(12.1a.1s.1x)},2Q:13(){1b e=A.1v(12.1j);e&&(e.2Q(),12.1M()&&12.1e())},3Q:13(t,n){1b r=e.1m({4n:12.1a.4n,1L:!1},n||{});12.1O(),12.1I("1M")&&e(12.1k).1J(),I.4L.3Q(12,t,e.1w(13(){1b t=12.1I("1M");t||12.2b("1M",!0),12.7E(),t||12.2b("1M",!1),12.1I("1M")&&(e(12.1k).1J(),12.1e(),12.5a(),e(12.1k).1T()),12.2b("3k",!0),r.4n&&r.4n(12.3h.5d,12.1j),r.5f&&r.5f()},12),{1L:r.1L})},7I:13(t){12.1I("2v")||12.1a.2h.4j&&12.1I("3k")||(12.2b("2v",!0),12.1a.1L&&(12.1L?12.1L.62():(12.1L=12.61(12.1a.1L),12.2b("3k",!1)),12.1e(t)),12.1r.2v&&(12.1r.2v.7L(),12.1r.2v=1C),12.1r.2v=e.2h({9x:12.2M,1t:12.1a.2h.1t,20:12.1a.2h.20||{},7T:12.1a.2h.7T||"7A",9y:e.1w(13(t,n,r){r.9z!==0&&12.3Q(r.9A,{1L:12.1a.1L&&12.1L,5f:e.1w(13(){12.2b("2v",!1),12.1I("1M")&&12.1a.5c&&12.1a.5c(12.3h.5d,12.1j),12.1L&&(12.1L.1D(),12.1L=1C)},12)})},12)}))},61:13(t){1b n=1y.24("2g");e(n).20("7w",!0);1b r=5X.4B(n,e.1m({},t||{})),t=5X.5D(n);1c e(n).1q(i(t)),12.3Q(n,{4n:!1,5f:13(){r.62()}}),r},1e:13(t){1h(12.1M()){1b n;1h("2N"==12.1a.1E){n=I.2w.60(t);1b r=I.2w.4D;n?r.x||r.y?(12.1r.2r={x:r.x,y:r.y},n=1C):n=t:(r.x||r.y?12.1r.2r={x:r.x,y:r.y}:12.1r.2r||(n=I.2w.7t(12.1j),12.1r.2r={x:n.15,y:n.17}),n=1C)}26 n=12.1E;I.2w.7o(12,12.1a.1s.1x,n,12.1a.1s.1E);1h(t&&I.2w.60(t)){1b r=e(12.1k).7k(),i=e(12.1k).7l(),t=p.5q(t);n=p.1j.4y(12.1k),t.x>=n.15&&t.x<=n.15+r&&t.y>=n.17&&t.y<=n.17+i&&p.3T(e.1w(13(){12.2i("1J")},12))}}},5a:13(){1h(12.1I("1O")&&!12.1a.2j){1b t=I.7h();t&&t!=12&&12.2j<=t.2j&&e(12.1k).1q({2j:12.2j=t.2j+1})}},68:13(){1b t;12.3R&&12.39&&((t=e(12.39).20("7x"))&&e(12.39).1q({7y:t}),e(12.3R).5S(12.39).1D(),12.3R=1C)},1D:13(){p.3T(e.1w(13(){12.7R()},12)),12.7O(),12.68(),p.3T(e.1w(13(){e(12.1k).5L("7z[4c]").7S("9B")},12)),A.1D(12.1j),12.1I("1O")&&12.1k&&(e(12.1k).1D(),12.1k=1C);1b t;(t=e(12.1j).20("5j"))&&e(12.1j).2F("5i",t).7U("5j"),e(12.1j).7U("2o-1R")}}),1V.3m()})(3U)',62,596,'||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||this|function|width|left||top||height|options|var|return|Math|position|lineTo|dimensions|if|case|element|container|border|extend|background|stem|radius|css|_cache|hook|type|shadow|get|proxy|tooltip|document|each|closeButton|break|null|remove|target|offset|ceil|bubble|getState|hide|opacity|spinner|visible|max|build|color|switch|uid|window|show|horizontal|Tipped|bottom|right|addClass|append|data|for|_hookPosition|length|createElement||else|round|hideOn|arc|skin|setState|getTooltip||beginPath|closePath|div|ajax|clearTimer|zIndex|isElement|anchor|padding|getOrderLayout|tipped|states|string|event|containment|px|_globalAlpha|xhr|Position|number|size|abs|click|setEvent|180|getOrientation|vertical|attr|Skins|showOn|tooltips|overlap|score|globalAlpha|content|mouse|split|parseInt|refresh|push|fillStyle|hex2fill|middle|center|closeButtonShadow|iframeShim|blurs|PI|add|blur|scripts|support|toggle|fill|isCenter|cleanup|bubbleCanvas|inlineContent|contentDimensions|timers|body|match|canvas|box|maxWidth|contentElement|shadows|getSkin|updated|indexOf|init|new|moveTo|charAt|toLowerCase|diameter|layout|stemLayout|hookPosition|cornerOffset|t_Tooltip|constructor|preloading_images|prototype|getContext|getVisible|x1|y1|x2|y2|topleft|topright|righttop|lefttop|math|getLayout|bind|defaultSkin|fadeOut|contained|update|inlineMarker|setTimer|defer|jQuery|cssTransitions|G_vmlCanvasManager|items|createFillStyle|positions|topmiddle|rightmiddle|rightbottom|bottomright|bottommiddle||bottomleft|leftbottom|leftmiddle|regex|getBorderDimensions|delete|src|setHookPosition|mouseenter|getStemLayout|transition|Stem|boolean|cache|sideOffset|fadeIn|fadeTransition|afterUpdate|000|startingZIndex|active|skinned|self|delay|cumulativeScrollOffset|scrollTop|scrollLeft|parentNode|cumulativeOffset|pow|touch|create|hideAll|mouseBuffer|getCenterBorderDimensions|cos|substring|skins|prepare|skinElement|order|UpdateQueue|mouseleave|rotate|borderRadius|test|topcenter|rightcenter|bottomcenter|leftcenter|closeButtonCanvas|selector|closest|_resizeTimer|_getTooltip|_remove|||mousemove|et|_updateTooltip|10000px|setFadeDuration|setActive|getTimer|contentFunction|raise|hideAfter|onShow|firstChild|ms|callback|in|Object|title|tipped_restore_title|events|toggles|fnCallContent|call|arguments|apply|pointer|pageX|isAttached|opera|required|available|console|findElement|setDefaultSkin|setStartingZIndex|isVisibleByElement|undefined|getSide|getDimensions|getBubbleLayout|100|min|floor|prepend|hoverCloseButton|defaultCloseButton|find|auto|getMeasureElementDimensions|drawCloseButtonState|default|hover|_drawBackgroundPath|before|_|reset|CloseButtons|black|Spinners|getByTooltipElement|clearTimeout|isPointerEvent|insertSpinner|play|onload|t_hidden|setIdle|hideDelayed|inArray|_restoreInlineContent|_hide|idle|createOptions|getAttribute|getElementById|_preBuild|Array|concat|pageY|RegExp|parseFloat|Opera|version|AppleWebKit|Chrome|Za|check|checked|notified|requires|warn|alert|try|DocumentTouch|catch|ready|startDelegating|removeDetached|drawRoundedRectangle|fillRect|isArray|Gradient|addColorStops|toOrientation|side|toDimension|isCorner|atan|red|green|blue|360|createHookCache|drawBubble|drawCloseButton|t_ContentContainer|first|25000px|t_Close|closeButtonShift|closeButtonMouseover|closeButtonMouseout|CloseButton|_drawBorderPath|backgroundRadius|setGlobalAlpha|sqrt|drawBackground|getBlurOpacity|base|getInversedPosition|getTooltipPositionFromTarget|adjustOffsetBasedOnHooks|closeButtonSkin|flip|viewport|hideOnClickOutside|documentElement|onWindowResize|is|getHighestTooltip|resetZ|typeof|outerWidth|outerHeight|innerWidth|innerHeight|set|distance|targetOverlap|tooltipOverlap|orientationOffset|getAbsoluteOffset|t_Content|inline|isSpinner|tipped_restore_inline_display|display|img|html|t_hideOnClickOutside|createPostBuildObservers|createPreBuildObservers|_buildSkin|showDelayed|showDelay|touchmove|ajaxUpdate|t_visible|removeClass|abort|resetHookPosition|onHide|clearTimers|eventName|handler|clearEvents|unbind|dataType|removeData|_stemPosition|object|setAttribute|slice|wrap|nodeType|setTimeout|do|while|navigator|userAgent|exec|attachEvent|MSIE|Gecko|KHTML|rv|Apple|Mobile|Safari|z_|z0|fn|jquery|log|_t_uid_|ontouchstart|instanceof|WebKitTransitionEvent|TransitionEvent|OTransitionEvent|createEvent|ExplorerCanvas|excanvas|js|initElement|drawPixelArray|createLinearGradient|addColorStop|spacing|replace|0123456789abcdef|hex2rgb|rgba|join|getSaturatedBW|255|hue|saturation|brightness|fff|init_|t_Bubble|iframe|t_iframeShim|frameBorder|javascript|15000px|t_CloseButtonShift|t_CloseState|translate|lineWidth|stemOffset|270|sin|setOpacity|getCenterBorderDimensions2||acos|t_Shadow|t_ShadowBubble|t_CloseButtonShadow|outside|999999|touchstart|delegate|close|preventDefault|stopPropagation|resize|200|getBySelector|move|t_UpdateQueue|t_clearfix|t_Content_|filter|8e3|750|Image|t_Skin|t_Tooltip_|fixed|hideOthers|hideDelay|style|MozTransitionDuration|webkitTransitionDuration|OTransitionDuration|transitionDuration|url|success|status|responseText|load'.split('|'),0,{}));
// MIT License

// Copyright (c) 2019 Jitbit (the company behind "Jitbit Helpdesk" software)

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// JavaScript HTML Sanitizer, (c) Alexander Yumashev, Jitbit Software.
// homepage https://github.com/jitbit/HtmlSanitizer
// License: MIT https://github.com/jitbit/HtmlSanitizer/blob/master/LICENSE

// iLab needs some changes on defaults and the way to handle browsers with no sandbox support.

var HtmlSanitizer = new (function () {

  var tagWhitelist_ = {
    'A': true, 'ABBR': true, 'B': true, 'BLOCKQUOTE': true, 'BODY': true, 'BR': true, 'CENTER': true, 'CODE': true,
    'DIV': true, 'EM': true, 'FONT': true, 'H1': true, 'H2': true, 'H3': true, 'H4': true, 'H5': true, 'H6': true,
    'HR': true, 'I': true, 'IMG': true, 'LABEL': true, 'LI': true, 'OL': true, 'P': true, 'PRE': true, 'SMALL': true,
    'SOURCE': true, 'SPAN': true, 'STRONG': true, 'TABLE': true, 'TBODY': true, 'TR': true, 'TD': true, 'TH': true,
    'THEAD': true, 'UL': true, 'U': true, 'VIDEO': true
  };
  var contentTagWhiteList_ = { 'FORM': true }; //tags that will be converted to DIVs
  var attributeWhitelist_ = {
    'align': true, 'color': true, 'controls': true, 'height': true, 'href': true, 'src': true, 'style': true,
    'target': true, 'title': true, 'type': true, 'width': true, 'alt': true, 'cite': true, 'datetime': true,
    'class': true, 'name': true, 'xml:lang': true, 'abbr': true
  };

  var cssWhitelist_ = {
    'color': true, 'background-color': true, 'font-size': true, 'text-align': true, 'text-decoration': true,
    'font-weight': true
  };
  var schemaWhiteList_ = [ 'https:']; //which "protocols" are allowed in "href", "src" etc
  var uriAttributes_ = { 'href': true, 'action': true };

  this.SanitizeHtml = function(input) {
    input = input.trim();
    if (input == "") return ""; //to save performance and not create iframe

    //firefox "bogus node" workaround
    if (input == "<br>") return "";

    var iframe = document.createElement('iframe');
    var sandboxSupported = 'sandbox' in iframe
    if (!sandboxSupported) {
      throw new SandboxNotSupportedException();
    }

    iframe['sandbox'] = 'allow-same-origin';
    iframe.style.display = 'none';
    document.body.appendChild(iframe); // necessary so the iframe contains a document
    var iframedoc = iframe.contentDocument || iframe.contentWindow.document;
    if (iframedoc.body == null) iframedoc.write("<body></body>"); // null in IE
    iframedoc.body.innerHTML = input;

    function makeSanitizedCopy(node) {
      if (node.nodeType == Node.TEXT_NODE) {
        var newNode = node.cloneNode(true);
      } else if (node.nodeType == Node.ELEMENT_NODE && (tagWhitelist_[node.tagName] || contentTagWhiteList_[node.tagName])) {

        //remove useless empty spans (lots of those when pasting from MS Outlook)
        if ((node.tagName == "SPAN" || node.tagName == "B" || node.tagName == "I" || node.tagName == "U")
          && node.innerHTML.trim() == "") {
          return document.createDocumentFragment();
        }

        if (contentTagWhiteList_[node.tagName])
          newNode = iframedoc.createElement('DIV'); //convert to DIV
        else
          newNode = iframedoc.createElement(node.tagName);

        for (var i = 0; i < node.attributes.length; i++) {
          var attr = node.attributes[i];
          if (attributeWhitelist_[attr.name]) {
            if (attr.name == "style") {
              for (s = 0; s < node.style.length; s++) {
                var styleName = node.style[s];
                if (cssWhitelist_[styleName])
                  newNode.style.setProperty(styleName, node.style.getPropertyValue(styleName));
              }
            }
            else {
              if (uriAttributes_[attr.name]) { //if this is a "uri" attribute, that can have "javascript:" or something
                if (attr.value.indexOf(":") > -1 && !startsWithAny(attr.value, schemaWhiteList_))
                  continue;
              }
              newNode.setAttribute(attr.name, attr.value);
            }
          }
        }
        for (i = 0; i < node.childNodes.length; i++) {
          var subCopy = makeSanitizedCopy(node.childNodes[i]);
          newNode.appendChild(subCopy, false);
        }
      } else {
        newNode = document.createDocumentFragment();
      }
      return newNode;
    };

    var resultElement = makeSanitizedCopy(iframedoc.body);
    iframedoc.documentElement.innerHTML = '';
    document.body.removeChild(iframe);
    return resultElement.innerHTML;
  }

  function startsWithAny(str, substrings) {
    for (var i = 0; i < substrings.length; i++) {
      if (str.indexOf(substrings[i]) == 0) {
        return true;
      }
    }
    return false;
  }

  this.AllowedTags = tagWhitelist_;
  this.AllowedAttributes = attributeWhitelist_;
  this.AllowedCssStyles = cssWhitelist_;
  this.AllowedSchemas = schemaWhiteList_;
});

function SandboxNotSupportedException() {
   this.message = 'The browser does not support sandboxed iframes';
   this.toString = function() {
      return this.message;
   };
}
;
// The MIT License

// Copyright (c) 2008 Jason Frame (jason@onehackoranother.com)

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// released under the MIT license
// ----------------------------------------------------
// iLab history note:
//
// It looks like this copy of Tipsy we're using started as commit 9fe119e27f31870a
// from the Tipsy repo (https://github.com/jaz303/tipsy), then was customized with
// a couple of patches:  one to clean up tips from removed DOM elements, another
// for an IE fix.  We later fixed a bug in the original clean up patch.  As of Oct
// 2013, the Tipsy repo was ahead of us by two commits, neither useful for us.



(function($) {

    function maybeCall(thing, ctx) {
        return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
    };

    // CAUTION the current implementation does not allow for tipsied elements to stay out of DOM (in between events)
    // i.e. don't remove, store, then re-insert tipsied elements (and why would you want to do that anyway?)
    var garbageCollect = (function() {
        var currentInterval;
        var to = null;
        var tipsies = [];

        function _do() {
            for (var i = 0; i < tipsies.length;) {
                var t = tipsies[i];
                // FIXME? the 2nd (non-paranoid) check is from the link below, it should be replaced if a better way is found
                // http://stackoverflow.com/questions/4040715/check-if-cached-jquery-object-is-still-in-dom
                if (t.options.gcInterval == 0 || t.$element.closest('body').length == 0) {
                    t.hoverState = 'out';
                    t.hide();
                    tipsies.splice(i,1);
                } else {
                    i++
                }
            }
        }
        function _loop() {
            to = setTimeout(function() { _do(); _loop(); }, currentInterval);
        }

        return function(t) {
            if (t.options.gcInterval == 0) return;

            if (!to || t.options.gcInterval < currentInterval) {
                clearTimeout(to); to = null;
                currentInterval = t.options.gcInterval;
            }
            tipsies.push(t);
            if (!to) _loop();
        };
    })();

    function Tipsy(element, options) {
        this.$element = $(element);
        this.options = options;
        this.enabled = true;
        this.fixTitle();

        garbageCollect(this);
    };

    Tipsy.prototype = {
        show: function() {
            var title = this.getTitle();
            if (title && this.enabled) {
                var $tip = this.tip();

                $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
                $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
                $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);

                var pos = $.extend({}, this.$element.offset(), {
                    width: this.$element[0].offsetWidth,
                    height: this.$element[0].offsetHeight
                });

                var actualWidth = $tip[0].offsetWidth,
                    actualHeight = $tip[0].offsetHeight,
                    gravity = maybeCall(this.options.gravity, this.$element[0]);

                var tp;
                switch (gravity.charAt(0)) {
                    case 'n':
                        tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 's':
                        tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 'e':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
                        break;
                    case 'w':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
                        break;
                }

                if (gravity.length == 2) {
                    if (gravity.charAt(1) == 'w') {
                        tp.left = pos.left + pos.width / 2 - 15;
                    } else {
                        tp.left = pos.left + pos.width / 2 - actualWidth + 15;
                    }
                }

                $tip.css(tp).addClass('tipsy-' + gravity);
                $tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
                if (this.options.className) {
                    $tip.addClass(maybeCall(this.options.className, this.$element[0]));
                }

                if (this.options.fade) {
                    $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
                } else {
                    $tip.css({visibility: 'visible', opacity: this.options.opacity});
                }
            }
        },

        hide: function() {
            if (this.options.fade) {
                this.tip().stop().fadeOut(function() { $(this).remove(); });
            } else {
                this.tip().remove();
            }
        },

        fixTitle: function() {
            var $e = this.$element;
            if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
                $e.attr('original-title', $e.attr('title') || '').removeAttr('title').attr("title", "");
            }
        },

        getTitle: function() {
            var title, $e = this.$element, o = this.options;
            this.fixTitle();
            var title, o = this.options;
            if (typeof o.title == 'string') {
                title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
            } else if (typeof o.title == 'function') {
                title = o.title.call($e[0]);
            }
            title = ('' + title).replace(/(^\s*|\s*$)/, "");
            return title || o.fallback;
        },

        tip: function() {
            if (!this.$tip) {
                this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>');
            }
            return this.$tip;
        },

        validate: function() {
            if (!this.$element[0].parentNode) {
                this.hide();
                this.$element = null;
                this.options = null;
            }
        },

        enable: function() { this.enabled = true; },
        disable: function() { this.enabled = false; },
        toggleEnabled: function() { this.enabled = !this.enabled; }
    };

    $.fn.tipsy = function(options) {

        if (options === true) {
            return this.data('tipsy');
        } else if (typeof options == 'string') {
            var tipsy = this.data('tipsy');
            if (tipsy) tipsy[options]();
            return this;
        }

        options = $.extend({}, $.fn.tipsy.defaults, options);

        function get(ele) {
            var tipsy = $.data(ele, 'tipsy');
            if (!tipsy) {
                tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));

                // Apply the HTML Sanitizer extension
                tipsy.getTitle = function() {
                    var title = Tipsy.prototype.getTitle.call(this);
                    var sanitizer = Object.create(HtmlSanitizer);
                    // Here we could customize what tags we do allow for tipsy using "sanitizer.AllowedTags".
                    try {
                        return sanitizer.SanitizeHtml(title);
                    } catch(ex) {
                        var isSandboxException = ex instanceof SandboxNotSupportedException;
                        if (!isSandboxException) {
                            throw ex;
                        }
                        console.warn(ex.toString());
                    }
                    return '';
                }

                $.data(ele, 'tipsy', tipsy);
            }
            return tipsy;
        }

        function enter() {
            var tipsy = get(this);
            tipsy.hoverState = 'in';
            if (options.delayIn == 0) {
                tipsy.show();
            } else {
                tipsy.fixTitle();
                setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
            }
        };

        function leave() {
            var tipsy = get(this);
            tipsy.hoverState = 'out';
            if (options.delayOut == 0) {
                tipsy.hide();
            } else {
                setTimeout(function() { if (tipsy.hoverState == 'out') tipsy.hide(); }, options.delayOut);
            }
        };

        if (!options.live) this.each(function() { get(this); });

        if (options.trigger != 'manual') {
            var binder   = options.live ? 'live' : 'bind',
                eventIn  = options.trigger == 'hover' ? 'mouseenter' : 'focus',
                eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
            this[binder](eventIn, enter)[binder](eventOut, leave);
        }

        return this;

    };

    $.fn.tipsy.defaults = {
        className: null,
        delayIn: 0,
        delayOut: 0,
        fade: false,
        fallback: '',
        gcInterval: 1500,
        gravity: 'n',
        html: false,
        live: false,
        offset: 0,
        opacity: 0.8,
        title: 'title',
        trigger: 'hover'
    };

    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.fn.tipsy.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };

    $.fn.tipsy.autoNS = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
    };

    $.fn.tipsy.autoWE = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
    };

    /**
     * yields a closure of the supplied parameters, producing a function that takes
     * no arguments and is suitable for use as an autogravity function like so:
     *
     * @param margin (int) - distance from the viewable region edge that an
     *        element should be before setting its tooltip's gravity to be away
     *        from that edge.
     * @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
     *        if there are no viewable region edges effecting the tooltip's
     *        gravity. It will try to vary from this minimally, for example,
     *        if 'sw' is preferred and an element is near the right viewable
     *        region edge, but not the top edge, it will set the gravity for
     *        that element's tooltip to be 'se', preserving the southern
     *        component.
     */
     $.fn.tipsy.autoBounds = function(margin, prefer) {
        return function() {
            var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
                boundTop = $(document).scrollTop() + margin,
                boundLeft = $(document).scrollLeft() + margin,
                $this = $(this);

            if ($this.offset().top < boundTop) dir.ns = 'n';
            if ($this.offset().left < boundLeft) dir.ew = 'w';
            if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
            if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';

            return dir.ns + (dir.ew ? dir.ew : '');
        }
    };

})(jQuery);
/*!
 * (The MIT License)
 * 
 * Copyright (c) 2012-2014 Marcin Warpechowski
 * Copyright (c) 2015 Handsoncode sp. z o.o. <hello@handsoncode.net>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 * Version: 0.35.1
 * Release date: 25/01/2018 (built at 25/01/2018 10:06:15)
 */

(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define("Handsontable", [], factory);
	else if(typeof exports === 'object')
		exports["Handsontable"] = factory();
	else
		root["Handsontable"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 318);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.HTML_CHARACTERS = undefined;
exports.getParent = getParent;
exports.closest = closest;
exports.closestDown = closestDown;
exports.isChildOf = isChildOf;
exports.isChildOfWebComponentTable = isChildOfWebComponentTable;
exports.polymerWrap = polymerWrap;
exports.polymerUnwrap = polymerUnwrap;
exports.index = index;
exports.overlayContainsElement = overlayContainsElement;
exports.hasClass = hasClass;
exports.addClass = addClass;
exports.removeClass = removeClass;
exports.removeTextNodes = removeTextNodes;
exports.empty = empty;
exports.fastInnerHTML = fastInnerHTML;
exports.fastInnerText = fastInnerText;
exports.isVisible = isVisible;
exports.offset = offset;
exports.getWindowScrollTop = getWindowScrollTop;
exports.getWindowScrollLeft = getWindowScrollLeft;
exports.getScrollTop = getScrollTop;
exports.getScrollLeft = getScrollLeft;
exports.getScrollableElement = getScrollableElement;
exports.getTrimmingContainer = getTrimmingContainer;
exports.getStyle = getStyle;
exports.getComputedStyle = getComputedStyle;
exports.outerWidth = outerWidth;
exports.outerHeight = outerHeight;
exports.innerHeight = innerHeight;
exports.innerWidth = innerWidth;
exports.addEvent = addEvent;
exports.removeEvent = removeEvent;
exports.getCaretPosition = getCaretPosition;
exports.getSelectionEndPosition = getSelectionEndPosition;
exports.getSelectionText = getSelectionText;
exports.setCaretPosition = setCaretPosition;
exports.getScrollbarWidth = getScrollbarWidth;
exports.hasVerticalScrollbar = hasVerticalScrollbar;
exports.hasHorizontalScrollbar = hasHorizontalScrollbar;
exports.setOverlayPosition = setOverlayPosition;
exports.getCssTransform = getCssTransform;
exports.resetCssTransform = resetCssTransform;
exports.isInput = isInput;
exports.isOutsideInput = isOutsideInput;

var _browser = __webpack_require__(28);

var _feature = __webpack_require__(39);

/**
 * Get the parent of the specified node in the DOM tree.
 *
 * @param  {HTMLElement} element Element from which traversing is started.
 * @param  {Number} [level=0] Traversing deep level.
 * @return {HTMLElement|null}
 */
function getParent(element) {
  var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

  var iteration = -1;
  var parent = null;

  while (element != null) {
    if (iteration === level) {
      parent = element;
      break;
    }

    if (element.host && element.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
      element = element.host;
    } else {
      iteration++;
      element = element.parentNode;
    }
  }

  return parent;
}

/**
 * Goes up the DOM tree (including given element) until it finds an element that matches the nodes or nodes name.
 * This method goes up through web components.
 *
 * @param {HTMLElement} element Element from which traversing is started
 * @param {Array} nodes Array of elements or Array of elements name
 * @param {HTMLElement} [until]
 * @returns {HTMLElement|null}
 */
function closest(element, nodes, until) {
  while (element != null && element !== until) {
    if (element.nodeType === Node.ELEMENT_NODE && (nodes.indexOf(element.nodeName) > -1 || nodes.indexOf(element) > -1)) {
      return element;
    }
    if (element.host && element.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
      element = element.host;
    } else {
      element = element.parentNode;
    }
  }

  return null;
}

/**
 * Goes "down" the DOM tree (including given element) until it finds an element that matches the nodes or nodes name.
 *
 * @param {HTMLElement} element Element from which traversing is started
 * @param {Array} nodes Array of elements or Array of elements name
 * @param {HTMLElement} [until]
 * @returns {HTMLElement|null}
 */
function closestDown(element, nodes, until) {
  var matched = [];

  while (element) {
    element = closest(element, nodes, until);

    if (!element || until && !until.contains(element)) {
      break;
    }
    matched.push(element);

    if (element.host && element.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
      element = element.host;
    } else {
      element = element.parentNode;
    }
  }
  var length = matched.length;

  return length ? matched[length - 1] : null;
}

/**
 * Goes up the DOM tree and checks if element is child of another element.
 *
 * @param child Child element
 * @param {Object|String} parent Parent element OR selector of the parent element.
 *                               If string provided, function returns `true` for the first occurrence of element with that class.
 * @returns {Boolean}
 */
function isChildOf(child, parent) {
  var node = child.parentNode;
  var queriedParents = [];

  if (typeof parent === 'string') {
    queriedParents = Array.prototype.slice.call(document.querySelectorAll(parent), 0);
  } else {
    queriedParents.push(parent);
  }

  while (node != null) {
    if (queriedParents.indexOf(node) > -1) {
      return true;
    }
    node = node.parentNode;
  }

  return false;
}

/**
 * Check if an element is part of `hot-table` web component.
 *
 * @param {Element} element
 * @returns {Boolean}
 */
function isChildOfWebComponentTable(element) {
  var hotTableName = 'hot-table',
      result = false,
      parentNode;

  parentNode = polymerWrap(element);

  function isHotTable(element) {
    return element.nodeType === Node.ELEMENT_NODE && element.nodeName === hotTableName.toUpperCase();
  }

  while (parentNode != null) {
    if (isHotTable(parentNode)) {
      result = true;
      break;
    } else if (parentNode.host && parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
      result = isHotTable(parentNode.host);

      if (result) {
        break;
      }
      parentNode = parentNode.host;
    }
    parentNode = parentNode.parentNode;
  }

  return result;
}

/**
 * Wrap element into polymer/webcomponent container if exists
 *
 * @param element
 * @returns {*}
 */
function polymerWrap(element) {
  /* global Polymer */
  return typeof Polymer !== 'undefined' && typeof wrap === 'function' ? wrap(element) : element;
}

/**
 * Unwrap element from polymer/webcomponent container if exists
 *
 * @param element
 * @returns {*}
 */
function polymerUnwrap(element) {
  /* global Polymer */
  return typeof Polymer !== 'undefined' && typeof unwrap === 'function' ? unwrap(element) : element;
}

/**
 * Counts index of element within its parent
 * WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable
 * Otherwise would need to check for nodeType or use previousElementSibling
 *
 * @see http://jsperf.com/sibling-index/10
 * @param {Element} element
 * @return {Number}
 */
function index(element) {
  var i = 0;

  if (element.previousSibling) {
    /* eslint-disable no-cond-assign */
    while (element = element.previousSibling) {
      ++i;
    }
  }

  return i;
}

/**
 * Check if the provided overlay contains the provided element
 *
 * @param {String} overlay
 * @param {HTMLElement} element
 * @returns {boolean}
 */
function overlayContainsElement(overlayType, element) {
  var overlayElement = document.querySelector('.ht_clone_' + overlayType);
  return overlayElement ? overlayElement.contains(element) : null;
}

var classListSupport = !!document.documentElement.classList;
var _hasClass, _addClass, _removeClass;

function filterEmptyClassNames(classNames) {
  var len = 0,
      result = [];

  if (!classNames || !classNames.length) {
    return result;
  }
  while (classNames[len]) {
    result.push(classNames[len]);
    len++;
  }

  return result;
}

if (classListSupport) {
  var isSupportMultipleClassesArg = function () {
    var element = document.createElement('div');

    element.classList.add('test', 'test2');

    return element.classList.contains('test2');
  }();

  _hasClass = function _hasClass(element, className) {
    if (element.classList === void 0 || className === '') {
      return false;
    }

    return element.classList.contains(className);
  };

  _addClass = function _addClass(element, className) {
    var len = 0;

    if (typeof className === 'string') {
      className = className.split(' ');
    }
    className = filterEmptyClassNames(className);

    if (isSupportMultipleClassesArg) {
      element.classList.add.apply(element.classList, className);
    } else {
      while (className && className[len]) {
        element.classList.add(className[len]);
        len++;
      }
    }
  };

  _removeClass = function _removeClass(element, className) {
    var len = 0;

    if (typeof className === 'string') {
      className = className.split(' ');
    }
    className = filterEmptyClassNames(className);

    if (isSupportMultipleClassesArg) {
      element.classList.remove.apply(element.classList, className);
    } else {
      while (className && className[len]) {
        element.classList.remove(className[len]);
        len++;
      }
    }
  };
} else {
  var createClassNameRegExp = function createClassNameRegExp(className) {
    return new RegExp('(\\s|^)' + className + '(\\s|$)');
  };

  _hasClass = function _hasClass(element, className) {
    // http://snipplr.com/view/3561/addclass-removeclass-hasclass/
    return element.className !== void 0 && createClassNameRegExp(className).test(element.className);
  };

  _addClass = function _addClass(element, className) {
    var len = 0,
        _className = element.className;

    if (typeof className === 'string') {
      className = className.split(' ');
    }
    if (_className === '') {
      _className = className.join(' ');
    } else {
      while (className && className[len]) {
        if (!createClassNameRegExp(className[len]).test(_className)) {
          _className += ' ' + className[len];
        }
        len++;
      }
    }
    element.className = _className;
  };

  _removeClass = function _removeClass(element, className) {
    var len = 0,
        _className = element.className;

    if (typeof className === 'string') {
      className = className.split(' ');
    }
    while (className && className[len]) {
      // String.prototype.trim is defined in polyfill.js
      _className = _className.replace(createClassNameRegExp(className[len]), ' ').trim();
      len++;
    }
    if (element.className !== _className) {
      element.className = _className;
    }
  };
}

/**
 * Checks if element has class name
 *
 * @param {HTMLElement} element
 * @param {String} className Class name to check
 * @returns {Boolean}
 */
function hasClass(element, className) {
  return _hasClass(element, className);
}

/**
 * Add class name to an element
 *
 * @param {HTMLElement} element
 * @param {String|Array} className Class name as string or array of strings
 */
function addClass(element, className) {
  return _addClass(element, className);
}

/**
 * Remove class name from an element
 *
 * @param {HTMLElement} element
 * @param {String|Array} className Class name as string or array of strings
 */
function removeClass(element, className) {
  return _removeClass(element, className);
}

function removeTextNodes(element, parent) {
  if (element.nodeType === 3) {
    parent.removeChild(element); // bye text nodes!
  } else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(element.nodeName) > -1) {
    var childs = element.childNodes;
    for (var i = childs.length - 1; i >= 0; i--) {
      removeTextNodes(childs[i], element);
    }
  }
}

/**
 * Remove childs function
 * WARNING - this doesn't unload events and data attached by jQuery
 * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9
 * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method
 *
 * @param element
 * @returns {void}
 */
//
function empty(element) {
  var child;
  /* eslint-disable no-cond-assign */
  while (child = element.lastChild) {
    element.removeChild(child);
  }
}

var HTML_CHARACTERS = exports.HTML_CHARACTERS = /(<(.*)>|&(.*);)/;

/**
 * Insert content into element trying avoid innerHTML method.
 * @return {void}
 */
function fastInnerHTML(element, content) {
  if (HTML_CHARACTERS.test(content)) {
    element.innerHTML = content;
  } else {
    fastInnerText(element, content);
  }
}

/**
 * Insert text content into element
 * @return {void}
 */

var textContextSupport = !!document.createTextNode('test').textContent;

function fastInnerText(element, content) {
  var child = element.firstChild;

  if (child && child.nodeType === 3 && child.nextSibling === null) {
    // fast lane - replace existing text node

    if (textContextSupport) {
      // http://jsperf.com/replace-text-vs-reuse
      child.textContent = content;
    } else {
      // http://jsperf.com/replace-text-vs-reuse
      child.data = content;
    }
  } else {
    // slow lane - empty element and insert a text node
    empty(element);
    element.appendChild(document.createTextNode(content));
  }
}

/**
 * Returns true if element is attached to the DOM and visible, false otherwise
 * @param elem
 * @returns {boolean}
 */
function isVisible(elem) {
  var next = elem;

  while (polymerUnwrap(next) !== document.documentElement) {
    // until <html> reached
    if (next === null) {
      // parent detached from DOM
      return false;
    } else if (next.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
      if (next.host) {
        // this is Web Components Shadow DOM
        // see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation
        // according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet
        if (next.host.impl) {
          // Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled
          return isVisible(next.host.impl);
        } else if (next.host) {
          // Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled
          return isVisible(next.host);
        }
        throw new Error('Lost in Web Components world');
      } else {
        return false; // this is a node detached from document in IE8
      }
    } else if (next.style.display === 'none') {
      return false;
    }
    next = next.parentNode;
  }

  return true;
}

/**
 * Returns elements top and left offset relative to the document. Function is not compatible with jQuery offset.
 *
 * @param {HTMLElement} elem
 * @return {Object} Returns object with `top` and `left` props
 */
function offset(elem) {
  var offsetLeft, offsetTop, lastElem, docElem, box;

  docElem = document.documentElement;

  if ((0, _feature.hasCaptionProblem)() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
    // fixes problem with Firefox ignoring <caption> in TABLE offset (see also export outerHeight)
    // http://jsperf.com/offset-vs-getboundingclientrect/8
    box = elem.getBoundingClientRect();

    return {
      top: box.top + (window.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
      left: box.left + (window.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0)
    };
  }
  offsetLeft = elem.offsetLeft;
  offsetTop = elem.offsetTop;
  lastElem = elem;

  /* eslint-disable no-cond-assign */
  while (elem = elem.offsetParent) {
    // from my observation, document.body always has scrollLeft/scrollTop == 0
    if (elem === document.body) {
      break;
    }
    offsetLeft += elem.offsetLeft;
    offsetTop += elem.offsetTop;
    lastElem = elem;
  }

  // slow - http://jsperf.com/offset-vs-getboundingclientrect/6
  if (lastElem && lastElem.style.position === 'fixed') {
    // if(lastElem !== document.body) { //faster but does gives false positive in Firefox
    offsetLeft += window.pageXOffset || docElem.scrollLeft;
    offsetTop += window.pageYOffset || docElem.scrollTop;
  }

  return {
    left: offsetLeft,
    top: offsetTop
  };
}

/**
 * Returns the document's scrollTop property.
 *
 * @returns {Number}
 */
function getWindowScrollTop() {
  var res = window.scrollY;

  if (res === void 0) {
    // IE8-11
    res = document.documentElement.scrollTop;
  }

  return res;
}

/**
 * Returns the document's scrollLeft property.
 *
 * @returns {Number}
 */
function getWindowScrollLeft() {
  var res = window.scrollX;

  if (res === void 0) {
    // IE8-11
    res = document.documentElement.scrollLeft;
  }

  return res;
}

/**
 * Returns the provided element's scrollTop property.
 *
 * @param element
 * @returns {Number}
 */
function getScrollTop(element) {
  if (element === window) {
    return getWindowScrollTop();
  }
  return element.scrollTop;
}

/**
 * Returns the provided element's scrollLeft property.
 *
 * @param element
 * @returns {Number}
 */
function getScrollLeft(element) {
  if (element === window) {
    return getWindowScrollLeft();
  }
  return element.scrollLeft;
}

/**
 * Returns a DOM element responsible for scrolling of the provided element.
 *
 * @param {HTMLElement} element
 * @returns {HTMLElement} Element's scrollable parent
 */
function getScrollableElement(element) {
  var el = element.parentNode,
      props = ['auto', 'scroll'],
      overflow,
      overflowX,
      overflowY,
      computedStyle = '',
      computedOverflow = '',
      computedOverflowY = '',
      computedOverflowX = '';

  while (el && el.style && document.body !== el) {
    overflow = el.style.overflow;
    overflowX = el.style.overflowX;
    overflowY = el.style.overflowY;

    if (overflow == 'scroll' || overflowX == 'scroll' || overflowY == 'scroll') {
      return el;
    } else if (window.getComputedStyle) {
      computedStyle = window.getComputedStyle(el);
      computedOverflow = computedStyle.getPropertyValue('overflow');
      computedOverflowY = computedStyle.getPropertyValue('overflow-y');
      computedOverflowX = computedStyle.getPropertyValue('overflow-x');

      if (computedOverflow === 'scroll' || computedOverflowX === 'scroll' || computedOverflowY === 'scroll') {
        return el;
      }
    }

    // The '+ 1' after the scrollHeight/scrollWidth is to prevent problems with zoomed out Chrome.
    if (el.clientHeight <= el.scrollHeight + 1 && (props.indexOf(overflowY) !== -1 || props.indexOf(overflow) !== -1 || props.indexOf(computedOverflow) !== -1 || props.indexOf(computedOverflowY) !== -1)) {
      return el;
    }
    if (el.clientWidth <= el.scrollWidth + 1 && (props.indexOf(overflowX) !== -1 || props.indexOf(overflow) !== -1 || props.indexOf(computedOverflow) !== -1 || props.indexOf(computedOverflowX) !== -1)) {
      return el;
    }
    el = el.parentNode;
  }

  return window;
}

/**
 * Returns a DOM element responsible for trimming the provided element.
 *
 * @param {HTMLElement} base Base element
 * @returns {HTMLElement} Base element's trimming parent
 */
function getTrimmingContainer(base) {
  var el = base.parentNode;

  while (el && el.style && document.body !== el) {
    if (el.style.overflow !== 'visible' && el.style.overflow !== '') {
      return el;
    } else if (window.getComputedStyle) {
      var computedStyle = window.getComputedStyle(el);

      if (computedStyle.getPropertyValue('overflow') !== 'visible' && computedStyle.getPropertyValue('overflow') !== '') {
        return el;
      }
    }

    el = el.parentNode;
  }

  return window;
}

/**
 * Returns a style property for the provided element. (Be it an inline or external style).
 *
 * @param {HTMLElement} element
 * @param {String} prop Wanted property
 * @returns {String|undefined} Element's style property
 */
function getStyle(element, prop) {
  /* eslint-disable */
  if (!element) {
    return;
  } else if (element === window) {
    if (prop === 'width') {
      return window.innerWidth + 'px';
    } else if (prop === 'height') {
      return window.innerHeight + 'px';
    }

    return;
  }

  var styleProp = element.style[prop],
      computedStyle;

  if (styleProp !== '' && styleProp !== void 0) {
    return styleProp;
  } else {
    computedStyle = getComputedStyle(element);

    if (computedStyle[prop] !== '' && computedStyle[prop] !== void 0) {
      return computedStyle[prop];
    }
  }
}

/**
 * Returns a computed style object for the provided element. (Needed if style is declared in external stylesheet).
 *
 * @param element
 * @returns {IEElementStyle|CssStyle} Elements computed style object
 */
function getComputedStyle(element) {
  return element.currentStyle || document.defaultView.getComputedStyle(element);
}

/**
 * Returns the element's outer width.
 *
 * @param element
 * @returns {number} Element's outer width
 */
function outerWidth(element) {
  return element.offsetWidth;
}

/**
 * Returns the element's outer height
 *
 * @param elem
 * @returns {number} Element's outer height
 */
function outerHeight(elem) {
  if ((0, _feature.hasCaptionProblem)() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
    // fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight
    // jQuery (1.10.1) still has this unsolved
    // may be better to just switch to getBoundingClientRect
    // http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/
    // http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html
    // http://bugs.jquery.com/ticket/2196
    // http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140
    return elem.offsetHeight + elem.firstChild.offsetHeight;
  }

  return elem.offsetHeight;
}

/**
 * Returns the element's inner height.
 *
 * @param element
 * @returns {number} Element's inner height
 */
function innerHeight(element) {
  return element.clientHeight || element.innerHeight;
}

/**
 * Returns the element's inner width.
 *
 * @param element
 * @returns {number} Element's inner width
 */
function innerWidth(element) {
  return element.clientWidth || element.innerWidth;
}

function addEvent(element, event, callback) {
  if (window.addEventListener) {
    element.addEventListener(event, callback, false);
  } else {
    element.attachEvent('on' + event, callback);
  }
}

function removeEvent(element, event, callback) {
  if (window.removeEventListener) {
    element.removeEventListener(event, callback, false);
  } else {
    element.detachEvent('on' + event, callback);
  }
}

/**
 * Returns caret position in text input
 *
 * @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea
 * @return {Number}
 */
function getCaretPosition(el) {
  if (el.selectionStart) {
    return el.selectionStart;
  } else if (document.selection) {
    // IE8
    el.focus();

    var r = document.selection.createRange();

    if (r == null) {
      return 0;
    }
    var re = el.createTextRange();
    var rc = re.duplicate();

    re.moveToBookmark(r.getBookmark());
    rc.setEndPoint('EndToStart', re);

    return rc.text.length;
  }

  return 0;
}

/**
 * Returns end of the selection in text input
 *
 * @return {Number}
 */
function getSelectionEndPosition(el) {
  if (el.selectionEnd) {
    return el.selectionEnd;
  } else if (document.selection) {
    // IE8
    var r = document.selection.createRange();

    if (r == null) {
      return 0;
    }
    var re = el.createTextRange();

    return re.text.indexOf(r.text) + r.text.length;
  }

  return 0;
}

/**
 * Returns text under selection.
 *
 * @returns {String}
 */
function getSelectionText() {
  var text = '';

  if (window.getSelection) {
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type !== 'Control') {
    text = document.selection.createRange().text;
  }

  return text;
}

/**
 * Sets caret position in text input.
 *
 * @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
 * @param {Element} element
 * @param {Number} pos
 * @param {Number} endPos
 */
function setCaretPosition(element, pos, endPos) {
  if (endPos === void 0) {
    endPos = pos;
  }
  if (element.setSelectionRange) {
    element.focus();

    try {
      element.setSelectionRange(pos, endPos);
    } catch (err) {
      var elementParent = element.parentNode;
      var parentDisplayValue = elementParent.style.display;
      elementParent.style.display = 'block';
      element.setSelectionRange(pos, endPos);
      elementParent.style.display = parentDisplayValue;
    }
  } else if (element.createTextRange) {
    // IE8
    var range = element.createTextRange();
    range.collapse(true);
    range.moveEnd('character', endPos);
    range.moveStart('character', pos);
    range.select();
  }
}

var cachedScrollbarWidth;

// http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes
function walkontableCalculateScrollbarWidth() {
  var inner = document.createElement('div');
  inner.style.height = '200px';
  inner.style.width = '100%';

  var outer = document.createElement('div');
  outer.style.boxSizing = 'content-box';
  outer.style.height = '150px';
  outer.style.left = '0px';
  outer.style.overflow = 'hidden';
  outer.style.position = 'absolute';
  outer.style.top = '0px';
  outer.style.width = '200px';
  outer.style.visibility = 'hidden';
  outer.appendChild(inner);

  (document.body || document.documentElement).appendChild(outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll';
  var w2 = inner.offsetWidth;
  if (w1 == w2) {
    w2 = outer.clientWidth;
  }

  (document.body || document.documentElement).removeChild(outer);

  return w1 - w2;
}

/**
 * Returns the computed width of the native browser scroll bar.
 *
 * @return {Number} width
 */
function getScrollbarWidth() {
  if (cachedScrollbarWidth === void 0) {
    cachedScrollbarWidth = walkontableCalculateScrollbarWidth();
  }

  return cachedScrollbarWidth;
}

/**
 * Checks if the provided element has a vertical scrollbar.
 *
 * @param {HTMLElement} element
 * @returns {Boolean}
 */
function hasVerticalScrollbar(element) {
  return element.offsetWidth !== element.clientWidth;
}

/**
 * Checks if the provided element has a vertical scrollbar.
 *
 * @param {HTMLElement} element
 * @returns {Boolean}
 */
function hasHorizontalScrollbar(element) {
  return element.offsetHeight !== element.clientHeight;
}

/**
 * Sets overlay position depending on it's type and used browser
 */
function setOverlayPosition(overlayElem, left, top) {
  if ((0, _browser.isIE8)() || (0, _browser.isIE9)()) {
    overlayElem.style.top = top;
    overlayElem.style.left = left;
  } else if ((0, _browser.isSafari)()) {
    overlayElem.style['-webkit-transform'] = 'translate3d(' + left + ',' + top + ',0)';
  } else {
    overlayElem.style.transform = 'translate3d(' + left + ',' + top + ',0)';
  }
}

function getCssTransform(element) {
  var transform;

  if (element.style.transform && (transform = element.style.transform) !== '') {
    return ['transform', transform];
  } else if (element.style['-webkit-transform'] && (transform = element.style['-webkit-transform']) !== '') {

    return ['-webkit-transform', transform];
  }

  return -1;
}

function resetCssTransform(element) {
  if (element.style.transform && element.style.transform !== '') {
    element.style.transform = '';
  } else if (element.style['-webkit-transform'] && element.style['-webkit-transform'] !== '') {
    element.style['-webkit-transform'] = '';
  }
}

/**
 * Determines if the given DOM element is an input field.
 * Notice: By 'input' we mean input, textarea and select nodes
 *
 * @param {HTMLElement} element - DOM element
 * @returns {Boolean}
 */
function isInput(element) {
  var inputs = ['INPUT', 'SELECT', 'TEXTAREA'];

  return element && (inputs.indexOf(element.nodeName) > -1 || element.contentEditable === 'true');
}

/**
 * Determines if the given DOM element is an input field placed OUTSIDE of HOT.
 * Notice: By 'input' we mean input, textarea and select nodes
 *
 * @param {HTMLElement} element - DOM element
 * @returns {Boolean}
 */
function isOutsideInput(element) {
  return isInput(element) && element.className.indexOf('handsontableInput') == -1 && element.className.indexOf('copyPaste') == -1;
}

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.duckSchema = duckSchema;
exports.inherit = inherit;
exports.extend = extend;
exports.deepExtend = deepExtend;
exports.deepClone = deepClone;
exports.clone = clone;
exports.mixin = mixin;
exports.isObjectEquals = isObjectEquals;
exports.isObject = isObject;
exports.defineGetter = defineGetter;
exports.objectEach = objectEach;
exports.getProperty = getProperty;
exports.deepObjectSize = deepObjectSize;
exports.createObjectPropListener = createObjectPropListener;
exports.hasOwnProperty = hasOwnProperty;

var _array = __webpack_require__(2);

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/**
 * Generate schema for passed object.
 *
 * @param {Array|Object} object
 * @returns {Array|Object}
 */
function duckSchema(object) {
  var schema;

  if (Array.isArray(object)) {
    schema = [];
  } else {
    schema = {};

    objectEach(object, function (value, key) {
      if (key === '__children') {
        return;
      }

      if (value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && !Array.isArray(value)) {
        schema[key] = duckSchema(value);
      } else if (Array.isArray(value)) {
        if (value.length && _typeof(value[0]) === 'object' && !Array.isArray(value[0])) {
          schema[key] = [duckSchema(value[0])];
        } else {
          schema[key] = [];
        }
      } else {
        schema[key] = null;
      }
    });
  }

  return schema;
}

/**
 * Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`.
 * Creates temporary dummy function to call it as constructor.
 * Described in ticket: https://github.com/handsontable/handsontable/pull/516
 *
 * @param  {Object} Child  child class
 * @param  {Object} Parent parent class
 * @return {Object}        extended Child
 */
function inherit(Child, Parent) {
  Parent.prototype.constructor = Parent;
  Child.prototype = new Parent();
  Child.prototype.constructor = Child;

  return Child;
}

/**
 * Perform shallow extend of a target object with extension's own properties.
 *
 * @param {Object} target An object that will receive the new properties.
 * @param {Object} extension An object containing additional properties to merge into the target.
 */
function extend(target, extension) {
  objectEach(extension, function (value, key) {
    target[key] = value;
  });

  return target;
}

/**
 * Perform deep extend of a target object with extension's own properties.
 *
 * @param {Object} target An object that will receive the new properties.
 * @param {Object} extension An object containing additional properties to merge into the target.
 */
function deepExtend(target, extension) {
  objectEach(extension, function (value, key) {
    if (extension[key] && _typeof(extension[key]) === 'object') {
      if (!target[key]) {
        if (Array.isArray(extension[key])) {
          target[key] = [];
        } else if (Object.prototype.toString.call(extension[key]) === '[object Date]') {
          target[key] = extension[key];
        } else {
          target[key] = {};
        }
      }
      deepExtend(target[key], extension[key]);
    } else {
      target[key] = extension[key];
    }
  });
}

/**
 * Perform deep clone of an object.
 * WARNING! Only clones JSON properties. Will cause error when `obj` contains a function, Date, etc.
 *
 * @param {Object} obj An object that will be cloned
 * @return {Object}
 */
function deepClone(obj) {
  if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object') {
    return JSON.parse(JSON.stringify(obj));
  }

  return obj;
}

/**
 * Shallow clone object.
 *
 * @param {Object} object
 * @returns {Object}
 */
function clone(object) {
  var result = {};

  objectEach(object, function (value, key) {
    result[key] = value;
  });

  return result;
}

/**
 * Extend the Base object (usually prototype) of the functionality the `mixins` objects.
 *
 * @param {Object} Base Base object which will be extended.
 * @param {Object} mixins The object of the functionality will be "copied".
 * @returns {Object}
 */
function mixin(Base) {
  if (!Base.MIXINS) {
    Base.MIXINS = [];
  }

  for (var _len = arguments.length, mixins = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    mixins[_key - 1] = arguments[_key];
  }

  (0, _array.arrayEach)(mixins, function (mixin) {
    Base.MIXINS.push(mixin.MIXIN_NAME);

    objectEach(mixin, function (value, key) {
      if (Base.prototype[key] !== void 0) {
        throw new Error('Mixin conflict. Property \'' + key + '\' already exist and cannot be overwritten.');
      }
      if (typeof value === 'function') {
        Base.prototype[key] = value;
      } else {
        var getter = function _getter(propertyName, initialValue) {
          propertyName = '_' + propertyName;

          var initValue = function initValue(value) {
            if (Array.isArray(value) || isObject(value)) {
              value = deepClone(value);
            }

            return value;
          };

          return function () {
            if (this[propertyName] === void 0) {
              this[propertyName] = initValue(initialValue);
            }

            return this[propertyName];
          };
        };
        var setter = function _setter(propertyName) {
          propertyName = '_' + propertyName;

          return function (value) {
            this[propertyName] = value;
          };
        };
        Object.defineProperty(Base.prototype, key, {
          get: getter(key, value),
          set: setter(key),
          configurable: true
        });
      }
    });
  });

  return Base;
}

/**
 * Checks if two objects or arrays are (deep) equal
 *
 * @param {Object|Array} object1
 * @param {Object|Array} object2
 * @returns {Boolean}
 */
function isObjectEquals(object1, object2) {
  return JSON.stringify(object1) === JSON.stringify(object2);
}

/**
 * Determines whether given object is a plain Object.
 * Note: String and Array are not plain Objects
 * @param {*} obj
 * @returns {boolean}
 */
function isObject(obj) {
  return Object.prototype.toString.call(obj) == '[object Object]';
}

function defineGetter(object, property, value, options) {
  options.value = value;
  options.writable = options.writable !== false;
  options.enumerable = options.enumerable !== false;
  options.configurable = options.configurable !== false;

  Object.defineProperty(object, property, options);
}

/**
 * A specialized version of `.forEach` for objects.
 *
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Object} Returns `object`.
 */
function objectEach(object, iteratee) {
  for (var key in object) {
    if (!object.hasOwnProperty || object.hasOwnProperty && Object.prototype.hasOwnProperty.call(object, key)) {
      if (iteratee(object[key], key, object) === false) {
        break;
      }
    }
  }

  return object;
}

/**
 * Get object property by its name. Access to sub properties can be achieved by dot notation (e.q. `'foo.bar.baz'`).
 *
 * @param {Object} object Object which value will be exported.
 * @param {String} name Object property name.
 * @returns {*}
 */
function getProperty(object, name) {
  var names = name.split('.');
  var result = object;

  objectEach(names, function (name) {
    result = result[name];

    if (result === void 0) {
      result = void 0;

      return false;
    }
  });

  return result;
}

/**
 * Return object length (recursively).
 *
 * @param {*} object Object for which we want get length.
 * @returns {Number}
 */
function deepObjectSize(object) {
  if (!isObject(object)) {
    return 0;
  }
  var recursObjLen = function recursObjLen(obj) {
    var result = 0;

    if (isObject(obj)) {
      objectEach(obj, function (key) {
        result += recursObjLen(key);
      });
    } else {
      result++;
    }

    return result;
  };

  return recursObjLen(object);
}

/**
 * Create object with property where its value change will be observed.
 *
 * @param {*} [defaultValue=undefined] Default value.
 * @param {String} [propertyToListen='value'] Property to listen.
 * @returns {Object}
 */
function createObjectPropListener(defaultValue) {
  var _holder;

  var propertyToListen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'value';

  var privateProperty = '_' + propertyToListen;
  var holder = (_holder = {
    _touched: false
  }, _defineProperty(_holder, privateProperty, defaultValue), _defineProperty(_holder, 'isTouched', function isTouched() {
    return this._touched;
  }), _holder);

  Object.defineProperty(holder, propertyToListen, {
    get: function get() {
      return this[privateProperty];
    },
    set: function set(value) {
      this._touched = true;
      this[privateProperty] = value;
    },

    enumerable: true,
    configurable: true
  });

  return holder;
}

/**
 * Check if at specified `key` there is any value for `object`.
 *
 * @param {Object} object Object to search value at specyfic key.
 * @param {String} key String key to check.
 */
function hasOwnProperty(object, key) {
  return Object.prototype.hasOwnProperty.call(object, key);
}

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.to2dArray = to2dArray;
exports.extendArray = extendArray;
exports.pivot = pivot;
exports.arrayReduce = arrayReduce;
exports.arrayFilter = arrayFilter;
exports.arrayMap = arrayMap;
exports.arrayEach = arrayEach;
exports.arraySum = arraySum;
exports.arrayMax = arrayMax;
exports.arrayMin = arrayMin;
exports.arrayAvg = arrayAvg;
exports.arrayFlatten = arrayFlatten;
exports.arrayUnique = arrayUnique;
function to2dArray(arr) {
  var i = 0,
      ilen = arr.length;

  while (i < ilen) {
    arr[i] = [arr[i]];
    i++;
  }
}

function extendArray(arr, extension) {
  var i = 0,
      ilen = extension.length;

  while (i < ilen) {
    arr.push(extension[i]);
    i++;
  }
}

function pivot(arr) {
  var pivotedArr = [];

  if (!arr || arr.length === 0 || !arr[0] || arr[0].length === 0) {
    return pivotedArr;
  }

  var rowCount = arr.length;
  var colCount = arr[0].length;

  for (var i = 0; i < rowCount; i++) {
    for (var j = 0; j < colCount; j++) {
      if (!pivotedArr[j]) {
        pivotedArr[j] = [];
      }

      pivotedArr[j][i] = arr[i][j];
    }
  }

  return pivotedArr;
}

/**
 * A specialized version of `.reduce` for arrays without support for callback
 * shorthands and `this` binding.
 *
 * {@link https://github.com/lodash/lodash/blob/master/lodash.js}
 *
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @param {Boolean} [initFromArray] Specify using the first element of `array` as the initial value.
 * @returns {*} Returns the accumulated value.
 */
function arrayReduce(array, iteratee, accumulator, initFromArray) {
  var index = -1,
      length = array.length;

  if (initFromArray && length) {
    accumulator = array[++index];
  }
  while (++index < length) {
    accumulator = iteratee(accumulator, array[index], index, array);
  }

  return accumulator;
}

/**
 * A specialized version of `.filter` for arrays without support for callback
 * shorthands and `this` binding.
 *
 * {@link https://github.com/lodash/lodash/blob/master/lodash.js}
 *
 * @param {Array} array The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
      length = array.length,
      resIndex = -1,
      result = [];

  while (++index < length) {
    var value = array[index];

    if (predicate(value, index, array)) {
      result[++resIndex] = value;
    }
  }

  return result;
}

/**
 * A specialized version of `.map` for arrays without support for callback
 * shorthands and `this` binding.
 *
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
      length = array.length,
      resIndex = -1,
      result = [];

  while (++index < length) {
    var value = array[index];

    result[++resIndex] = iteratee(value, index, array);
  }

  return result;
}

/**
 * A specialized version of `.forEach` for arrays without support for callback
 * shorthands and `this` binding.
 *
 * {@link https://github.com/lodash/lodash/blob/master/lodash.js}
 *
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  var index = -1,
      length = array.length;

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }

  return array;
}

/**
 * Calculate sum value for each item of the array.
 *
 * @param {Array} array The array to process.
 * @returns {Number} Returns calculated sum value.
 */
function arraySum(array) {
  return arrayReduce(array, function (a, b) {
    return a + b;
  }, 0);
}

/**
 * Returns the highest value from an array. Can be array of numbers or array of strings.
 * NOTICE: Mixed values is not supported.
 *
 * @param {Array} array The array to process.
 * @returns {Number} Returns the highest value from an array.
 */
function arrayMax(array) {
  return arrayReduce(array, function (a, b) {
    return a > b ? a : b;
  }, Array.isArray(array) ? array[0] : void 0);
}

/**
 * Returns the lowest value from an array. Can be array of numbers or array of strings.
 * NOTICE: Mixed values is not supported.
 *
 * @param {Array} array The array to process.
 * @returns {Number} Returns the lowest value from an array.
 */
function arrayMin(array) {
  return arrayReduce(array, function (a, b) {
    return a < b ? a : b;
  }, Array.isArray(array) ? array[0] : void 0);
}

/**
 * Calculate average value for each item of the array.
 *
 * @param {Array} array The array to process.
 * @returns {Number} Returns calculated average value.
 */
function arrayAvg(array) {
  if (!array.length) {
    return 0;
  }

  return arraySum(array) / array.length;
}

/**
 * Flatten multidimensional array.
 *
 * @param {Array} array Array of Arrays
 * @returns {Array}
 */
function arrayFlatten(array) {
  return arrayReduce(array, function (initial, value) {
    return initial.concat(Array.isArray(value) ? arrayFlatten(value) : value);
  }, []);
}

/**
 * Unique values in the array.
 *
 * @param {Array} array The array to process.
 * @returns {Array}
 */
function arrayUnique(array) {
  var unique = [];

  arrayEach(array, function (value) {
    if (unique.indexOf(value) === -1) {
      unique.push(value);
    }
  });

  return unique;
}

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(13);
var core = __webpack_require__(43);
var hide = __webpack_require__(31);
var redefine = __webpack_require__(30);
var ctx = __webpack_require__(32);
var PROTOTYPE = 'prototype';

var $export = function (type, name, source) {
  var IS_FORCED = type & $export.F;
  var IS_GLOBAL = type & $export.G;
  var IS_STATIC = type & $export.S;
  var IS_PROTO = type & $export.P;
  var IS_BIND = type & $export.B;
  var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
  var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
  var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
  var key, own, out, exp;
  if (IS_GLOBAL) source = name;
  for (key in source) {
    // contains in native
    own = !IS_FORCED && target && target[key] !== undefined;
    // export native or passed
    out = (own ? target : source)[key];
    // bind timers to global for call from export context
    exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
    // extend global
    if (target) redefine(target, key, out, type & $export.U);
    // export
    if (exports[key] != out) hide(exports, key, exp);
    if (IS_PROTO && expProto[key] != out) expProto[key] = out;
  }
};
global.core = core;
// type bitmap
$export.F = 1;   // forced
$export.G = 2;   // global
$export.S = 4;   // static
$export.P = 8;   // proto
$export.B = 16;  // bind
$export.W = 32;  // wrap
$export.U = 64;  // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;


/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.getListenersCounter = getListenersCounter;

var _element = __webpack_require__(0);

var _object = __webpack_require__(1);

var _feature = __webpack_require__(39);

var _event = __webpack_require__(12);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Counter which tracks unregistered listeners (useful for detecting memory leaks).
 *
 * @type {Number}
 */
var listenersCounter = 0;

/**
 * Event DOM manager for internal use in Handsontable.
 *
 * @class EventManager
 * @util
 */

var EventManager = function () {
  /**
   * @param {Object} [context=null]
   * @private
   */
  function EventManager() {
    var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

    _classCallCheck(this, EventManager);

    this.context = context || this;

    if (!this.context.eventListeners) {
      this.context.eventListeners = [];
    }
  }

  /**
   * Register specified listener (`eventName`) to the element.
   *
   * @param {Element} element Target element.
   * @param {String} eventName Event name.
   * @param {Function} callback Function which will be called after event occur.
   * @returns {Function} Returns function which you can easily call to remove that event
   */


  _createClass(EventManager, [{
    key: 'addEventListener',
    value: function addEventListener(element, eventName, callback) {
      var _this = this;

      var context = this.context;

      function callbackProxy(event) {
        event = extendEvent(context, event);

        callback.call(this, event);
      }
      this.context.eventListeners.push({
        element: element,
        event: eventName,
        callback: callback,
        callbackProxy: callbackProxy
      });

      if (window.addEventListener) {
        element.addEventListener(eventName, callbackProxy, false);
      } else {
        element.attachEvent('on' + eventName, callbackProxy);
      }
      listenersCounter++;

      return function () {
        _this.removeEventListener(element, eventName, callback);
      };
    }

    /**
     * Remove the event listener previously registered.
     *
     * @param {Element} element Target element.
     * @param {String} eventName Event name.
     * @param {Function} callback Function to remove from the event target. It must be the same as during registration listener.
     */

  }, {
    key: 'removeEventListener',
    value: function removeEventListener(element, eventName, callback) {
      var len = this.context.eventListeners.length;
      var tmpEvent = void 0;

      while (len--) {
        tmpEvent = this.context.eventListeners[len];

        if (tmpEvent.event == eventName && tmpEvent.element == element) {
          if (callback && callback != tmpEvent.callback) {
            /* eslint-disable no-continue */
            continue;
          }
          this.context.eventListeners.splice(len, 1);

          if (tmpEvent.element.removeEventListener) {
            tmpEvent.element.removeEventListener(tmpEvent.event, tmpEvent.callbackProxy, false);
          } else {
            tmpEvent.element.detachEvent('on' + tmpEvent.event, tmpEvent.callbackProxy);
          }
          listenersCounter--;
        }
      }
    }

    /**
     * Clear all previously registered events.
     *
     * @private
     * @since 0.15.0-beta3
     */

  }, {
    key: 'clearEvents',
    value: function clearEvents() {
      if (!this.context) {
        return;
      }
      var len = this.context.eventListeners.length;

      while (len--) {
        var event = this.context.eventListeners[len];

        if (event) {
          this.removeEventListener(event.element, event.event, event.callback);
        }
      }
    }

    /**
     * Clear all previously registered events.
     */

  }, {
    key: 'clear',
    value: function clear() {
      this.clearEvents();
    }

    /**
     * Destroy instance of EventManager.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.clearEvents();
      this.context = null;
    }

    /**
     * Trigger event at the specified target element.
     *
     * @param {Element} element Target element.
     * @param {String} eventName Event name.
     */

  }, {
    key: 'fireEvent',
    value: function fireEvent(element, eventName) {
      var options = {
        bubbles: true,
        cancelable: eventName !== 'mousemove',
        view: window,
        detail: 0,
        screenX: 0,
        screenY: 0,
        clientX: 1,
        clientY: 1,
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false,
        button: 0,
        relatedTarget: undefined
      };
      var event;

      if (document.createEvent) {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent(eventName, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget || document.body.parentNode);
      } else {
        event = document.createEventObject();
      }

      if (element.dispatchEvent) {
        element.dispatchEvent(event);
      } else {
        element.fireEvent('on' + eventName, event);
      }
    }
  }]);

  return EventManager;
}();

/**
 * @param {Object} context
 * @param {Event} event
 * @private
 * @returns {*}
 */


function extendEvent(context, event) {
  var componentName = 'HOT-TABLE';
  var isHotTableSpotted = void 0;
  var fromElement = void 0;
  var realTarget = void 0;
  var target = void 0;
  var len = void 0;
  var nativeStopImmediatePropagation = void 0;

  event.isTargetWebComponent = false;
  event.realTarget = event.target;

  nativeStopImmediatePropagation = event.stopImmediatePropagation;
  event.stopImmediatePropagation = function () {
    nativeStopImmediatePropagation.apply(this);
    (0, _event.stopImmediatePropagation)(this);
  };

  if (!EventManager.isHotTableEnv) {
    return event;
  }
  event = (0, _element.polymerWrap)(event);
  len = event.path ? event.path.length : 0;

  while (len--) {
    if (event.path[len].nodeName === componentName) {
      isHotTableSpotted = true;
    } else if (isHotTableSpotted && event.path[len].shadowRoot) {
      target = event.path[len];

      break;
    }
    if (len === 0 && !target) {
      target = event.path[len];
    }
  }
  if (!target) {
    target = event.target;
  }
  event.isTargetWebComponent = true;

  if ((0, _feature.isWebComponentSupportedNatively)()) {
    event.realTarget = event.srcElement || event.toElement;
  } else if ((0, _object.hasOwnProperty)(context, 'hot') || context.isHotTableEnv || context.wtTable) {
    // Polymer doesn't support `event.target` property properly we must emulate it ourselves
    if ((0, _object.hasOwnProperty)(context, 'hot')) {
      // Custom element
      fromElement = context.hot ? context.hot.view.wt.wtTable.TABLE : null;
    } else if (context.isHotTableEnv) {
      // Handsontable.Core
      fromElement = context.view.activeWt.wtTable.TABLE.parentNode.parentNode;
    } else if (context.wtTable) {
      // Walkontable
      fromElement = context.wtTable.TABLE.parentNode.parentNode;
    }
    realTarget = (0, _element.closest)(event.target, [componentName], fromElement);

    if (realTarget) {
      event.realTarget = fromElement.querySelector(componentName) || event.target;
    } else {
      event.realTarget = event.target;
    }
  }

  Object.defineProperty(event, 'target', {
    get: function get() {
      return (0, _element.polymerWrap)(target);
    },

    enumerable: true,
    configurable: true
  });

  return event;
}

exports.default = EventManager;
function getListenersCounter() {
  return listenersCounter;
};

/***/ }),
/* 5 */
/***/ (function(module, exports) {

module.exports = function (it) {
  return typeof it === 'object' ? it !== null : typeof it === 'function';
};


/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.isNumeric = isNumeric;
exports.rangeEach = rangeEach;
exports.rangeEachReverse = rangeEachReverse;
exports.valueAccordingPercent = valueAccordingPercent;
/**
 * Checks if value of n is a numeric one
 * http://jsperf.com/isnan-vs-isnumeric/4
 * @param n
 * @returns {boolean}
 */
function isNumeric(n) {
  /* eslint-disable */
  var t = typeof n === 'undefined' ? 'undefined' : _typeof(n);

  return t == 'number' ? !isNaN(n) && isFinite(n) : t == 'string' ? !n.length ? false : n.length == 1 ? /\d/.test(n) : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) : t == 'object' ? !!n && typeof n.valueOf() == 'number' && !(n instanceof Date) : false;
}

/**
 * A specialized version of `.forEach` defined by ranges.
 *
 * @param {Number} rangeFrom The number from start iterate.
 * @param {Number|Function} rangeTo The number where finish iterate or function as a iteratee.
 * @param {Function} [iteratee] The function invoked per iteration.
 */
function rangeEach(rangeFrom, rangeTo, iteratee) {
  var index = -1;

  if (typeof rangeTo === 'function') {
    iteratee = rangeTo;
    rangeTo = rangeFrom;
  } else {
    index = rangeFrom - 1;
  }
  while (++index <= rangeTo) {
    if (iteratee(index) === false) {
      break;
    }
  }
}

/**
 * A specialized version of `.forEach` defined by ranges iterable in reverse order.
 *
 * @param {Number} rangeFrom The number from start iterate.
 * @param {Number} rangeTo The number where finish iterate.
 * @param {Function} iteratee The function invoked per iteration.
 */
function rangeEachReverse(rangeFrom, rangeTo, iteratee) {
  var index = rangeFrom + 1;

  if (typeof rangeTo === 'function') {
    iteratee = rangeTo;
    rangeTo = 0;
  }
  while (--index >= rangeTo) {
    if (iteratee(index) === false) {
      break;
    }
  }
}

/**
 * Calculate value from percent.
 *
 * @param {Number} value Base value from percent will be calculated.
 * @param {String|Number} percent Can be Number or String (eq. `'33%'`).
 * @returns {Number}
 */
function valueAccordingPercent(value, percent) {
  percent = parseInt(percent.toString().replace('%', ''), 10);
  percent = parseInt(value * percent / 100, 10);

  return percent;
}

/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.getPluginName = exports.getRegistredPluginNames = exports.getPlugin = exports.registerPlugin = undefined;

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _object = __webpack_require__(1);

var _string = __webpack_require__(36);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var registeredPlugins = new WeakMap();

/**
 * Registers plugin under given name
 *
 * @param {String} pluginName
 * @param {Function} PluginClass
 */
/**
 * Utility to register plugins and common namespace for keeping reference to all plugins classes
 */
function registerPlugin(pluginName, PluginClass) {
  pluginName = (0, _string.toUpperCaseFirst)(pluginName);

  _pluginHooks2.default.getSingleton().add('construct', function () {
    var holder = void 0;

    if (!registeredPlugins.has(this)) {
      registeredPlugins.set(this, {});
    }
    holder = registeredPlugins.get(this);

    if (!holder[pluginName]) {
      holder[pluginName] = new PluginClass(this);
    }
  });
  _pluginHooks2.default.getSingleton().add('afterDestroy', function () {
    if (registeredPlugins.has(this)) {
      var pluginsHolder = registeredPlugins.get(this);

      (0, _object.objectEach)(pluginsHolder, function (plugin) {
        return plugin.destroy();
      });
      registeredPlugins.delete(this);
    }
  });
}

/**
 * @param {Object} instance
 * @param {String|Function} pluginName
 * @returns {Function} pluginClass Returns plugin instance if exists or `undefined` if not exists.
 */
function getPlugin(instance, pluginName) {
  if (typeof pluginName != 'string') {
    throw Error('Only strings can be passed as "plugin" parameter');
  }
  var _pluginName = (0, _string.toUpperCaseFirst)(pluginName);

  if (!registeredPlugins.has(instance) || !registeredPlugins.get(instance)[_pluginName]) {
    return void 0;
  }

  return registeredPlugins.get(instance)[_pluginName];
}

/**
 * Get all registred plugins names for concrete Handsontable instance.
 *
 * @param {Object} hotInstance
 * @returns {Array}
 */
function getRegistredPluginNames(hotInstance) {
  return registeredPlugins.has(hotInstance) ? Object.keys(registeredPlugins.get(hotInstance)) : [];
}

/**
 * Get plugin name.
 *
 * @param {Object} hotInstance
 * @param {Object} plugin
 * @returns {String|null}
 */
function getPluginName(hotInstance, plugin) {
  var pluginName = null;

  if (registeredPlugins.has(hotInstance)) {
    (0, _object.objectEach)(registeredPlugins.get(hotInstance), function (pluginInstance, name) {
      if (pluginInstance === plugin) {
        pluginName = name;
      }
    });
  }

  return pluginName;
}

exports.registerPlugin = registerPlugin;
exports.getPlugin = getPlugin;
exports.getRegistredPluginNames = getRegistredPluginNames;
exports.getPluginName = getPluginName;

/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
/**
 * Constants for parts of translation.
 */

var CONTEXT_MENU_ITEMS_NAMESPACE = exports.CONTEXT_MENU_ITEMS_NAMESPACE = 'ContextMenu:items';
var CONTEXTMENU_ITEMS_ROW_ABOVE = exports.CONTEXTMENU_ITEMS_ROW_ABOVE = CONTEXT_MENU_ITEMS_NAMESPACE + '.insertRowAbove';
var CONTEXTMENU_ITEMS_ROW_BELOW = exports.CONTEXTMENU_ITEMS_ROW_BELOW = CONTEXT_MENU_ITEMS_NAMESPACE + '.insertRowBelow';
var CONTEXTMENU_ITEMS_INSERT_LEFT = exports.CONTEXTMENU_ITEMS_INSERT_LEFT = CONTEXT_MENU_ITEMS_NAMESPACE + '.insertColumnOnTheLeft';
var CONTEXTMENU_ITEMS_INSERT_RIGHT = exports.CONTEXTMENU_ITEMS_INSERT_RIGHT = CONTEXT_MENU_ITEMS_NAMESPACE + '.insertColumnOnTheRight';
var CONTEXTMENU_ITEMS_REMOVE_ROW = exports.CONTEXTMENU_ITEMS_REMOVE_ROW = CONTEXT_MENU_ITEMS_NAMESPACE + '.removeRow';
var CONTEXTMENU_ITEMS_REMOVE_COLUMN = exports.CONTEXTMENU_ITEMS_REMOVE_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.removeColumn';
var CONTEXTMENU_ITEMS_UNDO = exports.CONTEXTMENU_ITEMS_UNDO = CONTEXT_MENU_ITEMS_NAMESPACE + '.undo';
var CONTEXTMENU_ITEMS_REDO = exports.CONTEXTMENU_ITEMS_REDO = CONTEXT_MENU_ITEMS_NAMESPACE + '.redo';
var CONTEXTMENU_ITEMS_READ_ONLY = exports.CONTEXTMENU_ITEMS_READ_ONLY = CONTEXT_MENU_ITEMS_NAMESPACE + '.readOnly';
var CONTEXTMENU_ITEMS_CLEAR_COLUMN = exports.CONTEXTMENU_ITEMS_CLEAR_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.clearColumn';

var CONTEXTMENU_ITEMS_COPY = exports.CONTEXTMENU_ITEMS_COPY = CONTEXT_MENU_ITEMS_NAMESPACE + '.copy';
var CONTEXTMENU_ITEMS_CUT = exports.CONTEXTMENU_ITEMS_CUT = CONTEXT_MENU_ITEMS_NAMESPACE + '.cut';

var CONTEXTMENU_ITEMS_FREEZE_COLUMN = exports.CONTEXTMENU_ITEMS_FREEZE_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.freezeColumn';
var CONTEXTMENU_ITEMS_UNFREEZE_COLUMN = exports.CONTEXTMENU_ITEMS_UNFREEZE_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.unfreezeColumn';

var CONTEXTMENU_ITEMS_MERGE_CELLS = exports.CONTEXTMENU_ITEMS_MERGE_CELLS = CONTEXT_MENU_ITEMS_NAMESPACE + '.mergeCells';
var CONTEXTMENU_ITEMS_UNMERGE_CELLS = exports.CONTEXTMENU_ITEMS_UNMERGE_CELLS = CONTEXT_MENU_ITEMS_NAMESPACE + '.unmergeCells';

var CONTEXTMENU_ITEMS_ADD_COMMENT = exports.CONTEXTMENU_ITEMS_ADD_COMMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.addComment';
var CONTEXTMENU_ITEMS_EDIT_COMMENT = exports.CONTEXTMENU_ITEMS_EDIT_COMMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.editComment';
var CONTEXTMENU_ITEMS_REMOVE_COMMENT = exports.CONTEXTMENU_ITEMS_REMOVE_COMMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.removeComment';
var CONTEXTMENU_ITEMS_READ_ONLY_COMMENT = exports.CONTEXTMENU_ITEMS_READ_ONLY_COMMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.readOnlyComment';

var CONTEXTMENU_ITEMS_ALIGNMENT = exports.CONTEXTMENU_ITEMS_ALIGNMENT = CONTEXT_MENU_ITEMS_NAMESPACE + '.align';
var CONTEXTMENU_ITEMS_ALIGNMENT_LEFT = exports.CONTEXTMENU_ITEMS_ALIGNMENT_LEFT = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.left';
var CONTEXTMENU_ITEMS_ALIGNMENT_CENTER = exports.CONTEXTMENU_ITEMS_ALIGNMENT_CENTER = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.center';
var CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT = exports.CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.right';
var CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY = exports.CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.justify';
var CONTEXTMENU_ITEMS_ALIGNMENT_TOP = exports.CONTEXTMENU_ITEMS_ALIGNMENT_TOP = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.top';
var CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE = exports.CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.middle';
var CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM = exports.CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM = CONTEXT_MENU_ITEMS_NAMESPACE + '.align.bottom';

var CONTEXTMENU_ITEMS_BORDERS = exports.CONTEXTMENU_ITEMS_BORDERS = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders';
var CONTEXTMENU_ITEMS_BORDERS_TOP = exports.CONTEXTMENU_ITEMS_BORDERS_TOP = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.top';
var CONTEXTMENU_ITEMS_BORDERS_RIGHT = exports.CONTEXTMENU_ITEMS_BORDERS_RIGHT = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.right';
var CONTEXTMENU_ITEMS_BORDERS_BOTTOM = exports.CONTEXTMENU_ITEMS_BORDERS_BOTTOM = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.bottom';
var CONTEXTMENU_ITEMS_BORDERS_LEFT = exports.CONTEXTMENU_ITEMS_BORDERS_LEFT = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.left';
var CONTEXTMENU_ITEMS_REMOVE_BORDERS = exports.CONTEXTMENU_ITEMS_REMOVE_BORDERS = CONTEXT_MENU_ITEMS_NAMESPACE + '.borders.remove';

var CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD = exports.CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD = CONTEXT_MENU_ITEMS_NAMESPACE + '.nestedHeaders.insertChildRow';
var CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD = exports.CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD = CONTEXT_MENU_ITEMS_NAMESPACE + '.nestedHeaders.detachFromParent';

var CONTEXTMENU_ITEMS_HIDE_COLUMN = exports.CONTEXTMENU_ITEMS_HIDE_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.hideColumn';
var CONTEXTMENU_ITEMS_SHOW_COLUMN = exports.CONTEXTMENU_ITEMS_SHOW_COLUMN = CONTEXT_MENU_ITEMS_NAMESPACE + '.showColumn';

var CONTEXTMENU_ITEMS_HIDE_ROW = exports.CONTEXTMENU_ITEMS_HIDE_ROW = CONTEXT_MENU_ITEMS_NAMESPACE + '.hideRow';
var CONTEXTMENU_ITEMS_SHOW_ROW = exports.CONTEXTMENU_ITEMS_SHOW_ROW = CONTEXT_MENU_ITEMS_NAMESPACE + '.showRow';

var FILTERS_NAMESPACE = exports.FILTERS_NAMESPACE = 'Filters:';
var FILTERS_CONDITIONS_NAMESPACE = exports.FILTERS_CONDITIONS_NAMESPACE = FILTERS_NAMESPACE + 'conditions';
var FILTERS_CONDITIONS_NONE = exports.FILTERS_CONDITIONS_NONE = FILTERS_CONDITIONS_NAMESPACE + '.none';
var FILTERS_CONDITIONS_EMPTY = exports.FILTERS_CONDITIONS_EMPTY = FILTERS_CONDITIONS_NAMESPACE + '.isEmpty';
var FILTERS_CONDITIONS_NOT_EMPTY = exports.FILTERS_CONDITIONS_NOT_EMPTY = FILTERS_CONDITIONS_NAMESPACE + '.isNotEmpty';
var FILTERS_CONDITIONS_EQUAL = exports.FILTERS_CONDITIONS_EQUAL = FILTERS_CONDITIONS_NAMESPACE + '.isEqualTo';
var FILTERS_CONDITIONS_NOT_EQUAL = exports.FILTERS_CONDITIONS_NOT_EQUAL = FILTERS_CONDITIONS_NAMESPACE + '.isNotEqualTo';
var FILTERS_CONDITIONS_BEGINS_WITH = exports.FILTERS_CONDITIONS_BEGINS_WITH = FILTERS_CONDITIONS_NAMESPACE + '.beginsWith';
var FILTERS_CONDITIONS_ENDS_WITH = exports.FILTERS_CONDITIONS_ENDS_WITH = FILTERS_CONDITIONS_NAMESPACE + '.endsWith';
var FILTERS_CONDITIONS_CONTAINS = exports.FILTERS_CONDITIONS_CONTAINS = FILTERS_CONDITIONS_NAMESPACE + '.contains';
var FILTERS_CONDITIONS_NOT_CONTAIN = exports.FILTERS_CONDITIONS_NOT_CONTAIN = FILTERS_CONDITIONS_NAMESPACE + '.doesNotContain';
var FILTERS_CONDITIONS_BY_VALUE = exports.FILTERS_CONDITIONS_BY_VALUE = FILTERS_CONDITIONS_NAMESPACE + '.byValue';
var FILTERS_CONDITIONS_GREATER_THAN = exports.FILTERS_CONDITIONS_GREATER_THAN = FILTERS_CONDITIONS_NAMESPACE + '.greaterThan';
var FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL = exports.FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL = FILTERS_CONDITIONS_NAMESPACE + '.greaterThanOrEqualTo';
var FILTERS_CONDITIONS_LESS_THAN = exports.FILTERS_CONDITIONS_LESS_THAN = FILTERS_CONDITIONS_NAMESPACE + '.lessThan';
var FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL = exports.FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL = FILTERS_CONDITIONS_NAMESPACE + '.lessThanOrEqualTo';
var FILTERS_CONDITIONS_BETWEEN = exports.FILTERS_CONDITIONS_BETWEEN = FILTERS_CONDITIONS_NAMESPACE + '.isBetween';
var FILTERS_CONDITIONS_NOT_BETWEEN = exports.FILTERS_CONDITIONS_NOT_BETWEEN = FILTERS_CONDITIONS_NAMESPACE + '.isNotBetween';
var FILTERS_CONDITIONS_AFTER = exports.FILTERS_CONDITIONS_AFTER = FILTERS_CONDITIONS_NAMESPACE + '.after';
var FILTERS_CONDITIONS_BEFORE = exports.FILTERS_CONDITIONS_BEFORE = FILTERS_CONDITIONS_NAMESPACE + '.before';
var FILTERS_CONDITIONS_TODAY = exports.FILTERS_CONDITIONS_TODAY = FILTERS_CONDITIONS_NAMESPACE + '.today';
var FILTERS_CONDITIONS_TOMORROW = exports.FILTERS_CONDITIONS_TOMORROW = FILTERS_CONDITIONS_NAMESPACE + '.tomorrow';
var FILTERS_CONDITIONS_YESTERDAY = exports.FILTERS_CONDITIONS_YESTERDAY = FILTERS_CONDITIONS_NAMESPACE + '.yesterday';

var FILTERS_DIVS_FILTER_BY_CONDITION = exports.FILTERS_DIVS_FILTER_BY_CONDITION = FILTERS_NAMESPACE + 'labels.filterByCondition';
var FILTERS_DIVS_FILTER_BY_VALUE = exports.FILTERS_DIVS_FILTER_BY_VALUE = FILTERS_NAMESPACE + 'labels.filterByValue';

var FILTERS_LABELS_CONJUNCTION = exports.FILTERS_LABELS_CONJUNCTION = FILTERS_NAMESPACE + 'labels.conjunction';
var FILTERS_LABELS_DISJUNCTION = exports.FILTERS_LABELS_DISJUNCTION = FILTERS_NAMESPACE + 'labels.disjunction';

var FILTERS_VALUES_BLANK_CELLS = exports.FILTERS_VALUES_BLANK_CELLS = FILTERS_NAMESPACE + 'values.blankCells';

var FILTERS_BUTTONS_SELECT_ALL = exports.FILTERS_BUTTONS_SELECT_ALL = FILTERS_NAMESPACE + 'buttons.selectAll';
var FILTERS_BUTTONS_CLEAR = exports.FILTERS_BUTTONS_CLEAR = FILTERS_NAMESPACE + 'buttons.clear';
var FILTERS_BUTTONS_OK = exports.FILTERS_BUTTONS_OK = FILTERS_NAMESPACE + 'buttons.ok';
var FILTERS_BUTTONS_CANCEL = exports.FILTERS_BUTTONS_CANCEL = FILTERS_NAMESPACE + 'buttons.cancel';

var FILTERS_BUTTONS_PLACEHOLDER_SEARCH = exports.FILTERS_BUTTONS_PLACEHOLDER_SEARCH = FILTERS_NAMESPACE + 'buttons.placeholder.search';
var FILTERS_BUTTONS_PLACEHOLDER_VALUE = exports.FILTERS_BUTTONS_PLACEHOLDER_VALUE = FILTERS_NAMESPACE + 'buttons.placeholder.value';
var FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE = exports.FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE = FILTERS_NAMESPACE + 'buttons.placeholder.secondValue';

/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.getRegisteredRenderers = exports.getRegisteredRendererNames = exports.hasRenderer = exports.getRenderer = exports.registerRenderer = undefined;

var _staticRegister2 = __webpack_require__(46);

var _staticRegister3 = _interopRequireDefault(_staticRegister2);

var _cellDecorator = __webpack_require__(357);

var _cellDecorator2 = _interopRequireDefault(_cellDecorator);

var _autocompleteRenderer = __webpack_require__(358);

var _autocompleteRenderer2 = _interopRequireDefault(_autocompleteRenderer);

var _checkboxRenderer = __webpack_require__(359);

var _checkboxRenderer2 = _interopRequireDefault(_checkboxRenderer);

var _htmlRenderer = __webpack_require__(360);

var _htmlRenderer2 = _interopRequireDefault(_htmlRenderer);

var _numericRenderer = __webpack_require__(361);

var _numericRenderer2 = _interopRequireDefault(_numericRenderer);

var _passwordRenderer = __webpack_require__(363);

var _passwordRenderer2 = _interopRequireDefault(_passwordRenderer);

var _textRenderer = __webpack_require__(364);

var _textRenderer2 = _interopRequireDefault(_textRenderer);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _staticRegister = (0, _staticRegister3.default)('renderers'),
    register = _staticRegister.register,
    getItem = _staticRegister.getItem,
    hasItem = _staticRegister.hasItem,
    getNames = _staticRegister.getNames,
    getValues = _staticRegister.getValues;

register('base', _cellDecorator2.default);
register('autocomplete', _autocompleteRenderer2.default);
register('checkbox', _checkboxRenderer2.default);
register('html', _htmlRenderer2.default);
register('numeric', _numericRenderer2.default);
register('password', _passwordRenderer2.default);
register('text', _textRenderer2.default);

/**
 * Retrieve renderer function.
 *
 * @param {String} name Renderer identification.
 * @returns {Function} Returns renderer function.
 */
function _getItem(name) {
  if (typeof name === 'function') {
    return name;
  }
  if (!hasItem(name)) {
    throw Error('No registered renderer found under "' + name + '" name');
  }

  return getItem(name);
}

exports.registerRenderer = register;
exports.getRenderer = _getItem;
exports.hasRenderer = hasItem;
exports.getRegisteredRendererNames = getNames;
exports.getRegisteredRenderers = getValues;

/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {

var store = __webpack_require__(73)('wks');
var uid = __webpack_require__(48);
var Symbol = __webpack_require__(13).Symbol;
var USE_SYMBOL = typeof Symbol == 'function';

var $exports = module.exports = function (name) {
  return store[name] || (store[name] =
    USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};

$exports.store = store;


/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _array = __webpack_require__(2);

var _object = __webpack_require__(1);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @description
 * Handsontable events are the common interface that function in 2 ways: as __callbacks__ and as __hooks__.
 *
 * @example
 *
 * ```js
 * // Using events as callbacks:
 * ...
 * var hot1 = new Handsontable(document.getElementById('example1'), {
 *   afterChange: function(changes, source) {
 *     $.ajax({
 *       url: "save.php',
 *       data: change
 *     });
 *   }
 * });
 * ...
 * ```
 *
 * ```js
 * // Using events as plugin hooks:
 * ...
 * var hot1 = new Handsontable(document.getElementById('example1'), {
 *   myPlugin: true
 * });
 *
 * var hot2 = new Handsontable(document.getElementById('example2'), {
 *   myPlugin: false
 * });
 *
 * // global hook
 * Handsontable.hooks.add('afterChange', function() {
 *   // Fired twice - for hot1 and hot2
 *   if (this.getSettings().myPlugin) {
 *     // function body - will only run for hot1
 *   }
 * });
 *
 * // local hook (has same effect as a callback)
 * hot2.addHook('afterChange', function() {
 *   // function body - will only run in #example2
 * });
 * ```
 * ...
 */

// @TODO: Move plugin description hooks to plugin?
var REGISTERED_HOOKS = [
/**
 * Callback fired after resetting a cell's meta.
 *
 * @event Hooks#afterCellMetaReset
 * @since 0.11
 */
'afterCellMetaReset',

/**
 * @description
 * Callback fired after one or more cells has been changed. Its main use case is to save the input.
 *
 * __Note:__ For performance reasons, the `changes` array is null for `"loadData"` source.
 *
 * @event Hooks#afterChange
 * @param {Array} changes 2D array containing information about each of the edited cells `[[row, prop, oldVal, newVal], ...]`.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'afterChange',

/**
 * @description
 * Fired after observing changes.
 *
 * @event Hooks#afterChangesObserved
 */
'afterChangesObserved',

/**
 * @description
 * Fired after setting up the Context Menu's default options. These options are a collection which user can select by setting
 * an array of keys or an array of objects in `contextMenu` option.
 *
 * @event Hooks#afterContextMenuDefaultOptions
 * @param {Array} predefinedItems Array of objects containing information about the pre-defined Context Menu items.
 */
'afterContextMenuDefaultOptions',

/**
 * @description
 * Fired before setting up the Context Menu's items but after filtering these options by user (`contextMenu` option). This hook
 * can by helpful to determine if user use specified menu item or to set up one of the menu item to by always visible.
 *
 * @event Hooks#beforeContextMenuSetItems
 * @param {Array} menuItems Array of objects containing information about to generated Context Menu items.
 */
'beforeContextMenuSetItems',

/**
 * @description
 * Fired after setting up the Context Menu's default options. These options are a collection which user can select by setting
 * an array of keys or an array of objects in `contextMenu` option.
 *
 * @pro
 * @event Hooks#afterDropdownMenuDefaultOptions
 * @param {Array} predefinedItems Array of objects containing information about the pre-defined Context Menu items.
 */
'afterDropdownMenuDefaultOptions',

/**
 * @description
 * Fired before setting up the Dropdown Menu's items but after filtering these options by user (`dropdownMenu` option). This hook
 * can by helpful to determine if user use specified menu item or to set up one of the menu item to by always visible.
 *
 * @pro
 * @event Hooks#beforeDropdownMenuSetItems
 * @param {Array} menuItems Array of objects containing information about to generated Dropdown Menu items.
 */
'beforeDropdownMenuSetItems',

/**
 * @description
 * Fired after hiding the Context Menu.
 *
 * @event Hooks#afterContextMenuHide
 * @param {Object} context The Context menu instance.
 */
'afterContextMenuHide',

/**
 * @description
 * Fired after opening the Context Menu.
 *
 * @event Hooks#afterContextMenuShow
 * @param {Object} context The Context Menu instance.
 */
'afterContextMenuShow',

/**
 * @description
 * Fired after reaching the copy limit while copying data.
 *
 * @event Hooks#afterCopyLimit
 * @param {Number} selectedRows Count of selected copyable rows.
 * @param {Number} selectedColumns Count of selected copyable columns.
 * @param {Number} copyRowsLimit Current copy rows limit.
 * @param {Number} copyColumnsLimit Current copy columns limit.
 */
'afterCopyLimit',

/**
 * Callback is fired before a new column was created.
 *
 * @since 0.28.0
 * @event Hooks#beforeCreateCol
 * @param {Number} index Represents the visual index of first newly created column in the data source array.
 * @param {Number} amount Number of newly created columns in the data source array.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'beforeCreateCol',

/**
 * Callback is fired after a new column was created.
 *
 * @event Hooks#afterCreateCol
 * @param {Number} index Represents the visual index of first newly created column in the data source array.
 * @param {Number} amount Number of newly created columns in the data source array.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'afterCreateCol',

/**
 * Callback is fired before a new row was created.
 *
 * @since 0.28.0
 * @event Hooks#beforeCreateRow
 * @param {Number} index Represents the visual index of first newly created row in the data source array.
 * @param {Number} amount Number of newly created rows in the data source array.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'beforeCreateRow',

/**
 * Callback is fired after a new row was created.
 *
 * @event Hooks#afterCreateRow
 * @param {Number} index Represents the visual index of first newly created row in the data source array.
 * @param {Number} amount Number of newly created rows in the data source array.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'afterCreateRow',

/**
 * Fired after the current cell is deselected.
 *
 * @event Hooks#afterDeselect
 */
'afterDeselect',

/**
 * Fired after destroying the Handsontable instance.
 *
 * @event Hooks#afterDestroy
 */
'afterDestroy',

/**
 * Fired on a `keydown` event on the document body.
 *
 * @event Hooks#afterDocumentKeyDown
 * @param {Event} event A `keydown` event.
 */
'afterDocumentKeyDown',

/**
 * Callback fired after getting the cell settings.
 *
 * @event Hooks#afterGetCellMeta
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @param {Object} cellProperties Object containing the cell properties.
 */
'afterGetCellMeta',

/**
 * Callback fired after retrieving information about a column header and appending it to the table header.
 *
 * @event Hooks#afterGetColHeader
 * @param {Number} col Visual column index.
 * @param {Element} TH Header's TH element.
 */
'afterGetColHeader',

/**
 * Callback fired after retrieving information about a column header and appending it to the table header.
 *
 * @event Hooks#afterGetRowHeader
 * @param {Number} row Visual row index.
 * @param {Element} TH Header's TH element.
 */
'afterGetRowHeader',

/**
 * Callback fired after Handsontable instance is initiated.
 *
 * @event Hooks#afterInit
 */
'afterInit',

/**
 * Callback fired after new data is loaded (by `loadData` method) into the data source array.
 *
 * @event Hooks#afterLoadData
 * @param {Boolean} firstTime flag that determines whether the data has been loaded during the initialization.
 */
'afterLoadData',

/**
 * Fired after a scroll event, which is identified as a momentum scroll (e.g. on an iPad).
 *
 * @event Hooks#afterMomentumScroll
 */
'afterMomentumScroll',

/**
 * Fired after a `mousedown` event is triggered on the cell corner (the drag handle).
 *
 * @event Hooks#afterOnCellCornerMouseDown
 * @since 0.11
 * @param {Object} event `mousedown` event object.
 */
'afterOnCellCornerMouseDown',

/**
 * Fired after a `dblclick` event is triggered on the cell corner (the drag handle).
 *
 * @event Hooks#afterOnCellCornerDblClick
 * @since 0.30.0
 * @param {Object} event `dblclick` event object.
 */
'afterOnCellCornerDblClick',

/**
 * Callback fired after clicking on a cell or row/column header.
 * In case the row/column header was clicked, the index is negative.
 * For example clicking on the row header of cell (0, 0) results with `afterOnCellMouseDown` called
 * with coords `{row: 0, col: -1}`.
 *
 * @event Hooks#afterOnCellMouseDown
 * @since 0.11
 * @param {Object} event `mousedown` event object.
 * @param {Object} coords Coordinates object containing the visual row and visual column indexes of the clicked cell.
 * @param {Element} TD Cell's TD (or TH) element.
 */
'afterOnCellMouseDown',

/**
 * Callback fired after hovering a cell or row/column header with the mouse cursor.
 * In case the row/column header was hovered, the index is negative.
 * For example, hovering over the row header of cell (0, 0) results with `afterOnCellMouseOver` called
 * with coords `{row: 0, col: -1}`.
 *
 * @event Hooks#afterOnCellMouseOver
 * @since 0.11
 * @param {Object} event `mouseover` event object.
 * @param {Object} coords Hovered cell's visual coordinate object.
 * @param {Element} TD Cell's TD (or TH) element.
 */
'afterOnCellMouseOver',

/**
 * Callback fired after leaving a cell or row/column header with the mouse cursor.
 *
 * @event Hooks#afterOnCellMouseOut
 * @since 0.31.1
 * @param {Object} event `mouseout` event object.
 * @param {Object} coords Leaved cell's visual coordinate object.
 * @param {Element} TD Cell's TD (or TH) element.
 */
'afterOnCellMouseOut',

/**
 * Callback is fired when one or more columns are removed.
 *
 * @event Hooks#afterRemoveCol
 * @param {Number} index Is an visual index of starter column.
 * @param {Number} amount Is an amount of removed columns.
 */
'afterRemoveCol',

/**
 * Callback is fired when one or more rows are removed.
 *
 * @event Hooks#afterRemoveRow
 * @param {Number} index Is an visual index of starter row.
 * @param {Number} amount Is an amount of removed rows.
 */
'afterRemoveRow',

/**
 * Callback fired after the Handsontable table is rendered.
 *
 * @event Hooks#afterRender
 * @param {Boolean} isForced Is `true` if rendering was triggered by a change of settings or data; or `false` if
 *                           rendering was triggered by scrolling or moving selection.
 */
'afterRender',

/**
 * Fired before starting rendering the cell.
 *
 * @event Hooks#beforeRenderer
 * @since 0.24.2
 * @param {Element} TD Currently rendered cell's TD element.
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @param {String|Number} prop Column property name or a column index, if datasource is an array of arrays.
 * @param {String} value Value of the rendered cell.
 * @param {Object} cellProperties Object containing the cell's properties.
 */
'beforeRenderer',

/**
 * Fired after finishing rendering the cell (after the renderer finishes).
 *
 * @event Hooks#afterRenderer
 * @since 0.11.0
 * @param {Element} TD Currently rendered cell's TD element.
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @param {String|Number} prop Column property name or a column index, if datasource is an array of arrays.
 * @param {String} value Value of the rendered cell.
 * @param {Object} cellProperties Object containing the cell's properties.
 */
'afterRenderer',

/**
 * Fired after the horizontal scroll event.
 *
 * @event Hooks#afterScrollHorizontally
 * @since 0.11
 */
'afterScrollHorizontally',

/**
 * Fired after the vertical scroll event.
 *
 * @event Hooks#afterScrollVertically
 * @since 0.11
 */
'afterScrollVertically',

/**
 * Callback fired after one or more cells are selected (e.g. during mouse move).
 *
 * @event Hooks#afterSelection
 * @param {Number} r Selection start visual row index.
 * @param {Number} c Selection start visual column index.
 * @param {Number} r2 Selection end visual row index.
 * @param {Number} c2 Selection end visual column index.
 * @param {Object} preventScrolling Object with `value` property where its value change will be observed.
 *    * @example
 * ```js
 * handsontable({
 *   afterSelection: function (r, c, r2, c2, preventScrolling) {
 *     // setting if prevent scrolling after selection
 *
 *     preventScrolling.value = true;
 *   }
 * })
 * ```
 */
'afterSelection',

/**
 * Callback fired after one or more cells are selected. The `p` argument represents the source object property name instead of the column number.
 *
 * @event Hooks#afterSelectionByProp
 * @param {Number} r Selection start visual row index.
 * @param {String} p Selection start data source object property name.
 * @param {Number} r2 Selection end visual row index.
 * @param {String} p2 Selection end data source object property name.
 * @param {Object} preventScrolling Object with `value` property where its value change will be observed.
 *    * @example
 * ```js
 * handsontable({
 *   afterSelectionByProp: function (r, c, r2, c2, preventScrolling) {
 *     // setting if prevent scrolling after selection
 *
 *     preventScrolling.value = true;
 *   }
 * })
 * ```
 */
'afterSelectionByProp',

/**
 * Callback fired after one or more cells are selected (e.g. on mouse up).
 *
 * @event Hooks#afterSelectionEnd
 * @param {Number} r Selection start visual row index.
 * @param {Number} c Selection start visual column index.
 * @param {Number} r2 Selection end visual row index.
 * @param {Number} c2 Selection end visual column index.
 */
'afterSelectionEnd',

/**
 * Callback fired after one or more cells are selected (e.g. on mouse up). The `p` argument represents the data source object
 * property name instead of the column number.
 *
 * @event Hooks#afterSelectionEndByProp
 * @param {Number} r Selection start visual row index.
 * @param {String} p Selection start data source object property index.
 * @param {Number} r2 Selection end visual row index.
 * @param {String} p2 Selection end data source object property index.
 */
'afterSelectionEndByProp',

/**
 * Called after cell meta is changed.
 *
 * @event Hooks#afterSetCellMeta
 * @since 0.11.0
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @param {String} key The updated meta key.
 * @param {*} value The updated meta value.
 */
'afterSetCellMeta',

/**
 * Called after cell meta is removed.
 *
 * @event Hooks#afterRemoveCellMeta
 * @since 0.33.1
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @param {String} key The removed meta key.
 * @param {*} value Value which was under removed key of cell meta.
 */
'afterRemoveCellMeta',

/**
 * Called after cell data was changed.
 *
 * @event Hooks#afterSetDataAtCell
 * @since 0.28.0
 * @param {Array} changes An array of changes in format `[[row, col, oldValue, value], ...]`.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'afterSetDataAtCell',

/**
 * Called after cell data was changed.
 *
 * @event Hooks#afterSetDataAtRowProp
 * @since 0.28.0
 * @param {Array} changes An array of changes in format `[[row, prop, oldValue, value], ...]`.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'afterSetDataAtRowProp',

/**
 * Fired after calling the `updateSettings` method.
 *
 * @event Hooks#afterUpdateSettings
 * @param {Object} settings New settings object.
 */
'afterUpdateSettings',

/**
 * @description
 * A plugin hook executed after validator function, only if validator function is defined.
 * Validation result is the first parameter. This can be used to determinate if validation passed successfully or not.
 *
 * __Returning false from the callback will mark the cell as invalid.__
 *
 * @event Hooks#afterValidate
 * @since 0.9.5
 * @param {Boolean} isValid `true` if valid, `false` if not.
 * @param {*} value The value in question.
 * @param {Number} row Row index.
 * @param {String|Number} prop Property name / column index.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'afterValidate',

/**
 * Fired before successful change of language (when proper language code was set)
 *
 * @event Hooks#beforeLanguageChange
 * @since 0.35.0
 * @param {String} languageCode New language code.
 */
'beforeLanguageChange',

/**
 * Fired after successful change of language (when proper language code was set)
 *
 * @event Hooks#afterLanguageChange
 * @since 0.35.0
 * @param {String} languageCode New language code.
 */
'afterLanguageChange',

/**
 * Fired before populating the data in the autofill feature.
 *
 * @event Hooks#beforeAutofill
 * @param {Object} start Object containing information about first filled cell: `{row: 2, col: 0}`.
 * @param {Object} end Object containing information about last filled cell: `{row: 4, col: 1}`.
 * @param {Array} data 2D array containing information about fill pattern: `[["1', "Ted"], ["1', "John"]]`.
 */
'beforeAutofill',

/**
 * Fired before aligning the cell contents.
 *
 * @event Hooks#beforeCellAlignment
 * @param stateBefore
 * @param range
 * @param {String} type Type of the alignment - either `horizontal` or `vertical`
 * @param {String} alignmentClass String defining the alignment class added to the cell.
 * Possible values:
 * * `htLeft`,
 * * `htCenter`,
 * * `htRight`,
 * * `htJustify`
 * for horizontal alignment,
 *
 *
 * * `htTop`,
 * * `htMiddle`,
 * * `htBottom`
 * for vertical alignment.
 */
'beforeCellAlignment',

/**
 * Callback fired before one or more cells is changed. Its main purpose is to alter changes silently before input.
 *
 * @event Hooks#beforeChange
 * @param {Array} changes 2D array containing information about each of the edited cells.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 * @example
 * ```js
 * // To disregard a single change, set changes[i] to null or remove it from array using changes.splice(i, 1).
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforeChange: function(changes, source) {
 *     // [[row, prop, oldVal, newVal], ...]
 *     changes[0] = null;
 *   }
 * });
 * ...
 *
 * // To alter a single change, overwrite the desired value to changes[i][3].
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforeChange: function(changes, source) {
 *     // [[row, prop, oldVal, newVal], ...]
 *     changes[0][3] = 10;
 *   }
 * });
 * ...
 *
 * // To cancel all edit, return false from the callback or set array length to 0 (changes.length = 0).
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforeChange: function(changes, source) {
 *     // [[row, prop, oldVal, newVal], ...]
 *     return false;
 *   }
 * });
 * ...
 * ```
 */
'beforeChange',

/**
 * Fired right before rendering the changes.
 *
 * @event Hooks#beforeChangeRender
 * @since 0.11
 * @param {Array} changes Array in form of [row, prop, oldValue, newValue].
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'beforeChangeRender',

/**
 * Fired before drawing the borders.
 *
 * @event Hooks#beforeDrawBorders
 * @param {Array} corners Array specifying the current selection borders.
 * @param {String} borderClassName Specifies the border class name.
 */
'beforeDrawBorders',

/**
 * Callback fired before getting cell settings.
 *
 * @event Hooks#beforeGetCellMeta
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @param {Object} cellProperties Object containing the cell's properties.
 */
'beforeGetCellMeta',

/**
 * Called before cell meta is removed.
 *
 * @event Hooks#beforeRemoveCellMeta
 * @since 0.33.1
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @param {String} key The removed meta key.
 * @param {*} value Value which is under removed key of cell meta.
 */
'beforeRemoveCellMeta',

/**
 * @description
 * Callback fired before Handsontable instance is initiated.
 *
 * @event Hooks#beforeInit
 */
'beforeInit',

/**
 * Callback fired before Walkontable instance is initiated.
 *
 * @since 0.11
 * @event Hooks#beforeInitWalkontable
 * @param {Object} walkontableConfig Walkontable configuration object.
 */
'beforeInitWalkontable',

/**
 * Callback fired before keydown event is handled. It can be used to overwrite default key bindings.
 * Caution - in your `beforeKeyDown` handler you need to call `event.stopImmediatePropagation()` to prevent default key behavior.
 *
 * @event Hooks#beforeKeyDown
 * @since 0.9.0
 * @param {Event} event Original DOM event.
 */
'beforeKeyDown',

/**
 * Fired after the user clicked a cell, but before all the calculations related with it.
 *
 * @event Hooks#beforeOnCellMouseDown
 * @param {Event} event The `mousedown` event object.
 * @param {CellCoords} coords Cell coords object containing the visual coordinates of the clicked cell.
 * @param {Element} TD TD element.
 */
'beforeOnCellMouseDown',

/**
 * Fired after the user moved cursor over a cell, but before all the calculations related with it.
 *
 * @event Hooks#beforeOnCellMouseOver
 * @param {Event} event The `mouseover` event object.
 * @param {CellCoords} coords CellCoords object containing the visual coordinates of the clicked cell.
 * @param {Element} TD TD element.
 * @param {Object} blockCalculations Contain keys 'row' and 'column' with boolean value.
 */
'beforeOnCellMouseOver',

/**
 * Fired after the user moved cursor out from a cell, but before all the calculations related with it.
 *
 * @event Hooks#beforeOnCellMouseOut
 * @since 0.31.1
 * @param {Event} event The `mouseout` event object.
 * @param {WalkontableCellCoords} coords WalkontableCellCoords object containing the visual coordinates of the leaved cell.
 * @param {Element} TD TD element.
 */
'beforeOnCellMouseOut',

/**
 * Callback is fired when one or more columns are about to be removed.
 *
 * @event Hooks#beforeRemoveCol
 * @param {Number} index Visual index of starter column.
 * @param {Number} amount Amount of columns to be removed.
 * @param {Array} [visualCols] Consists of visual indexes of processed columns.
 */
'beforeRemoveCol',

/**
 * Callback is fired when one or more rows are about to be removed.
 *
 * @event Hooks#beforeRemoveRow
 * @param {Number} index Visual index of starter column.
 * @param {Number} amount Amount of columns to be removed.
 * @param {Array} [visualRows] Consists of visual indexes of processed rows.
 */
'beforeRemoveRow',

/**
 * Callback fired before Handsontable table is rendered.
 *
 * @event Hooks#beforeRender
 * @param {Boolean} isForced If `true` rendering was triggered by a change of settings or data; or `false` if
 *                           rendering was triggered by scrolling or moving selection.
 */
'beforeRender',

/**
 * Callback fired before setting range is started.
 *
 * @event Hooks#beforeSetRangeStart
 * @param {Array} coords CellCoords array.
 */
'beforeSetRangeStart',

/**
 * Callback fired before setting range is ended.
 *
 * @event Hooks#beforeSetRangeEnd
 * @param {Array} coords CellCoords array.
 */
'beforeSetRangeEnd',

/**
 * Fired before the logic of handling a touch scroll, when user started scrolling on a touch-enabled device.
 *
 * @event Hooks#beforeTouchScroll
 */
'beforeTouchScroll',

/**
 * @description
 * A plugin hook executed before validator function, only if validator function is defined.
 * This can be used to manipulate the value of changed cell before it is applied to the validator function.
 *
 * __Notice:__ this will not affect values of changes. This will change value ONLY for validation!
 *
 * @event Hooks#beforeValidate
 * @since 0.9.5
 * @param {*} value Value of the cell.
 * @param {Number} row Row index.
 * @param {String|Number} prop Property name / column index.
 * @param {String} [source] String that identifies source of hook call
 *                          ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}).
 */
'beforeValidate',

/**
 * Callback fired before cell value is rendered into the DOM (through renderer function).
 *
 * @event Hooks#beforeValueRender
 * @since 0.29.0
 * @param {*} value Cell value to render.
 */
'beforeValueRender',

/**
 * Callback fired after Handsontable instance is constructed (via `new` operator).
 *
 * @event Hooks#construct
 * @since 0.16.1
 */
'construct',

/**
 * Callback fired after Handsontable instance is initiated but before table is rendered.
 *
 * @event Hooks#init
 * @since 0.16.1
 */
'init',

/**
 * Fired when a column index is about to be modified by a callback function.
 *
 * @event Hooks#modifyCol
 * @since 0.11
 * @param {Number} col Visual column index.
 */
'modifyCol',

/**
 * Fired when a column index is about to be de-modified by a callback function.
 *
 * @event Hooks#unmodifyCol
 * @since 0.23.0
 * @param {Number} col Physical column index.
 */
'unmodifyCol',

/**
 * Fired when a physical row index is about to be de-modified by a callback function.
 *
 * @event Hooks#unmodifyRow
 * @since 0.26.2
 * @param {Number} row Physical row index.
 */
'unmodifyRow',
/**
 * Fired when a column header index is about to be modified by a callback function.
 *
 * @event Hooks#modifyColHeader
 * @since 0.20.0
 * @param {Number} column Visual column header index.
 */
'modifyColHeader',

/**
 * Fired when a column width is about to be modified by a callback function.
 *
 * @event Hooks#modifyColWidth
 * @since 0.11
 * @param {Number} width Current column width.
 * @param {Number} col Column index.
 */
'modifyColWidth',

/**
 * Fired when a row index is about to be modified by a callback function.
 *
 * @event Hooks#modifyRow
 * @since 0.11
 * @param {Number} row Row index.
 */
'modifyRow',

/**
 * Fired when a row header index is about to be modified by a callback function.
 *
 * @event Hooks#modifyRowHeader
 * @since 0.20.0
 * @param {Number} row Row header index.
 */
'modifyRowHeader',

/**
 * Fired when a row height is about to be modified by a callback function.
 *
 * @event Hooks#modifyRowHeight
 * @since 0.11.0
 * @param {Number} height Row height.
 * @param {Number} row Row index.
 */
'modifyRowHeight',

/**
 * Fired when a data was retrieved or modified.
 *
 * @event Hooks#modifyData
 * @since 0.28.0
 * @param {Number} row Row height.
 * @param {Number} column Column index.
 * @param {Object} valueHolder Object which contains original value which can be modified by overwriting `.value` property.
 * @param {String} ioMode String which indicates for what operation hook is fired (`get` or `set`).
 */
'modifyData',

/**
 * Fired when a data was retrieved or modified.
 *
 * @event Hooks#modifyRowData
 * @since 0.28.0
 * @param {Number} row Physical row index.
 */
'modifyRowData',

/**
 * Fired after loading data using the Persistent State plugin.
 *
 * @event Hooks#persistentStateLoad
 * @param {String} key Key string.
 * @param {Object} valuePlaceholder Object containing the loaded data.
 */
'persistentStateLoad',

/**
 * Fired after resetting data using the Persistent State plugin.
 *
 * @event Hooks#persistentStateReset
 * @param {String} key Key string.
 */
'persistentStateReset',

/**
 * Fired after resetting data using the Persistent State plugin.
 *
 * @event Hooks#persistentStateSave
 * @param {String} key Key string.
 * @param {Mixed} value Value to save.
 */
'persistentStateSave',

/**
 * Fired before sorting the column. If you return `false` value then sorting will be not applied by
 * Handsontable (useful for server-side sorting).
 *
 * @event Hooks#beforeColumnSort
 * @param {Number} column Sorted visual column index.
 * @param {Boolean} order Soring order where:
 *  * `true` means ascending order,
 *  * `false` means descending order,
 *  * `undefined` means original order.
 */
'beforeColumnSort',

/**
 * Fired after sorting the column.
 *
 * @event Hooks#afterColumnSort
 * @param {Number} column Sorted visual column index.
 * @param {Boolean} order Soring order where:
 *  * `true` means ascending order
 *  * `false` means descending order
 *  * `undefined` means original order
 */
'afterColumnSort',

/**
 * @description
 * Fired after setting range of autofill.
 * Both arguments are provided in the following format:
 * ```js
 * [startRow, startColumn, endRow, endColumn]
 * ```
 *
 * @event Hooks#modifyAutofillRange
 * @param {Array} startArea Array of visual coordinates of the starting point for the drag-down operation.
 * @param {Array} entireArea Array of visual coordinates of the entire area of the drag-down operation.
 */
'modifyAutofillRange',

/**
 * Fired to allow modifying the copyable range with a callback function.
 *
 * @since 0.19.0
 * @event Hooks#modifyCopyableRange
 * @param {Array} copyableRanges Array of objects defining copyable cells.
 */
'modifyCopyableRange',

/**
 * Called before copying the values into clipboard and before clearing values of the selected cells.
 *
 * @event Hooks#beforeCut
 * @since 0.31.1
 * @param {Array} data An array of arrays which contains data to cut.
 * @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
 *                       which will be cut out.
 * @returns {*} If returns `false` then operation of the cutting out is cancelled.
 *
 * @example
 * ```js
 * // To disregard a single row, remove it from array using data.splice(i, 1).
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforeCut: function(data, coords) {
 *     // data -> [[1, 2, 3], [4, 5, 6]]
 *     data.splice(0, 1);
 *     // data -> [[4, 5, 6]]
 *     // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}]
 *   }
 * });
 * ...
 *
 * // To cancel cutting out, return false from the callback.
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforeCut: function(data, coords) {
 *     return false;
 *   }
 * });
 * ...
 * ```
 */
'beforeCut',

/**
 * Fired after data are cutted out from the table.
 *
 * @event Hooks#afterCut
 * @since 0.31.1
 * @param {Array} data An array of arrays which contains the cutted out data.
 * @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
 *                       which was cut out.
 */
'afterCut',

/**
 * Fired before values are copied into clipboard.
 *
 * @event Hooks#beforeCopy
 * @since 0.31.1
 * @param {Array} data An array of arrays which contains data to copied.
 * @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
 *                       which will copied.
 * @returns {*} If returns `false` then copying is cancelled.
 *
 * @example
 * ```js
 * // To disregard a single row, remove it from array using data.splice(i, 1).
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforeCopy: function(data, coords) {
 *     // data -> [[1, 2, 3], [4, 5, 6]]
 *     data.splice(0, 1);
 *     // data -> [[4, 5, 6]]
 *     // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}]
 *   }
 * });
 * ...
 *
 * // To cancel copying, return false from the callback.
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforeCopy: function(data, coords) {
 *     return false;
 *   }
 * });
 * ...
 * ```
 */
'beforeCopy',

/**
 * Fired after data are pasted into table.
 *
 * @event Hooks#afterCopy
 * @since 0.31.1
 * @param {Array} data An array of arrays which contains the copied data.
 * @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
 *                       which was copied.
 */
'afterCopy',

/**
 * Fired before values are pasted into table.
 *
 * @event Hooks#beforePaste
 * @since 0.31.1
 * @param {Array} data An array of arrays which contains data to paste.
 * @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
 *                       that correspond to the previously selected area.
 * @returns {*} If returns `false` then pasting is cancelled.
 *
 * @example
 * ```js
 * // To disregard a single row, remove it from array using data.splice(i, 1).
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforePaste: function(data, coords) {
 *     // data -> [[1, 2, 3], [4, 5, 6]]
 *     data.splice(0, 1);
 *     // data -> [[4, 5, 6]]
 *     // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}]
 *   }
 * });
 * ...
 *
 * // To cancel pasting, return false from the callback.
 * ...
 * new Handsontable(document.getElementById('example'), {
 *   beforePaste: function(data, coords) {
 *     return false;
 *   }
 * });
 * ...
 * ```
 */
'beforePaste',

/**
 * Fired after values are pasted into table.
 *
 * @event Hooks#afterPaste
 * @since 0.31.1
 * @param {Array} data An array of arrays which contains the pasted data.
 * @param {Array} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`)
 *                       that correspond to the previously selected area.
 */
'afterPaste',

/**
 * Fired before change order of the visual indexes.
 *
 * @event Hooks#beforeColumnMove
 * @param {Array} columns Array of visual column indexes to be moved.
 * @param {Number} target Visual column index being a target for moved columns.
 */
'beforeColumnMove',

/**
 * Fired after change order of the visual indexes.
 *
 * @event Hooks#afterColumnMove
 * @param {Array} columns Array of visual column indexes that were moved.
 * @param {Number} target Visual column index being a target for moved columns.
 */
'afterColumnMove',

/**
 * Fired before change order of the visual indexes.
 *
 * @event Hooks#beforeRowMove
 * @param {Array} rows Array of visual row indexes to be moved.
 * @param {Number} target Visual row index being a target for moved rows.
 */
'beforeRowMove',

/**
 * Fired after change order of the visual indexes.
 *
 * @event Hooks#afterRowMove
 * @param {Array} rows Array of visual row indexes that were moved.
 * @param {Number} target Visual row index being a target for moved rows.
 */
'afterRowMove',

/**
 * Fired before rendering the table with modified column sizes.
 *
 * @event Hooks#beforeColumnResize
 * @param {Number} currentColumn Visual index of the resized column.
 * @param {Number} newSize Calculated new column width.
 * @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
 * @returns {Number} Returns a new column size or `undefined`, if column size should be calculated automatically.
 */
'beforeColumnResize',

/**
 * Fired after rendering the table with modified column sizes.
 *
 * @event Hooks#afterColumnResize
 * @param {Number} currentColumn Visual index of the resized column.
 * @param {Number} newSize Calculated new column width.
 * @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
 */
'afterColumnResize',

/**
 * Fired before rendering the table with modified row sizes.
 *
 * @event Hooks#beforeRowResize
 * @param {Number} currentRow Visual index of the resized row.
 * @param {Number} newSize Calculated new row height.
 * @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
 * @returns {Number} Returns the new row size or `undefined` if row size should be calculated automatically.
 */
'beforeRowResize',

/**
 * Fired after rendering the table with modified row sizes.
 *
 * @event Hooks#afterRowResize
 * @param {Number} currentRow Visual index of the resized row.
 * @param {Number} newSize Calculated new row height.
 * @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
 */
'afterRowResize',

/**
 * Fired after getting the column header renderers.
 *
 * @event Hooks#afterGetColumnHeaderRenderers
 * @param {Array} array Array of the column header renderers.
 */
'afterGetColumnHeaderRenderers',

/**
 * Fired after getting the row header renderers.
 *
 * @event Hooks#afterGetRowHeaderRenderers
 * @param {Array} array Array of the row header renderers.
 */
'afterGetRowHeaderRenderers',

/**
 * Fired before applying stretched column width to column.
 *
 * @event Hooks#beforeStretchingColumnWidth
 * @param {Number} stretchedWidth Calculated width.
 * @param {Number} column Visual column index.
 * @returns {Number} Returns new width which will be applied to the column element.
 */
'beforeStretchingColumnWidth',

/**
 * Fired before applying [filtering]{@link http://docs.handsontable.com/pro/demo-filtering.html}.
 *
 * @pro
 * @event Hooks#beforeFilter
 * @param {Array} conditionsStack An array of objects with added formulas.
 * @returns {Boolean} If hook returns `false` value then filtering won't be applied on the UI side (server-side filtering).
 */
'beforeFilter',

/**
 * Fired after applying [filtering]{@link http://docs.handsontable.com/pro/demo-filtering.html}.
 *
 * @pro
 * @event Hooks#afterFilter
 * @param {Array} conditionsStack An array of objects with added formulas.
 */
'afterFilter',

/**
 * Used to modify the column header height.
 *
 * @event Hooks#modifyColumnHeaderHeight
 * @since 0.25.0
 * @param {Number} col Visual column index.
 */
'modifyColumnHeaderHeight',

/**
 * Fired before the undo action. Contains information about the action that is being undone.
 *
 * @event Hooks#beforeUndo
 * @since 0.26.2
 * @param {Object} action The action object. Contains information about the action being undone. The `actionType`
 * property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`).
 */
'beforeUndo',

/**
 * Fired after the undo action. Contains information about the action that is being undone.
 *
 * @event Hooks#afterUndo
 * @since 0.26.2
 * @param {Object} action The action object. Contains information about the action being undone. The `actionType`
 * property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`).
 */
'afterUndo',

/**
 * Fired before the redo action. Contains information about the action that is being redone.
 *
 * @event Hooks#beforeRedo
 * @since 0.26.2
 * @param {Object} action The action object. Contains information about the action being redone. The `actionType`
 * property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`).
 */
'beforeRedo',

/**
 * Fired after the redo action. Contains information about the action that is being redone.
 *
 * @event Hooks#afterRedo
 * @since 0.26.2
 * @param {Object} action The action object. Contains information about the action being redone. The `actionType`
 * property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`).
 */
'afterRedo',

/**
 * Used to modify the row header width.
 *
 * @event Hooks#modifyRowHeaderWidth
 * @param {Number} rowHeaderWidth Row header width.
 */
'modifyRowHeaderWidth',

/**
 * Fired from the `populateFromArray` method during the `autofill` process. Fired for each "autofilled" cell individually.
 *
 * @event Hooks#beforeAutofillInsidePopulate
 * @param {Object} index Object containing `row` and `col` properties, defining the number of rows/columns from the initial cell of the autofill.
 * @param {String} direction Declares the direction of the autofill. Possible values: `up`, `down`, `left`, `right`.
 * @param {Array} input Array of arrays. Contains an array of rows with data being used in the autofill.
 * @param {Array} deltas The deltas array passed to the `populateFromArray` method.
 */
'beforeAutofillInsidePopulate',

/**
 * Fired when the start of the selection is being modified. (e.g. moving the selection with the arrow keys).
 *
 * @event Hooks#modifyTransformStart
 * @param {CellCoords} delta Cell coords object declaring the delta of the new selection relative to the previous one.
 */
'modifyTransformStart',

/**
 * Fired when the end of the selection is being modified. (e.g. moving the selection with the arrow keys).
 *
 * @event Hooks#modifyTransformEnd
 * @param {CellCoords} delta Cell coords object declaring the delta of the new selection relative to the previous one.
 */
'modifyTransformEnd',

/**
 * Fired after the start of the selection is being modified. (e.g. moving the selection with the arrow keys).
 *
 * @event Hooks#afterModifyTransformStart
 * @param {CellCoords} coords Coords of the freshly selected cell.
 * @param {Number} rowTransformDir `-1` if trying to select a cell with a negative row index. `0` otherwise.
 * @param {Number} colTransformDir `-1` if trying to select a cell with a negative column index. `0` otherwise.
 */
'afterModifyTransformStart',

/**
 * Fired after the end of the selection is being modified. (e.g. moving the selection with the arrow keys).
 *
 * @event Hooks#afterModifyTransformEnd
 * @param {CellCoords} coords Visual coords of the freshly selected cell.
 * @param {Number} rowTransformDir `-1` if trying to select a cell with a negative row index. `0` otherwise.
 * @param {Number} colTransformDir `-1` if trying to select a cell with a negative column index. `0` otherwise.
 */
'afterModifyTransformEnd',

/**
 * Fired inside the `viewportRowCalculatorOverride` method. Allows modifying the row calculator parameters.
 *
 * @event Hooks#afterViewportRowCalculatorOverride
 * @param {Object} calc The row calculator.
 */
'afterViewportRowCalculatorOverride',

/**
 * Fired inside the `viewportColumnCalculatorOverride` method. Allows modifying the row calculator parameters.
 *
 * @event Hooks#afterViewportColumnCalculatorOverride
 * @param {Object} calc The row calculator.
 */
'afterViewportColumnCalculatorOverride',

/**
 * Fired after initializing all the plugins.
 *
 * @event Hooks#afterPluginsInitialized
 */
'afterPluginsInitialized',

/**
 * Used when saving/loading the manual row heights state.
 *
 * @event Hooks#manualRowHeights
 * @param {Array} state The current manual row heights state.
 */
'manualRowHeights',

/**
 * Used to skip the length cache calculation for a defined period of time.
 *
 * @event Hooks#skipLengthCache
 * @param {Number} delay The delay in milliseconds.
 */
'skipLengthCache',

/**
 * Fired after trimming rows in the TrimRows plugin.
 *
 * @pro
 * @event Hooks#afterTrimRow
 * @param {Array} rows Physical indexes of trimmed rows.
 */
'afterTrimRow',

/**
 * Fired after untrimming rows in the TrimRows plugin.
 *
 * @pro
 * @event Hooks#afterUntrimRow
 * @param {Array} rows Physical indexes of untrimmed rows.
 */
'afterUntrimRow',

/**
 * Fired after opening the dropdown menu.
 *
 * @pro
 * @event Hooks#afterDropdownMenuShow
 * @param {DropdownMenu} instance The DropdownMenu instance.
 */
'afterDropdownMenuShow',

/**
 * Fired after hiding the dropdown menu.
 *
 * @pro
 * @event Hooks#afterDropdownMenuHide
 * @param {DropdownMenu} instance The DropdownMenu instance.
 */
'afterDropdownMenuHide',

/**
 * Used to check whether the provided row index is hidden.
 *
 * @pro
 * @event Hooks#hiddenRow
 * @param {Number} row The visual row index in question.
 */
'hiddenRow',

/**
 * Used to check whether the provided column index is hidden.
 *
 * @pro
 * @event Hooks#hiddenColumn
 * @param {Number} column The visual column index in question.
 */
'hiddenColumn',

/**
 * Fired before adding a children to the NestedRows structure.
 *
 * @pro
 * @event Hooks#beforeAddChild
 * @param {Object} parent The parent object.
 * @param {Object|undefined} element The element added as a child. If `undefined`, a blank child was added.
 * @param {Number|undefined} index The index within the parent where the new child was added. If `undefined`, the element was added as the last child.
 */
'beforeAddChild',

/**
 * Fired after adding a children to the NestedRows structure.
 *
 * @pro
 * @event Hooks#afterAddChild
 * @param {Object} parent The parent object.
 * @param {Object|undefined} element The element added as a child. If `undefined`, a blank child was added.
 * @param {Number|undefined} index The index within the parent where the new child was added. If `undefined`, the element was added as the last child.
 */
'afterAddChild',

/**
 * Fired before detaching a child from its parent in the NestedRows plugin.
 *
 * @pro
 * @event Hooks#beforeDetachChild
 * @param {Object} parent An object representing the parent from which the element is to be detached.
 * @param {Object} element The detached element.
 */
'beforeDetachChild',

/**
 * Fired after detaching a child from its parent in the NestedRows plugin.
 *
 * @pro
 * @event Hooks#afterDetachChild
 * @param {Object} parent An object representing the parent from which the element was detached.
 * @param {Object} element The detached element.
 */
'afterDetachChild',

/**
 * Fired after the editor is opened and rendered.
 *
 * @event Hooks#afterBeginEditing
 * @param {Number} row Row index of the edited cell.
 * @param {Number} column Column index of the edited cell.
 */
'afterBeginEditing',

/**
 * Fired after the listening is turned on.
 *
 * @event Hooks#afterListen
 * @since 0.34.5
 */
'afterListen',

/**
 * Fired after the listening is turned off.
 *
 * @event Hooks#afterUnlisten
 * @since 0.34.5
 */
'afterUnlisten'];

var Hooks = function () {
  _createClass(Hooks, null, [{
    key: 'getSingleton',
    value: function getSingleton() {
      return globalSingleton;
    }

    /**
     *
     */

  }]);

  function Hooks() {
    _classCallCheck(this, Hooks);

    this.globalBucket = this.createEmptyBucket();
  }

  /**
   * Returns a new object with empty handlers related to every registered hook name.
   *
   * @returns {Object} The empty bucket object.
   *
   * @example
   * ```js
   * Handsontable.hooks.createEmptyBucket();
   * // Results:
   * {
   * ...
   * afterCreateCol: [],
   * afterCreateRow: [],
   * beforeInit: [],
   * ...
   * }
   * ```
   */


  _createClass(Hooks, [{
    key: 'createEmptyBucket',
    value: function createEmptyBucket() {
      var bucket = Object.create(null);

      // eslint-disable-next-line no-return-assign
      (0, _array.arrayEach)(REGISTERED_HOOKS, function (hook) {
        return bucket[hook] = [];
      });

      return bucket;
    }

    /**
     * Get hook bucket based on the context of the object or if argument is `undefined`, get the global hook bucket.
     *
     * @param {Object} [context=null] A Handsontable instance.
     * @returns {Object} Returns a global or Handsontable instance bucket.
     */

  }, {
    key: 'getBucket',
    value: function getBucket() {
      var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

      if (context) {
        if (!context.pluginHookBucket) {
          context.pluginHookBucket = this.createEmptyBucket();
        }

        return context.pluginHookBucket;
      }

      return this.globalBucket;
    }

    /**
     * Adds a listener (globally or locally) to a specified hook name.
     * If the `context` parameter is provided, the hook will be added only to the instance it references.
     * Otherwise, the callback will be used everytime the hook fires on any Handsontable instance.
     * You can provide an array of callback functions as the `callback` argument, this way they will all be fired
     * once the hook is triggered.
     *
     * @see Core#addHook
     * @param {String} key Hook name.
     * @param {Function|Array} callback Callback function or an array of functions.
     * @param {Object} [context=null] The context for the hook callback to be added - a Handsontable instance or leave empty.
     * @returns {Hooks} Instance of Hooks.
     *
     * @example
     * ```js
     * // single callback, added locally
     * Handsontable.hooks.add('beforeInit', myCallback, hotInstance);
     *
     * // single callback, added globally
     * Handsontable.hooks.add('beforeInit', myCallback);
     *
     * // multiple callbacks, added locally
     * Handsontable.hooks.add('beforeInit', [myCallback, anotherCallback], hotInstance);
     *
     * // multiple callbacks, added globally
     * Handsontable.hooks.add('beforeInit', [myCallback, anotherCallback]);
     * ```
     */

  }, {
    key: 'add',
    value: function add(key, callback) {
      var _this = this;

      var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

      if (Array.isArray(callback)) {
        (0, _array.arrayEach)(callback, function (c) {
          return _this.add(key, c, context);
        });
      } else {
        var bucket = this.getBucket(context);

        if (typeof bucket[key] === 'undefined') {
          this.register(key);
          bucket[key] = [];
        }
        callback.skip = false;

        if (bucket[key].indexOf(callback) === -1) {
          // only add a hook if it has not already been added (adding the same hook twice is now silently ignored)
          var foundInitialHook = false;

          if (callback.initialHook) {
            (0, _array.arrayEach)(bucket[key], function (cb, i) {
              if (cb.initialHook) {
                bucket[key][i] = callback;
                foundInitialHook = true;

                return false;
              }
            });
          }

          if (!foundInitialHook) {
            bucket[key].push(callback);
          }
        }
      }

      return this;
    }

    /**
     * Adds a listener to a specified hook. After the hook runs this listener will be automatically removed from the bucket.
     *
     * @see Core#addHookOnce
     * @param {String} key Hook/Event name.
     * @param {Function|Array} callback Callback function.
     * @param {Object} [context=null] A Handsontable instance.
     *
     * @example
     * ```js
     * Handsontable.hooks.once('beforeInit', myCallback, hotInstance);
     * ```
     */

  }, {
    key: 'once',
    value: function once(key, callback) {
      var _this2 = this;

      var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

      if (Array.isArray(callback)) {
        (0, _array.arrayEach)(callback, function (c) {
          return _this2.once(key, c, context);
        });
      } else {
        callback.runOnce = true;
        this.add(key, callback, context);
      }
    }

    /**
     * Removes a listener from a hook with a given name. If the `context` argument is provided, it removes a listener from a local hook assigned to the given Handsontable instance.
     *
     * @see Core#removeHook
     * @param {String} key Hook/Event name.
     * @param {Function} callback Callback function (needs the be the function that was previously added to the hook).
     * @param {Object} [context=null] Handsontable instance.
     * @return {Boolean} Returns `true` if hook was removed, `false` otherwise.
     *
     * @example
     * ```js
     * Handsontable.hooks.remove('beforeInit', myCallback);
     * ```
     */

  }, {
    key: 'remove',
    value: function remove(key, callback) {
      var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

      var bucket = this.getBucket(context);

      if (typeof bucket[key] !== 'undefined') {
        if (bucket[key].indexOf(callback) >= 0) {
          callback.skip = true;

          return true;
        }
      }

      return false;
    }

    /**
     * Checks whether there are any registered listeners for the provided hook name.
     * If the `context` parameter is provided, it only checks for listeners assigned to the given Handsontable instance.
     *
     * @param {String} key Hook name.
     * @param {Object} [context=null] A Handsontable instance.
     * @returns {Boolean} `true` for success, `false` otherwise.
     */

  }, {
    key: 'has',
    value: function has(key) {
      var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

      var bucket = this.getBucket(context);

      return !!(bucket[key] !== void 0 && bucket[key].length);
    }

    /**
     * Runs all local and global callbacks assigned to the hook identified by the `key` parameter.
     * It returns either a return value from the last called callback or the first parameter (`p1`) passed to the `run` function.
     *
     * @see Core#runHooks
     * @param {Object} context Handsontable instance.
     * @param {String} key Hook/Event name.
     * @param {*} [p1] Parameter to be passed as an argument to the callback function.
     * @param {*} [p2] Parameter to be passed as an argument to the callback function.
     * @param {*} [p3] Parameter to be passed as an argument to the callback function.
     * @param {*} [p4] Parameter to be passed as an argument to the callback function.
     * @param {*} [p5] Parameter to be passed as an argument to the callback function.
     * @param {*} [p6] Parameter to be passed as an argument to the callback function.
     * @returns {*} Either a return value from the last called callback or `p1`.
     *
     * @example
     * ```js
     * Handsontable.hooks.run(hot, 'beforeInit');
     * ```
     */

  }, {
    key: 'run',
    value: function run(context, key, p1, p2, p3, p4, p5, p6) {
      {
        var globalHandlers = this.globalBucket[key];
        var index = -1;
        var length = globalHandlers ? globalHandlers.length : 0;

        if (length) {
          // Do not optimise this loop with arrayEach or arrow function! If you do You'll decrease perf because of GC.
          while (++index < length) {
            if (!globalHandlers[index] || globalHandlers[index].skip) {
              /* eslint-disable no-continue */
              continue;
            }
            // performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
            var res = globalHandlers[index].call(context, p1, p2, p3, p4, p5, p6);

            if (res !== void 0) {
              p1 = res;
            }
            if (globalHandlers[index] && globalHandlers[index].runOnce) {
              this.remove(key, globalHandlers[index]);
            }
          }
        }
      }
      {
        var localHandlers = this.getBucket(context)[key];
        var _index = -1;
        var _length = localHandlers ? localHandlers.length : 0;

        if (_length) {
          // Do not optimise this loop with arrayEach or arrow function! If you do You'll decrease perf because of GC.
          while (++_index < _length) {
            if (!localHandlers[_index] || localHandlers[_index].skip) {
              /* eslint-disable no-continue */
              continue;
            }
            // performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
            var _res = localHandlers[_index].call(context, p1, p2, p3, p4, p5, p6);

            if (_res !== void 0) {
              p1 = _res;
            }
            if (localHandlers[_index] && localHandlers[_index].runOnce) {
              this.remove(key, localHandlers[_index], context);
            }
          }
        }
      }

      return p1;
    }

    /**
     * Destroy all listeners connected to the context. If no context is provided, the global listeners will be destroyed.
     *
     * @param {Object} [context=null] A Handsontable instance.
     * @example
     * ```js
     * // destroy the global listeners
     * Handsontable.hooks.destroy();
     *
     * // destroy the local listeners
     * Handsontable.hooks.destroy(hotInstance);
     * ```
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

      // eslint-disable-next-line no-return-assign
      (0, _object.objectEach)(this.getBucket(context), function (value, key, bucket) {
        return bucket[key].length = 0;
      });
    }

    /**
     * Registers a hook name (adds it to the list of the known hook names). Used by plugins.
     * It is not necessary to call register, but if you use it, your plugin hook will be used returned by
     * the `getRegistered` method. (which itself is used in the demo http://docs.handsontable.com/tutorial-callbacks.html).
     *
     * @param key {String} The hook name.
     *
     * @example
     * ```js
     * Handsontable.hooks.register('myHook');
     * ```
     */

  }, {
    key: 'register',
    value: function register(key) {
      if (!this.isRegistered(key)) {
        REGISTERED_HOOKS.push(key);
      }
    }

    /**
     * Deregisters a hook name (removes it from the list of known hook names).
     *
     * @param key {String} Hook name.
     *
     * @example
     * ```js
     * Handsontable.hooks.deregister('myHook');
     * ```
     */

  }, {
    key: 'deregister',
    value: function deregister(key) {
      if (this.isRegistered(key)) {
        REGISTERED_HOOKS.splice(REGISTERED_HOOKS.indexOf(key), 1);
      }
    }

    /**
     * Returns a boolean depending on if a hook by such name has been registered.
     *
     * @param key {String} Hook name.
     * @returns {Boolean} `true` for success, `false` otherwise.
     *
     * @example
     * ```js
     * Handsontable.hooks.isRegistered('beforeInit');
     *
     * // Results:
     * true
     * ```
     */

  }, {
    key: 'isRegistered',
    value: function isRegistered(key) {
      return REGISTERED_HOOKS.indexOf(key) >= 0;
    }

    /**
     * Returns an array of registered hooks.
     *
     * @returns {Array} An array of registered hooks.
     *
     * @example
     * ```js
     * Handsontable.hooks.getRegistered();
     *
     * // Results:
     * [
     * ...
     *   'beforeInit',
     *   'beforeRender',
     *   'beforeSetRangeEnd',
     *   'beforeDrawBorders',
     *   'beforeChange',
     * ...
     * ]
     * ```
     */

  }, {
    key: 'getRegistered',
    value: function getRegistered() {
      return REGISTERED_HOOKS;
    }
  }]);

  return Hooks;
}();

var globalSingleton = new Hooks();

exports.default = Hooks;

/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.stopImmediatePropagation = stopImmediatePropagation;
exports.isImmediatePropagationStopped = isImmediatePropagationStopped;
exports.stopPropagation = stopPropagation;
exports.pageX = pageX;
exports.pageY = pageY;
exports.isRightClick = isRightClick;
exports.isLeftClick = isLeftClick;

var _element = __webpack_require__(0);

/**
 * Prevent other listeners of the same event from being called.
 *
 * @param {Event} event
 */
function stopImmediatePropagation(event) {
  event.isImmediatePropagationEnabled = false;
  event.cancelBubble = true;
}

/**
 * Check if event was stopped by `stopImmediatePropagation`.
 *
 * @param event {Event}
 * @returns {Boolean}
 */
function isImmediatePropagationStopped(event) {
  return event.isImmediatePropagationEnabled === false;
}

/**
 * Prevent further propagation of the current event (prevent bubbling).
 *
 * @param event {Event}
 */
function stopPropagation(event) {
  // ie8
  // http://msdn.microsoft.com/en-us/library/ie/ff975462(v=vs.85).aspx
  if (typeof event.stopPropagation === 'function') {
    event.stopPropagation();
  } else {
    event.cancelBubble = true;
  }
}

/**
 * Get horizontal coordinate of the event object relative to the whole document.
 *
 * @param {Event} event
 * @returns {Number}
 */
function pageX(event) {
  if (event.pageX) {
    return event.pageX;
  }

  return event.clientX + (0, _element.getWindowScrollLeft)();
}

/**
 * Get vertical coordinate of the event object relative to the whole document.
 *
 * @param {Event} event
 * @returns {Number}
 */
function pageY(event) {
  if (event.pageY) {
    return event.pageY;
  }

  return event.clientY + (0, _element.getWindowScrollTop)();
}

/**
 * Check if provided event was triggered by clicking the right mouse button.
 *
 * @param {Event} event DOM Event.
 * @returns {Boolean}
 */
function isRightClick(event) {
  return event.button === 2;
}

/**
 * Check if provided event was triggered by clicking the left mouse button.
 *
 * @param {Event} event DOM Event.
 * @returns {Boolean}
 */
function isLeftClick(event) {
  return event.button === 0;
}

/***/ }),
/* 13 */
/***/ (function(module, exports) {

// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
  ? window : typeof self != 'undefined' && self.Math == Math ? self
  // eslint-disable-next-line no-new-func
  : Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef


/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _object = __webpack_require__(1);

var _array = __webpack_require__(2);

var _recordTranslator = __webpack_require__(308);

var _plugins = __webpack_require__(7);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var privatePool = new WeakMap();
var initializedPlugins = null;

/**
 * @private
 */

var BasePlugin = function () {
  /**
   * @param {Object} hotInstance Handsontable instance.
   */
  function BasePlugin(hotInstance) {
    var _this = this;

    _classCallCheck(this, BasePlugin);

    /**
     * Handsontable instance.
     *
     * @type {Core}
     */
    (0, _object.defineGetter)(this, 'hot', hotInstance, {
      writable: false
    });
    (0, _object.defineGetter)(this, 't', (0, _recordTranslator.getTranslator)(hotInstance), {
      writable: false
    });

    privatePool.set(this, { hooks: {} });
    initializedPlugins = null;

    this.pluginName = null;
    this.pluginsInitializedCallbacks = [];
    this.isPluginsReady = false;
    this.enabled = false;
    this.initialized = false;

    this.hot.addHook('afterPluginsInitialized', function () {
      return _this.onAfterPluginsInitialized();
    });
    this.hot.addHook('afterUpdateSettings', function () {
      return _this.onUpdateSettings();
    });
    this.hot.addHook('beforeInit', function () {
      return _this.init();
    });
  }

  _createClass(BasePlugin, [{
    key: 'init',
    value: function init() {
      this.pluginName = (0, _plugins.getPluginName)(this.hot, this);

      if (this.isEnabled && this.isEnabled()) {
        this.enablePlugin();
      }
      if (!initializedPlugins) {
        initializedPlugins = (0, _plugins.getRegistredPluginNames)(this.hot);
      }
      if (initializedPlugins.indexOf(this.pluginName) >= 0) {
        initializedPlugins.splice(initializedPlugins.indexOf(this.pluginName), 1);
      }
      if (!initializedPlugins.length) {
        this.hot.runHooks('afterPluginsInitialized');
      }
      this.initialized = true;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      this.enabled = true;
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      if (this.eventManager) {
        this.eventManager.clear();
      }
      this.clearHooks();
      this.enabled = false;
    }

    /**
     * Add listener to plugin hooks system.
     *
     * @param {String} name
     * @param {Function} callback
     */

  }, {
    key: 'addHook',
    value: function addHook(name, callback) {
      privatePool.get(this).hooks[name] = privatePool.get(this).hooks[name] || [];

      var hooks = privatePool.get(this).hooks[name];

      this.hot.addHook(name, callback);
      hooks.push(callback);
      privatePool.get(this).hooks[name] = hooks;
    }

    /**
     * Remove all hooks listeners by hook name.
     *
     * @param {String} name
     */

  }, {
    key: 'removeHooks',
    value: function removeHooks(name) {
      var _this2 = this;

      (0, _array.arrayEach)(privatePool.get(this).hooks[name] || [], function (callback) {
        _this2.hot.removeHook(name, callback);
      });
    }

    /**
     * Clear all hooks.
     */

  }, {
    key: 'clearHooks',
    value: function clearHooks() {
      var _this3 = this;

      var hooks = privatePool.get(this).hooks;

      (0, _object.objectEach)(hooks, function (callbacks, name) {
        return _this3.removeHooks(name);
      });
      hooks.length = 0;
    }

    /**
     * Register function which will be immediately called after all plugins initialized.
     *
     * @param {Function} callback
     */

  }, {
    key: 'callOnPluginsReady',
    value: function callOnPluginsReady(callback) {
      if (this.isPluginsReady) {
        callback();
      } else {
        this.pluginsInitializedCallbacks.push(callback);
      }
    }

    /**
     * On after plugins initialized listener.
     *
     * @private
     */

  }, {
    key: 'onAfterPluginsInitialized',
    value: function onAfterPluginsInitialized() {
      (0, _array.arrayEach)(this.pluginsInitializedCallbacks, function (callback) {
        return callback();
      });
      this.pluginsInitializedCallbacks.length = 0;
      this.isPluginsReady = true;
    }

    /**
     * On update settings listener.
     *
     * @private
     */

  }, {
    key: 'onUpdateSettings',
    value: function onUpdateSettings() {
      if (this.isEnabled) {
        if (this.enabled && !this.isEnabled()) {
          this.disablePlugin();
        }
        if (!this.enabled && this.isEnabled()) {
          this.enablePlugin();
        }
        if (this.enabled && this.isEnabled()) {
          this.updatePlugin();
        }
      }
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     *
     * @private
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {}

    /**
     * Destroy plugin.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      var _this4 = this;

      if (this.eventManager) {
        this.eventManager.destroy();
      }
      this.clearHooks();

      (0, _object.objectEach)(this, function (value, property) {
        if (property !== 'hot' && property !== 't') {
          _this4[property] = null;
        }
      });
      delete this.t;
      delete this.hot;
    }
  }]);

  return BasePlugin;
}();

exports.default = BasePlugin;

/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.Viewport = exports.TableRenderer = exports.Table = exports.Settings = exports.Selection = exports.Scroll = exports.Overlays = exports.Event = exports.Core = exports.default = exports.Border = exports.TopLeftCornerOverlay = exports.TopOverlay = exports.LeftOverlay = exports.DebugOverlay = exports.RowFilter = exports.ColumnFilter = exports.CellRange = exports.CellCoords = exports.ViewportRowsCalculator = exports.ViewportColumnsCalculator = undefined;

__webpack_require__(91);

__webpack_require__(106);

__webpack_require__(107);

__webpack_require__(111);

__webpack_require__(112);

__webpack_require__(114);

__webpack_require__(117);

__webpack_require__(118);

__webpack_require__(119);

__webpack_require__(120);

__webpack_require__(121);

__webpack_require__(122);

__webpack_require__(123);

__webpack_require__(124);

__webpack_require__(125);

__webpack_require__(126);

__webpack_require__(127);

__webpack_require__(128);

__webpack_require__(129);

__webpack_require__(130);

__webpack_require__(131);

__webpack_require__(132);

__webpack_require__(133);

__webpack_require__(134);

__webpack_require__(136);

__webpack_require__(138);

__webpack_require__(139);

__webpack_require__(140);

__webpack_require__(141);

__webpack_require__(142);

__webpack_require__(143);

__webpack_require__(144);

__webpack_require__(145);

__webpack_require__(146);

__webpack_require__(147);

__webpack_require__(148);

__webpack_require__(149);

__webpack_require__(150);

__webpack_require__(81);

__webpack_require__(151);

__webpack_require__(152);

__webpack_require__(154);

__webpack_require__(155);

__webpack_require__(156);

__webpack_require__(157);

__webpack_require__(158);

__webpack_require__(159);

__webpack_require__(160);

__webpack_require__(162);

__webpack_require__(163);

__webpack_require__(164);

__webpack_require__(167);

__webpack_require__(168);

__webpack_require__(169);

var _viewportColumns = __webpack_require__(170);

var _viewportColumns2 = _interopRequireDefault(_viewportColumns);

var _viewportRows = __webpack_require__(171);

var _viewportRows2 = _interopRequireDefault(_viewportRows);

var _coords = __webpack_require__(53);

var _coords2 = _interopRequireDefault(_coords);

var _range = __webpack_require__(82);

var _range2 = _interopRequireDefault(_range);

var _column = __webpack_require__(172);

var _column2 = _interopRequireDefault(_column);

var _row = __webpack_require__(173);

var _row2 = _interopRequireDefault(_row);

var _debug = __webpack_require__(340);

var _debug2 = _interopRequireDefault(_debug);

var _left = __webpack_require__(343);

var _left2 = _interopRequireDefault(_left);

var _top = __webpack_require__(344);

var _top2 = _interopRequireDefault(_top);

var _topLeftCorner = __webpack_require__(345);

var _topLeftCorner2 = _interopRequireDefault(_topLeftCorner);

var _border = __webpack_require__(302);

var _border2 = _interopRequireDefault(_border);

var _core = __webpack_require__(174);

var _core2 = _interopRequireDefault(_core);

var _event = __webpack_require__(295);

var _event2 = _interopRequireDefault(_event);

var _overlays = __webpack_require__(296);

var _overlays2 = _interopRequireDefault(_overlays);

var _scroll = __webpack_require__(297);

var _scroll2 = _interopRequireDefault(_scroll);

var _selection = __webpack_require__(346);

var _selection2 = _interopRequireDefault(_selection);

var _settings = __webpack_require__(298);

var _settings2 = _interopRequireDefault(_settings);

var _table = __webpack_require__(299);

var _table2 = _interopRequireDefault(_table);

var _tableRenderer = __webpack_require__(300);

var _tableRenderer2 = _interopRequireDefault(_tableRenderer);

var _viewport = __webpack_require__(301);

var _viewport2 = _interopRequireDefault(_viewport);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.ViewportColumnsCalculator = _viewportColumns2.default;
exports.ViewportRowsCalculator = _viewportRows2.default;
exports.CellCoords = _coords2.default;
exports.CellRange = _range2.default;
exports.ColumnFilter = _column2.default;
exports.RowFilter = _row2.default;
exports.DebugOverlay = _debug2.default;
exports.LeftOverlay = _left2.default;
exports.TopOverlay = _top2.default;
exports.TopLeftCornerOverlay = _topLeftCorner2.default;
exports.Border = _border2.default;
exports.default = _core2.default;
exports.Core = _core2.default;
exports.Event = _event2.default;
exports.Overlays = _overlays2.default;
exports.Scroll = _scroll2.default;
exports.Selection = _selection2.default;
exports.Settings = _settings2.default;
exports.Table = _table2.default;
exports.TableRenderer = _tableRenderer2.default;
exports.Viewport = _viewport2.default;

/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.getRegisteredEditors = exports.getRegisteredEditorNames = exports.hasEditor = exports.getEditorInstance = exports.getEditor = exports.registerEditor = undefined;
exports.RegisteredEditor = RegisteredEditor;
exports._getEditorInstance = _getEditorInstance;

var _staticRegister2 = __webpack_require__(46);

var _staticRegister3 = _interopRequireDefault(_staticRegister2);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _baseEditor = __webpack_require__(47);

var _baseEditor2 = _interopRequireDefault(_baseEditor);

var _autocompleteEditor = __webpack_require__(303);

var _autocompleteEditor2 = _interopRequireDefault(_autocompleteEditor);

var _checkboxEditor = __webpack_require__(348);

var _checkboxEditor2 = _interopRequireDefault(_checkboxEditor);

var _dateEditor = __webpack_require__(349);

var _dateEditor2 = _interopRequireDefault(_dateEditor);

var _dropdownEditor = __webpack_require__(352);

var _dropdownEditor2 = _interopRequireDefault(_dropdownEditor);

var _handsontableEditor = __webpack_require__(304);

var _handsontableEditor2 = _interopRequireDefault(_handsontableEditor);

var _mobileTextEditor = __webpack_require__(353);

var _mobileTextEditor2 = _interopRequireDefault(_mobileTextEditor);

var _numericEditor = __webpack_require__(354);

var _numericEditor2 = _interopRequireDefault(_numericEditor);

var _passwordEditor = __webpack_require__(355);

var _passwordEditor2 = _interopRequireDefault(_passwordEditor);

var _selectEditor = __webpack_require__(356);

var _selectEditor2 = _interopRequireDefault(_selectEditor);

var _textEditor = __webpack_require__(54);

var _textEditor2 = _interopRequireDefault(_textEditor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var registeredEditorClasses = new WeakMap(); /**
                                              * Utility to register editors and common namespace for keeping reference to all editor classes
                                              */

var _staticRegister = (0, _staticRegister3.default)('editors'),
    register = _staticRegister.register,
    getItem = _staticRegister.getItem,
    hasItem = _staticRegister.hasItem,
    getNames = _staticRegister.getNames,
    getValues = _staticRegister.getValues;

_register('base', _baseEditor2.default);
_register('autocomplete', _autocompleteEditor2.default);
_register('checkbox', _checkboxEditor2.default);
_register('date', _dateEditor2.default);
_register('dropdown', _dropdownEditor2.default);
_register('handsontable', _handsontableEditor2.default);
_register('mobile', _mobileTextEditor2.default);
_register('numeric', _numericEditor2.default);
_register('password', _passwordEditor2.default);
_register('select', _selectEditor2.default);
_register('text', _textEditor2.default);

function RegisteredEditor(editorClass) {
  var instances = {};
  var Clazz = editorClass;

  this.getConstructor = function () {
    return editorClass;
  };

  this.getInstance = function (hotInstance) {
    if (!(hotInstance.guid in instances)) {
      instances[hotInstance.guid] = new Clazz(hotInstance);
    }

    return instances[hotInstance.guid];
  };

  _pluginHooks2.default.getSingleton().add('afterDestroy', function () {
    instances = {};
  });
}

/**
 * Returns instance (singleton) of editor class.
 *
 * @param {String} name Name of an editor under which it has been stored.
 * @param {Object} hotInstance Instance of Handsontable.
 * @returns {Function} Returns instance of editor.
 */
function _getEditorInstance(name, hotInstance) {
  var editor = void 0;

  if (typeof name === 'function') {
    if (!registeredEditorClasses.get(name)) {
      _register(null, name);
    }
    editor = registeredEditorClasses.get(name);
  } else if (typeof name === 'string') {
    editor = getItem(name);
  } else {
    throw Error('Only strings and functions can be passed as "editor" parameter');
  }

  if (!editor) {
    throw Error('No editor registered under name "' + name + '"');
  }

  return editor.getInstance(hotInstance);
}

/**
 * Retrieve editor class.
 *
 * @param {String} name Editor identification.
 * @returns {Function} Returns editor class.
 */
function _getItem(name) {
  if (!hasItem(name)) {
    throw Error('No registered editor found under "' + name + '" name');
  }

  return getItem(name).getConstructor();
}

/**
 * Register editor class under specified name.
 *
 * @param {String} name Editor identification.
 * @param {Function} editorClass Editor class.
 */
function _register(name, editorClass) {
  var editorWrapper = new RegisteredEditor(editorClass);

  if (typeof name === 'string') {
    register(name, editorWrapper);
  }
  registeredEditorClasses.set(editorClass, editorWrapper);
}

exports.registerEditor = _register;
exports.getEditor = _getItem;
exports.getEditorInstance = _getEditorInstance;
exports.hasEditor = hasItem;
exports.getRegisteredEditorNames = getNames;
exports.getRegisteredEditors = getValues;

/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _templateObject = _taggedTemplateLiteral(['\n          Your license key of Handsontable Pro has expired.\u200C\u200C\u200C\u200C \n          Renew your maintenance plan at https://handsontable.com or downgrade to the previous version of the software.\n          '], ['\n          Your license key of Handsontable Pro has expired.\u200C\u200C\u200C\u200C\\x20\n          Renew your maintenance plan at https://handsontable.com or downgrade to the previous version of the software.\n          ']);

exports.stringify = stringify;
exports.isDefined = isDefined;
exports.isUndefined = isUndefined;
exports.isEmpty = isEmpty;
exports.isRegExp = isRegExp;
exports._injectProductInfo = _injectProductInfo;

var _moment = __webpack_require__(40);

var _moment2 = _interopRequireDefault(_moment);

var _templateLiteralTag = __webpack_require__(294);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }

/**
 * Converts any value to string.
 *
 * @param {*} value
 * @returns {String}
 */
function stringify(value) {
  var result = void 0;

  switch (typeof value === 'undefined' ? 'undefined' : _typeof(value)) {
    case 'string':
    case 'number':
      result = '' + value;
      break;

    case 'object':
      result = value === null ? '' : value.toString();
      break;
    case 'undefined':
      result = '';
      break;
    default:
      result = value.toString();
      break;
  }

  return result;
}

/**
 * Checks if given variable is defined.
 *
 * @param {*} variable Variable to check.
 * @returns {Boolean}
 */
function isDefined(variable) {
  return typeof variable !== 'undefined';
}

/**
 * Checks if given variable is undefined.
 *
 * @param {*} variable Variable to check.
 * @returns {Boolean}
 */
function isUndefined(variable) {
  return typeof variable === 'undefined';
}

/**
 * Check if given variable is null, empty string or undefined.
 *
 * @param {*} variable Variable to check.
 * @returns {Boolean}
 */
function isEmpty(variable) {
  return variable === null || variable === '' || isUndefined(variable);
}

/**
 * Check if given variable is a regular expression.
 *
 * @param {*} variable Variable to check.
 * @returns {Boolean}
 */
function isRegExp(variable) {
  return Object.prototype.toString.call(variable) === '[object RegExp]';
}

/* eslint-disable */
var _m = '\x6C\x65\x6E\x67\x74\x68';
var _hd = function _hd(v) {
  return parseInt(v, 16);
};
var _pi = function _pi(v) {
  return parseInt(v, 10);
};
var _ss = function _ss(v, s, l) {
  return v['\x73\x75\x62\x73\x74\x72'](s, l);
};
var _cp = function _cp(v) {
  return v['\x63\x6F\x64\x65\x50\x6F\x69\x6E\x74\x41\x74'](0) - 65;
};
var _norm = function _norm(v) {
  return ('' + v).replace(/\-/g, '');
};
var _extractTime = function _extractTime(v) {
  return _hd(_ss(_norm(v), _hd('12'), _cp('\x46'))) / (_hd(_ss(_norm(v), _cp('\x42'), ~~![][_m])) || 9);
};
var _ignored = function _ignored() {
  return typeof location !== 'undefined' && /^([a-z0-9\-]+\.)?\x68\x61\x6E\x64\x73\x6F\x6E\x74\x61\x62\x6C\x65\x2E\x63\x6F\x6D$/i.test(location.host);
};
var _notified = false;

function _injectProductInfo(key, element) {
  key = _norm(key || '');

  var warningMessage = '';
  var showDomMessage = true;
  var schemaValidity = _checkKeySchema(key);
  var ignored = _ignored();
  var trial = isEmpty(key) || key === 'trial';

  if (trial || schemaValidity) {
    if (schemaValidity) {
      var releaseTime = Math.floor((0, _moment2.default)('25/01/2018', 'DD/MM/YYYY').toDate().getTime() / 8.64e7);
      var keyGenTime = _extractTime(key);

      if (keyGenTime > 45000 || keyGenTime !== parseInt(keyGenTime, 10)) {
        warningMessage = 'The license key provided to Handsontable Pro is invalid. Make sure you pass it correctly.';
      }

      if (!warningMessage) {
        if (releaseTime > keyGenTime + 1) {
          warningMessage = (0, _templateLiteralTag.toSingleLine)(_templateObject);
        }
        showDomMessage = releaseTime > keyGenTime + 15;
      }
    } else {
      warningMessage = 'Evaluation version of Handsontable Pro. Not licensed for use in a production environment.';
    }
  } else {
    warningMessage = 'The license key provided to Handsontable Pro is invalid. Make sure you pass it correctly.';
  }
  if (ignored) {
    warningMessage = false;
    showDomMessage = false;
  }

  if (warningMessage && !_notified) {
    console[trial ? 'info' : 'warn'](warningMessage);
    _notified = true;
  }
  if (showDomMessage && element.parentNode) {
    var message = document.createElement('div');

    message.id = 'hot-display-license-info';
    message.appendChild(document.createTextNode('Evaluation version of Handsontable Pro.'));
    message.appendChild(document.createElement('br'));
    message.appendChild(document.createTextNode('Not licensed for production use.'));

    element.parentNode.insertBefore(message, element.nextSibling);
  }
}

function _checkKeySchema(v) {
  var z = [][_m];
  var p = z;

  if (v[_m] !== _cp('\x5A')) {
    return false;
  }

  for (var c = '', i = '\x42\x3C\x48\x34\x50\x2B'.split(''), j = _cp(i.shift()); j; j = _cp(i.shift() || 'A')) {
    --j < ''[_m] ? p = p | (_pi('' + _pi(_hd(c) + (_hd(_ss(v, Math.abs(j), 2)) + []).padStart(2, '0'))) % 97 || 2) >> 1 : c = _ss(v, j, !j ? 6 : i[_m] === 1 ? 9 : 8);
  }

  return p === z;
}
/* eslint-enable */

/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(5);
module.exports = function (it) {
  if (!isObject(it)) throw TypeError(it + ' is not an object!');
  return it;
};


/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {

var anObject = __webpack_require__(18);
var IE8_DOM_DEFINE = __webpack_require__(93);
var toPrimitive = __webpack_require__(69);
var dP = Object.defineProperty;

exports.f = __webpack_require__(22) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
  anObject(O);
  P = toPrimitive(P, true);
  anObject(Attributes);
  if (IE8_DOM_DEFINE) try {
    return dP(O, P, Attributes);
  } catch (e) { /* empty */ }
  if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
  if ('value' in Attributes) O[P] = Attributes.value;
  return O;
};


/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY_CODES = undefined;
exports.isPrintableChar = isPrintableChar;
exports.isMetaKey = isMetaKey;
exports.isCtrlKey = isCtrlKey;
exports.isKey = isKey;

var _array = __webpack_require__(2);

var KEY_CODES = exports.KEY_CODES = {
  MOUSE_LEFT: 1,
  MOUSE_RIGHT: 3,
  MOUSE_MIDDLE: 2,
  BACKSPACE: 8,
  COMMA: 188,
  INSERT: 45,
  DELETE: 46,
  END: 35,
  ENTER: 13,
  ESCAPE: 27,
  CONTROL_LEFT: 91,
  COMMAND_LEFT: 17,
  COMMAND_RIGHT: 93,
  ALT: 18,
  HOME: 36,
  PAGE_DOWN: 34,
  PAGE_UP: 33,
  PERIOD: 190,
  SPACE: 32,
  SHIFT: 16,
  CAPS_LOCK: 20,
  TAB: 9,
  ARROW_RIGHT: 39,
  ARROW_LEFT: 37,
  ARROW_UP: 38,
  ARROW_DOWN: 40,
  F1: 112,
  F2: 113,
  F3: 114,
  F4: 115,
  F5: 116,
  F6: 117,
  F7: 118,
  F8: 119,
  F9: 120,
  F10: 121,
  F11: 122,
  F12: 123,
  A: 65,
  X: 88,
  C: 67,
  V: 86
};

/**
 * Returns true if keyCode represents a printable character.
 *
 * @param {Number} keyCode
 * @returns {Boolean}
 */
function isPrintableChar(keyCode) {
  return keyCode == 32 || // space
  keyCode >= 48 && keyCode <= 57 || // 0-9
  keyCode >= 96 && keyCode <= 111 || // numpad
  keyCode >= 186 && keyCode <= 192 || // ;=,-./`
  keyCode >= 219 && keyCode <= 222 || // []{}\|"'
  keyCode >= 226 || // special chars (229 for Asian chars)
  keyCode >= 65 && keyCode <= 90; // a-z
}

/**
 * @param {Number} keyCode
 * @returns {Boolean}
 */
function isMetaKey(keyCode) {
  var metaKeys = [KEY_CODES.ARROW_DOWN, KEY_CODES.ARROW_UP, KEY_CODES.ARROW_LEFT, KEY_CODES.ARROW_RIGHT, KEY_CODES.HOME, KEY_CODES.END, KEY_CODES.DELETE, KEY_CODES.BACKSPACE, KEY_CODES.F1, KEY_CODES.F2, KEY_CODES.F3, KEY_CODES.F4, KEY_CODES.F5, KEY_CODES.F6, KEY_CODES.F7, KEY_CODES.F8, KEY_CODES.F9, KEY_CODES.F10, KEY_CODES.F11, KEY_CODES.F12, KEY_CODES.TAB, KEY_CODES.PAGE_DOWN, KEY_CODES.PAGE_UP, KEY_CODES.ENTER, KEY_CODES.ESCAPE, KEY_CODES.SHIFT, KEY_CODES.CAPS_LOCK, KEY_CODES.ALT];

  return metaKeys.indexOf(keyCode) !== -1;
}

/**
 * @param {Number} keyCode
 * @returns {Boolean}
 */
function isCtrlKey(keyCode) {
  return [KEY_CODES.CONTROL_LEFT, 224, KEY_CODES.COMMAND_LEFT, KEY_CODES.COMMAND_RIGHT].indexOf(keyCode) !== -1;
}

/**
 * @param {Number} keyCode
 * @param {String} baseCode
 * @returns {Boolean}
 */
function isKey(keyCode, baseCode) {
  var keys = baseCode.split('|');
  var result = false;

  (0, _array.arrayEach)(keys, function (key) {
    if (keyCode === KEY_CODES[key]) {
      result = true;

      return false;
    }
  });

  return result;
}

/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.normalizeSelection = normalizeSelection;
exports.isSeparator = isSeparator;
exports.hasSubMenu = hasSubMenu;
exports.isDisabled = isDisabled;
exports.isSelectionDisabled = isSelectionDisabled;
exports.getValidSelection = getValidSelection;
exports.prepareVerticalAlignClass = prepareVerticalAlignClass;
exports.prepareHorizontalAlignClass = prepareHorizontalAlignClass;
exports.getAlignmentClasses = getAlignmentClasses;
exports.align = align;
exports.checkSelectionConsistency = checkSelectionConsistency;
exports.markLabelAsSelected = markLabelAsSelected;
exports.isItemHidden = isItemHidden;
exports.filterSeparators = filterSeparators;

var _array = __webpack_require__(2);

var _element = __webpack_require__(0);

var _separator = __webpack_require__(88);

function normalizeSelection(selRange) {
  return {
    start: selRange.getTopLeftCorner(),
    end: selRange.getBottomRightCorner()
  };
}

function isSeparator(cell) {
  return (0, _element.hasClass)(cell, 'htSeparator');
}

function hasSubMenu(cell) {
  return (0, _element.hasClass)(cell, 'htSubmenu');
}

function isDisabled(cell) {
  return (0, _element.hasClass)(cell, 'htDisabled');
}

function isSelectionDisabled(cell) {
  return (0, _element.hasClass)(cell, 'htSelectionDisabled');
}

function getValidSelection(hot) {
  var selected = hot.getSelected();

  if (!selected) {
    return null;
  }
  if (selected[0] < 0) {
    return null;
  }

  return selected;
}

function prepareVerticalAlignClass(className, alignment) {
  if (className.indexOf(alignment) != -1) {
    return className;
  }
  className = className.replace('htTop', '').replace('htMiddle', '').replace('htBottom', '').replace('  ', '');

  className += ' ' + alignment;

  return className;
}

function prepareHorizontalAlignClass(className, alignment) {
  if (className.indexOf(alignment) != -1) {
    return className;
  }
  className = className.replace('htLeft', '').replace('htCenter', '').replace('htRight', '').replace('htJustify', '').replace('  ', '');

  className += ' ' + alignment;

  return className;
}

function getAlignmentClasses(range, callback) {
  var classes = {};

  for (var row = range.from.row; row <= range.to.row; row++) {
    for (var col = range.from.col; col <= range.to.col; col++) {
      if (!classes[row]) {
        classes[row] = [];
      }
      classes[row][col] = callback(row, col);
    }
  }

  return classes;
}

function align(range, type, alignment, cellDescriptor, propertySetter) {
  if (range.from.row == range.to.row && range.from.col == range.to.col) {
    applyAlignClassName(range.from.row, range.from.col, type, alignment, cellDescriptor, propertySetter);
  } else {
    for (var row = range.from.row; row <= range.to.row; row++) {
      for (var col = range.from.col; col <= range.to.col; col++) {
        applyAlignClassName(row, col, type, alignment, cellDescriptor, propertySetter);
      }
    }
  }
}

function applyAlignClassName(row, col, type, alignment, cellDescriptor, propertySetter) {
  var cellMeta = cellDescriptor(row, col);
  var className = alignment;

  if (cellMeta.className) {
    if (type === 'vertical') {
      className = prepareVerticalAlignClass(cellMeta.className, alignment);
    } else {
      className = prepareHorizontalAlignClass(cellMeta.className, alignment);
    }
  }

  propertySetter(row, col, 'className', className);
}

function checkSelectionConsistency(range, comparator) {
  var result = false;

  if (range) {
    range.forAll(function (row, col) {
      if (comparator(row, col)) {
        result = true;

        return false;
      }
    });
  }

  return result;
}

function markLabelAsSelected(label) {
  // workaround for https://github.com/handsontable/handsontable/issues/1946
  return '<span class="selected">' + String.fromCharCode(10003) + '</span>' + label;
}

function isItemHidden(item, instance) {
  return !item.hidden || !(typeof item.hidden == 'function' && item.hidden.call(instance));
}

function shiftSeparators(items, separator) {
  var result = items.slice(0);

  for (var i = 0; i < result.length;) {
    if (result[i].name === separator) {
      result.shift();
    } else {
      break;
    }
  }
  return result;
}

function popSeparators(items, separator) {
  var result = items.slice(0);

  result.reverse();
  result = shiftSeparators(result, separator);
  result.reverse();

  return result;
}

function removeDuplicatedSeparators(items) {
  var result = [];

  (0, _array.arrayEach)(items, function (value, index) {
    if (index > 0) {
      if (result[result.length - 1].name !== value.name) {
        result.push(value);
      }
    } else {
      result.push(value);
    }
  });

  return result;
}

function filterSeparators(items) {
  var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _separator.KEY;

  var result = items.slice(0);

  result = shiftSeparators(result, separator);
  result = popSeparators(result, separator);
  result = removeDuplicatedSeparators(result);

  return result;
}

/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {

// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(23)(function () {
  return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});


/***/ }),
/* 23 */
/***/ (function(module, exports) {

module.exports = function (exec) {
  try {
    return !!exec();
  } catch (e) {
    return true;
  }
};


/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {

// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(71);
var defined = __webpack_require__(38);
module.exports = function (it) {
  return IObject(defined(it));
};


/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.15 ToLength
var toInteger = __webpack_require__(55);
var min = Math.min;
module.exports = function (it) {
  return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};


/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {

// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(3);
var core = __webpack_require__(43);
var fails = __webpack_require__(23);
module.exports = function (KEY, exec) {
  var fn = (core.Object || {})[KEY] || Object[KEY];
  var exp = {};
  exp[KEY] = exec(fn);
  $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};


/***/ }),
/* 27 */
/***/ (function(module, exports) {

var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
  return hasOwnProperty.call(it, key);
};


/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.isIE8 = isIE8;
exports.isIE9 = isIE9;
exports.isSafari = isSafari;
exports.isChrome = isChrome;
exports.isMobileBrowser = isMobileBrowser;

var _isIE8 = !document.createTextNode('test').textContent;

function isIE8() {
  return _isIE8;
}

var _isIE9 = !!document.documentMode;

function isIE9() {
  return _isIE9;
}

var _isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

function isSafari() {
  return _isSafari;
}

var _isChrome = /Chrome/.test(navigator.userAgent) && /Google/.test(navigator.vendor);

function isChrome() {
  return _isChrome;
}

function isMobileBrowser(userAgent) {
  if (!userAgent) {
    userAgent = navigator.userAgent;
  }

  return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)
  );
}

/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.getRegisteredValidators = exports.getRegisteredValidatorNames = exports.hasValidator = exports.getValidator = exports.registerValidator = undefined;

var _staticRegister2 = __webpack_require__(46);

var _staticRegister3 = _interopRequireDefault(_staticRegister2);

var _autocompleteValidator = __webpack_require__(365);

var _autocompleteValidator2 = _interopRequireDefault(_autocompleteValidator);

var _dateValidator = __webpack_require__(366);

var _dateValidator2 = _interopRequireDefault(_dateValidator);

var _numericValidator = __webpack_require__(367);

var _numericValidator2 = _interopRequireDefault(_numericValidator);

var _timeValidator = __webpack_require__(368);

var _timeValidator2 = _interopRequireDefault(_timeValidator);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _staticRegister = (0, _staticRegister3.default)('validators'),
    register = _staticRegister.register,
    getItem = _staticRegister.getItem,
    hasItem = _staticRegister.hasItem,
    getNames = _staticRegister.getNames,
    getValues = _staticRegister.getValues;

register('autocomplete', _autocompleteValidator2.default);
register('date', _dateValidator2.default);
register('numeric', _numericValidator2.default);
register('time', _timeValidator2.default);

/**
 * Retrieve validator function.
 *
 * @param {String} name Validator identification.
 * @returns {Function} Returns validator function.
 */
function _getItem(name) {
  if (typeof name === 'function') {
    return name;
  }
  if (!hasItem(name)) {
    throw Error('No registered validator found under "' + name + '" name');
  }

  return getItem(name);
}

exports.registerValidator = register;
exports.getValidator = _getItem;
exports.hasValidator = hasItem;
exports.getRegisteredValidatorNames = getNames;
exports.getRegisteredValidators = getValues;

/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(13);
var hide = __webpack_require__(31);
var has = __webpack_require__(27);
var SRC = __webpack_require__(48)('src');
var TO_STRING = 'toString';
var $toString = Function[TO_STRING];
var TPL = ('' + $toString).split(TO_STRING);

__webpack_require__(43).inspectSource = function (it) {
  return $toString.call(it);
};

(module.exports = function (O, key, val, safe) {
  var isFunction = typeof val == 'function';
  if (isFunction) has(val, 'name') || hide(val, 'name', key);
  if (O[key] === val) return;
  if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
  if (O === global) {
    O[key] = val;
  } else if (!safe) {
    delete O[key];
    hide(O, key, val);
  } else if (O[key]) {
    O[key] = val;
  } else {
    hide(O, key, val);
  }
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString() {
  return typeof this == 'function' && this[SRC] || $toString.call(this);
});


/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {

var dP = __webpack_require__(19);
var createDesc = __webpack_require__(49);
module.exports = __webpack_require__(22) ? function (object, key, value) {
  return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
  object[key] = value;
  return object;
};


/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {

// optional / simple context binding
var aFunction = __webpack_require__(58);
module.exports = function (fn, that, length) {
  aFunction(fn);
  if (that === undefined) return fn;
  switch (length) {
    case 1: return function (a) {
      return fn.call(that, a);
    };
    case 2: return function (a, b) {
      return fn.call(that, a, b);
    };
    case 3: return function (a, b, c) {
      return fn.call(that, a, b, c);
    };
  }
  return function (/* ...args */) {
    return fn.apply(that, arguments);
  };
};


/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.13 ToObject(argument)
var defined = __webpack_require__(38);
module.exports = function (it) {
  return Object(defined(it));
};


/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {

var META = __webpack_require__(48)('meta');
var isObject = __webpack_require__(5);
var has = __webpack_require__(27);
var setDesc = __webpack_require__(19).f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
  return true;
};
var FREEZE = !__webpack_require__(23)(function () {
  return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
  setDesc(it, META, { value: {
    i: 'O' + ++id, // object ID
    w: {}          // weak collections IDs
  } });
};
var fastKey = function (it, create) {
  // return primitive with prefix
  if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
  if (!has(it, META)) {
    // can't set metadata to uncaught frozen object
    if (!isExtensible(it)) return 'F';
    // not necessary to add metadata
    if (!create) return 'E';
    // add missing metadata
    setMeta(it);
  // return object ID
  } return it[META].i;
};
var getWeak = function (it, create) {
  if (!has(it, META)) {
    // can't set metadata to uncaught frozen object
    if (!isExtensible(it)) return true;
    // not necessary to add metadata
    if (!create) return false;
    // add missing metadata
    setMeta(it);
  // return hash weak collections IDs
  } return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
  if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
  return it;
};
var meta = module.exports = {
  KEY: META,
  NEED: false,
  fastKey: fastKey,
  getWeak: getWeak,
  onFreeze: onFreeze
};


/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _object = __webpack_require__(1);

var _array = __webpack_require__(2);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _core = __webpack_require__(174);

var _core2 = _interopRequireDefault(_core);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var registeredOverlays = {};

/**
 * Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable
 * and (optionally) implements behavior needed for native horizontal and vertical scrolling.
 *
 * @class Overlay
 */

var Overlay = function () {
  _createClass(Overlay, null, [{
    key: 'registerOverlay',


    /**
     * Register overlay class.
     *
     * @param {String} type Overlay type, one of the CLONE_TYPES value
     * @param {Overlay} overlayClass Overlay class extended from base overlay class {@link Overlay}
     */
    value: function registerOverlay(type, overlayClass) {
      if (Overlay.CLONE_TYPES.indexOf(type) === -1) {
        throw new Error('Unsupported overlay (' + type + ').');
      }
      registeredOverlays[type] = overlayClass;
    }

    /**
     * Create new instance of overlay type.
     *
     * @param {String} type Overlay type, one of the CLONE_TYPES value
     * @param {Walkontable} wot Walkontable instance
     */

  }, {
    key: 'createOverlay',
    value: function createOverlay(type, wot) {
      return new registeredOverlays[type](wot);
    }

    /**
     * Check if specified overlay was registered.
     *
     * @param {String} type Overlay type, one of the CLONE_TYPES value
     * @returns {Boolean}
     */

  }, {
    key: 'hasOverlay',
    value: function hasOverlay(type) {
      return registeredOverlays[type] !== void 0;
    }

    /**
     * Checks if overlay object (`overlay`) is instance of overlay type (`type`).
     *
     * @param {Overlay} overlay Overlay object
     * @param {String} type Overlay type, one of the CLONE_TYPES value
     * @returns {Boolean}
     */

  }, {
    key: 'isOverlayTypeOf',
    value: function isOverlayTypeOf(overlay, type) {
      if (!overlay || !registeredOverlays[type]) {
        return false;
      }

      return overlay instanceof registeredOverlays[type];
    }

    /**
     * @param {Walkontable} wotInstance
     */

  }, {
    key: 'CLONE_TOP',

    /**
     * @type {String}
     */
    get: function get() {
      return 'top';
    }

    /**
     * @type {String}
     */

  }, {
    key: 'CLONE_BOTTOM',
    get: function get() {
      return 'bottom';
    }

    /**
     * @type {String}
     */

  }, {
    key: 'CLONE_LEFT',
    get: function get() {
      return 'left';
    }

    /**
     * @type {String}
     */

  }, {
    key: 'CLONE_TOP_LEFT_CORNER',
    get: function get() {
      return 'top_left_corner';
    }

    /**
     * @type {String}
     */

  }, {
    key: 'CLONE_BOTTOM_LEFT_CORNER',
    get: function get() {
      return 'bottom_left_corner';
    }

    /**
     * @type {String}
     */

  }, {
    key: 'CLONE_DEBUG',
    get: function get() {
      return 'debug';
    }

    /**
     * List of all availables clone types
     *
     * @type {Array}
     */

  }, {
    key: 'CLONE_TYPES',
    get: function get() {
      return [Overlay.CLONE_TOP, Overlay.CLONE_BOTTOM, Overlay.CLONE_LEFT, Overlay.CLONE_TOP_LEFT_CORNER, Overlay.CLONE_BOTTOM_LEFT_CORNER, Overlay.CLONE_DEBUG];
    }
  }]);

  function Overlay(wotInstance) {
    _classCallCheck(this, Overlay);

    (0, _object.defineGetter)(this, 'wot', wotInstance, {
      writable: false
    });

    // legacy support, deprecated in the future
    this.instance = this.wot;

    this.type = '';
    this.mainTableScrollableElement = null;
    this.TABLE = this.wot.wtTable.TABLE;
    this.hider = this.wot.wtTable.hider;
    this.spreader = this.wot.wtTable.spreader;
    this.holder = this.wot.wtTable.holder;
    this.wtRootElement = this.wot.wtTable.wtRootElement;
    this.trimmingContainer = (0, _element.getTrimmingContainer)(this.hider.parentNode.parentNode);
    this.areElementSizesAdjusted = false;
    this.updateStateOfRendering();
  }

  /**
   * Update internal state of object with an information about the need of full rendering of the overlay.
   *
   * @returns {Boolean} Returns `true` if the state has changed since the last check.
   */


  _createClass(Overlay, [{
    key: 'updateStateOfRendering',
    value: function updateStateOfRendering() {
      var previousState = this.needFullRender;

      this.needFullRender = this.shouldBeRendered();

      var changed = previousState !== this.needFullRender;

      if (changed && !this.needFullRender) {
        this.reset();
      }

      return changed;
    }

    /**
     * Checks if overlay should be fully rendered
     *
     * @returns {Boolean}
     */

  }, {
    key: 'shouldBeRendered',
    value: function shouldBeRendered() {
      return true;
    }

    /**
     * Update the trimming container.
     */

  }, {
    key: 'updateTrimmingContainer',
    value: function updateTrimmingContainer() {
      this.trimmingContainer = (0, _element.getTrimmingContainer)(this.hider.parentNode.parentNode);
    }

    /**
     * Update the main scrollable element.
     */

  }, {
    key: 'updateMainScrollableElement',
    value: function updateMainScrollableElement() {
      this.mainTableScrollableElement = (0, _element.getScrollableElement)(this.wot.wtTable.TABLE);
    }

    /**
     * Make a clone of table for overlay
     *
     * @param {String} direction Can be `Overlay.CLONE_TOP`, `Overlay.CLONE_LEFT`,
     *                           `Overlay.CLONE_TOP_LEFT_CORNER`, `Overlay.CLONE_DEBUG`
     * @returns {Walkontable}
     */

  }, {
    key: 'makeClone',
    value: function makeClone(direction) {
      if (Overlay.CLONE_TYPES.indexOf(direction) === -1) {
        throw new Error('Clone type "' + direction + '" is not supported.');
      }
      var clone = document.createElement('DIV');
      var clonedTable = document.createElement('TABLE');

      clone.className = 'ht_clone_' + direction + ' handsontable';
      clone.style.position = 'absolute';
      clone.style.top = 0;
      clone.style.left = 0;
      clone.style.overflow = 'hidden';

      clonedTable.className = this.wot.wtTable.TABLE.className;
      clone.appendChild(clonedTable);

      this.type = direction;
      this.wot.wtTable.wtRootElement.parentNode.appendChild(clone);

      var preventOverflow = this.wot.getSetting('preventOverflow');

      if (preventOverflow === true || preventOverflow === 'horizontal' && this.type === Overlay.CLONE_TOP || preventOverflow === 'vertical' && this.type === Overlay.CLONE_LEFT) {
        this.mainTableScrollableElement = window;
      } else {
        this.mainTableScrollableElement = (0, _element.getScrollableElement)(this.wot.wtTable.TABLE);
      }

      return new _core2.default({
        cloneSource: this.wot,
        cloneOverlay: this,
        table: clonedTable
      });
    }

    /**
     * Refresh/Redraw overlay
     *
     * @param {Boolean} [fastDraw=false]
     */

  }, {
    key: 'refresh',
    value: function refresh() {
      var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      // When hot settings are changed we allow to refresh overlay once before blocking
      var nextCycleRenderFlag = this.shouldBeRendered();

      if (this.clone && (this.needFullRender || nextCycleRenderFlag)) {
        this.clone.draw(fastDraw);
      }
      this.needFullRender = nextCycleRenderFlag;
    }

    /**
     * Reset overlay styles to initial values.
     */

  }, {
    key: 'reset',
    value: function reset() {
      if (!this.clone) {
        return;
      }
      var holder = this.clone.wtTable.holder;
      var hider = this.clone.wtTable.hider;
      var holderStyle = holder.style;
      var hidderStyle = hider.style;
      var rootStyle = holder.parentNode.style;

      (0, _array.arrayEach)([holderStyle, hidderStyle, rootStyle], function (style) {
        style.width = '';
        style.height = '';
      });
    }

    /**
     * Destroy overlay instance
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      new _eventManager2.default(this.clone).destroy();
    }
  }]);

  return Overlay;
}();

exports.default = Overlay;

/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.toUpperCaseFirst = toUpperCaseFirst;
exports.equalsIgnoreCase = equalsIgnoreCase;
exports.randomString = randomString;
exports.isPercentValue = isPercentValue;
exports.substitute = substitute;
exports.stripTags = stripTags;

var _mixed = __webpack_require__(17);

var _number = __webpack_require__(6);

/**
 * Convert string to upper case first letter.
 *
 * @param {String} string String to convert.
 * @returns {String}
 */
function toUpperCaseFirst(string) {
  return string[0].toUpperCase() + string.substr(1);
}

/**
 * Compare strings case insensitively.
 *
 * @param {...String} strings Strings to compare.
 * @returns {Boolean}
 */
function equalsIgnoreCase() {
  var unique = [];

  for (var _len = arguments.length, strings = Array(_len), _key = 0; _key < _len; _key++) {
    strings[_key] = arguments[_key];
  }

  var length = strings.length;

  while (length--) {
    var string = (0, _mixed.stringify)(strings[length]).toLowerCase();

    if (unique.indexOf(string) === -1) {
      unique.push(string);
    }
  }

  return unique.length === 1;
}

/**
 * Generates a random hex string. Used as namespace for Handsontable instance events.
 *
 * @return {String} Returns 16-long character random string (eq. `'92b1bfc74ec4'`).
 */
function randomString() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  }

  return s4() + s4() + s4() + s4();
}

/**
 * Checks if value is valid percent.
 *
 * @param {String} value
 * @returns {Boolean}
 */
function isPercentValue(value) {
  return (/^([0-9][0-9]?%$)|(^100%$)/.test(value)
  );
}

/**
 * Substitute strings placed beetwen square brackets into value defined in `variables` object. String names defined in
 * square brackets must be the same as property name of `variables` object.
 *
 * @param {String} template Template string.
 * @param {Object} variables Object which contains all available values which can be injected into template.
 * @returns {String}
 */
function substitute(template) {
  var variables = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  return ('' + template).replace(/(?:\\)?\[([^[\]]+)]/g, function (match, name) {
    if (match.charAt(0) === '\\') {
      return match.substr(1, match.length - 1);
    }

    return variables[name] === void 0 ? '' : variables[name];
  });
}

var STRIP_TAGS_REGEX = /<\/?\w+\/?>|<\w+[\s|/][^>]*>/gi;

/**
 * Strip any HTML tag from the string.
 *
 * @param  {String} string String to cut HTML from.
 * @return {String}
 */
function stripTags(string) {
  string += '';

  return string.replace(STRIP_TAGS_REGEX, '');
}

/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(94);
var enumBugKeys = __webpack_require__(74);

module.exports = Object.keys || function keys(O) {
  return $keys(O, enumBugKeys);
};


/***/ }),
/* 38 */
/***/ (function(module, exports) {

// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
  if (it == undefined) throw TypeError("Can't call method on  " + it);
  return it;
};


/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.requestAnimationFrame = requestAnimationFrame;
exports.cancelAnimationFrame = cancelAnimationFrame;
exports.isTouchSupported = isTouchSupported;
exports.isWebComponentSupportedNatively = isWebComponentSupportedNatively;
exports.hasCaptionProblem = hasCaptionProblem;
exports.getComparisonFunction = getComparisonFunction;
// https://gist.github.com/paulirish/1579671
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
var _requestAnimationFrame = window.requestAnimationFrame;
var _cancelAnimationFrame = window.cancelAnimationFrame;

for (var x = 0; x < vendors.length && !_requestAnimationFrame; ++x) {
  _requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
  _cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}

if (!_requestAnimationFrame) {
  _requestAnimationFrame = function _requestAnimationFrame(callback) {
    var currTime = new Date().getTime();
    var timeToCall = Math.max(0, 16 - (currTime - lastTime));
    var id = window.setTimeout(function () {
      callback(currTime + timeToCall);
    }, timeToCall);
    lastTime = currTime + timeToCall;

    return id;
  };
}

if (!_cancelAnimationFrame) {
  _cancelAnimationFrame = function _cancelAnimationFrame(id) {
    clearTimeout(id);
  };
}

/**
 * Polyfill for requestAnimationFrame
 *
 * @param {Function} callback
 * @returns {Number}
 */
function requestAnimationFrame(callback) {
  return _requestAnimationFrame.call(window, callback);
}

/**
 * Polyfill for cancelAnimationFrame
 *
 * @param {Number} id
 */
function cancelAnimationFrame(id) {
  _cancelAnimationFrame.call(window, id);
}

function isTouchSupported() {
  return 'ontouchstart' in window;
}

/**
 * Checks if browser is support web components natively
 *
 * @returns {Boolean}
 */
function isWebComponentSupportedNatively() {
  var test = document.createElement('div');

  return !!(test.createShadowRoot && test.createShadowRoot.toString().match(/\[native code\]/));
}

var _hasCaptionProblem;

function detectCaptionProblem() {
  var TABLE = document.createElement('TABLE');
  TABLE.style.borderSpacing = 0;
  TABLE.style.borderWidth = 0;
  TABLE.style.padding = 0;
  var TBODY = document.createElement('TBODY');
  TABLE.appendChild(TBODY);
  TBODY.appendChild(document.createElement('TR'));
  TBODY.firstChild.appendChild(document.createElement('TD'));
  TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>';

  var CAPTION = document.createElement('CAPTION');
  CAPTION.innerHTML = 'c<br>c<br>c<br>c';
  CAPTION.style.padding = 0;
  CAPTION.style.margin = 0;
  TABLE.insertBefore(CAPTION, TBODY);

  document.body.appendChild(TABLE);
  _hasCaptionProblem = TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight; // boolean
  document.body.removeChild(TABLE);
}

function hasCaptionProblem() {
  if (_hasCaptionProblem === void 0) {
    detectCaptionProblem();
  }

  return _hasCaptionProblem;
}

var comparisonFunction = void 0;

/**
 * Get string comparison function for sorting purposes. It supports multilingual string comparison base on Internationalization API.
 *
 * @param {String} [language]
 * @param {Object} [options]
 * @returns {*}
 */
function getComparisonFunction(language) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  if (comparisonFunction) {
    return comparisonFunction;
  }

  if ((typeof Intl === 'undefined' ? 'undefined' : _typeof(Intl)) === 'object') {
    comparisonFunction = new Intl.Collator(language, options).compare;
  } else if (typeof String.prototype.localeCompare === 'function') {
    comparisonFunction = function comparisonFunction(a, b) {
      return ('' + a).localeCompare(b);
    };
  } else {
    comparisonFunction = function comparisonFunction(a, b) {
      if (a === b) {
        return 0;
      }

      return a > b ? -1 : 1;
    };
  }

  return comparisonFunction;
}

/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var require;//! moment.js
//! version : 2.20.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com

;(function (global, factory) {
     true ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    global.moment = factory()
}(this, (function () { 'use strict';

var hookCallback;

function hooks () {
    return hookCallback.apply(null, arguments);
}

// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback (callback) {
    hookCallback = callback;
}

function isArray(input) {
    return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
}

function isObject(input) {
    // IE8 will treat undefined and null as object if it wasn't for
    // input != null
    return input != null && Object.prototype.toString.call(input) === '[object Object]';
}

function isObjectEmpty(obj) {
    if (Object.getOwnPropertyNames) {
        return (Object.getOwnPropertyNames(obj).length === 0);
    } else {
        var k;
        for (k in obj) {
            if (obj.hasOwnProperty(k)) {
                return false;
            }
        }
        return true;
    }
}

function isUndefined(input) {
    return input === void 0;
}

function isNumber(input) {
    return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
}

function isDate(input) {
    return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
}

function map(arr, fn) {
    var res = [], i;
    for (i = 0; i < arr.length; ++i) {
        res.push(fn(arr[i], i));
    }
    return res;
}

function hasOwnProp(a, b) {
    return Object.prototype.hasOwnProperty.call(a, b);
}

function extend(a, b) {
    for (var i in b) {
        if (hasOwnProp(b, i)) {
            a[i] = b[i];
        }
    }

    if (hasOwnProp(b, 'toString')) {
        a.toString = b.toString;
    }

    if (hasOwnProp(b, 'valueOf')) {
        a.valueOf = b.valueOf;
    }

    return a;
}

function createUTC (input, format, locale, strict) {
    return createLocalOrUTC(input, format, locale, strict, true).utc();
}

function defaultParsingFlags() {
    // We need to deep clone this object.
    return {
        empty           : false,
        unusedTokens    : [],
        unusedInput     : [],
        overflow        : -2,
        charsLeftOver   : 0,
        nullInput       : false,
        invalidMonth    : null,
        invalidFormat   : false,
        userInvalidated : false,
        iso             : false,
        parsedDateParts : [],
        meridiem        : null,
        rfc2822         : false,
        weekdayMismatch : false
    };
}

function getParsingFlags(m) {
    if (m._pf == null) {
        m._pf = defaultParsingFlags();
    }
    return m._pf;
}

var some;
if (Array.prototype.some) {
    some = Array.prototype.some;
} else {
    some = function (fun) {
        var t = Object(this);
        var len = t.length >>> 0;

        for (var i = 0; i < len; i++) {
            if (i in t && fun.call(this, t[i], i, t)) {
                return true;
            }
        }

        return false;
    };
}

function isValid(m) {
    if (m._isValid == null) {
        var flags = getParsingFlags(m);
        var parsedParts = some.call(flags.parsedDateParts, function (i) {
            return i != null;
        });
        var isNowValid = !isNaN(m._d.getTime()) &&
            flags.overflow < 0 &&
            !flags.empty &&
            !flags.invalidMonth &&
            !flags.invalidWeekday &&
            !flags.weekdayMismatch &&
            !flags.nullInput &&
            !flags.invalidFormat &&
            !flags.userInvalidated &&
            (!flags.meridiem || (flags.meridiem && parsedParts));

        if (m._strict) {
            isNowValid = isNowValid &&
                flags.charsLeftOver === 0 &&
                flags.unusedTokens.length === 0 &&
                flags.bigHour === undefined;
        }

        if (Object.isFrozen == null || !Object.isFrozen(m)) {
            m._isValid = isNowValid;
        }
        else {
            return isNowValid;
        }
    }
    return m._isValid;
}

function createInvalid (flags) {
    var m = createUTC(NaN);
    if (flags != null) {
        extend(getParsingFlags(m), flags);
    }
    else {
        getParsingFlags(m).userInvalidated = true;
    }

    return m;
}

// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = hooks.momentProperties = [];

function copyConfig(to, from) {
    var i, prop, val;

    if (!isUndefined(from._isAMomentObject)) {
        to._isAMomentObject = from._isAMomentObject;
    }
    if (!isUndefined(from._i)) {
        to._i = from._i;
    }
    if (!isUndefined(from._f)) {
        to._f = from._f;
    }
    if (!isUndefined(from._l)) {
        to._l = from._l;
    }
    if (!isUndefined(from._strict)) {
        to._strict = from._strict;
    }
    if (!isUndefined(from._tzm)) {
        to._tzm = from._tzm;
    }
    if (!isUndefined(from._isUTC)) {
        to._isUTC = from._isUTC;
    }
    if (!isUndefined(from._offset)) {
        to._offset = from._offset;
    }
    if (!isUndefined(from._pf)) {
        to._pf = getParsingFlags(from);
    }
    if (!isUndefined(from._locale)) {
        to._locale = from._locale;
    }

    if (momentProperties.length > 0) {
        for (i = 0; i < momentProperties.length; i++) {
            prop = momentProperties[i];
            val = from[prop];
            if (!isUndefined(val)) {
                to[prop] = val;
            }
        }
    }

    return to;
}

var updateInProgress = false;

// Moment prototype object
function Moment(config) {
    copyConfig(this, config);
    this._d = new Date(config._d != null ? config._d.getTime() : NaN);
    if (!this.isValid()) {
        this._d = new Date(NaN);
    }
    // Prevent infinite loop in case updateOffset creates new moment
    // objects.
    if (updateInProgress === false) {
        updateInProgress = true;
        hooks.updateOffset(this);
        updateInProgress = false;
    }
}

function isMoment (obj) {
    return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
}

function absFloor (number) {
    if (number < 0) {
        // -0 -> 0
        return Math.ceil(number) || 0;
    } else {
        return Math.floor(number);
    }
}

function toInt(argumentForCoercion) {
    var coercedNumber = +argumentForCoercion,
        value = 0;

    if (coercedNumber !== 0 && isFinite(coercedNumber)) {
        value = absFloor(coercedNumber);
    }

    return value;
}

// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
    var len = Math.min(array1.length, array2.length),
        lengthDiff = Math.abs(array1.length - array2.length),
        diffs = 0,
        i;
    for (i = 0; i < len; i++) {
        if ((dontConvert && array1[i] !== array2[i]) ||
            (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
            diffs++;
        }
    }
    return diffs + lengthDiff;
}

function warn(msg) {
    if (hooks.suppressDeprecationWarnings === false &&
            (typeof console !==  'undefined') && console.warn) {
        console.warn('Deprecation warning: ' + msg);
    }
}

function deprecate(msg, fn) {
    var firstTime = true;

    return extend(function () {
        if (hooks.deprecationHandler != null) {
            hooks.deprecationHandler(null, msg);
        }
        if (firstTime) {
            var args = [];
            var arg;
            for (var i = 0; i < arguments.length; i++) {
                arg = '';
                if (typeof arguments[i] === 'object') {
                    arg += '\n[' + i + '] ';
                    for (var key in arguments[0]) {
                        arg += key + ': ' + arguments[0][key] + ', ';
                    }
                    arg = arg.slice(0, -2); // Remove trailing comma and space
                } else {
                    arg = arguments[i];
                }
                args.push(arg);
            }
            warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
            firstTime = false;
        }
        return fn.apply(this, arguments);
    }, fn);
}

var deprecations = {};

function deprecateSimple(name, msg) {
    if (hooks.deprecationHandler != null) {
        hooks.deprecationHandler(name, msg);
    }
    if (!deprecations[name]) {
        warn(msg);
        deprecations[name] = true;
    }
}

hooks.suppressDeprecationWarnings = false;
hooks.deprecationHandler = null;

function isFunction(input) {
    return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}

function set (config) {
    var prop, i;
    for (i in config) {
        prop = config[i];
        if (isFunction(prop)) {
            this[i] = prop;
        } else {
            this['_' + i] = prop;
        }
    }
    this._config = config;
    // Lenient ordinal parsing accepts just a number in addition to
    // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
    // TODO: Remove "ordinalParse" fallback in next major release.
    this._dayOfMonthOrdinalParseLenient = new RegExp(
        (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
            '|' + (/\d{1,2}/).source);
}

function mergeConfigs(parentConfig, childConfig) {
    var res = extend({}, parentConfig), prop;
    for (prop in childConfig) {
        if (hasOwnProp(childConfig, prop)) {
            if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
                res[prop] = {};
                extend(res[prop], parentConfig[prop]);
                extend(res[prop], childConfig[prop]);
            } else if (childConfig[prop] != null) {
                res[prop] = childConfig[prop];
            } else {
                delete res[prop];
            }
        }
    }
    for (prop in parentConfig) {
        if (hasOwnProp(parentConfig, prop) &&
                !hasOwnProp(childConfig, prop) &&
                isObject(parentConfig[prop])) {
            // make sure changes to properties don't modify parent config
            res[prop] = extend({}, res[prop]);
        }
    }
    return res;
}

function Locale(config) {
    if (config != null) {
        this.set(config);
    }
}

var keys;

if (Object.keys) {
    keys = Object.keys;
} else {
    keys = function (obj) {
        var i, res = [];
        for (i in obj) {
            if (hasOwnProp(obj, i)) {
                res.push(i);
            }
        }
        return res;
    };
}

var defaultCalendar = {
    sameDay : '[Today at] LT',
    nextDay : '[Tomorrow at] LT',
    nextWeek : 'dddd [at] LT',
    lastDay : '[Yesterday at] LT',
    lastWeek : '[Last] dddd [at] LT',
    sameElse : 'L'
};

function calendar (key, mom, now) {
    var output = this._calendar[key] || this._calendar['sameElse'];
    return isFunction(output) ? output.call(mom, now) : output;
}

var defaultLongDateFormat = {
    LTS  : 'h:mm:ss A',
    LT   : 'h:mm A',
    L    : 'MM/DD/YYYY',
    LL   : 'MMMM D, YYYY',
    LLL  : 'MMMM D, YYYY h:mm A',
    LLLL : 'dddd, MMMM D, YYYY h:mm A'
};

function longDateFormat (key) {
    var format = this._longDateFormat[key],
        formatUpper = this._longDateFormat[key.toUpperCase()];

    if (format || !formatUpper) {
        return format;
    }

    this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
        return val.slice(1);
    });

    return this._longDateFormat[key];
}

var defaultInvalidDate = 'Invalid date';

function invalidDate () {
    return this._invalidDate;
}

var defaultOrdinal = '%d';
var defaultDayOfMonthOrdinalParse = /\d{1,2}/;

function ordinal (number) {
    return this._ordinal.replace('%d', number);
}

var defaultRelativeTime = {
    future : 'in %s',
    past   : '%s ago',
    s  : 'a few seconds',
    ss : '%d seconds',
    m  : 'a minute',
    mm : '%d minutes',
    h  : 'an hour',
    hh : '%d hours',
    d  : 'a day',
    dd : '%d days',
    M  : 'a month',
    MM : '%d months',
    y  : 'a year',
    yy : '%d years'
};

function relativeTime (number, withoutSuffix, string, isFuture) {
    var output = this._relativeTime[string];
    return (isFunction(output)) ?
        output(number, withoutSuffix, string, isFuture) :
        output.replace(/%d/i, number);
}

function pastFuture (diff, output) {
    var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
    return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}

var aliases = {};

function addUnitAlias (unit, shorthand) {
    var lowerCase = unit.toLowerCase();
    aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}

function normalizeUnits(units) {
    return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
}

function normalizeObjectUnits(inputObject) {
    var normalizedInput = {},
        normalizedProp,
        prop;

    for (prop in inputObject) {
        if (hasOwnProp(inputObject, prop)) {
            normalizedProp = normalizeUnits(prop);
            if (normalizedProp) {
                normalizedInput[normalizedProp] = inputObject[prop];
            }
        }
    }

    return normalizedInput;
}

var priorities = {};

function addUnitPriority(unit, priority) {
    priorities[unit] = priority;
}

function getPrioritizedUnits(unitsObj) {
    var units = [];
    for (var u in unitsObj) {
        units.push({unit: u, priority: priorities[u]});
    }
    units.sort(function (a, b) {
        return a.priority - b.priority;
    });
    return units;
}

function zeroFill(number, targetLength, forceSign) {
    var absNumber = '' + Math.abs(number),
        zerosToFill = targetLength - absNumber.length,
        sign = number >= 0;
    return (sign ? (forceSign ? '+' : '') : '-') +
        Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
}

var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;

var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;

var formatFunctions = {};

var formatTokenFunctions = {};

// token:    'M'
// padded:   ['MM', 2]
// ordinal:  'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken (token, padded, ordinal, callback) {
    var func = callback;
    if (typeof callback === 'string') {
        func = function () {
            return this[callback]();
        };
    }
    if (token) {
        formatTokenFunctions[token] = func;
    }
    if (padded) {
        formatTokenFunctions[padded[0]] = function () {
            return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
        };
    }
    if (ordinal) {
        formatTokenFunctions[ordinal] = function () {
            return this.localeData().ordinal(func.apply(this, arguments), token);
        };
    }
}

function removeFormattingTokens(input) {
    if (input.match(/\[[\s\S]/)) {
        return input.replace(/^\[|\]$/g, '');
    }
    return input.replace(/\\/g, '');
}

function makeFormatFunction(format) {
    var array = format.match(formattingTokens), i, length;

    for (i = 0, length = array.length; i < length; i++) {
        if (formatTokenFunctions[array[i]]) {
            array[i] = formatTokenFunctions[array[i]];
        } else {
            array[i] = removeFormattingTokens(array[i]);
        }
    }

    return function (mom) {
        var output = '', i;
        for (i = 0; i < length; i++) {
            output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
        }
        return output;
    };
}

// format date using native date object
function formatMoment(m, format) {
    if (!m.isValid()) {
        return m.localeData().invalidDate();
    }

    format = expandFormat(format, m.localeData());
    formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);

    return formatFunctions[format](m);
}

function expandFormat(format, locale) {
    var i = 5;

    function replaceLongDateFormatTokens(input) {
        return locale.longDateFormat(input) || input;
    }

    localFormattingTokens.lastIndex = 0;
    while (i >= 0 && localFormattingTokens.test(format)) {
        format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
        localFormattingTokens.lastIndex = 0;
        i -= 1;
    }

    return format;
}

var match1         = /\d/;            //       0 - 9
var match2         = /\d\d/;          //      00 - 99
var match3         = /\d{3}/;         //     000 - 999
var match4         = /\d{4}/;         //    0000 - 9999
var match6         = /[+-]?\d{6}/;    // -999999 - 999999
var match1to2      = /\d\d?/;         //       0 - 99
var match3to4      = /\d\d\d\d?/;     //     999 - 9999
var match5to6      = /\d\d\d\d\d\d?/; //   99999 - 999999
var match1to3      = /\d{1,3}/;       //       0 - 999
var match1to4      = /\d{1,4}/;       //       0 - 9999
var match1to6      = /[+-]?\d{1,6}/;  // -999999 - 999999

var matchUnsigned  = /\d+/;           //       0 - inf
var matchSigned    = /[+-]?\d+/;      //    -inf - inf

var matchOffset    = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z

var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123

// any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;


var regexes = {};

function addRegexToken (token, regex, strictRegex) {
    regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
        return (isStrict && strictRegex) ? strictRegex : regex;
    };
}

function getParseRegexForToken (token, config) {
    if (!hasOwnProp(regexes, token)) {
        return new RegExp(unescapeFormat(token));
    }

    return regexes[token](config._strict, config._locale);
}

// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function unescapeFormat(s) {
    return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
        return p1 || p2 || p3 || p4;
    }));
}

function regexEscape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var tokens = {};

function addParseToken (token, callback) {
    var i, func = callback;
    if (typeof token === 'string') {
        token = [token];
    }
    if (isNumber(callback)) {
        func = function (input, array) {
            array[callback] = toInt(input);
        };
    }
    for (i = 0; i < token.length; i++) {
        tokens[token[i]] = func;
    }
}

function addWeekParseToken (token, callback) {
    addParseToken(token, function (input, array, config, token) {
        config._w = config._w || {};
        callback(input, config._w, config, token);
    });
}

function addTimeToArrayFromToken(token, input, config) {
    if (input != null && hasOwnProp(tokens, token)) {
        tokens[token](input, config._a, config, token);
    }
}

var YEAR = 0;
var MONTH = 1;
var DATE = 2;
var HOUR = 3;
var MINUTE = 4;
var SECOND = 5;
var MILLISECOND = 6;
var WEEK = 7;
var WEEKDAY = 8;

// FORMATTING

addFormatToken('Y', 0, 0, function () {
    var y = this.year();
    return y <= 9999 ? '' + y : '+' + y;
});

addFormatToken(0, ['YY', 2], 0, function () {
    return this.year() % 100;
});

addFormatToken(0, ['YYYY',   4],       0, 'year');
addFormatToken(0, ['YYYYY',  5],       0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');

// ALIASES

addUnitAlias('year', 'y');

// PRIORITIES

addUnitPriority('year', 1);

// PARSING

addRegexToken('Y',      matchSigned);
addRegexToken('YY',     match1to2, match2);
addRegexToken('YYYY',   match1to4, match4);
addRegexToken('YYYYY',  match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);

addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
    array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
    array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
    array[YEAR] = parseInt(input, 10);
});

// HELPERS

function daysInYear(year) {
    return isLeapYear(year) ? 366 : 365;
}

function isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

// HOOKS

hooks.parseTwoDigitYear = function (input) {
    return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};

// MOMENTS

var getSetYear = makeGetSet('FullYear', true);

function getIsLeapYear () {
    return isLeapYear(this.year());
}

function makeGetSet (unit, keepTime) {
    return function (value) {
        if (value != null) {
            set$1(this, unit, value);
            hooks.updateOffset(this, keepTime);
            return this;
        } else {
            return get(this, unit);
        }
    };
}

function get (mom, unit) {
    return mom.isValid() ?
        mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
}

function set$1 (mom, unit, value) {
    if (mom.isValid() && !isNaN(value)) {
        if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
            mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
        }
        else {
            mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
        }
    }
}

// MOMENTS

function stringGet (units) {
    units = normalizeUnits(units);
    if (isFunction(this[units])) {
        return this[units]();
    }
    return this;
}


function stringSet (units, value) {
    if (typeof units === 'object') {
        units = normalizeObjectUnits(units);
        var prioritized = getPrioritizedUnits(units);
        for (var i = 0; i < prioritized.length; i++) {
            this[prioritized[i].unit](units[prioritized[i].unit]);
        }
    } else {
        units = normalizeUnits(units);
        if (isFunction(this[units])) {
            return this[units](value);
        }
    }
    return this;
}

function mod(n, x) {
    return ((n % x) + x) % x;
}

var indexOf;

if (Array.prototype.indexOf) {
    indexOf = Array.prototype.indexOf;
} else {
    indexOf = function (o) {
        // I know
        var i;
        for (i = 0; i < this.length; ++i) {
            if (this[i] === o) {
                return i;
            }
        }
        return -1;
    };
}

function daysInMonth(year, month) {
    if (isNaN(year) || isNaN(month)) {
        return NaN;
    }
    var modMonth = mod(month, 12);
    year += (month - modMonth) / 12;
    return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
}

// FORMATTING

addFormatToken('M', ['MM', 2], 'Mo', function () {
    return this.month() + 1;
});

addFormatToken('MMM', 0, 0, function (format) {
    return this.localeData().monthsShort(this, format);
});

addFormatToken('MMMM', 0, 0, function (format) {
    return this.localeData().months(this, format);
});

// ALIASES

addUnitAlias('month', 'M');

// PRIORITY

addUnitPriority('month', 8);

// PARSING

addRegexToken('M',    match1to2);
addRegexToken('MM',   match1to2, match2);
addRegexToken('MMM',  function (isStrict, locale) {
    return locale.monthsShortRegex(isStrict);
});
addRegexToken('MMMM', function (isStrict, locale) {
    return locale.monthsRegex(isStrict);
});

addParseToken(['M', 'MM'], function (input, array) {
    array[MONTH] = toInt(input) - 1;
});

addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
    var month = config._locale.monthsParse(input, token, config._strict);
    // if we didn't find a month name, mark the date as invalid.
    if (month != null) {
        array[MONTH] = month;
    } else {
        getParsingFlags(config).invalidMonth = input;
    }
});

// LOCALES

var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
function localeMonths (m, format) {
    if (!m) {
        return isArray(this._months) ? this._months :
            this._months['standalone'];
    }
    return isArray(this._months) ? this._months[m.month()] :
        this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
}

var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
function localeMonthsShort (m, format) {
    if (!m) {
        return isArray(this._monthsShort) ? this._monthsShort :
            this._monthsShort['standalone'];
    }
    return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
        this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
}

function handleStrictParse(monthName, format, strict) {
    var i, ii, mom, llc = monthName.toLocaleLowerCase();
    if (!this._monthsParse) {
        // this is not used
        this._monthsParse = [];
        this._longMonthsParse = [];
        this._shortMonthsParse = [];
        for (i = 0; i < 12; ++i) {
            mom = createUTC([2000, i]);
            this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
            this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
        }
    }

    if (strict) {
        if (format === 'MMM') {
            ii = indexOf.call(this._shortMonthsParse, llc);
            return ii !== -1 ? ii : null;
        } else {
            ii = indexOf.call(this._longMonthsParse, llc);
            return ii !== -1 ? ii : null;
        }
    } else {
        if (format === 'MMM') {
            ii = indexOf.call(this._shortMonthsParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._longMonthsParse, llc);
            return ii !== -1 ? ii : null;
        } else {
            ii = indexOf.call(this._longMonthsParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._shortMonthsParse, llc);
            return ii !== -1 ? ii : null;
        }
    }
}

function localeMonthsParse (monthName, format, strict) {
    var i, mom, regex;

    if (this._monthsParseExact) {
        return handleStrictParse.call(this, monthName, format, strict);
    }

    if (!this._monthsParse) {
        this._monthsParse = [];
        this._longMonthsParse = [];
        this._shortMonthsParse = [];
    }

    // TODO: add sorting
    // Sorting makes sure if one month (or abbr) is a prefix of another
    // see sorting in computeMonthsParse
    for (i = 0; i < 12; i++) {
        // make the regex if we don't have it already
        mom = createUTC([2000, i]);
        if (strict && !this._longMonthsParse[i]) {
            this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
            this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
        }
        if (!strict && !this._monthsParse[i]) {
            regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
            this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
        }
        // test the regex
        if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
            return i;
        } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
            return i;
        } else if (!strict && this._monthsParse[i].test(monthName)) {
            return i;
        }
    }
}

// MOMENTS

function setMonth (mom, value) {
    var dayOfMonth;

    if (!mom.isValid()) {
        // No op
        return mom;
    }

    if (typeof value === 'string') {
        if (/^\d+$/.test(value)) {
            value = toInt(value);
        } else {
            value = mom.localeData().monthsParse(value);
            // TODO: Another silent failure?
            if (!isNumber(value)) {
                return mom;
            }
        }
    }

    dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
    mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
    return mom;
}

function getSetMonth (value) {
    if (value != null) {
        setMonth(this, value);
        hooks.updateOffset(this, true);
        return this;
    } else {
        return get(this, 'Month');
    }
}

function getDaysInMonth () {
    return daysInMonth(this.year(), this.month());
}

var defaultMonthsShortRegex = matchWord;
function monthsShortRegex (isStrict) {
    if (this._monthsParseExact) {
        if (!hasOwnProp(this, '_monthsRegex')) {
            computeMonthsParse.call(this);
        }
        if (isStrict) {
            return this._monthsShortStrictRegex;
        } else {
            return this._monthsShortRegex;
        }
    } else {
        if (!hasOwnProp(this, '_monthsShortRegex')) {
            this._monthsShortRegex = defaultMonthsShortRegex;
        }
        return this._monthsShortStrictRegex && isStrict ?
            this._monthsShortStrictRegex : this._monthsShortRegex;
    }
}

var defaultMonthsRegex = matchWord;
function monthsRegex (isStrict) {
    if (this._monthsParseExact) {
        if (!hasOwnProp(this, '_monthsRegex')) {
            computeMonthsParse.call(this);
        }
        if (isStrict) {
            return this._monthsStrictRegex;
        } else {
            return this._monthsRegex;
        }
    } else {
        if (!hasOwnProp(this, '_monthsRegex')) {
            this._monthsRegex = defaultMonthsRegex;
        }
        return this._monthsStrictRegex && isStrict ?
            this._monthsStrictRegex : this._monthsRegex;
    }
}

function computeMonthsParse () {
    function cmpLenRev(a, b) {
        return b.length - a.length;
    }

    var shortPieces = [], longPieces = [], mixedPieces = [],
        i, mom;
    for (i = 0; i < 12; i++) {
        // make the regex if we don't have it already
        mom = createUTC([2000, i]);
        shortPieces.push(this.monthsShort(mom, ''));
        longPieces.push(this.months(mom, ''));
        mixedPieces.push(this.months(mom, ''));
        mixedPieces.push(this.monthsShort(mom, ''));
    }
    // Sorting makes sure if one month (or abbr) is a prefix of another it
    // will match the longer piece.
    shortPieces.sort(cmpLenRev);
    longPieces.sort(cmpLenRev);
    mixedPieces.sort(cmpLenRev);
    for (i = 0; i < 12; i++) {
        shortPieces[i] = regexEscape(shortPieces[i]);
        longPieces[i] = regexEscape(longPieces[i]);
    }
    for (i = 0; i < 24; i++) {
        mixedPieces[i] = regexEscape(mixedPieces[i]);
    }

    this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
    this._monthsShortRegex = this._monthsRegex;
    this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
    this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
}

function createDate (y, m, d, h, M, s, ms) {
    // can't just apply() to create a date:
    // https://stackoverflow.com/q/181348
    var date = new Date(y, m, d, h, M, s, ms);

    // the date constructor remaps years 0-99 to 1900-1999
    if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
        date.setFullYear(y);
    }
    return date;
}

function createUTCDate (y) {
    var date = new Date(Date.UTC.apply(null, arguments));

    // the Date.UTC function remaps years 0-99 to 1900-1999
    if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
        date.setUTCFullYear(y);
    }
    return date;
}

// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
    var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
        fwd = 7 + dow - doy,
        // first-week day local weekday -- which local weekday is fwd
        fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;

    return -fwdlw + fwd - 1;
}

// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
    var localWeekday = (7 + weekday - dow) % 7,
        weekOffset = firstWeekOffset(year, dow, doy),
        dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
        resYear, resDayOfYear;

    if (dayOfYear <= 0) {
        resYear = year - 1;
        resDayOfYear = daysInYear(resYear) + dayOfYear;
    } else if (dayOfYear > daysInYear(year)) {
        resYear = year + 1;
        resDayOfYear = dayOfYear - daysInYear(year);
    } else {
        resYear = year;
        resDayOfYear = dayOfYear;
    }

    return {
        year: resYear,
        dayOfYear: resDayOfYear
    };
}

function weekOfYear(mom, dow, doy) {
    var weekOffset = firstWeekOffset(mom.year(), dow, doy),
        week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
        resWeek, resYear;

    if (week < 1) {
        resYear = mom.year() - 1;
        resWeek = week + weeksInYear(resYear, dow, doy);
    } else if (week > weeksInYear(mom.year(), dow, doy)) {
        resWeek = week - weeksInYear(mom.year(), dow, doy);
        resYear = mom.year() + 1;
    } else {
        resYear = mom.year();
        resWeek = week;
    }

    return {
        week: resWeek,
        year: resYear
    };
}

function weeksInYear(year, dow, doy) {
    var weekOffset = firstWeekOffset(year, dow, doy),
        weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
    return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}

// FORMATTING

addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');

// ALIASES

addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');

// PRIORITIES

addUnitPriority('week', 5);
addUnitPriority('isoWeek', 5);

// PARSING

addRegexToken('w',  match1to2);
addRegexToken('ww', match1to2, match2);
addRegexToken('W',  match1to2);
addRegexToken('WW', match1to2, match2);

addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
    week[token.substr(0, 1)] = toInt(input);
});

// HELPERS

// LOCALES

function localeWeek (mom) {
    return weekOfYear(mom, this._week.dow, this._week.doy).week;
}

var defaultLocaleWeek = {
    dow : 0, // Sunday is the first day of the week.
    doy : 6  // The week that contains Jan 1st is the first week of the year.
};

function localeFirstDayOfWeek () {
    return this._week.dow;
}

function localeFirstDayOfYear () {
    return this._week.doy;
}

// MOMENTS

function getSetWeek (input) {
    var week = this.localeData().week(this);
    return input == null ? week : this.add((input - week) * 7, 'd');
}

function getSetISOWeek (input) {
    var week = weekOfYear(this, 1, 4).week;
    return input == null ? week : this.add((input - week) * 7, 'd');
}

// FORMATTING

addFormatToken('d', 0, 'do', 'day');

addFormatToken('dd', 0, 0, function (format) {
    return this.localeData().weekdaysMin(this, format);
});

addFormatToken('ddd', 0, 0, function (format) {
    return this.localeData().weekdaysShort(this, format);
});

addFormatToken('dddd', 0, 0, function (format) {
    return this.localeData().weekdays(this, format);
});

addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');

// ALIASES

addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');

// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);

// PARSING

addRegexToken('d',    match1to2);
addRegexToken('e',    match1to2);
addRegexToken('E',    match1to2);
addRegexToken('dd',   function (isStrict, locale) {
    return locale.weekdaysMinRegex(isStrict);
});
addRegexToken('ddd',   function (isStrict, locale) {
    return locale.weekdaysShortRegex(isStrict);
});
addRegexToken('dddd',   function (isStrict, locale) {
    return locale.weekdaysRegex(isStrict);
});

addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
    var weekday = config._locale.weekdaysParse(input, token, config._strict);
    // if we didn't get a weekday name, mark the date as invalid
    if (weekday != null) {
        week.d = weekday;
    } else {
        getParsingFlags(config).invalidWeekday = input;
    }
});

addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
    week[token] = toInt(input);
});

// HELPERS

function parseWeekday(input, locale) {
    if (typeof input !== 'string') {
        return input;
    }

    if (!isNaN(input)) {
        return parseInt(input, 10);
    }

    input = locale.weekdaysParse(input);
    if (typeof input === 'number') {
        return input;
    }

    return null;
}

function parseIsoWeekday(input, locale) {
    if (typeof input === 'string') {
        return locale.weekdaysParse(input) % 7 || 7;
    }
    return isNaN(input) ? null : input;
}

// LOCALES

var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
function localeWeekdays (m, format) {
    if (!m) {
        return isArray(this._weekdays) ? this._weekdays :
            this._weekdays['standalone'];
    }
    return isArray(this._weekdays) ? this._weekdays[m.day()] :
        this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
}

var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
function localeWeekdaysShort (m) {
    return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
}

var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
function localeWeekdaysMin (m) {
    return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
}

function handleStrictParse$1(weekdayName, format, strict) {
    var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
    if (!this._weekdaysParse) {
        this._weekdaysParse = [];
        this._shortWeekdaysParse = [];
        this._minWeekdaysParse = [];

        for (i = 0; i < 7; ++i) {
            mom = createUTC([2000, 1]).day(i);
            this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
            this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
            this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
        }
    }

    if (strict) {
        if (format === 'dddd') {
            ii = indexOf.call(this._weekdaysParse, llc);
            return ii !== -1 ? ii : null;
        } else if (format === 'ddd') {
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        } else {
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        }
    } else {
        if (format === 'dddd') {
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        } else if (format === 'ddd') {
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        } else {
            ii = indexOf.call(this._minWeekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
                return ii;
            }
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
        }
    }
}

function localeWeekdaysParse (weekdayName, format, strict) {
    var i, mom, regex;

    if (this._weekdaysParseExact) {
        return handleStrictParse$1.call(this, weekdayName, format, strict);
    }

    if (!this._weekdaysParse) {
        this._weekdaysParse = [];
        this._minWeekdaysParse = [];
        this._shortWeekdaysParse = [];
        this._fullWeekdaysParse = [];
    }

    for (i = 0; i < 7; i++) {
        // make the regex if we don't have it already

        mom = createUTC([2000, 1]).day(i);
        if (strict && !this._fullWeekdaysParse[i]) {
            this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
            this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
            this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
        }
        if (!this._weekdaysParse[i]) {
            regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
            this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
        }
        // test the regex
        if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
            return i;
        } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
            return i;
        } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
            return i;
        } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
            return i;
        }
    }
}

// MOMENTS

function getSetDayOfWeek (input) {
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }
    var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
    if (input != null) {
        input = parseWeekday(input, this.localeData());
        return this.add(input - day, 'd');
    } else {
        return day;
    }
}

function getSetLocaleDayOfWeek (input) {
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }
    var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
    return input == null ? weekday : this.add(input - weekday, 'd');
}

function getSetISODayOfWeek (input) {
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }

    // behaves the same as moment#day except
    // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
    // as a setter, sunday should belong to the previous week.

    if (input != null) {
        var weekday = parseIsoWeekday(input, this.localeData());
        return this.day(this.day() % 7 ? weekday : weekday - 7);
    } else {
        return this.day() || 7;
    }
}

var defaultWeekdaysRegex = matchWord;
function weekdaysRegex (isStrict) {
    if (this._weekdaysParseExact) {
        if (!hasOwnProp(this, '_weekdaysRegex')) {
            computeWeekdaysParse.call(this);
        }
        if (isStrict) {
            return this._weekdaysStrictRegex;
        } else {
            return this._weekdaysRegex;
        }
    } else {
        if (!hasOwnProp(this, '_weekdaysRegex')) {
            this._weekdaysRegex = defaultWeekdaysRegex;
        }
        return this._weekdaysStrictRegex && isStrict ?
            this._weekdaysStrictRegex : this._weekdaysRegex;
    }
}

var defaultWeekdaysShortRegex = matchWord;
function weekdaysShortRegex (isStrict) {
    if (this._weekdaysParseExact) {
        if (!hasOwnProp(this, '_weekdaysRegex')) {
            computeWeekdaysParse.call(this);
        }
        if (isStrict) {
            return this._weekdaysShortStrictRegex;
        } else {
            return this._weekdaysShortRegex;
        }
    } else {
        if (!hasOwnProp(this, '_weekdaysShortRegex')) {
            this._weekdaysShortRegex = defaultWeekdaysShortRegex;
        }
        return this._weekdaysShortStrictRegex && isStrict ?
            this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
    }
}

var defaultWeekdaysMinRegex = matchWord;
function weekdaysMinRegex (isStrict) {
    if (this._weekdaysParseExact) {
        if (!hasOwnProp(this, '_weekdaysRegex')) {
            computeWeekdaysParse.call(this);
        }
        if (isStrict) {
            return this._weekdaysMinStrictRegex;
        } else {
            return this._weekdaysMinRegex;
        }
    } else {
        if (!hasOwnProp(this, '_weekdaysMinRegex')) {
            this._weekdaysMinRegex = defaultWeekdaysMinRegex;
        }
        return this._weekdaysMinStrictRegex && isStrict ?
            this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
    }
}


function computeWeekdaysParse () {
    function cmpLenRev(a, b) {
        return b.length - a.length;
    }

    var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
        i, mom, minp, shortp, longp;
    for (i = 0; i < 7; i++) {
        // make the regex if we don't have it already
        mom = createUTC([2000, 1]).day(i);
        minp = this.weekdaysMin(mom, '');
        shortp = this.weekdaysShort(mom, '');
        longp = this.weekdays(mom, '');
        minPieces.push(minp);
        shortPieces.push(shortp);
        longPieces.push(longp);
        mixedPieces.push(minp);
        mixedPieces.push(shortp);
        mixedPieces.push(longp);
    }
    // Sorting makes sure if one weekday (or abbr) is a prefix of another it
    // will match the longer piece.
    minPieces.sort(cmpLenRev);
    shortPieces.sort(cmpLenRev);
    longPieces.sort(cmpLenRev);
    mixedPieces.sort(cmpLenRev);
    for (i = 0; i < 7; i++) {
        shortPieces[i] = regexEscape(shortPieces[i]);
        longPieces[i] = regexEscape(longPieces[i]);
        mixedPieces[i] = regexEscape(mixedPieces[i]);
    }

    this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
    this._weekdaysShortRegex = this._weekdaysRegex;
    this._weekdaysMinRegex = this._weekdaysRegex;

    this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
    this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
    this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
}

// FORMATTING

function hFormat() {
    return this.hours() % 12 || 12;
}

function kFormat() {
    return this.hours() || 24;
}

addFormatToken('H', ['HH', 2], 0, 'hour');
addFormatToken('h', ['hh', 2], 0, hFormat);
addFormatToken('k', ['kk', 2], 0, kFormat);

addFormatToken('hmm', 0, 0, function () {
    return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
});

addFormatToken('hmmss', 0, 0, function () {
    return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
        zeroFill(this.seconds(), 2);
});

addFormatToken('Hmm', 0, 0, function () {
    return '' + this.hours() + zeroFill(this.minutes(), 2);
});

addFormatToken('Hmmss', 0, 0, function () {
    return '' + this.hours() + zeroFill(this.minutes(), 2) +
        zeroFill(this.seconds(), 2);
});

function meridiem (token, lowercase) {
    addFormatToken(token, 0, 0, function () {
        return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
    });
}

meridiem('a', true);
meridiem('A', false);

// ALIASES

addUnitAlias('hour', 'h');

// PRIORITY
addUnitPriority('hour', 13);

// PARSING

function matchMeridiem (isStrict, locale) {
    return locale._meridiemParse;
}

addRegexToken('a',  matchMeridiem);
addRegexToken('A',  matchMeridiem);
addRegexToken('H',  match1to2);
addRegexToken('h',  match1to2);
addRegexToken('k',  match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('kk', match1to2, match2);

addRegexToken('hmm', match3to4);
addRegexToken('hmmss', match5to6);
addRegexToken('Hmm', match3to4);
addRegexToken('Hmmss', match5to6);

addParseToken(['H', 'HH'], HOUR);
addParseToken(['k', 'kk'], function (input, array, config) {
    var kInput = toInt(input);
    array[HOUR] = kInput === 24 ? 0 : kInput;
});
addParseToken(['a', 'A'], function (input, array, config) {
    config._isPm = config._locale.isPM(input);
    config._meridiem = input;
});
addParseToken(['h', 'hh'], function (input, array, config) {
    array[HOUR] = toInt(input);
    getParsingFlags(config).bigHour = true;
});
addParseToken('hmm', function (input, array, config) {
    var pos = input.length - 2;
    array[HOUR] = toInt(input.substr(0, pos));
    array[MINUTE] = toInt(input.substr(pos));
    getParsingFlags(config).bigHour = true;
});
addParseToken('hmmss', function (input, array, config) {
    var pos1 = input.length - 4;
    var pos2 = input.length - 2;
    array[HOUR] = toInt(input.substr(0, pos1));
    array[MINUTE] = toInt(input.substr(pos1, 2));
    array[SECOND] = toInt(input.substr(pos2));
    getParsingFlags(config).bigHour = true;
});
addParseToken('Hmm', function (input, array, config) {
    var pos = input.length - 2;
    array[HOUR] = toInt(input.substr(0, pos));
    array[MINUTE] = toInt(input.substr(pos));
});
addParseToken('Hmmss', function (input, array, config) {
    var pos1 = input.length - 4;
    var pos2 = input.length - 2;
    array[HOUR] = toInt(input.substr(0, pos1));
    array[MINUTE] = toInt(input.substr(pos1, 2));
    array[SECOND] = toInt(input.substr(pos2));
});

// LOCALES

function localeIsPM (input) {
    // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
    // Using charAt should be more compatible.
    return ((input + '').toLowerCase().charAt(0) === 'p');
}

var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
function localeMeridiem (hours, minutes, isLower) {
    if (hours > 11) {
        return isLower ? 'pm' : 'PM';
    } else {
        return isLower ? 'am' : 'AM';
    }
}


// MOMENTS

// Setting the hour should keep the time, because the user explicitly
// specified which hour he wants. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
var getSetHour = makeGetSet('Hours', true);

// months
// week
// weekdays
// meridiem
var baseConfig = {
    calendar: defaultCalendar,
    longDateFormat: defaultLongDateFormat,
    invalidDate: defaultInvalidDate,
    ordinal: defaultOrdinal,
    dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
    relativeTime: defaultRelativeTime,

    months: defaultLocaleMonths,
    monthsShort: defaultLocaleMonthsShort,

    week: defaultLocaleWeek,

    weekdays: defaultLocaleWeekdays,
    weekdaysMin: defaultLocaleWeekdaysMin,
    weekdaysShort: defaultLocaleWeekdaysShort,

    meridiemParse: defaultLocaleMeridiemParse
};

// internal storage for locale config files
var locales = {};
var localeFamilies = {};
var globalLocale;

function normalizeLocale(key) {
    return key ? key.toLowerCase().replace('_', '-') : key;
}

// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
    var i = 0, j, next, locale, split;

    while (i < names.length) {
        split = normalizeLocale(names[i]).split('-');
        j = split.length;
        next = normalizeLocale(names[i + 1]);
        next = next ? next.split('-') : null;
        while (j > 0) {
            locale = loadLocale(split.slice(0, j).join('-'));
            if (locale) {
                return locale;
            }
            if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                //the next array item is better than a shallower substring of this one
                break;
            }
            j--;
        }
        i++;
    }
    return null;
}

function loadLocale(name) {
    var oldLocale = null;
    // TODO: Find a better way to register and load all the locales in Node
    if (!locales[name] && (typeof module !== 'undefined') &&
            module && module.exports) {
        try {
            oldLocale = globalLocale._abbr;
            var aliasedRequire = require;
            __webpack_require__(342)("./" + name);
            getSetGlobalLocale(oldLocale);
        } catch (e) {}
    }
    return locales[name];
}

// This function will load locale and then set the global locale.  If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale (key, values) {
    var data;
    if (key) {
        if (isUndefined(values)) {
            data = getLocale(key);
        }
        else {
            data = defineLocale(key, values);
        }

        if (data) {
            // moment.duration._locale = moment._locale = data;
            globalLocale = data;
        }
    }

    return globalLocale._abbr;
}

function defineLocale (name, config) {
    if (config !== null) {
        var parentConfig = baseConfig;
        config.abbr = name;
        if (locales[name] != null) {
            deprecateSimple('defineLocaleOverride',
                    'use moment.updateLocale(localeName, config) to change ' +
                    'an existing locale. moment.defineLocale(localeName, ' +
                    'config) should only be used for creating a new locale ' +
                    'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
            parentConfig = locales[name]._config;
        } else if (config.parentLocale != null) {
            if (locales[config.parentLocale] != null) {
                parentConfig = locales[config.parentLocale]._config;
            } else {
                if (!localeFamilies[config.parentLocale]) {
                    localeFamilies[config.parentLocale] = [];
                }
                localeFamilies[config.parentLocale].push({
                    name: name,
                    config: config
                });
                return null;
            }
        }
        locales[name] = new Locale(mergeConfigs(parentConfig, config));

        if (localeFamilies[name]) {
            localeFamilies[name].forEach(function (x) {
                defineLocale(x.name, x.config);
            });
        }

        // backwards compat for now: also set the locale
        // make sure we set the locale AFTER all child locales have been
        // created, so we won't end up with the child locale set.
        getSetGlobalLocale(name);


        return locales[name];
    } else {
        // useful for testing
        delete locales[name];
        return null;
    }
}

function updateLocale(name, config) {
    if (config != null) {
        var locale, tmpLocale, parentConfig = baseConfig;
        // MERGE
        tmpLocale = loadLocale(name);
        if (tmpLocale != null) {
            parentConfig = tmpLocale._config;
        }
        config = mergeConfigs(parentConfig, config);
        locale = new Locale(config);
        locale.parentLocale = locales[name];
        locales[name] = locale;

        // backwards compat for now: also set the locale
        getSetGlobalLocale(name);
    } else {
        // pass null for config to unupdate, useful for tests
        if (locales[name] != null) {
            if (locales[name].parentLocale != null) {
                locales[name] = locales[name].parentLocale;
            } else if (locales[name] != null) {
                delete locales[name];
            }
        }
    }
    return locales[name];
}

// returns locale data
function getLocale (key) {
    var locale;

    if (key && key._locale && key._locale._abbr) {
        key = key._locale._abbr;
    }

    if (!key) {
        return globalLocale;
    }

    if (!isArray(key)) {
        //short-circuit everything else
        locale = loadLocale(key);
        if (locale) {
            return locale;
        }
        key = [key];
    }

    return chooseLocale(key);
}

function listLocales() {
    return keys(locales);
}

function checkOverflow (m) {
    var overflow;
    var a = m._a;

    if (a && getParsingFlags(m).overflow === -2) {
        overflow =
            a[MONTH]       < 0 || a[MONTH]       > 11  ? MONTH :
            a[DATE]        < 1 || a[DATE]        > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
            a[HOUR]        < 0 || a[HOUR]        > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
            a[MINUTE]      < 0 || a[MINUTE]      > 59  ? MINUTE :
            a[SECOND]      < 0 || a[SECOND]      > 59  ? SECOND :
            a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
            -1;

        if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
            overflow = DATE;
        }
        if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
            overflow = WEEK;
        }
        if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
            overflow = WEEKDAY;
        }

        getParsingFlags(m).overflow = overflow;
    }

    return m;
}

// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
    if (a != null) {
        return a;
    }
    if (b != null) {
        return b;
    }
    return c;
}

function currentDateArray(config) {
    // hooks is actually the exported moment object
    var nowValue = new Date(hooks.now());
    if (config._useUTC) {
        return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
    }
    return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
}

// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray (config) {
    var i, date, input = [], currentDate, expectedWeekday, yearToUse;

    if (config._d) {
        return;
    }

    currentDate = currentDateArray(config);

    //compute day of the year from weeks and weekdays
    if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
        dayOfYearFromWeekInfo(config);
    }

    //if the day of the year is set, figure out what it is
    if (config._dayOfYear != null) {
        yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);

        if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
            getParsingFlags(config)._overflowDayOfYear = true;
        }

        date = createUTCDate(yearToUse, 0, config._dayOfYear);
        config._a[MONTH] = date.getUTCMonth();
        config._a[DATE] = date.getUTCDate();
    }

    // Default to current date.
    // * if no year, month, day of month are given, default to today
    // * if day of month is given, default month and year
    // * if month is given, default only year
    // * if year is given, don't default anything
    for (i = 0; i < 3 && config._a[i] == null; ++i) {
        config._a[i] = input[i] = currentDate[i];
    }

    // Zero out whatever was not defaulted, including time
    for (; i < 7; i++) {
        config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
    }

    // Check for 24:00:00.000
    if (config._a[HOUR] === 24 &&
            config._a[MINUTE] === 0 &&
            config._a[SECOND] === 0 &&
            config._a[MILLISECOND] === 0) {
        config._nextDay = true;
        config._a[HOUR] = 0;
    }

    config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
    expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();

    // Apply timezone offset from input. The actual utcOffset can be changed
    // with parseZone.
    if (config._tzm != null) {
        config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
    }

    if (config._nextDay) {
        config._a[HOUR] = 24;
    }

    // check for mismatching day of week
    if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
        getParsingFlags(config).weekdayMismatch = true;
    }
}

function dayOfYearFromWeekInfo(config) {
    var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;

    w = config._w;
    if (w.GG != null || w.W != null || w.E != null) {
        dow = 1;
        doy = 4;

        // TODO: We need to take the current isoWeekYear, but that depends on
        // how we interpret now (local, utc, fixed offset). So create
        // a now version of current config (take local/utc/offset flags, and
        // create now).
        weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
        week = defaults(w.W, 1);
        weekday = defaults(w.E, 1);
        if (weekday < 1 || weekday > 7) {
            weekdayOverflow = true;
        }
    } else {
        dow = config._locale._week.dow;
        doy = config._locale._week.doy;

        var curWeek = weekOfYear(createLocal(), dow, doy);

        weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);

        // Default to current week.
        week = defaults(w.w, curWeek.week);

        if (w.d != null) {
            // weekday -- low day numbers are considered next week
            weekday = w.d;
            if (weekday < 0 || weekday > 6) {
                weekdayOverflow = true;
            }
        } else if (w.e != null) {
            // local weekday -- counting starts from begining of week
            weekday = w.e + dow;
            if (w.e < 0 || w.e > 6) {
                weekdayOverflow = true;
            }
        } else {
            // default to begining of week
            weekday = dow;
        }
    }
    if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
        getParsingFlags(config)._overflowWeeks = true;
    } else if (weekdayOverflow != null) {
        getParsingFlags(config)._overflowWeekday = true;
    } else {
        temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
        config._a[YEAR] = temp.year;
        config._dayOfYear = temp.dayOfYear;
    }
}

// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;

var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;

var isoDates = [
    ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
    ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
    ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
    ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
    ['YYYY-DDD', /\d{4}-\d{3}/],
    ['YYYY-MM', /\d{4}-\d\d/, false],
    ['YYYYYYMMDD', /[+-]\d{10}/],
    ['YYYYMMDD', /\d{8}/],
    // YYYYMM is NOT allowed by the standard
    ['GGGG[W]WWE', /\d{4}W\d{3}/],
    ['GGGG[W]WW', /\d{4}W\d{2}/, false],
    ['YYYYDDD', /\d{7}/]
];

// iso time formats and regexes
var isoTimes = [
    ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
    ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
    ['HH:mm:ss', /\d\d:\d\d:\d\d/],
    ['HH:mm', /\d\d:\d\d/],
    ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
    ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
    ['HHmmss', /\d\d\d\d\d\d/],
    ['HHmm', /\d\d\d\d/],
    ['HH', /\d\d/]
];

var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;

// date from iso format
function configFromISO(config) {
    var i, l,
        string = config._i,
        match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
        allowTime, dateFormat, timeFormat, tzFormat;

    if (match) {
        getParsingFlags(config).iso = true;

        for (i = 0, l = isoDates.length; i < l; i++) {
            if (isoDates[i][1].exec(match[1])) {
                dateFormat = isoDates[i][0];
                allowTime = isoDates[i][2] !== false;
                break;
            }
        }
        if (dateFormat == null) {
            config._isValid = false;
            return;
        }
        if (match[3]) {
            for (i = 0, l = isoTimes.length; i < l; i++) {
                if (isoTimes[i][1].exec(match[3])) {
                    // match[2] should be 'T' or space
                    timeFormat = (match[2] || ' ') + isoTimes[i][0];
                    break;
                }
            }
            if (timeFormat == null) {
                config._isValid = false;
                return;
            }
        }
        if (!allowTime && timeFormat != null) {
            config._isValid = false;
            return;
        }
        if (match[4]) {
            if (tzRegex.exec(match[4])) {
                tzFormat = 'Z';
            } else {
                config._isValid = false;
                return;
            }
        }
        config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
        configFromStringAndFormat(config);
    } else {
        config._isValid = false;
    }
}

// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;

function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
    var result = [
        untruncateYear(yearStr),
        defaultLocaleMonthsShort.indexOf(monthStr),
        parseInt(dayStr, 10),
        parseInt(hourStr, 10),
        parseInt(minuteStr, 10)
    ];

    if (secondStr) {
        result.push(parseInt(secondStr, 10));
    }

    return result;
}

function untruncateYear(yearStr) {
    var year = parseInt(yearStr, 10);
    if (year <= 49) {
        return 2000 + year;
    } else if (year <= 999) {
        return 1900 + year;
    }
    return year;
}

function preprocessRFC2822(s) {
    // Remove comments and folding whitespace and replace multiple-spaces with a single space
    return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').trim();
}

function checkWeekday(weekdayStr, parsedInput, config) {
    if (weekdayStr) {
        // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
        var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
            weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
        if (weekdayProvided !== weekdayActual) {
            getParsingFlags(config).weekdayMismatch = true;
            config._isValid = false;
            return false;
        }
    }
    return true;
}

var obsOffsets = {
    UT: 0,
    GMT: 0,
    EDT: -4 * 60,
    EST: -5 * 60,
    CDT: -5 * 60,
    CST: -6 * 60,
    MDT: -6 * 60,
    MST: -7 * 60,
    PDT: -7 * 60,
    PST: -8 * 60
};

function calculateOffset(obsOffset, militaryOffset, numOffset) {
    if (obsOffset) {
        return obsOffsets[obsOffset];
    } else if (militaryOffset) {
        // the only allowed military tz is Z
        return 0;
    } else {
        var hm = parseInt(numOffset, 10);
        var m = hm % 100, h = (hm - m) / 100;
        return h * 60 + m;
    }
}

// date and time from ref 2822 format
function configFromRFC2822(config) {
    var match = rfc2822.exec(preprocessRFC2822(config._i));
    if (match) {
        var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
        if (!checkWeekday(match[1], parsedArray, config)) {
            return;
        }

        config._a = parsedArray;
        config._tzm = calculateOffset(match[8], match[9], match[10]);

        config._d = createUTCDate.apply(null, config._a);
        config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);

        getParsingFlags(config).rfc2822 = true;
    } else {
        config._isValid = false;
    }
}

// date from iso format or fallback
function configFromString(config) {
    var matched = aspNetJsonRegex.exec(config._i);

    if (matched !== null) {
        config._d = new Date(+matched[1]);
        return;
    }

    configFromISO(config);
    if (config._isValid === false) {
        delete config._isValid;
    } else {
        return;
    }

    configFromRFC2822(config);
    if (config._isValid === false) {
        delete config._isValid;
    } else {
        return;
    }

    // Final attempt, use Input Fallback
    hooks.createFromInputFallback(config);
}

hooks.createFromInputFallback = deprecate(
    'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
    'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
    'discouraged and will be removed in an upcoming major release. Please refer to ' +
    'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
    function (config) {
        config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
    }
);

// constant that refers to the ISO standard
hooks.ISO_8601 = function () {};

// constant that refers to the RFC 2822 form
hooks.RFC_2822 = function () {};

// date from string and format string
function configFromStringAndFormat(config) {
    // TODO: Move this to another part of the creation flow to prevent circular deps
    if (config._f === hooks.ISO_8601) {
        configFromISO(config);
        return;
    }
    if (config._f === hooks.RFC_2822) {
        configFromRFC2822(config);
        return;
    }
    config._a = [];
    getParsingFlags(config).empty = true;

    // This array is used to make a Date, either with `new Date` or `Date.UTC`
    var string = '' + config._i,
        i, parsedInput, tokens, token, skipped,
        stringLength = string.length,
        totalParsedInputLength = 0;

    tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

    for (i = 0; i < tokens.length; i++) {
        token = tokens[i];
        parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
        // console.log('token', token, 'parsedInput', parsedInput,
        //         'regex', getParseRegexForToken(token, config));
        if (parsedInput) {
            skipped = string.substr(0, string.indexOf(parsedInput));
            if (skipped.length > 0) {
                getParsingFlags(config).unusedInput.push(skipped);
            }
            string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
            totalParsedInputLength += parsedInput.length;
        }
        // don't parse if it's not a known token
        if (formatTokenFunctions[token]) {
            if (parsedInput) {
                getParsingFlags(config).empty = false;
            }
            else {
                getParsingFlags(config).unusedTokens.push(token);
            }
            addTimeToArrayFromToken(token, parsedInput, config);
        }
        else if (config._strict && !parsedInput) {
            getParsingFlags(config).unusedTokens.push(token);
        }
    }

    // add remaining unparsed input length to the string
    getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
    if (string.length > 0) {
        getParsingFlags(config).unusedInput.push(string);
    }

    // clear _12h flag if hour is <= 12
    if (config._a[HOUR] <= 12 &&
        getParsingFlags(config).bigHour === true &&
        config._a[HOUR] > 0) {
        getParsingFlags(config).bigHour = undefined;
    }

    getParsingFlags(config).parsedDateParts = config._a.slice(0);
    getParsingFlags(config).meridiem = config._meridiem;
    // handle meridiem
    config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);

    configFromArray(config);
    checkOverflow(config);
}


function meridiemFixWrap (locale, hour, meridiem) {
    var isPm;

    if (meridiem == null) {
        // nothing to do
        return hour;
    }
    if (locale.meridiemHour != null) {
        return locale.meridiemHour(hour, meridiem);
    } else if (locale.isPM != null) {
        // Fallback
        isPm = locale.isPM(meridiem);
        if (isPm && hour < 12) {
            hour += 12;
        }
        if (!isPm && hour === 12) {
            hour = 0;
        }
        return hour;
    } else {
        // this is not supposed to happen
        return hour;
    }
}

// date from string and array of format strings
function configFromStringAndArray(config) {
    var tempConfig,
        bestMoment,

        scoreToBeat,
        i,
        currentScore;

    if (config._f.length === 0) {
        getParsingFlags(config).invalidFormat = true;
        config._d = new Date(NaN);
        return;
    }

    for (i = 0; i < config._f.length; i++) {
        currentScore = 0;
        tempConfig = copyConfig({}, config);
        if (config._useUTC != null) {
            tempConfig._useUTC = config._useUTC;
        }
        tempConfig._f = config._f[i];
        configFromStringAndFormat(tempConfig);

        if (!isValid(tempConfig)) {
            continue;
        }

        // if there is any input that was not parsed add a penalty for that format
        currentScore += getParsingFlags(tempConfig).charsLeftOver;

        //or tokens
        currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;

        getParsingFlags(tempConfig).score = currentScore;

        if (scoreToBeat == null || currentScore < scoreToBeat) {
            scoreToBeat = currentScore;
            bestMoment = tempConfig;
        }
    }

    extend(config, bestMoment || tempConfig);
}

function configFromObject(config) {
    if (config._d) {
        return;
    }

    var i = normalizeObjectUnits(config._i);
    config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
        return obj && parseInt(obj, 10);
    });

    configFromArray(config);
}

function createFromConfig (config) {
    var res = new Moment(checkOverflow(prepareConfig(config)));
    if (res._nextDay) {
        // Adding is smart enough around DST
        res.add(1, 'd');
        res._nextDay = undefined;
    }

    return res;
}

function prepareConfig (config) {
    var input = config._i,
        format = config._f;

    config._locale = config._locale || getLocale(config._l);

    if (input === null || (format === undefined && input === '')) {
        return createInvalid({nullInput: true});
    }

    if (typeof input === 'string') {
        config._i = input = config._locale.preparse(input);
    }

    if (isMoment(input)) {
        return new Moment(checkOverflow(input));
    } else if (isDate(input)) {
        config._d = input;
    } else if (isArray(format)) {
        configFromStringAndArray(config);
    } else if (format) {
        configFromStringAndFormat(config);
    }  else {
        configFromInput(config);
    }

    if (!isValid(config)) {
        config._d = null;
    }

    return config;
}

function configFromInput(config) {
    var input = config._i;
    if (isUndefined(input)) {
        config._d = new Date(hooks.now());
    } else if (isDate(input)) {
        config._d = new Date(input.valueOf());
    } else if (typeof input === 'string') {
        configFromString(config);
    } else if (isArray(input)) {
        config._a = map(input.slice(0), function (obj) {
            return parseInt(obj, 10);
        });
        configFromArray(config);
    } else if (isObject(input)) {
        configFromObject(config);
    } else if (isNumber(input)) {
        // from milliseconds
        config._d = new Date(input);
    } else {
        hooks.createFromInputFallback(config);
    }
}

function createLocalOrUTC (input, format, locale, strict, isUTC) {
    var c = {};

    if (locale === true || locale === false) {
        strict = locale;
        locale = undefined;
    }

    if ((isObject(input) && isObjectEmpty(input)) ||
            (isArray(input) && input.length === 0)) {
        input = undefined;
    }
    // object construction must be done this way.
    // https://github.com/moment/moment/issues/1423
    c._isAMomentObject = true;
    c._useUTC = c._isUTC = isUTC;
    c._l = locale;
    c._i = input;
    c._f = format;
    c._strict = strict;

    return createFromConfig(c);
}

function createLocal (input, format, locale, strict) {
    return createLocalOrUTC(input, format, locale, strict, false);
}

var prototypeMin = deprecate(
    'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
    function () {
        var other = createLocal.apply(null, arguments);
        if (this.isValid() && other.isValid()) {
            return other < this ? this : other;
        } else {
            return createInvalid();
        }
    }
);

var prototypeMax = deprecate(
    'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
    function () {
        var other = createLocal.apply(null, arguments);
        if (this.isValid() && other.isValid()) {
            return other > this ? this : other;
        } else {
            return createInvalid();
        }
    }
);

// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
    var res, i;
    if (moments.length === 1 && isArray(moments[0])) {
        moments = moments[0];
    }
    if (!moments.length) {
        return createLocal();
    }
    res = moments[0];
    for (i = 1; i < moments.length; ++i) {
        if (!moments[i].isValid() || moments[i][fn](res)) {
            res = moments[i];
        }
    }
    return res;
}

// TODO: Use [].sort instead?
function min () {
    var args = [].slice.call(arguments, 0);

    return pickBy('isBefore', args);
}

function max () {
    var args = [].slice.call(arguments, 0);

    return pickBy('isAfter', args);
}

var now = function () {
    return Date.now ? Date.now() : +(new Date());
};

var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];

function isDurationValid(m) {
    for (var key in m) {
        if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
            return false;
        }
    }

    var unitHasDecimal = false;
    for (var i = 0; i < ordering.length; ++i) {
        if (m[ordering[i]]) {
            if (unitHasDecimal) {
                return false; // only allow non-integers for smallest unit
            }
            if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
                unitHasDecimal = true;
            }
        }
    }

    return true;
}

function isValid$1() {
    return this._isValid;
}

function createInvalid$1() {
    return createDuration(NaN);
}

function Duration (duration) {
    var normalizedInput = normalizeObjectUnits(duration),
        years = normalizedInput.year || 0,
        quarters = normalizedInput.quarter || 0,
        months = normalizedInput.month || 0,
        weeks = normalizedInput.week || 0,
        days = normalizedInput.day || 0,
        hours = normalizedInput.hour || 0,
        minutes = normalizedInput.minute || 0,
        seconds = normalizedInput.second || 0,
        milliseconds = normalizedInput.millisecond || 0;

    this._isValid = isDurationValid(normalizedInput);

    // representation for dateAddRemove
    this._milliseconds = +milliseconds +
        seconds * 1e3 + // 1000
        minutes * 6e4 + // 1000 * 60
        hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
    // Because of dateAddRemove treats 24 hours as different from a
    // day when working around DST, we need to store them separately
    this._days = +days +
        weeks * 7;
    // It is impossible to translate months into days without knowing
    // which months you are are talking about, so we have to store
    // it separately.
    this._months = +months +
        quarters * 3 +
        years * 12;

    this._data = {};

    this._locale = getLocale();

    this._bubble();
}

function isDuration (obj) {
    return obj instanceof Duration;
}

function absRound (number) {
    if (number < 0) {
        return Math.round(-1 * number) * -1;
    } else {
        return Math.round(number);
    }
}

// FORMATTING

function offset (token, separator) {
    addFormatToken(token, 0, 0, function () {
        var offset = this.utcOffset();
        var sign = '+';
        if (offset < 0) {
            offset = -offset;
            sign = '-';
        }
        return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
    });
}

offset('Z', ':');
offset('ZZ', '');

// PARSING

addRegexToken('Z',  matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
    config._useUTC = true;
    config._tzm = offsetFromString(matchShortOffset, input);
});

// HELPERS

// timezone chunker
// '+10:00' > ['10',  '00']
// '-1530'  > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;

function offsetFromString(matcher, string) {
    var matches = (string || '').match(matcher);

    if (matches === null) {
        return null;
    }

    var chunk   = matches[matches.length - 1] || [];
    var parts   = (chunk + '').match(chunkOffset) || ['-', 0, 0];
    var minutes = +(parts[1] * 60) + toInt(parts[2]);

    return minutes === 0 ?
      0 :
      parts[0] === '+' ? minutes : -minutes;
}

// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
    var res, diff;
    if (model._isUTC) {
        res = model.clone();
        diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
        // Use low-level api, because this fn is low-level api.
        res._d.setTime(res._d.valueOf() + diff);
        hooks.updateOffset(res, false);
        return res;
    } else {
        return createLocal(input).local();
    }
}

function getDateOffset (m) {
    // On Firefox.24 Date#getTimezoneOffset returns a floating point.
    // https://github.com/moment/moment/pull/1871
    return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
}

// HOOKS

// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};

// MOMENTS

// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function getSetOffset (input, keepLocalTime, keepMinutes) {
    var offset = this._offset || 0,
        localAdjust;
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }
    if (input != null) {
        if (typeof input === 'string') {
            input = offsetFromString(matchShortOffset, input);
            if (input === null) {
                return this;
            }
        } else if (Math.abs(input) < 16 && !keepMinutes) {
            input = input * 60;
        }
        if (!this._isUTC && keepLocalTime) {
            localAdjust = getDateOffset(this);
        }
        this._offset = input;
        this._isUTC = true;
        if (localAdjust != null) {
            this.add(localAdjust, 'm');
        }
        if (offset !== input) {
            if (!keepLocalTime || this._changeInProgress) {
                addSubtract(this, createDuration(input - offset, 'm'), 1, false);
            } else if (!this._changeInProgress) {
                this._changeInProgress = true;
                hooks.updateOffset(this, true);
                this._changeInProgress = null;
            }
        }
        return this;
    } else {
        return this._isUTC ? offset : getDateOffset(this);
    }
}

function getSetZone (input, keepLocalTime) {
    if (input != null) {
        if (typeof input !== 'string') {
            input = -input;
        }

        this.utcOffset(input, keepLocalTime);

        return this;
    } else {
        return -this.utcOffset();
    }
}

function setOffsetToUTC (keepLocalTime) {
    return this.utcOffset(0, keepLocalTime);
}

function setOffsetToLocal (keepLocalTime) {
    if (this._isUTC) {
        this.utcOffset(0, keepLocalTime);
        this._isUTC = false;

        if (keepLocalTime) {
            this.subtract(getDateOffset(this), 'm');
        }
    }
    return this;
}

function setOffsetToParsedOffset () {
    if (this._tzm != null) {
        this.utcOffset(this._tzm, false, true);
    } else if (typeof this._i === 'string') {
        var tZone = offsetFromString(matchOffset, this._i);
        if (tZone != null) {
            this.utcOffset(tZone);
        }
        else {
            this.utcOffset(0, true);
        }
    }
    return this;
}

function hasAlignedHourOffset (input) {
    if (!this.isValid()) {
        return false;
    }
    input = input ? createLocal(input).utcOffset() : 0;

    return (this.utcOffset() - input) % 60 === 0;
}

function isDaylightSavingTime () {
    return (
        this.utcOffset() > this.clone().month(0).utcOffset() ||
        this.utcOffset() > this.clone().month(5).utcOffset()
    );
}

function isDaylightSavingTimeShifted () {
    if (!isUndefined(this._isDSTShifted)) {
        return this._isDSTShifted;
    }

    var c = {};

    copyConfig(c, this);
    c = prepareConfig(c);

    if (c._a) {
        var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
        this._isDSTShifted = this.isValid() &&
            compareArrays(c._a, other.toArray()) > 0;
    } else {
        this._isDSTShifted = false;
    }

    return this._isDSTShifted;
}

function isLocal () {
    return this.isValid() ? !this._isUTC : false;
}

function isUtcOffset () {
    return this.isValid() ? this._isUTC : false;
}

function isUtc () {
    return this.isValid() ? this._isUTC && this._offset === 0 : false;
}

// ASP.NET json date format regex
var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;

// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;

function createDuration (input, key) {
    var duration = input,
        // matching against regexp is expensive, do it on demand
        match = null,
        sign,
        ret,
        diffRes;

    if (isDuration(input)) {
        duration = {
            ms : input._milliseconds,
            d  : input._days,
            M  : input._months
        };
    } else if (isNumber(input)) {
        duration = {};
        if (key) {
            duration[key] = input;
        } else {
            duration.milliseconds = input;
        }
    } else if (!!(match = aspNetRegex.exec(input))) {
        sign = (match[1] === '-') ? -1 : 1;
        duration = {
            y  : 0,
            d  : toInt(match[DATE])                         * sign,
            h  : toInt(match[HOUR])                         * sign,
            m  : toInt(match[MINUTE])                       * sign,
            s  : toInt(match[SECOND])                       * sign,
            ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
        };
    } else if (!!(match = isoRegex.exec(input))) {
        sign = (match[1] === '-') ? -1 : (match[1] === '+') ? 1 : 1;
        duration = {
            y : parseIso(match[2], sign),
            M : parseIso(match[3], sign),
            w : parseIso(match[4], sign),
            d : parseIso(match[5], sign),
            h : parseIso(match[6], sign),
            m : parseIso(match[7], sign),
            s : parseIso(match[8], sign)
        };
    } else if (duration == null) {// checks for null or undefined
        duration = {};
    } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
        diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));

        duration = {};
        duration.ms = diffRes.milliseconds;
        duration.M = diffRes.months;
    }

    ret = new Duration(duration);

    if (isDuration(input) && hasOwnProp(input, '_locale')) {
        ret._locale = input._locale;
    }

    return ret;
}

createDuration.fn = Duration.prototype;
createDuration.invalid = createInvalid$1;

function parseIso (inp, sign) {
    // We'd normally use ~~inp for this, but unfortunately it also
    // converts floats to ints.
    // inp may be undefined, so careful calling replace on it.
    var res = inp && parseFloat(inp.replace(',', '.'));
    // apply sign while we're at it
    return (isNaN(res) ? 0 : res) * sign;
}

function positiveMomentsDifference(base, other) {
    var res = {milliseconds: 0, months: 0};

    res.months = other.month() - base.month() +
        (other.year() - base.year()) * 12;
    if (base.clone().add(res.months, 'M').isAfter(other)) {
        --res.months;
    }

    res.milliseconds = +other - +(base.clone().add(res.months, 'M'));

    return res;
}

function momentsDifference(base, other) {
    var res;
    if (!(base.isValid() && other.isValid())) {
        return {milliseconds: 0, months: 0};
    }

    other = cloneWithOffset(other, base);
    if (base.isBefore(other)) {
        res = positiveMomentsDifference(base, other);
    } else {
        res = positiveMomentsDifference(other, base);
        res.milliseconds = -res.milliseconds;
        res.months = -res.months;
    }

    return res;
}

// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
    return function (val, period) {
        var dur, tmp;
        //invert the arguments, but complain about it
        if (period !== null && !isNaN(+period)) {
            deprecateSimple(name, 'moment().' + name  + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
            'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
            tmp = val; val = period; period = tmp;
        }

        val = typeof val === 'string' ? +val : val;
        dur = createDuration(val, period);
        addSubtract(this, dur, direction);
        return this;
    };
}

function addSubtract (mom, duration, isAdding, updateOffset) {
    var milliseconds = duration._milliseconds,
        days = absRound(duration._days),
        months = absRound(duration._months);

    if (!mom.isValid()) {
        // No op
        return;
    }

    updateOffset = updateOffset == null ? true : updateOffset;

    if (months) {
        setMonth(mom, get(mom, 'Month') + months * isAdding);
    }
    if (days) {
        set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
    }
    if (milliseconds) {
        mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
    }
    if (updateOffset) {
        hooks.updateOffset(mom, days || months);
    }
}

var add      = createAdder(1, 'add');
var subtract = createAdder(-1, 'subtract');

function getCalendarFormat(myMoment, now) {
    var diff = myMoment.diff(now, 'days', true);
    return diff < -6 ? 'sameElse' :
            diff < -1 ? 'lastWeek' :
            diff < 0 ? 'lastDay' :
            diff < 1 ? 'sameDay' :
            diff < 2 ? 'nextDay' :
            diff < 7 ? 'nextWeek' : 'sameElse';
}

function calendar$1 (time, formats) {
    // We want to compare the start of today, vs this.
    // Getting start-of-today depends on whether we're local/utc/offset or not.
    var now = time || createLocal(),
        sod = cloneWithOffset(now, this).startOf('day'),
        format = hooks.calendarFormat(this, sod) || 'sameElse';

    var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);

    return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
}

function clone () {
    return new Moment(this);
}

function isAfter (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input);
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
    if (units === 'millisecond') {
        return this.valueOf() > localInput.valueOf();
    } else {
        return localInput.valueOf() < this.clone().startOf(units).valueOf();
    }
}

function isBefore (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input);
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
    if (units === 'millisecond') {
        return this.valueOf() < localInput.valueOf();
    } else {
        return this.clone().endOf(units).valueOf() < localInput.valueOf();
    }
}

function isBetween (from, to, units, inclusivity) {
    inclusivity = inclusivity || '()';
    return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
        (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
}

function isSame (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input),
        inputMs;
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(units || 'millisecond');
    if (units === 'millisecond') {
        return this.valueOf() === localInput.valueOf();
    } else {
        inputMs = localInput.valueOf();
        return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
    }
}

function isSameOrAfter (input, units) {
    return this.isSame(input, units) || this.isAfter(input,units);
}

function isSameOrBefore (input, units) {
    return this.isSame(input, units) || this.isBefore(input,units);
}

function diff (input, units, asFloat) {
    var that,
        zoneDelta,
        delta, output;

    if (!this.isValid()) {
        return NaN;
    }

    that = cloneWithOffset(input, this);

    if (!that.isValid()) {
        return NaN;
    }

    zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;

    units = normalizeUnits(units);

    switch (units) {
        case 'year': output = monthDiff(this, that) / 12; break;
        case 'month': output = monthDiff(this, that); break;
        case 'quarter': output = monthDiff(this, that) / 3; break;
        case 'second': output = (this - that) / 1e3; break; // 1000
        case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
        case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
        case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
        case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
        default: output = this - that;
    }

    return asFloat ? output : absFloor(output);
}

function monthDiff (a, b) {
    // difference in months
    var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
        // b is in (anchor - 1 month, anchor + 1 month)
        anchor = a.clone().add(wholeMonthDiff, 'months'),
        anchor2, adjust;

    if (b - anchor < 0) {
        anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
        // linear across the month
        adjust = (b - anchor) / (anchor - anchor2);
    } else {
        anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
        // linear across the month
        adjust = (b - anchor) / (anchor2 - anchor);
    }

    //check for negative zero, return zero if negative zero
    return -(wholeMonthDiff + adjust) || 0;
}

hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';

function toString () {
    return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}

function toISOString(keepOffset) {
    if (!this.isValid()) {
        return null;
    }
    var utc = keepOffset !== true;
    var m = utc ? this.clone().utc() : this;
    if (m.year() < 0 || m.year() > 9999) {
        return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
    }
    if (isFunction(Date.prototype.toISOString)) {
        // native implementation is ~50x faster, use it when we can
        if (utc) {
            return this.toDate().toISOString();
        } else {
            return new Date(this._d.valueOf()).toISOString().replace('Z', formatMoment(m, 'Z'));
        }
    }
    return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
}

/**
 * Return a human readable representation of a moment that can
 * also be evaluated to get a new moment which is the same
 *
 * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
 */
function inspect () {
    if (!this.isValid()) {
        return 'moment.invalid(/* ' + this._i + ' */)';
    }
    var func = 'moment';
    var zone = '';
    if (!this.isLocal()) {
        func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
        zone = 'Z';
    }
    var prefix = '[' + func + '("]';
    var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
    var datetime = '-MM-DD[T]HH:mm:ss.SSS';
    var suffix = zone + '[")]';

    return this.format(prefix + year + datetime + suffix);
}

function format (inputString) {
    if (!inputString) {
        inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
    }
    var output = formatMoment(this, inputString);
    return this.localeData().postformat(output);
}

function from (time, withoutSuffix) {
    if (this.isValid() &&
            ((isMoment(time) && time.isValid()) ||
             createLocal(time).isValid())) {
        return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
    } else {
        return this.localeData().invalidDate();
    }
}

function fromNow (withoutSuffix) {
    return this.from(createLocal(), withoutSuffix);
}

function to (time, withoutSuffix) {
    if (this.isValid() &&
            ((isMoment(time) && time.isValid()) ||
             createLocal(time).isValid())) {
        return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
    } else {
        return this.localeData().invalidDate();
    }
}

function toNow (withoutSuffix) {
    return this.to(createLocal(), withoutSuffix);
}

// If passed a locale key, it will set the locale for this
// instance.  Otherwise, it will return the locale configuration
// variables for this instance.
function locale (key) {
    var newLocaleData;

    if (key === undefined) {
        return this._locale._abbr;
    } else {
        newLocaleData = getLocale(key);
        if (newLocaleData != null) {
            this._locale = newLocaleData;
        }
        return this;
    }
}

var lang = deprecate(
    'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
    function (key) {
        if (key === undefined) {
            return this.localeData();
        } else {
            return this.locale(key);
        }
    }
);

function localeData () {
    return this._locale;
}

function startOf (units) {
    units = normalizeUnits(units);
    // the following switch intentionally omits break keywords
    // to utilize falling through the cases.
    switch (units) {
        case 'year':
            this.month(0);
            /* falls through */
        case 'quarter':
        case 'month':
            this.date(1);
            /* falls through */
        case 'week':
        case 'isoWeek':
        case 'day':
        case 'date':
            this.hours(0);
            /* falls through */
        case 'hour':
            this.minutes(0);
            /* falls through */
        case 'minute':
            this.seconds(0);
            /* falls through */
        case 'second':
            this.milliseconds(0);
    }

    // weeks are a special case
    if (units === 'week') {
        this.weekday(0);
    }
    if (units === 'isoWeek') {
        this.isoWeekday(1);
    }

    // quarters are also special
    if (units === 'quarter') {
        this.month(Math.floor(this.month() / 3) * 3);
    }

    return this;
}

function endOf (units) {
    units = normalizeUnits(units);
    if (units === undefined || units === 'millisecond') {
        return this;
    }

    // 'date' is an alias for 'day', so it should be considered as such.
    if (units === 'date') {
        units = 'day';
    }

    return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
}

function valueOf () {
    return this._d.valueOf() - ((this._offset || 0) * 60000);
}

function unix () {
    return Math.floor(this.valueOf() / 1000);
}

function toDate () {
    return new Date(this.valueOf());
}

function toArray () {
    var m = this;
    return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
}

function toObject () {
    var m = this;
    return {
        years: m.year(),
        months: m.month(),
        date: m.date(),
        hours: m.hours(),
        minutes: m.minutes(),
        seconds: m.seconds(),
        milliseconds: m.milliseconds()
    };
}

function toJSON () {
    // new Date(NaN).toJSON() === null
    return this.isValid() ? this.toISOString() : null;
}

function isValid$2 () {
    return isValid(this);
}

function parsingFlags () {
    return extend({}, getParsingFlags(this));
}

function invalidAt () {
    return getParsingFlags(this).overflow;
}

function creationData() {
    return {
        input: this._i,
        format: this._f,
        locale: this._locale,
        isUTC: this._isUTC,
        strict: this._strict
    };
}

// FORMATTING

addFormatToken(0, ['gg', 2], 0, function () {
    return this.weekYear() % 100;
});

addFormatToken(0, ['GG', 2], 0, function () {
    return this.isoWeekYear() % 100;
});

function addWeekYearFormatToken (token, getter) {
    addFormatToken(0, [token, token.length], 0, getter);
}

addWeekYearFormatToken('gggg',     'weekYear');
addWeekYearFormatToken('ggggg',    'weekYear');
addWeekYearFormatToken('GGGG',  'isoWeekYear');
addWeekYearFormatToken('GGGGG', 'isoWeekYear');

// ALIASES

addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');

// PRIORITY

addUnitPriority('weekYear', 1);
addUnitPriority('isoWeekYear', 1);


// PARSING

addRegexToken('G',      matchSigned);
addRegexToken('g',      matchSigned);
addRegexToken('GG',     match1to2, match2);
addRegexToken('gg',     match1to2, match2);
addRegexToken('GGGG',   match1to4, match4);
addRegexToken('gggg',   match1to4, match4);
addRegexToken('GGGGG',  match1to6, match6);
addRegexToken('ggggg',  match1to6, match6);

addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
    week[token.substr(0, 2)] = toInt(input);
});

addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
    week[token] = hooks.parseTwoDigitYear(input);
});

// MOMENTS

function getSetWeekYear (input) {
    return getSetWeekYearHelper.call(this,
            input,
            this.week(),
            this.weekday(),
            this.localeData()._week.dow,
            this.localeData()._week.doy);
}

function getSetISOWeekYear (input) {
    return getSetWeekYearHelper.call(this,
            input, this.isoWeek(), this.isoWeekday(), 1, 4);
}

function getISOWeeksInYear () {
    return weeksInYear(this.year(), 1, 4);
}

function getWeeksInYear () {
    var weekInfo = this.localeData()._week;
    return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}

function getSetWeekYearHelper(input, week, weekday, dow, doy) {
    var weeksTarget;
    if (input == null) {
        return weekOfYear(this, dow, doy).year;
    } else {
        weeksTarget = weeksInYear(input, dow, doy);
        if (week > weeksTarget) {
            week = weeksTarget;
        }
        return setWeekAll.call(this, input, week, weekday, dow, doy);
    }
}

function setWeekAll(weekYear, week, weekday, dow, doy) {
    var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
        date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);

    this.year(date.getUTCFullYear());
    this.month(date.getUTCMonth());
    this.date(date.getUTCDate());
    return this;
}

// FORMATTING

addFormatToken('Q', 0, 'Qo', 'quarter');

// ALIASES

addUnitAlias('quarter', 'Q');

// PRIORITY

addUnitPriority('quarter', 7);

// PARSING

addRegexToken('Q', match1);
addParseToken('Q', function (input, array) {
    array[MONTH] = (toInt(input) - 1) * 3;
});

// MOMENTS

function getSetQuarter (input) {
    return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
}

// FORMATTING

addFormatToken('D', ['DD', 2], 'Do', 'date');

// ALIASES

addUnitAlias('date', 'D');

// PRIOROITY
addUnitPriority('date', 9);

// PARSING

addRegexToken('D',  match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
    // TODO: Remove "ordinalParse" fallback in next major release.
    return isStrict ?
      (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
      locale._dayOfMonthOrdinalParseLenient;
});

addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
    array[DATE] = toInt(input.match(match1to2)[0]);
});

// MOMENTS

var getSetDayOfMonth = makeGetSet('Date', true);

// FORMATTING

addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');

// ALIASES

addUnitAlias('dayOfYear', 'DDD');

// PRIORITY
addUnitPriority('dayOfYear', 4);

// PARSING

addRegexToken('DDD',  match1to3);
addRegexToken('DDDD', match3);
addParseToken(['DDD', 'DDDD'], function (input, array, config) {
    config._dayOfYear = toInt(input);
});

// HELPERS

// MOMENTS

function getSetDayOfYear (input) {
    var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
    return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
}

// FORMATTING

addFormatToken('m', ['mm', 2], 0, 'minute');

// ALIASES

addUnitAlias('minute', 'm');

// PRIORITY

addUnitPriority('minute', 14);

// PARSING

addRegexToken('m',  match1to2);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);

// MOMENTS

var getSetMinute = makeGetSet('Minutes', false);

// FORMATTING

addFormatToken('s', ['ss', 2], 0, 'second');

// ALIASES

addUnitAlias('second', 's');

// PRIORITY

addUnitPriority('second', 15);

// PARSING

addRegexToken('s',  match1to2);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);

// MOMENTS

var getSetSecond = makeGetSet('Seconds', false);

// FORMATTING

addFormatToken('S', 0, 0, function () {
    return ~~(this.millisecond() / 100);
});

addFormatToken(0, ['SS', 2], 0, function () {
    return ~~(this.millisecond() / 10);
});

addFormatToken(0, ['SSS', 3], 0, 'millisecond');
addFormatToken(0, ['SSSS', 4], 0, function () {
    return this.millisecond() * 10;
});
addFormatToken(0, ['SSSSS', 5], 0, function () {
    return this.millisecond() * 100;
});
addFormatToken(0, ['SSSSSS', 6], 0, function () {
    return this.millisecond() * 1000;
});
addFormatToken(0, ['SSSSSSS', 7], 0, function () {
    return this.millisecond() * 10000;
});
addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
    return this.millisecond() * 100000;
});
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
    return this.millisecond() * 1000000;
});


// ALIASES

addUnitAlias('millisecond', 'ms');

// PRIORITY

addUnitPriority('millisecond', 16);

// PARSING

addRegexToken('S',    match1to3, match1);
addRegexToken('SS',   match1to3, match2);
addRegexToken('SSS',  match1to3, match3);

var token;
for (token = 'SSSS'; token.length <= 9; token += 'S') {
    addRegexToken(token, matchUnsigned);
}

function parseMs(input, array) {
    array[MILLISECOND] = toInt(('0.' + input) * 1000);
}

for (token = 'S'; token.length <= 9; token += 'S') {
    addParseToken(token, parseMs);
}
// MOMENTS

var getSetMillisecond = makeGetSet('Milliseconds', false);

// FORMATTING

addFormatToken('z',  0, 0, 'zoneAbbr');
addFormatToken('zz', 0, 0, 'zoneName');

// MOMENTS

function getZoneAbbr () {
    return this._isUTC ? 'UTC' : '';
}

function getZoneName () {
    return this._isUTC ? 'Coordinated Universal Time' : '';
}

var proto = Moment.prototype;

proto.add               = add;
proto.calendar          = calendar$1;
proto.clone             = clone;
proto.diff              = diff;
proto.endOf             = endOf;
proto.format            = format;
proto.from              = from;
proto.fromNow           = fromNow;
proto.to                = to;
proto.toNow             = toNow;
proto.get               = stringGet;
proto.invalidAt         = invalidAt;
proto.isAfter           = isAfter;
proto.isBefore          = isBefore;
proto.isBetween         = isBetween;
proto.isSame            = isSame;
proto.isSameOrAfter     = isSameOrAfter;
proto.isSameOrBefore    = isSameOrBefore;
proto.isValid           = isValid$2;
proto.lang              = lang;
proto.locale            = locale;
proto.localeData        = localeData;
proto.max               = prototypeMax;
proto.min               = prototypeMin;
proto.parsingFlags      = parsingFlags;
proto.set               = stringSet;
proto.startOf           = startOf;
proto.subtract          = subtract;
proto.toArray           = toArray;
proto.toObject          = toObject;
proto.toDate            = toDate;
proto.toISOString       = toISOString;
proto.inspect           = inspect;
proto.toJSON            = toJSON;
proto.toString          = toString;
proto.unix              = unix;
proto.valueOf           = valueOf;
proto.creationData      = creationData;

// Year
proto.year       = getSetYear;
proto.isLeapYear = getIsLeapYear;

// Week Year
proto.weekYear    = getSetWeekYear;
proto.isoWeekYear = getSetISOWeekYear;

// Quarter
proto.quarter = proto.quarters = getSetQuarter;

// Month
proto.month       = getSetMonth;
proto.daysInMonth = getDaysInMonth;

// Week
proto.week           = proto.weeks        = getSetWeek;
proto.isoWeek        = proto.isoWeeks     = getSetISOWeek;
proto.weeksInYear    = getWeeksInYear;
proto.isoWeeksInYear = getISOWeeksInYear;

// Day
proto.date       = getSetDayOfMonth;
proto.day        = proto.days             = getSetDayOfWeek;
proto.weekday    = getSetLocaleDayOfWeek;
proto.isoWeekday = getSetISODayOfWeek;
proto.dayOfYear  = getSetDayOfYear;

// Hour
proto.hour = proto.hours = getSetHour;

// Minute
proto.minute = proto.minutes = getSetMinute;

// Second
proto.second = proto.seconds = getSetSecond;

// Millisecond
proto.millisecond = proto.milliseconds = getSetMillisecond;

// Offset
proto.utcOffset            = getSetOffset;
proto.utc                  = setOffsetToUTC;
proto.local                = setOffsetToLocal;
proto.parseZone            = setOffsetToParsedOffset;
proto.hasAlignedHourOffset = hasAlignedHourOffset;
proto.isDST                = isDaylightSavingTime;
proto.isLocal              = isLocal;
proto.isUtcOffset          = isUtcOffset;
proto.isUtc                = isUtc;
proto.isUTC                = isUtc;

// Timezone
proto.zoneAbbr = getZoneAbbr;
proto.zoneName = getZoneName;

// Deprecations
proto.dates  = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
proto.years  = deprecate('years accessor is deprecated. Use year instead', getSetYear);
proto.zone   = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);

function createUnix (input) {
    return createLocal(input * 1000);
}

function createInZone () {
    return createLocal.apply(null, arguments).parseZone();
}

function preParsePostFormat (string) {
    return string;
}

var proto$1 = Locale.prototype;

proto$1.calendar        = calendar;
proto$1.longDateFormat  = longDateFormat;
proto$1.invalidDate     = invalidDate;
proto$1.ordinal         = ordinal;
proto$1.preparse        = preParsePostFormat;
proto$1.postformat      = preParsePostFormat;
proto$1.relativeTime    = relativeTime;
proto$1.pastFuture      = pastFuture;
proto$1.set             = set;

// Month
proto$1.months            =        localeMonths;
proto$1.monthsShort       =        localeMonthsShort;
proto$1.monthsParse       =        localeMonthsParse;
proto$1.monthsRegex       = monthsRegex;
proto$1.monthsShortRegex  = monthsShortRegex;

// Week
proto$1.week = localeWeek;
proto$1.firstDayOfYear = localeFirstDayOfYear;
proto$1.firstDayOfWeek = localeFirstDayOfWeek;

// Day of Week
proto$1.weekdays       =        localeWeekdays;
proto$1.weekdaysMin    =        localeWeekdaysMin;
proto$1.weekdaysShort  =        localeWeekdaysShort;
proto$1.weekdaysParse  =        localeWeekdaysParse;

proto$1.weekdaysRegex       =        weekdaysRegex;
proto$1.weekdaysShortRegex  =        weekdaysShortRegex;
proto$1.weekdaysMinRegex    =        weekdaysMinRegex;

// Hours
proto$1.isPM = localeIsPM;
proto$1.meridiem = localeMeridiem;

function get$1 (format, index, field, setter) {
    var locale = getLocale();
    var utc = createUTC().set(setter, index);
    return locale[field](utc, format);
}

function listMonthsImpl (format, index, field) {
    if (isNumber(format)) {
        index = format;
        format = undefined;
    }

    format = format || '';

    if (index != null) {
        return get$1(format, index, field, 'month');
    }

    var i;
    var out = [];
    for (i = 0; i < 12; i++) {
        out[i] = get$1(format, i, field, 'month');
    }
    return out;
}

// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl (localeSorted, format, index, field) {
    if (typeof localeSorted === 'boolean') {
        if (isNumber(format)) {
            index = format;
            format = undefined;
        }

        format = format || '';
    } else {
        format = localeSorted;
        index = format;
        localeSorted = false;

        if (isNumber(format)) {
            index = format;
            format = undefined;
        }

        format = format || '';
    }

    var locale = getLocale(),
        shift = localeSorted ? locale._week.dow : 0;

    if (index != null) {
        return get$1(format, (index + shift) % 7, field, 'day');
    }

    var i;
    var out = [];
    for (i = 0; i < 7; i++) {
        out[i] = get$1(format, (i + shift) % 7, field, 'day');
    }
    return out;
}

function listMonths (format, index) {
    return listMonthsImpl(format, index, 'months');
}

function listMonthsShort (format, index) {
    return listMonthsImpl(format, index, 'monthsShort');
}

function listWeekdays (localeSorted, format, index) {
    return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
}

function listWeekdaysShort (localeSorted, format, index) {
    return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
}

function listWeekdaysMin (localeSorted, format, index) {
    return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
}

getSetGlobalLocale('en', {
    dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
    ordinal : function (number) {
        var b = number % 10,
            output = (toInt(number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    }
});

// Side effect imports
hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);

var mathAbs = Math.abs;

function abs () {
    var data           = this._data;

    this._milliseconds = mathAbs(this._milliseconds);
    this._days         = mathAbs(this._days);
    this._months       = mathAbs(this._months);

    data.milliseconds  = mathAbs(data.milliseconds);
    data.seconds       = mathAbs(data.seconds);
    data.minutes       = mathAbs(data.minutes);
    data.hours         = mathAbs(data.hours);
    data.months        = mathAbs(data.months);
    data.years         = mathAbs(data.years);

    return this;
}

function addSubtract$1 (duration, input, value, direction) {
    var other = createDuration(input, value);

    duration._milliseconds += direction * other._milliseconds;
    duration._days         += direction * other._days;
    duration._months       += direction * other._months;

    return duration._bubble();
}

// supports only 2.0-style add(1, 's') or add(duration)
function add$1 (input, value) {
    return addSubtract$1(this, input, value, 1);
}

// supports only 2.0-style subtract(1, 's') or subtract(duration)
function subtract$1 (input, value) {
    return addSubtract$1(this, input, value, -1);
}

function absCeil (number) {
    if (number < 0) {
        return Math.floor(number);
    } else {
        return Math.ceil(number);
    }
}

function bubble () {
    var milliseconds = this._milliseconds;
    var days         = this._days;
    var months       = this._months;
    var data         = this._data;
    var seconds, minutes, hours, years, monthsFromDays;

    // if we have a mix of positive and negative values, bubble down first
    // check: https://github.com/moment/moment/issues/2166
    if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
            (milliseconds <= 0 && days <= 0 && months <= 0))) {
        milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
        days = 0;
        months = 0;
    }

    // The following code bubbles up values, see the tests for
    // examples of what that means.
    data.milliseconds = milliseconds % 1000;

    seconds           = absFloor(milliseconds / 1000);
    data.seconds      = seconds % 60;

    minutes           = absFloor(seconds / 60);
    data.minutes      = minutes % 60;

    hours             = absFloor(minutes / 60);
    data.hours        = hours % 24;

    days += absFloor(hours / 24);

    // convert days to months
    monthsFromDays = absFloor(daysToMonths(days));
    months += monthsFromDays;
    days -= absCeil(monthsToDays(monthsFromDays));

    // 12 months -> 1 year
    years = absFloor(months / 12);
    months %= 12;

    data.days   = days;
    data.months = months;
    data.years  = years;

    return this;
}

function daysToMonths (days) {
    // 400 years have 146097 days (taking into account leap year rules)
    // 400 years have 12 months === 4800
    return days * 4800 / 146097;
}

function monthsToDays (months) {
    // the reverse of daysToMonths
    return months * 146097 / 4800;
}

function as (units) {
    if (!this.isValid()) {
        return NaN;
    }
    var days;
    var months;
    var milliseconds = this._milliseconds;

    units = normalizeUnits(units);

    if (units === 'month' || units === 'year') {
        days   = this._days   + milliseconds / 864e5;
        months = this._months + daysToMonths(days);
        return units === 'month' ? months : months / 12;
    } else {
        // handle milliseconds separately because of floating point math errors (issue #1867)
        days = this._days + Math.round(monthsToDays(this._months));
        switch (units) {
            case 'week'   : return days / 7     + milliseconds / 6048e5;
            case 'day'    : return days         + milliseconds / 864e5;
            case 'hour'   : return days * 24    + milliseconds / 36e5;
            case 'minute' : return days * 1440  + milliseconds / 6e4;
            case 'second' : return days * 86400 + milliseconds / 1000;
            // Math.floor prevents floating point math errors here
            case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
            default: throw new Error('Unknown unit ' + units);
        }
    }
}

// TODO: Use this.as('ms')?
function valueOf$1 () {
    if (!this.isValid()) {
        return NaN;
    }
    return (
        this._milliseconds +
        this._days * 864e5 +
        (this._months % 12) * 2592e6 +
        toInt(this._months / 12) * 31536e6
    );
}

function makeAs (alias) {
    return function () {
        return this.as(alias);
    };
}

var asMilliseconds = makeAs('ms');
var asSeconds      = makeAs('s');
var asMinutes      = makeAs('m');
var asHours        = makeAs('h');
var asDays         = makeAs('d');
var asWeeks        = makeAs('w');
var asMonths       = makeAs('M');
var asYears        = makeAs('y');

function clone$1 () {
    return createDuration(this);
}

function get$2 (units) {
    units = normalizeUnits(units);
    return this.isValid() ? this[units + 's']() : NaN;
}

function makeGetter(name) {
    return function () {
        return this.isValid() ? this._data[name] : NaN;
    };
}

var milliseconds = makeGetter('milliseconds');
var seconds      = makeGetter('seconds');
var minutes      = makeGetter('minutes');
var hours        = makeGetter('hours');
var days         = makeGetter('days');
var months       = makeGetter('months');
var years        = makeGetter('years');

function weeks () {
    return absFloor(this.days() / 7);
}

var round = Math.round;
var thresholds = {
    ss: 44,         // a few seconds to seconds
    s : 45,         // seconds to minute
    m : 45,         // minutes to hour
    h : 22,         // hours to day
    d : 26,         // days to month
    M : 11          // months to year
};

// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
    return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}

function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
    var duration = createDuration(posNegDuration).abs();
    var seconds  = round(duration.as('s'));
    var minutes  = round(duration.as('m'));
    var hours    = round(duration.as('h'));
    var days     = round(duration.as('d'));
    var months   = round(duration.as('M'));
    var years    = round(duration.as('y'));

    var a = seconds <= thresholds.ss && ['s', seconds]  ||
            seconds < thresholds.s   && ['ss', seconds] ||
            minutes <= 1             && ['m']           ||
            minutes < thresholds.m   && ['mm', minutes] ||
            hours   <= 1             && ['h']           ||
            hours   < thresholds.h   && ['hh', hours]   ||
            days    <= 1             && ['d']           ||
            days    < thresholds.d   && ['dd', days]    ||
            months  <= 1             && ['M']           ||
            months  < thresholds.M   && ['MM', months]  ||
            years   <= 1             && ['y']           || ['yy', years];

    a[2] = withoutSuffix;
    a[3] = +posNegDuration > 0;
    a[4] = locale;
    return substituteTimeAgo.apply(null, a);
}

// This function allows you to set the rounding function for relative time strings
function getSetRelativeTimeRounding (roundingFunction) {
    if (roundingFunction === undefined) {
        return round;
    }
    if (typeof(roundingFunction) === 'function') {
        round = roundingFunction;
        return true;
    }
    return false;
}

// This function allows you to set a threshold for relative time strings
function getSetRelativeTimeThreshold (threshold, limit) {
    if (thresholds[threshold] === undefined) {
        return false;
    }
    if (limit === undefined) {
        return thresholds[threshold];
    }
    thresholds[threshold] = limit;
    if (threshold === 's') {
        thresholds.ss = limit - 1;
    }
    return true;
}

function humanize (withSuffix) {
    if (!this.isValid()) {
        return this.localeData().invalidDate();
    }

    var locale = this.localeData();
    var output = relativeTime$1(this, !withSuffix, locale);

    if (withSuffix) {
        output = locale.pastFuture(+this, output);
    }

    return locale.postformat(output);
}

var abs$1 = Math.abs;

function sign(x) {
    return ((x > 0) - (x < 0)) || +x;
}

function toISOString$1() {
    // for ISO strings we do not use the normal bubbling rules:
    //  * milliseconds bubble up until they become hours
    //  * days do not bubble at all
    //  * months bubble up until they become years
    // This is because there is no context-free conversion between hours and days
    // (think of clock changes)
    // and also not between days and months (28-31 days per month)
    if (!this.isValid()) {
        return this.localeData().invalidDate();
    }

    var seconds = abs$1(this._milliseconds) / 1000;
    var days         = abs$1(this._days);
    var months       = abs$1(this._months);
    var minutes, hours, years;

    // 3600 seconds -> 60 minutes -> 1 hour
    minutes           = absFloor(seconds / 60);
    hours             = absFloor(minutes / 60);
    seconds %= 60;
    minutes %= 60;

    // 12 months -> 1 year
    years  = absFloor(months / 12);
    months %= 12;


    // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
    var Y = years;
    var M = months;
    var D = days;
    var h = hours;
    var m = minutes;
    var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
    var total = this.asSeconds();

    if (!total) {
        // this is the same as C#'s (Noda) and python (isodate)...
        // but not other JS (goog.date)
        return 'P0D';
    }

    var totalSign = total < 0 ? '-' : '';
    var ymSign = sign(this._months) !== sign(total) ? '-' : '';
    var daysSign = sign(this._days) !== sign(total) ? '-' : '';
    var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';

    return totalSign + 'P' +
        (Y ? ymSign + Y + 'Y' : '') +
        (M ? ymSign + M + 'M' : '') +
        (D ? daysSign + D + 'D' : '') +
        ((h || m || s) ? 'T' : '') +
        (h ? hmsSign + h + 'H' : '') +
        (m ? hmsSign + m + 'M' : '') +
        (s ? hmsSign + s + 'S' : '');
}

var proto$2 = Duration.prototype;

proto$2.isValid        = isValid$1;
proto$2.abs            = abs;
proto$2.add            = add$1;
proto$2.subtract       = subtract$1;
proto$2.as             = as;
proto$2.asMilliseconds = asMilliseconds;
proto$2.asSeconds      = asSeconds;
proto$2.asMinutes      = asMinutes;
proto$2.asHours        = asHours;
proto$2.asDays         = asDays;
proto$2.asWeeks        = asWeeks;
proto$2.asMonths       = asMonths;
proto$2.asYears        = asYears;
proto$2.valueOf        = valueOf$1;
proto$2._bubble        = bubble;
proto$2.clone          = clone$1;
proto$2.get            = get$2;
proto$2.milliseconds   = milliseconds;
proto$2.seconds        = seconds;
proto$2.minutes        = minutes;
proto$2.hours          = hours;
proto$2.days           = days;
proto$2.weeks          = weeks;
proto$2.months         = months;
proto$2.years          = years;
proto$2.humanize       = humanize;
proto$2.toISOString    = toISOString$1;
proto$2.toString       = toISOString$1;
proto$2.toJSON         = toISOString$1;
proto$2.locale         = locale;
proto$2.localeData     = localeData;

// Deprecations
proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
proto$2.lang = lang;

// Side effect imports

// FORMATTING

addFormatToken('X', 0, 0, 'unix');
addFormatToken('x', 0, 0, 'valueOf');

// PARSING

addRegexToken('x', matchSigned);
addRegexToken('X', matchTimestamp);
addParseToken('X', function (input, array, config) {
    config._d = new Date(parseFloat(input, 10) * 1000);
});
addParseToken('x', function (input, array, config) {
    config._d = new Date(toInt(input));
});

// Side effect imports


hooks.version = '2.20.1';

setHookCallback(createLocal);

hooks.fn                    = proto;
hooks.min                   = min;
hooks.max                   = max;
hooks.now                   = now;
hooks.utc                   = createUTC;
hooks.unix                  = createUnix;
hooks.months                = listMonths;
hooks.isDate                = isDate;
hooks.locale                = getSetGlobalLocale;
hooks.invalid               = createInvalid;
hooks.duration              = createDuration;
hooks.isMoment              = isMoment;
hooks.weekdays              = listWeekdays;
hooks.parseZone             = createInZone;
hooks.localeData            = getLocale;
hooks.isDuration            = isDuration;
hooks.monthsShort           = listMonthsShort;
hooks.weekdaysMin           = listWeekdaysMin;
hooks.defineLocale          = defineLocale;
hooks.updateLocale          = updateLocale;
hooks.locales               = listLocales;
hooks.weekdaysShort         = listWeekdaysShort;
hooks.normalizeUnits        = normalizeUnits;
hooks.relativeTimeRounding  = getSetRelativeTimeRounding;
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
hooks.calendarFormat        = getCalendarFormat;
hooks.prototype             = proto;

// currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
    DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm',             // <input type="datetime-local" />
    DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss',  // <input type="datetime-local" step="1" />
    DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS',   // <input type="datetime-local" step="0.001" />
    DATE: 'YYYY-MM-DD',                             // <input type="date" />
    TIME: 'HH:mm',                                  // <input type="time" />
    TIME_SECONDS: 'HH:mm:ss',                       // <input type="time" step="1" />
    TIME_MS: 'HH:mm:ss.SSS',                        // <input type="time" step="0.001" />
    WEEK: 'YYYY-[W]WW',                             // <input type="week" />
    MONTH: 'YYYY-MM'                                // <input type="month" />
};

return hooks;

})));


/*** EXPORTS FROM exports-to-window-loader ***/
window['moment'] = __webpack_require__(40);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(341)(module)))

/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.isFunction = isFunction;
exports.throttle = throttle;
exports.throttleAfterHits = throttleAfterHits;
exports.debounce = debounce;
exports.pipe = pipe;
exports.partial = partial;
exports.curry = curry;
exports.curryRight = curryRight;

var _array = __webpack_require__(2);

/**
 * Checks if given variable is function.
 *
 * @param {*} func Variable to check.
 * @returns {Boolean}
 */
function isFunction(func) {
  return typeof func === 'function';
}

/**
 * Creates throttle function that enforces a maximum number of times a function (`func`) can be called over time (`wait`).
 *
 * @param {Function} func Function to invoke.
 * @param {Number} wait Delay in miliseconds.
 * @returns {Function}
 */
function throttle(func) {
  var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;

  var lastCalled = 0;
  var result = {
    lastCallThrottled: true
  };
  var lastTimer = null;

  function _throttle() {
    var _this = this;

    var args = arguments;
    var stamp = Date.now();
    var needCall = false;

    result.lastCallThrottled = true;

    if (!lastCalled) {
      lastCalled = stamp;
      needCall = true;
    }
    var remaining = wait - (stamp - lastCalled);

    if (needCall) {
      result.lastCallThrottled = false;
      func.apply(this, args);
    } else {
      if (lastTimer) {
        clearTimeout(lastTimer);
      }
      lastTimer = setTimeout(function () {
        result.lastCallThrottled = false;
        func.apply(_this, args);
        lastCalled = 0;
        lastTimer = void 0;
      }, remaining);
    }

    return result;
  }

  return _throttle;
}

/**
 * Creates throttle function that enforces a maximum number of times a function (`func`) can be called over
 * time (`wait`) after specified hits.
 *
 * @param {Function} func Function to invoke.
 * @param {Number} wait Delay in miliseconds.
 * @param {Number} hits Number of hits after throttling will be applied.
 * @returns {Function}
 */
function throttleAfterHits(func) {
  var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;
  var hits = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;

  var funcThrottle = throttle(func, wait);
  var remainHits = hits;

  function _clearHits() {
    remainHits = hits;
  }
  function _throttleAfterHits() {
    if (remainHits) {
      remainHits--;

      return func.apply(this, arguments);
    }

    return funcThrottle.apply(this, arguments);
  }
  _throttleAfterHits.clearHits = _clearHits;

  return _throttleAfterHits;
}

/**
 * Creates debounce function that enforces a function (`func`) not be called again until a certain amount of time (`wait`)
 * has passed without it being called.
 *
 * @param {Function} func Function to invoke.
 * @param {Number} wait Delay in milliseconds.
 * @returns {Function}
 */
function debounce(func) {
  var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;

  var lastTimer = null;
  var result = void 0;

  function _debounce() {
    var _this2 = this;

    var args = arguments;

    if (lastTimer) {
      clearTimeout(lastTimer);
    }
    lastTimer = setTimeout(function () {
      result = func.apply(_this2, args);
    }, wait);

    return result;
  }

  return _debounce;
}

/**
 * Creates the function that returns the result of calling the given functions. Result of the first function is passed to
 * the second as an argument and so on. Only first function in the chain can handle multiple arguments.
 *
 * @param {Function} functions Functions to compose.
 * @returns {Function}
 */
function pipe() {
  for (var _len = arguments.length, functions = Array(_len), _key = 0; _key < _len; _key++) {
    functions[_key] = arguments[_key];
  }

  var firstFunc = functions[0],
      restFunc = functions.slice(1);


  return function _pipe() {
    return (0, _array.arrayReduce)(restFunc, function (acc, fn) {
      return fn(acc);
    }, firstFunc.apply(this, arguments));
  };
}

/**
 * Creates the function that returns the function with cached arguments.
 *
 * @param {Function} func Function to partialization.
 * @param {Array} params Function arguments to cache.
 * @returns {Function}
 */
function partial(func) {
  for (var _len2 = arguments.length, params = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
    params[_key2 - 1] = arguments[_key2];
  }

  return function _partial() {
    for (var _len3 = arguments.length, restParams = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
      restParams[_key3] = arguments[_key3];
    }

    return func.apply(this, params.concat(restParams));
  };
}

/**
 * Creates the functions that returns the function with cached arguments. If count if passed arguments will be matched
 * to the arguments defined in `func` then function will be invoked.
 * Arguments are added to the stack in direction from the left to the right.
 *
 * @example
 * ```
 * var replace = curry(function(find, replace, string) {
 *   return string.replace(find, replace);
 * });
 *
 * // returns function with bounded first argument
 * var replace = replace('foo')
 *
 * // returns replaced string - all arguments was passed so function was invoked
 * replace('bar', 'Some test with foo...');
 *
 * ```
 *
 * @param {Function} func Function to currying.
 * @returns {Function}
 */
function curry(func) {
  var argsLength = func.length;

  function given(argsSoFar) {
    return function _curry() {
      for (var _len4 = arguments.length, params = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
        params[_key4] = arguments[_key4];
      }

      var passedArgsSoFar = argsSoFar.concat(params);
      var result = void 0;

      if (passedArgsSoFar.length >= argsLength) {
        result = func.apply(this, passedArgsSoFar);
      } else {
        result = given(passedArgsSoFar);
      }

      return result;
    };
  }

  return given([]);
}

/**
 * Creates the functions that returns the function with cached arguments. If count if passed arguments will be matched
 * to the arguments defined in `func` then function will be invoked.
 * Arguments are added to the stack in direction from the right to the left.
 *
 * @example
 * ```
 * var replace = curry(function(find, replace, string) {
 *   return string.replace(find, replace);
 * });
 *
 * // returns function with bounded first argument
 * var replace = replace('Some test with foo...')
 *
 * // returns replaced string - all arguments was passed so function was invoked
 * replace('bar', 'foo');
 *
 * ```
 *
 * @param {Function} func Function to currying.
 * @returns {Function}
 */
function curryRight(func) {
  var argsLength = func.length;

  function given(argsSoFar) {
    return function _curry() {
      for (var _len5 = arguments.length, params = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
        params[_key5] = arguments[_key5];
      }

      var passedArgsSoFar = argsSoFar.concat(params.reverse());
      var result = void 0;

      if (passedArgsSoFar.length >= argsLength) {
        result = func.apply(this, passedArgsSoFar);
      } else {
        result = given(passedArgsSoFar);
      }

      return result;
    };
  }

  return given([]);
}

/***/ }),
/* 42 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = function (it) {
  return toString.call(it).slice(8, -1);
};


/***/ }),
/* 43 */
/***/ (function(module, exports) {

var core = module.exports = { version: '2.5.3' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef


/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(5);
module.exports = function (it, TYPE) {
  if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
  return it;
};


/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {

// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__(10)('unscopables');
var ArrayProto = Array.prototype;
if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(31)(ArrayProto, UNSCOPABLES, {});
module.exports = function (key) {
  ArrayProto[UNSCOPABLES][key] = true;
};


/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = staticRegister;

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var collection = exports.collection = new Map();

function staticRegister() {
  var namespace = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'common';

  if (!collection.has(namespace)) {
    collection.set(namespace, new Map());
  }
  var subCollection = collection.get(namespace);

  /**
   * Register an item to the collection. If the item under the same was exist earlier then this item will be replaced with new one.
   *
   * @param {String} name Identification of the item.
   * @param {*} item Item to save in the collection.
   */
  function register(name, item) {
    subCollection.set(name, item);
  }

  /**
   * Retrieve the item from the collection.
   *
   * @param {String} name Identification of the item.
   * @returns {*} Returns item which was saved in the collection.
   */
  function getItem(name) {
    return subCollection.get(name);
  }

  /**
   * Check if item under specyfied name is exists.
   *
   * @param {String} name Identification of the item.
   * @returns {Boolean} Returns `true` or `false` depends on if element exists in the collection.
   */
  function hasItem(name) {
    return subCollection.has(name);
  }

  /**
   * Retrieve list of names registered from the collection.
   *
   * @returns {Array} Returns an array of strings with all names under which objects are stored.
   */
  function getNames() {
    return [].concat(_toConsumableArray(subCollection.keys()));
  }

  /**
   * Retrieve all registered values from the collection.
   *
   * @returns {Array} Returns an array with all values stored in the collection.
   */
  function getValues() {
    return [].concat(_toConsumableArray(subCollection.values()));
  }

  return {
    register: register,
    getItem: getItem,
    hasItem: hasItem,
    getNames: getNames,
    getValues: getValues
  };
}

/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.EditorState = undefined;

var _src = __webpack_require__(15);

var _mixed = __webpack_require__(17);

var EditorState = exports.EditorState = {
  VIRGIN: 'STATE_VIRGIN', // before editing
  EDITING: 'STATE_EDITING',
  WAITING: 'STATE_WAITING', // waiting for async validation
  FINISHED: 'STATE_FINISHED'
};

function BaseEditor(instance) {
  this.instance = instance;
  this.state = EditorState.VIRGIN;

  this._opened = false;
  this._fullEditMode = false;
  this._closeCallback = null;

  this.init();
}

BaseEditor.prototype._fireCallbacks = function (result) {
  if (this._closeCallback) {
    this._closeCallback(result);
    this._closeCallback = null;
  }
};

BaseEditor.prototype.init = function () {};

BaseEditor.prototype.getValue = function () {
  throw Error('Editor getValue() method unimplemented');
};

BaseEditor.prototype.setValue = function (newValue) {
  throw Error('Editor setValue() method unimplemented');
};

BaseEditor.prototype.open = function () {
  throw Error('Editor open() method unimplemented');
};

BaseEditor.prototype.close = function () {
  throw Error('Editor close() method unimplemented');
};

BaseEditor.prototype.prepare = function (row, col, prop, td, originalValue, cellProperties) {
  this.TD = td;
  this.row = row;
  this.col = col;
  this.prop = prop;
  this.originalValue = originalValue;
  this.cellProperties = cellProperties;
  this.state = EditorState.VIRGIN;
};

BaseEditor.prototype.extend = function () {
  var baseClass = this.constructor;

  function Editor() {
    baseClass.apply(this, arguments);
  }

  function inherit(Child, Parent) {
    function Bridge() {}
    Bridge.prototype = Parent.prototype;
    Child.prototype = new Bridge();
    Child.prototype.constructor = Child;

    return Child;
  }

  return inherit(Editor, baseClass);
};

BaseEditor.prototype.saveValue = function (value, ctrlDown) {
  var selection = void 0;
  var tmp = void 0;

  // if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)
  if (ctrlDown) {
    selection = this.instance.getSelected();

    if (selection[0] > selection[2]) {
      tmp = selection[0];
      selection[0] = selection[2];
      selection[2] = tmp;
    }
    if (selection[1] > selection[3]) {
      tmp = selection[1];
      selection[1] = selection[3];
      selection[3] = tmp;
    }
  } else {
    selection = [this.row, this.col, null, null];
  }

  this.instance.populateFromArray(selection[0], selection[1], value, selection[2], selection[3], 'edit');
};

BaseEditor.prototype.beginEditing = function (newInitialValue, event) {
  if (this.state !== EditorState.VIRGIN) {
    return;
  }
  this.instance.view.scrollViewport(new _src.CellCoords(this.row, this.col));
  this.instance.view.render();
  this.state = EditorState.EDITING;

  newInitialValue = typeof newInitialValue === 'string' ? newInitialValue : this.originalValue;
  this.setValue((0, _mixed.stringify)(newInitialValue));

  this.open(event);
  this._opened = true;
  this.focus();

  // only rerender the selections (FillHandle should disappear when beginediting is triggered)
  this.instance.view.render();

  this.instance.runHooks('afterBeginEditing', this.row, this.col);
};

BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) {
  var _this = this,
      val;

  if (callback) {
    var previousCloseCallback = this._closeCallback;

    this._closeCallback = function (result) {
      if (previousCloseCallback) {
        previousCloseCallback(result);
      }

      callback(result);
      _this.instance.view.render();
    };
  }

  if (this.isWaiting()) {
    return;
  }

  if (this.state == EditorState.VIRGIN) {
    this.instance._registerTimeout(setTimeout(function () {
      _this._fireCallbacks(true);
    }, 0));

    return;
  }

  if (this.state == EditorState.EDITING) {
    if (restoreOriginalValue) {
      this.cancelChanges();
      this.instance.view.render();

      return;
    }

    var value = this.getValue();

    if (this.instance.getSettings().trimWhitespace) {
      // We trim only string values
      val = [[typeof value === 'string' ? String.prototype.trim.call(value || '') : value]];
    } else {
      val = [[value]];
    }

    this.state = EditorState.WAITING;
    this.saveValue(val, ctrlDown);

    if (this.instance.getCellValidator(this.cellProperties)) {
      this.instance.addHookOnce('postAfterValidate', function (result) {
        _this.state = EditorState.FINISHED;
        _this.discardEditor(result);
      });
    } else {
      this.state = EditorState.FINISHED;
      this.discardEditor(true);
    }
  }
};

BaseEditor.prototype.cancelChanges = function () {
  this.state = EditorState.FINISHED;
  this.discardEditor();
};

BaseEditor.prototype.discardEditor = function (result) {
  if (this.state !== EditorState.FINISHED) {
    return;
  }
  // validator was defined and failed
  if (result === false && this.cellProperties.allowInvalid !== true) {
    this.instance.selectCell(this.row, this.col);
    this.focus();
    this.state = EditorState.EDITING;
    this._fireCallbacks(false);
  } else {
    this.close();
    this._opened = false;
    this._fullEditMode = false;
    this.state = EditorState.VIRGIN;
    this._fireCallbacks(true);
  }
};

/**
 * Switch editor into full edit mode. In this state navigation keys don't close editor. This mode is activated
 * automatically after hit ENTER or F2 key on the cell or while editing cell press F2 key.
 */
BaseEditor.prototype.enableFullEditMode = function () {
  this._fullEditMode = true;
};

/**
 * Checks if editor is in full edit mode.
 *
 * @returns {Boolean}
 */
BaseEditor.prototype.isInFullEditMode = function () {
  return this._fullEditMode;
};

BaseEditor.prototype.isOpened = function () {
  return this._opened;
};

BaseEditor.prototype.isWaiting = function () {
  return this.state === EditorState.WAITING;
};

BaseEditor.prototype.checkEditorSection = function () {
  var totalRows = this.instance.countRows();
  var section = '';

  if (this.row < this.instance.getSettings().fixedRowsTop) {
    if (this.col < this.instance.getSettings().fixedColumnsLeft) {
      section = 'top-left-corner';
    } else {
      section = 'top';
    }
  } else if (this.instance.getSettings().fixedRowsBottom && this.row >= totalRows - this.instance.getSettings().fixedRowsBottom) {
    if (this.col < this.instance.getSettings().fixedColumnsLeft) {
      section = 'bottom-left-corner';
    } else {
      section = 'bottom';
    }
  } else if (this.col < this.instance.getSettings().fixedColumnsLeft) {
    section = 'left';
  }

  return section;
};

exports.default = BaseEditor;

/***/ }),
/* 48 */
/***/ (function(module, exports) {

var id = 0;
var px = Math.random();
module.exports = function (key) {
  return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};


/***/ }),
/* 49 */
/***/ (function(module, exports) {

module.exports = function (bitmap, value) {
  return {
    enumerable: !(bitmap & 1),
    configurable: !(bitmap & 2),
    writable: !(bitmap & 4),
    value: value
  };
};


/***/ }),
/* 50 */
/***/ (function(module, exports) {

module.exports = {};


/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {

var def = __webpack_require__(19).f;
var has = __webpack_require__(27);
var TAG = __webpack_require__(10)('toStringTag');

module.exports = function (it, tag, stat) {
  if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};


/***/ }),
/* 52 */
/***/ (function(module, exports) {

exports.f = {}.propertyIsEnumerable;


/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * CellCoords holds cell coordinates (row, column) and few method to validate them and
 * retrieve as an array or an object
 *
 * @class CellCoords
 */
var CellCoords = function () {
  /**
   * @param {Number} row Row index
   * @param {Number} col Column index
   */
  function CellCoords(row, col) {
    _classCallCheck(this, CellCoords);

    if (typeof row !== 'undefined' && typeof col !== 'undefined') {
      this.row = row;
      this.col = col;
    } else {
      this.row = null;
      this.col = null;
    }
  }

  /**
   * Checks if given set of coordinates is valid in context of a given Walkontable instance
   *
   * @param {Walkontable} wotInstance
   * @returns {Boolean}
   */


  _createClass(CellCoords, [{
    key: 'isValid',
    value: function isValid(wotInstance) {
      // is it a valid cell index (0 or higher)
      if (this.row < 0 || this.col < 0) {
        return false;
      }
      // is selection within total rows and columns
      if (this.row >= wotInstance.getSetting('totalRows') || this.col >= wotInstance.getSetting('totalColumns')) {
        return false;
      }

      return true;
    }

    /**
     * Checks if this cell coords are the same as cell coords given as a parameter
     *
     * @param {CellCoords} cellCoords
     * @returns {Boolean}
     */

  }, {
    key: 'isEqual',
    value: function isEqual(cellCoords) {
      if (cellCoords === this) {
        return true;
      }

      return this.row === cellCoords.row && this.col === cellCoords.col;
    }

    /**
     * Checks if tested coordinates are positioned in south-east from this cell coords
     *
     * @param {Object} testedCoords
     * @returns {Boolean}
     */

  }, {
    key: 'isSouthEastOf',
    value: function isSouthEastOf(testedCoords) {
      return this.row >= testedCoords.row && this.col >= testedCoords.col;
    }

    /**
     * Checks if tested coordinates are positioned in north-east from this cell coords
     *
     * @param {Object} testedCoords
     * @returns {Boolean}
     */

  }, {
    key: 'isNorthWestOf',
    value: function isNorthWestOf(testedCoords) {
      return this.row <= testedCoords.row && this.col <= testedCoords.col;
    }

    /**
     * Checks if tested coordinates are positioned in south-west from this cell coords
     *
     * @param {Object} testedCoords
     * @returns {Boolean}
     */

  }, {
    key: 'isSouthWestOf',
    value: function isSouthWestOf(testedCoords) {
      return this.row >= testedCoords.row && this.col <= testedCoords.col;
    }

    /**
     * Checks if tested coordinates are positioned in north-east from this cell coords
     *
     * @param {Object} testedCoords
     * @returns {Boolean}
     */

  }, {
    key: 'isNorthEastOf',
    value: function isNorthEastOf(testedCoords) {
      return this.row <= testedCoords.row && this.col >= testedCoords.col;
    }
  }]);

  return CellCoords;
}();

exports.default = CellCoords;

/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

var _autoResize = __webpack_require__(347);

var _autoResize2 = _interopRequireDefault(_autoResize);

var _baseEditor = __webpack_require__(47);

var _baseEditor2 = _interopRequireDefault(_baseEditor);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _unicode = __webpack_require__(20);

var _event = __webpack_require__(12);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var TextEditor = _baseEditor2.default.prototype.extend();

/**
 * @private
 * @editor TextEditor
 * @class TextEditor
 * @dependencies autoResize
 */
TextEditor.prototype.init = function () {
  var that = this;
  this.createElements();
  this.eventManager = new _eventManager2.default(this);
  this.bindEvents();
  this.autoResize = (0, _autoResize2.default)();

  this.instance.addHook('afterDestroy', function () {
    that.destroy();
  });
};

TextEditor.prototype.getValue = function () {
  return this.TEXTAREA.value;
};

TextEditor.prototype.setValue = function (newValue) {
  this.TEXTAREA.value = newValue;
};

var onBeforeKeyDown = function onBeforeKeyDown(event) {
  var instance = this,
      that = instance.getActiveEditor(),
      ctrlDown;

  // catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
  ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;

  // Process only events that have been fired in the editor
  if (event.target !== that.TEXTAREA || (0, _event.isImmediatePropagationStopped)(event)) {
    return;
  }

  if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
    // when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea
    (0, _event.stopImmediatePropagation)(event);
    return;
  }

  switch (event.keyCode) {
    case _unicode.KEY_CODES.ARROW_RIGHT:
      if (that.isInFullEditMode()) {
        if (!that.isWaiting() && !that.allowKeyEventPropagation || !that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode)) {
          (0, _event.stopImmediatePropagation)(event);
        }
      }
      break;
    case _unicode.KEY_CODES.ARROW_LEFT:
      if (that.isInFullEditMode()) {
        if (!that.isWaiting() && !that.allowKeyEventPropagation || !that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode)) {
          (0, _event.stopImmediatePropagation)(event);
        }
      }
      break;
    case _unicode.KEY_CODES.ARROW_UP:
    case _unicode.KEY_CODES.ARROW_DOWN:
      if (that.isInFullEditMode()) {
        if (!that.isWaiting() && !that.allowKeyEventPropagation || !that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode)) {
          (0, _event.stopImmediatePropagation)(event);
        }
      }
      break;

    case _unicode.KEY_CODES.ENTER:
      var selected = that.instance.getSelected();
      var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]);
      if (ctrlDown && !isMultipleSelection || event.altKey) {
        // if ctrl+enter or alt+enter, add new line
        if (that.isOpened()) {
          var caretPosition = (0, _element.getCaretPosition)(that.TEXTAREA),
              value = that.getValue();

          var newValue = value.slice(0, caretPosition) + '\n' + value.slice(caretPosition);

          that.setValue(newValue);

          (0, _element.setCaretPosition)(that.TEXTAREA, caretPosition + 1);
        } else {
          that.beginEditing(that.originalValue + '\n');
        }
        (0, _event.stopImmediatePropagation)(event);
      }
      event.preventDefault(); // don't add newline to field
      break;

    case _unicode.KEY_CODES.A:
    case _unicode.KEY_CODES.X:
    case _unicode.KEY_CODES.C:
    case _unicode.KEY_CODES.V:
      if (ctrlDown) {
        (0, _event.stopImmediatePropagation)(event); // CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context)
      }
      break;

    case _unicode.KEY_CODES.BACKSPACE:
    case _unicode.KEY_CODES.DELETE:
    case _unicode.KEY_CODES.HOME:
    case _unicode.KEY_CODES.END:
      (0, _event.stopImmediatePropagation)(event); // backspace, delete, home, end should only work locally when cell is edited (not in table context)
      break;
    default:
      break;
  }

  if ([_unicode.KEY_CODES.ARROW_UP, _unicode.KEY_CODES.ARROW_RIGHT, _unicode.KEY_CODES.ARROW_DOWN, _unicode.KEY_CODES.ARROW_LEFT].indexOf(event.keyCode) === -1) {
    that.autoResize.resize(String.fromCharCode(event.keyCode));
  }
};

TextEditor.prototype.open = function () {
  this.refreshDimensions(); // need it instantly, to prevent https://github.com/handsontable/handsontable/issues/348

  this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};

TextEditor.prototype.close = function (tdOutside) {
  this.textareaParentStyle.display = 'none';

  this.autoResize.unObserve();

  if (document.activeElement === this.TEXTAREA) {
    this.instance.listen(); // don't refocus the table if user focused some cell outside of HT on purpose
  }
  this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};

TextEditor.prototype.focus = function () {
  this.TEXTAREA.focus();
  (0, _element.setCaretPosition)(this.TEXTAREA, this.TEXTAREA.value.length);
};

TextEditor.prototype.createElements = function () {
  //    this.$body = $(document.body);

  this.TEXTAREA = document.createElement('TEXTAREA');

  (0, _element.addClass)(this.TEXTAREA, 'handsontableInput');

  this.textareaStyle = this.TEXTAREA.style;
  this.textareaStyle.width = 0;
  this.textareaStyle.height = 0;

  this.TEXTAREA_PARENT = document.createElement('DIV');
  (0, _element.addClass)(this.TEXTAREA_PARENT, 'handsontableInputHolder');

  this.textareaParentStyle = this.TEXTAREA_PARENT.style;
  this.textareaParentStyle.top = 0;
  this.textareaParentStyle.left = 0;
  this.textareaParentStyle.display = 'none';

  this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);

  this.instance.rootElement.appendChild(this.TEXTAREA_PARENT);

  var that = this;
  this.instance._registerTimeout(setTimeout(function () {
    that.refreshDimensions();
  }, 0));
};

TextEditor.prototype.getEditedCell = function () {
  var editorSection = this.checkEditorSection(),
      editedCell;

  switch (editorSection) {
    case 'top':
      editedCell = this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 101;
      break;
    case 'top-left-corner':
      editedCell = this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 103;
      break;
    case 'bottom-left-corner':
      editedCell = this.instance.view.wt.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 103;
      break;
    case 'left':
      editedCell = this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 102;
      break;
    case 'bottom':
      editedCell = this.instance.view.wt.wtOverlays.bottomOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 102;
      break;
    default:
      editedCell = this.instance.getCell(this.row, this.col);
      this.textareaParentStyle.zIndex = '';
      break;
  }

  return editedCell != -1 && editedCell != -2 ? editedCell : void 0;
};

TextEditor.prototype.refreshValue = function () {
  var sourceData = this.instance.getSourceDataAtCell(this.row, this.prop);
  this.originalValue = sourceData;

  this.setValue(sourceData);
  this.refreshDimensions();
};

TextEditor.prototype.refreshDimensions = function () {
  if (this.state !== _baseEditor.EditorState.EDITING) {
    return;
  }
  this.TD = this.getEditedCell();

  // TD is outside of the viewport.
  if (!this.TD) {
    this.close(true);

    return;
  }
  var currentOffset = (0, _element.offset)(this.TD),
      containerOffset = (0, _element.offset)(this.instance.rootElement),
      scrollableContainer = (0, _element.getScrollableElement)(this.TD),
      totalRowsCount = this.instance.countRows(),


  // If colHeaders is disabled, cells in the first row have border-top
  editTopModifier = currentOffset.top === containerOffset.top ? 0 : 1,
      editTop = currentOffset.top - containerOffset.top - editTopModifier - (scrollableContainer.scrollTop || 0),
      editLeft = currentOffset.left - containerOffset.left - 1 - (scrollableContainer.scrollLeft || 0),
      settings = this.instance.getSettings(),
      rowHeadersCount = this.instance.hasRowHeaders(),
      colHeadersCount = this.instance.hasColHeaders(),
      editorSection = this.checkEditorSection(),
      backgroundColor = this.TD.style.backgroundColor,
      cssTransformOffset;

  // TODO: Refactor this to the new instance.getCell method (from #ply-59), after 0.12.1 is released
  switch (editorSection) {
    case 'top':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'left':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'top-left-corner':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'bottom-left-corner':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'bottom':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.bottomOverlay.clone.wtTable.holder.parentNode);
      break;
    default:
      break;
  }

  if (colHeadersCount && this.instance.getSelected()[0] === 0 || settings.fixedRowsBottom && this.instance.getSelected()[0] === totalRowsCount - settings.fixedRowsBottom) {
    editTop += 1;
  }

  if (this.instance.getSelected()[1] === 0) {
    editLeft += 1;
  }

  if (cssTransformOffset && cssTransformOffset != -1) {
    this.textareaParentStyle[cssTransformOffset[0]] = cssTransformOffset[1];
  } else {
    (0, _element.resetCssTransform)(this.TEXTAREA_PARENT);
  }

  this.textareaParentStyle.top = editTop + 'px';
  this.textareaParentStyle.left = editLeft + 'px';

  var firstRowOffset = this.instance.view.wt.wtViewport.rowsRenderCalculator.startPosition;
  var firstColumnOffset = this.instance.view.wt.wtViewport.columnsRenderCalculator.startPosition;
  var horizontalScrollPosition = this.instance.view.wt.wtOverlays.leftOverlay.getScrollPosition();
  var verticalScrollPosition = this.instance.view.wt.wtOverlays.topOverlay.getScrollPosition();
  var scrollbarWidth = (0, _element.getScrollbarWidth)();

  var cellTopOffset = this.TD.offsetTop + firstRowOffset - verticalScrollPosition;
  var cellLeftOffset = this.TD.offsetLeft + firstColumnOffset - horizontalScrollPosition;

  var width = (0, _element.innerWidth)(this.TD) - 8;
  var actualVerticalScrollbarWidth = (0, _element.hasVerticalScrollbar)(scrollableContainer) ? scrollbarWidth : 0;
  var actualHorizontalScrollbarWidth = (0, _element.hasHorizontalScrollbar)(scrollableContainer) ? scrollbarWidth : 0;
  var maxWidth = this.instance.view.maximumVisibleElementWidth(cellLeftOffset) - 9 - actualVerticalScrollbarWidth;
  var height = this.TD.scrollHeight + 1;
  var maxHeight = Math.max(this.instance.view.maximumVisibleElementHeight(cellTopOffset) - actualHorizontalScrollbarWidth, 23);

  var cellComputedStyle = (0, _element.getComputedStyle)(this.TD);

  this.TEXTAREA.style.fontSize = cellComputedStyle.fontSize;
  this.TEXTAREA.style.fontFamily = cellComputedStyle.fontFamily;
  this.TEXTAREA.style.backgroundColor = ''; // RESET STYLE
  this.TEXTAREA.style.backgroundColor = backgroundColor ? backgroundColor : (0, _element.getComputedStyle)(this.TEXTAREA).backgroundColor;

  this.autoResize.init(this.TEXTAREA, {
    minHeight: Math.min(height, maxHeight),
    maxHeight: maxHeight, // TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
    minWidth: Math.min(width, maxWidth),
    maxWidth: maxWidth // TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
  }, true);

  this.textareaParentStyle.display = 'block';
};

TextEditor.prototype.bindEvents = function () {
  var editor = this;

  this.eventManager.addEventListener(this.TEXTAREA, 'cut', function (event) {
    (0, _event.stopPropagation)(event);
  });

  this.eventManager.addEventListener(this.TEXTAREA, 'paste', function (event) {
    (0, _event.stopPropagation)(event);
  });

  this.instance.addHook('afterScrollHorizontally', function () {
    editor.refreshDimensions();
  });

  this.instance.addHook('afterScrollVertically', function () {
    editor.refreshDimensions();
  });

  this.instance.addHook('afterColumnResize', function () {
    editor.refreshDimensions();
    editor.focus();
  });

  this.instance.addHook('afterRowResize', function () {
    editor.refreshDimensions();
    editor.focus();
  });

  this.instance.addHook('afterDestroy', function () {
    editor.eventManager.destroy();
  });
};

TextEditor.prototype.destroy = function () {
  this.eventManager.destroy();
};

exports.default = TextEditor;

/***/ }),
/* 55 */
/***/ (function(module, exports) {

// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
  return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};


/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {

var toInteger = __webpack_require__(55);
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
  index = toInteger(index);
  return index < 0 ? max(index + length, 0) : min(index, length);
};


/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {

var redefine = __webpack_require__(30);
module.exports = function (target, src, safe) {
  for (var key in src) redefine(target, key, src[key], safe);
  return target;
};


/***/ }),
/* 58 */
/***/ (function(module, exports) {

module.exports = function (it) {
  if (typeof it != 'function') throw TypeError(it + ' is not a function!');
  return it;
};


/***/ }),
/* 59 */
/***/ (function(module, exports) {

module.exports = function (it, Constructor, name, forbiddenField) {
  if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
    throw TypeError(name + ': incorrect invocation!');
  } return it;
};


/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {

var ctx = __webpack_require__(32);
var call = __webpack_require__(97);
var isArrayIter = __webpack_require__(98);
var anObject = __webpack_require__(18);
var toLength = __webpack_require__(25);
var getIterFn = __webpack_require__(99);
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
  var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
  var f = ctx(fn, that, entries ? 2 : 1);
  var index = 0;
  var length, step, iterator, result;
  if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
  // fast case for arrays with default iterator
  if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
    result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
    if (result === BREAK || result === RETURN) return result;
  } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
    result = call(iterator, f, step.value, entries);
    if (result === BREAK || result === RETURN) return result;
  }
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;


/***/ }),
/* 61 */
/***/ (function(module, exports) {

module.exports = false;


/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var global = __webpack_require__(13);
var $export = __webpack_require__(3);
var redefine = __webpack_require__(30);
var redefineAll = __webpack_require__(57);
var meta = __webpack_require__(34);
var forOf = __webpack_require__(60);
var anInstance = __webpack_require__(59);
var isObject = __webpack_require__(5);
var fails = __webpack_require__(23);
var $iterDetect = __webpack_require__(75);
var setToStringTag = __webpack_require__(51);
var inheritIfRequired = __webpack_require__(321);

module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
  var Base = global[NAME];
  var C = Base;
  var ADDER = IS_MAP ? 'set' : 'add';
  var proto = C && C.prototype;
  var O = {};
  var fixMethod = function (KEY) {
    var fn = proto[KEY];
    redefine(proto, KEY,
      KEY == 'delete' ? function (a) {
        return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
      } : KEY == 'has' ? function has(a) {
        return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
      } : KEY == 'get' ? function get(a) {
        return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
      } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; }
        : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }
    );
  };
  if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
    new C().entries().next();
  }))) {
    // create collection constructor
    C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
    redefineAll(C.prototype, methods);
    meta.NEED = true;
  } else {
    var instance = new C();
    // early implementations not supports chaining
    var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
    // V8 ~  Chromium 40- weak-collections throws on primitives, but should return false
    var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });
    // most early implementations doesn't supports iterables, most modern - not close it correctly
    var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new
    // for early implementations -0 and +0 not the same
    var BUGGY_ZERO = !IS_WEAK && fails(function () {
      // V8 ~ Chromium 42- fails only with 5+ elements
      var $instance = new C();
      var index = 5;
      while (index--) $instance[ADDER](index, index);
      return !$instance.has(-0);
    });
    if (!ACCEPT_ITERABLES) {
      C = wrapper(function (target, iterable) {
        anInstance(target, C, NAME);
        var that = inheritIfRequired(new Base(), target, C);
        if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
        return that;
      });
      C.prototype = proto;
      proto.constructor = C;
    }
    if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
      fixMethod('delete');
      fixMethod('has');
      IS_MAP && fixMethod('get');
    }
    if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
    // weak collections should not contains .clear method
    if (IS_WEAK && proto.clear) delete proto.clear;
  }

  setToStringTag(C, NAME);

  O[NAME] = C;
  $export($export.G + $export.W + $export.F * (C != Base), O);

  if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);

  return C;
};


/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {

var pIE = __webpack_require__(52);
var createDesc = __webpack_require__(49);
var toIObject = __webpack_require__(24);
var toPrimitive = __webpack_require__(69);
var has = __webpack_require__(27);
var IE8_DOM_DEFINE = __webpack_require__(93);
var gOPD = Object.getOwnPropertyDescriptor;

exports.f = __webpack_require__(22) ? gOPD : function getOwnPropertyDescriptor(O, P) {
  O = toIObject(O);
  P = toPrimitive(P, true);
  if (IE8_DOM_DEFINE) try {
    return gOPD(O, P);
  } catch (e) { /* empty */ }
  if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};


/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {

// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(32);
var IObject = __webpack_require__(71);
var toObject = __webpack_require__(33);
var toLength = __webpack_require__(25);
var asc = __webpack_require__(322);
module.exports = function (TYPE, $create) {
  var IS_MAP = TYPE == 1;
  var IS_FILTER = TYPE == 2;
  var IS_SOME = TYPE == 3;
  var IS_EVERY = TYPE == 4;
  var IS_FIND_INDEX = TYPE == 6;
  var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
  var create = $create || asc;
  return function ($this, callbackfn, that) {
    var O = toObject($this);
    var self = IObject(O);
    var f = ctx(callbackfn, that, 3);
    var length = toLength(self.length);
    var index = 0;
    var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
    var val, res;
    for (;length > index; index++) if (NO_HOLES || index in self) {
      val = self[index];
      res = f(val, index, O);
      if (TYPE) {
        if (IS_MAP) result[index] = res;   // map
        else if (res) switch (TYPE) {
          case 3: return true;             // some
          case 5: return val;              // find
          case 6: return index;            // findIndex
          case 2: result.push(val);        // filter
        } else if (IS_EVERY) return false; // every
      }
    }
    return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
  };
};


/***/ }),
/* 65 */
/***/ (function(module, exports) {

exports.f = Object.getOwnPropertySymbols;


/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var hide = __webpack_require__(31);
var redefine = __webpack_require__(30);
var fails = __webpack_require__(23);
var defined = __webpack_require__(38);
var wks = __webpack_require__(10);

module.exports = function (KEY, length, exec) {
  var SYMBOL = wks(KEY);
  var fns = exec(defined, SYMBOL, ''[KEY]);
  var strfn = fns[0];
  var rxfn = fns[1];
  if (fails(function () {
    var O = {};
    O[SYMBOL] = function () { return 7; };
    return ''[KEY](O) != 7;
  })) {
    redefine(String.prototype, KEY, strfn);
    hide(RegExp.prototype, SYMBOL, length == 2
      // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
      // 21.2.5.11 RegExp.prototype[@@split](string, limit)
      ? function (string, arg) { return rxfn.call(string, this, arg); }
      // 21.2.5.6 RegExp.prototype[@@match](string)
      // 21.2.5.9 RegExp.prototype[@@search](string)
      : function (string) { return rxfn.call(string, this); }
    );
  }
};


/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.DEFAULT_LANGUAGE_CODE = exports.getLanguagesDictionaries = exports.getDefaultLanguageDictionary = exports.hasLanguageDictionary = exports.getLanguageDictionary = exports.registerLanguageDictionary = undefined;

var _object = __webpack_require__(1);

var _utils = __webpack_require__(312);

var _staticRegister2 = __webpack_require__(46);

var _staticRegister3 = _interopRequireDefault(_staticRegister2);

var _enUS = __webpack_require__(384);

var _enUS2 = _interopRequireDefault(_enUS);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var DEFAULT_LANGUAGE_CODE = _enUS2.default.languageCode;

var _staticRegister = (0, _staticRegister3.default)('languagesDictionaries'),
    registerGloballyLanguageDictionary = _staticRegister.register,
    getGlobalLanguageDictionary = _staticRegister.getItem,
    hasGlobalLanguageDictionary = _staticRegister.hasItem,
    getGlobalLanguagesDictionaries = _staticRegister.getValues;

/**
 * Register language dictionary for specific language code.
 *
 * @param {String|Object} languageCodeOrDictionary Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE' or object representing dictionary.
 * @param {Object} dictionary Dictionary for specific language (optional if first parameter has already dictionary).
 */


function registerLanguage(languageCodeOrDictionary, dictionary) {
  var languageCode = languageCodeOrDictionary;

  // Dictionary passed as first argument.
  if ((0, _object.isObject)(languageCodeOrDictionary)) {
    dictionary = languageCodeOrDictionary;
    languageCode = dictionary.languageCode;
  }

  extendLanguageDictionary(languageCode, dictionary);
  registerGloballyLanguageDictionary(languageCode, (0, _object.deepClone)(dictionary));

  // We do not allow user to work with dictionary by reference, it can cause lot of bugs.
  return (0, _object.deepClone)(dictionary);
};

/**
 * Get language dictionary for specific language code.
 *
 * @param {String} languageCode Language code.
 * @returns {Object} Object with constants representing identifiers for translation (as keys) and corresponding translation phrases (as values).
 */
function getLanguage(languageCode) {
  if (!hasLanguage(languageCode)) {
    return null;
  }

  return (0, _object.deepClone)(getGlobalLanguageDictionary(languageCode));
}

/**
 *
 * Get if language with specified language code was registered.
 *
 * @param {String} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'.
 * @returns {Boolean}
 */
function hasLanguage(languageCode) {
  return hasGlobalLanguageDictionary(languageCode);
}

/**
 * Get default language dictionary.
 *
 * @returns {Object} Object with constants representing identifiers for translation (as keys) and corresponding translation phrases (as values).
 */
function getDefaultLanguage() {
  return _enUS2.default;
}

/**
 * Extend handled dictionary by default language dictionary. As result, if any dictionary key isn't defined for specific language, it will be filled with default language value ("dictionary gaps" are supplemented).
 *
 * @private
 * @param {String} languageCode Language code.
 * @param {Object} dictionary Dictionary which is extended.
 */
function extendLanguageDictionary(languageCode, dictionary) {
  if (languageCode !== DEFAULT_LANGUAGE_CODE) {
    (0, _utils.extendNotExistingKeys)(dictionary, getGlobalLanguageDictionary(DEFAULT_LANGUAGE_CODE));
  }
}

/**
 * Get registered language dictionaries.
 *
 * @returns {Array}
 */
function getLanguages() {
  return getGlobalLanguagesDictionaries();
}

exports.registerLanguageDictionary = registerLanguage;
exports.getLanguageDictionary = getLanguage;
exports.hasLanguageDictionary = hasLanguage;
exports.getDefaultLanguageDictionary = getDefaultLanguage;
exports.getLanguagesDictionaries = getLanguages;
exports.DEFAULT_LANGUAGE_CODE = DEFAULT_LANGUAGE_CODE;

/**
 * Automatically registers default dictionary.
 */

registerLanguage(_enUS2.default);

/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(5);
var document = __webpack_require__(13).document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
  return is ? document.createElement(it) : {};
};


/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(5);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
  if (!isObject(it)) return it;
  var fn, val;
  if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
  if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  throw TypeError("Can't convert object to primitive value");
};


/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(18);
var dPs = __webpack_require__(319);
var enumBugKeys = __webpack_require__(74);
var IE_PROTO = __webpack_require__(72)('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';

// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
  // Thrash, waste and sodomy: IE GC bug
  var iframe = __webpack_require__(68)('iframe');
  var i = enumBugKeys.length;
  var lt = '<';
  var gt = '>';
  var iframeDocument;
  iframe.style.display = 'none';
  __webpack_require__(96).appendChild(iframe);
  iframe.src = 'javascript:'; // eslint-disable-line no-script-url
  // createDict = iframe.contentWindow.Object;
  // html.removeChild(iframe);
  iframeDocument = iframe.contentWindow.document;
  iframeDocument.open();
  iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
  iframeDocument.close();
  createDict = iframeDocument.F;
  while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
  return createDict();
};

module.exports = Object.create || function create(O, Properties) {
  var result;
  if (O !== null) {
    Empty[PROTOTYPE] = anObject(O);
    result = new Empty();
    Empty[PROTOTYPE] = null;
    // add "__proto__" for Object.getPrototypeOf polyfill
    result[IE_PROTO] = O;
  } else result = createDict();
  return Properties === undefined ? result : dPs(result, Properties);
};


/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {

// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(42);
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
  return cof(it) == 'String' ? it.split('') : Object(it);
};


/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {

var shared = __webpack_require__(73)('keys');
var uid = __webpack_require__(48);
module.exports = function (key) {
  return shared[key] || (shared[key] = uid(key));
};


/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(13);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
module.exports = function (key) {
  return store[key] || (store[key] = {});
};


/***/ }),
/* 74 */
/***/ (function(module, exports) {

// IE 8- don't enum bug keys
module.exports = (
  'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');


/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {

var ITERATOR = __webpack_require__(10)('iterator');
var SAFE_CLOSING = false;

try {
  var riter = [7][ITERATOR]();
  riter['return'] = function () { SAFE_CLOSING = true; };
  // eslint-disable-next-line no-throw-literal
  Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }

module.exports = function (exec, skipClosing) {
  if (!skipClosing && !SAFE_CLOSING) return false;
  var safe = false;
  try {
    var arr = [7];
    var iter = arr[ITERATOR]();
    iter.next = function () { return { done: safe = true }; };
    arr[ITERATOR] = function () { return iter; };
    exec(arr);
  } catch (e) { /* empty */ }
  return safe;
};


/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {

var ctx = __webpack_require__(32);
var invoke = __webpack_require__(325);
var html = __webpack_require__(96);
var cel = __webpack_require__(68);
var global = __webpack_require__(13);
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
  var id = +this;
  // eslint-disable-next-line no-prototype-builtins
  if (queue.hasOwnProperty(id)) {
    var fn = queue[id];
    delete queue[id];
    fn();
  }
};
var listener = function (event) {
  run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!setTask || !clearTask) {
  setTask = function setImmediate(fn) {
    var args = [];
    var i = 1;
    while (arguments.length > i) args.push(arguments[i++]);
    queue[++counter] = function () {
      // eslint-disable-next-line no-new-func
      invoke(typeof fn == 'function' ? fn : Function(fn), args);
    };
    defer(counter);
    return counter;
  };
  clearTask = function clearImmediate(id) {
    delete queue[id];
  };
  // Node.js 0.8-
  if (__webpack_require__(42)(process) == 'process') {
    defer = function (id) {
      process.nextTick(ctx(run, id, 1));
    };
  // Sphere (JS game engine) Dispatch API
  } else if (Dispatch && Dispatch.now) {
    defer = function (id) {
      Dispatch.now(ctx(run, id, 1));
    };
  // Browsers with MessageChannel, includes WebWorkers
  } else if (MessageChannel) {
    channel = new MessageChannel();
    port = channel.port2;
    channel.port1.onmessage = listener;
    defer = ctx(port.postMessage, port, 1);
  // Browsers with postMessage, skip WebWorkers
  // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
  } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
    defer = function (id) {
      global.postMessage(id + '', '*');
    };
    global.addEventListener('message', listener, false);
  // IE8-
  } else if (ONREADYSTATECHANGE in cel('script')) {
    defer = function (id) {
      html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
        html.removeChild(this);
        run.call(id);
      };
    };
  // Rest old browsers
  } else {
    defer = function (id) {
      setTimeout(ctx(run, id, 1), 0);
    };
  }
}
module.exports = {
  set: setTask,
  clear: clearTask
};


/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(94);
var hiddenKeys = __webpack_require__(74).concat('length', 'prototype');

exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  return $keys(O, hiddenKeys);
};


/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {

// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(137);
var defined = __webpack_require__(38);

module.exports = function (that, searchString, NAME) {
  if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
  return String(defined(that));
};


/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {

var MATCH = __webpack_require__(10)('match');
module.exports = function (KEY) {
  var re = /./;
  try {
    '/./'[KEY](re);
  } catch (e) {
    try {
      re[MATCH] = false;
      return !'/./'[KEY](re);
    } catch (f) { /* empty */ }
  } return true;
};


/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var $defineProperty = __webpack_require__(19);
var createDesc = __webpack_require__(49);

module.exports = function (object, index, value) {
  if (index in object) $defineProperty.f(object, index, createDesc(0, value));
  else object[index] = value;
};


/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var addToUnscopables = __webpack_require__(45);
var step = __webpack_require__(103);
var Iterators = __webpack_require__(50);
var toIObject = __webpack_require__(24);

// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(101)(Array, 'Array', function (iterated, kind) {
  this._t = toIObject(iterated); // target
  this._i = 0;                   // next index
  this._k = kind;                // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var kind = this._k;
  var index = this._i++;
  if (!O || index >= O.length) {
    this._t = undefined;
    return step(1);
  }
  if (kind == 'keys') return step(0, index);
  if (kind == 'values') return step(0, O[index]);
  return step(0, [index, O[index]]);
}, 'values');

// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;

addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');


/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _coords = __webpack_require__(53);

var _coords2 = _interopRequireDefault(_coords);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * A cell range is a set of exactly two CellCoords (that can be the same or different)
 *
 * @class CellRange
 */
var CellRange = function () {
  /**
   * @param {CellCoords} highlight Used to draw bold border around a cell where selection was
   *                                          started and to edit the cell when you press Enter
   * @param {CellCoords} from Usually the same as highlight, but in Excel there is distinction - one can change
   *                                     highlight within a selection
   * @param {CellCoords} to End selection
   */
  function CellRange(highlight, from, to) {
    _classCallCheck(this, CellRange);

    this.highlight = highlight;
    this.from = from;
    this.to = to;
  }

  /**
   * Checks if given coords are valid in context of a given Walkontable instance
   *
   * @param {Walkontable} wotInstance
   * @returns {Boolean}
   */


  _createClass(CellRange, [{
    key: 'isValid',
    value: function isValid(wotInstance) {
      return this.from.isValid(wotInstance) && this.to.isValid(wotInstance);
    }

    /**
     * Checks if this cell range is restricted to one cell
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isSingle',
    value: function isSingle() {
      return this.from.row === this.to.row && this.from.col === this.to.col;
    }

    /**
     * Returns selected range height (in number of rows)
     *
     * @returns {Number}
     */

  }, {
    key: 'getHeight',
    value: function getHeight() {
      return Math.max(this.from.row, this.to.row) - Math.min(this.from.row, this.to.row) + 1;
    }

    /**
     * Returns selected range width (in number of columns)
     *
     * @returns {Number}
     */

  }, {
    key: 'getWidth',
    value: function getWidth() {
      return Math.max(this.from.col, this.to.col) - Math.min(this.from.col, this.to.col) + 1;
    }

    /**
     * Checks if given cell coords is within `from` and `to` cell coords of this range
     *
     * @param {CellCoords} cellCoords
     * @returns {Boolean}
     */

  }, {
    key: 'includes',
    value: function includes(cellCoords) {
      var row = cellCoords.row,
          col = cellCoords.col;

      var topLeft = this.getTopLeftCorner();
      var bottomRight = this.getBottomRightCorner();

      return topLeft.row <= row && bottomRight.row >= row && topLeft.col <= col && bottomRight.col >= col;
    }

    /**
     * Checks if given range is within of this range
     *
     * @param {CellRange} testedRange
     * @returns {Boolean}
     */

  }, {
    key: 'includesRange',
    value: function includesRange(testedRange) {
      return this.includes(testedRange.getTopLeftCorner()) && this.includes(testedRange.getBottomRightCorner());
    }

    /**
     * Checks if given range is equal to this range
     *
     * @param {CellRange} testedRange
     * @returns {Boolean}
     */

  }, {
    key: 'isEqual',
    value: function isEqual(testedRange) {
      return Math.min(this.from.row, this.to.row) == Math.min(testedRange.from.row, testedRange.to.row) && Math.max(this.from.row, this.to.row) == Math.max(testedRange.from.row, testedRange.to.row) && Math.min(this.from.col, this.to.col) == Math.min(testedRange.from.col, testedRange.to.col) && Math.max(this.from.col, this.to.col) == Math.max(testedRange.from.col, testedRange.to.col);
    }

    /**
     * Checks if tested range overlaps with the range.
     * Range A is considered to to be overlapping with range B if intersection of A and B or B and A is not empty.
     *
     * @param {CellRange} testedRange
     * @returns {Boolean}
     */

  }, {
    key: 'overlaps',
    value: function overlaps(testedRange) {
      return testedRange.isSouthEastOf(this.getTopLeftCorner()) && testedRange.isNorthWestOf(this.getBottomRightCorner());
    }

    /**
     * @param {CellRange} testedCoords
     * @returns {Boolean}
     */

  }, {
    key: 'isSouthEastOf',
    value: function isSouthEastOf(testedCoords) {
      return this.getTopLeftCorner().isSouthEastOf(testedCoords) || this.getBottomRightCorner().isSouthEastOf(testedCoords);
    }

    /**
     * @param {CellRange} testedCoords
     * @returns {Boolean}
     */

  }, {
    key: 'isNorthWestOf',
    value: function isNorthWestOf(testedCoords) {
      return this.getTopLeftCorner().isNorthWestOf(testedCoords) || this.getBottomRightCorner().isNorthWestOf(testedCoords);
    }

    /**
     * Adds a cell to a range (only if exceeds corners of the range). Returns information if range was expanded
     *
     * @param {CellCoords} cellCoords
     * @returns {Boolean}
     */

  }, {
    key: 'expand',
    value: function expand(cellCoords) {
      var topLeft = this.getTopLeftCorner();
      var bottomRight = this.getBottomRightCorner();

      if (cellCoords.row < topLeft.row || cellCoords.col < topLeft.col || cellCoords.row > bottomRight.row || cellCoords.col > bottomRight.col) {
        this.from = new _coords2.default(Math.min(topLeft.row, cellCoords.row), Math.min(topLeft.col, cellCoords.col));
        this.to = new _coords2.default(Math.max(bottomRight.row, cellCoords.row), Math.max(bottomRight.col, cellCoords.col));

        return true;
      }

      return false;
    }

    /**
     * @param {CellRange} expandingRange
     * @returns {Boolean}
     */

  }, {
    key: 'expandByRange',
    value: function expandByRange(expandingRange) {
      if (this.includesRange(expandingRange) || !this.overlaps(expandingRange)) {
        return false;
      }

      var topLeft = this.getTopLeftCorner();
      var bottomRight = this.getBottomRightCorner();
      var topRight = this.getTopRightCorner();
      var bottomLeft = this.getBottomLeftCorner();

      var expandingTopLeft = expandingRange.getTopLeftCorner();
      var expandingBottomRight = expandingRange.getBottomRightCorner();

      var resultTopRow = Math.min(topLeft.row, expandingTopLeft.row);
      var resultTopCol = Math.min(topLeft.col, expandingTopLeft.col);
      var resultBottomRow = Math.max(bottomRight.row, expandingBottomRight.row);
      var resultBottomCol = Math.max(bottomRight.col, expandingBottomRight.col);

      var finalFrom = new _coords2.default(resultTopRow, resultTopCol),
          finalTo = new _coords2.default(resultBottomRow, resultBottomCol);
      var isCorner = new CellRange(finalFrom, finalFrom, finalTo).isCorner(this.from, expandingRange),
          onlyMerge = expandingRange.isEqual(new CellRange(finalFrom, finalFrom, finalTo));

      if (isCorner && !onlyMerge) {
        if (this.from.col > finalFrom.col) {
          finalFrom.col = resultBottomCol;
          finalTo.col = resultTopCol;
        }
        if (this.from.row > finalFrom.row) {
          finalFrom.row = resultBottomRow;
          finalTo.row = resultTopRow;
        }
      }
      this.from = finalFrom;
      this.to = finalTo;

      return true;
    }

    /**
     * @returns {String}
     */

  }, {
    key: 'getDirection',
    value: function getDirection() {
      if (this.from.isNorthWestOf(this.to)) {
        // NorthWest - SouthEast
        return 'NW-SE';
      } else if (this.from.isNorthEastOf(this.to)) {
        // NorthEast - SouthWest
        return 'NE-SW';
      } else if (this.from.isSouthEastOf(this.to)) {
        // SouthEast - NorthWest
        return 'SE-NW';
      } else if (this.from.isSouthWestOf(this.to)) {
        // SouthWest - NorthEast
        return 'SW-NE';
      }
    }

    /**
     * @param {String} direction
     */

  }, {
    key: 'setDirection',
    value: function setDirection(direction) {
      switch (direction) {
        case 'NW-SE':
          var _ref = [this.getTopLeftCorner(), this.getBottomRightCorner()];
          this.from = _ref[0];
          this.to = _ref[1];

          break;
        case 'NE-SW':
          var _ref2 = [this.getTopRightCorner(), this.getBottomLeftCorner()];
          this.from = _ref2[0];
          this.to = _ref2[1];

          break;
        case 'SE-NW':
          var _ref3 = [this.getBottomRightCorner(), this.getTopLeftCorner()];
          this.from = _ref3[0];
          this.to = _ref3[1];

          break;
        case 'SW-NE':
          var _ref4 = [this.getBottomLeftCorner(), this.getTopRightCorner()];
          this.from = _ref4[0];
          this.to = _ref4[1];

          break;
        default:
          break;
      }
    }

    /**
     * Get top left corner of this range
     *
     * @returns {CellCoords}
     */

  }, {
    key: 'getTopLeftCorner',
    value: function getTopLeftCorner() {
      return new _coords2.default(Math.min(this.from.row, this.to.row), Math.min(this.from.col, this.to.col));
    }

    /**
     * Get bottom right corner of this range
     *
     * @returns {CellCoords}
     */

  }, {
    key: 'getBottomRightCorner',
    value: function getBottomRightCorner() {
      return new _coords2.default(Math.max(this.from.row, this.to.row), Math.max(this.from.col, this.to.col));
    }

    /**
     * Get top right corner of this range
     *
     * @returns {CellCoords}
     */

  }, {
    key: 'getTopRightCorner',
    value: function getTopRightCorner() {
      return new _coords2.default(Math.min(this.from.row, this.to.row), Math.max(this.from.col, this.to.col));
    }

    /**
     * Get bottom left corner of this range
     *
     * @returns {CellCoords}
     */

  }, {
    key: 'getBottomLeftCorner',
    value: function getBottomLeftCorner() {
      return new _coords2.default(Math.max(this.from.row, this.to.row), Math.min(this.from.col, this.to.col));
    }

    /**
     * @param {CellCoords} coords
     * @param {CellRange} expandedRange
     * @returns {*}
     */

  }, {
    key: 'isCorner',
    value: function isCorner(coords, expandedRange) {
      if (expandedRange) {
        if (expandedRange.includes(coords)) {
          if (this.getTopLeftCorner().isEqual(new _coords2.default(expandedRange.from.row, expandedRange.from.col)) || this.getTopRightCorner().isEqual(new _coords2.default(expandedRange.from.row, expandedRange.to.col)) || this.getBottomLeftCorner().isEqual(new _coords2.default(expandedRange.to.row, expandedRange.from.col)) || this.getBottomRightCorner().isEqual(new _coords2.default(expandedRange.to.row, expandedRange.to.col))) {
            return true;
          }
        }
      }

      return coords.isEqual(this.getTopLeftCorner()) || coords.isEqual(this.getTopRightCorner()) || coords.isEqual(this.getBottomLeftCorner()) || coords.isEqual(this.getBottomRightCorner());
    }

    /**
     * @param {CellCoords} coords
     * @param {CellRange} expandedRange
     * @returns {CellCoords}
     */

  }, {
    key: 'getOppositeCorner',
    value: function getOppositeCorner(coords, expandedRange) {
      if (!(coords instanceof _coords2.default)) {
        return false;
      }

      if (expandedRange) {
        if (expandedRange.includes(coords)) {
          if (this.getTopLeftCorner().isEqual(new _coords2.default(expandedRange.from.row, expandedRange.from.col))) {
            return this.getBottomRightCorner();
          }
          if (this.getTopRightCorner().isEqual(new _coords2.default(expandedRange.from.row, expandedRange.to.col))) {
            return this.getBottomLeftCorner();
          }
          if (this.getBottomLeftCorner().isEqual(new _coords2.default(expandedRange.to.row, expandedRange.from.col))) {
            return this.getTopRightCorner();
          }
          if (this.getBottomRightCorner().isEqual(new _coords2.default(expandedRange.to.row, expandedRange.to.col))) {
            return this.getTopLeftCorner();
          }
        }
      }

      if (coords.isEqual(this.getBottomRightCorner())) {
        return this.getTopLeftCorner();
      } else if (coords.isEqual(this.getTopLeftCorner())) {
        return this.getBottomRightCorner();
      } else if (coords.isEqual(this.getTopRightCorner())) {
        return this.getBottomLeftCorner();
      } else if (coords.isEqual(this.getBottomLeftCorner())) {
        return this.getTopRightCorner();
      }
    }

    /**
     * @param {CellRange} range
     * @returns {Array}
     */

  }, {
    key: 'getBordersSharedWith',
    value: function getBordersSharedWith(range) {
      if (!this.includesRange(range)) {
        return [];
      }

      var thisBorders = {
        top: Math.min(this.from.row, this.to.row),
        bottom: Math.max(this.from.row, this.to.row),
        left: Math.min(this.from.col, this.to.col),
        right: Math.max(this.from.col, this.to.col)
      };
      var rangeBorders = {
        top: Math.min(range.from.row, range.to.row),
        bottom: Math.max(range.from.row, range.to.row),
        left: Math.min(range.from.col, range.to.col),
        right: Math.max(range.from.col, range.to.col)
      };
      var result = [];

      if (thisBorders.top == rangeBorders.top) {
        result.push('top');
      }
      if (thisBorders.right == rangeBorders.right) {
        result.push('right');
      }
      if (thisBorders.bottom == rangeBorders.bottom) {
        result.push('bottom');
      }
      if (thisBorders.left == rangeBorders.left) {
        result.push('left');
      }

      return result;
    }

    /**
     * Get inner selected cell coords defined by this range
     *
     * @returns {Array}
     */

  }, {
    key: 'getInner',
    value: function getInner() {
      var topLeft = this.getTopLeftCorner();
      var bottomRight = this.getBottomRightCorner();
      var out = [];

      for (var r = topLeft.row; r <= bottomRight.row; r++) {
        for (var c = topLeft.col; c <= bottomRight.col; c++) {
          if (!(this.from.row === r && this.from.col === c) && !(this.to.row === r && this.to.col === c)) {
            out.push(new _coords2.default(r, c));
          }
        }
      }
      return out;
    }

    /**
     * Get all selected cell coords defined by this range
     *
     * @returns {Array}
     */

  }, {
    key: 'getAll',
    value: function getAll() {
      var topLeft = this.getTopLeftCorner();
      var bottomRight = this.getBottomRightCorner();
      var out = [];

      for (var r = topLeft.row; r <= bottomRight.row; r++) {
        for (var c = topLeft.col; c <= bottomRight.col; c++) {
          if (topLeft.row === r && topLeft.col === c) {
            out.push(topLeft);
          } else if (bottomRight.row === r && bottomRight.col === c) {
            out.push(bottomRight);
          } else {
            out.push(new _coords2.default(r, c));
          }
        }
      }

      return out;
    }

    /**
     * Runs a callback function against all cells in the range. You can break the iteration by returning
     * `false` in the callback function
     *
     * @param callback {Function}
     */

  }, {
    key: 'forAll',
    value: function forAll(callback) {
      var topLeft = this.getTopLeftCorner();
      var bottomRight = this.getBottomRightCorner();

      for (var r = topLeft.row; r <= bottomRight.row; r++) {
        for (var c = topLeft.col; c <= bottomRight.col; c++) {
          var breakIteration = callback(r, c);

          if (breakIteration === false) {
            return;
          }
        }
      }
    }
  }]);

  return CellRange;
}();

exports.default = CellRange;

/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.getRegisteredCellTypes = exports.getRegisteredCellTypeNames = exports.hasCellType = exports.getCellType = exports.registerCellType = undefined;

var _staticRegister2 = __webpack_require__(46);

var _staticRegister3 = _interopRequireDefault(_staticRegister2);

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var _autocompleteType = __webpack_require__(369);

var _autocompleteType2 = _interopRequireDefault(_autocompleteType);

var _checkboxType = __webpack_require__(370);

var _checkboxType2 = _interopRequireDefault(_checkboxType);

var _dateType = __webpack_require__(371);

var _dateType2 = _interopRequireDefault(_dateType);

var _dropdownType = __webpack_require__(372);

var _dropdownType2 = _interopRequireDefault(_dropdownType);

var _handsontableType = __webpack_require__(373);

var _handsontableType2 = _interopRequireDefault(_handsontableType);

var _numericType = __webpack_require__(374);

var _numericType2 = _interopRequireDefault(_numericType);

var _passwordType = __webpack_require__(375);

var _passwordType2 = _interopRequireDefault(_passwordType);

var _textType = __webpack_require__(376);

var _textType2 = _interopRequireDefault(_textType);

var _timeType = __webpack_require__(377);

var _timeType2 = _interopRequireDefault(_timeType);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _staticRegister = (0, _staticRegister3.default)('cellTypes'),
    register = _staticRegister.register,
    getItem = _staticRegister.getItem,
    hasItem = _staticRegister.hasItem,
    getNames = _staticRegister.getNames,
    getValues = _staticRegister.getValues;

_register('autocomplete', _autocompleteType2.default);
_register('checkbox', _checkboxType2.default);
_register('date', _dateType2.default);
_register('dropdown', _dropdownType2.default);
_register('handsontable', _handsontableType2.default);
_register('numeric', _numericType2.default);
_register('password', _passwordType2.default);
_register('text', _textType2.default);
_register('time', _timeType2.default);

/**
 * Retrieve cell type object.
 *
 * @param {String} name Cell type identification.
 * @returns {Object} Returns cell type object.
 */
function _getItem(name) {
  if (!hasItem(name)) {
    throw Error('You declared cell type "' + name + '" as a string that is not mapped to a known object.\n                 Cell type must be an object or a string mapped to an object registered by "Handsontable.cellTypes.registerCellType" method');
  }

  return getItem(name);
}

/**
 * Register cell type under specified name.
 *
 * @param {String} name Cell type identification.
 * @param {Object} type An object with contains keys (eq: `editor`, `renderer`, `validator`) which describes specified behaviour of the cell.
 */
function _register(name, type) {
  var editor = type.editor,
      renderer = type.renderer,
      validator = type.validator;


  if (editor) {
    (0, _editors.registerEditor)(name, editor);
  }
  if (renderer) {
    (0, _renderers.registerRenderer)(name, renderer);
  }
  if (validator) {
    (0, _validators.registerValidator)(name, validator);
  }

  register(name, type);
}

exports.registerCellType = _register;
exports.getCellType = _getItem;
exports.hasCellType = hasItem;
exports.getRegisteredCellTypeNames = getNames;
exports.getRegisteredCellTypes = getValues;

/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.default = Core;

var _element = __webpack_require__(0);

var _setting = __webpack_require__(85);

var _function = __webpack_require__(41);

var _mixed = __webpack_require__(17);

var _browser = __webpack_require__(28);

var _dataMap = __webpack_require__(378);

var _dataMap2 = _interopRequireDefault(_dataMap);

var _editorManager = __webpack_require__(381);

var _editorManager2 = _interopRequireDefault(_editorManager);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _object = __webpack_require__(1);

var _array = __webpack_require__(2);

var _plugins = __webpack_require__(7);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var _string = __webpack_require__(36);

var _number = __webpack_require__(6);

var _tableView = __webpack_require__(382);

var _tableView2 = _interopRequireDefault(_tableView);

var _dataSource = __webpack_require__(383);

var _dataSource2 = _interopRequireDefault(_dataSource);

var _data = __webpack_require__(86);

var _recordTranslator = __webpack_require__(308);

var _rootInstance = __webpack_require__(309);

var _src = __webpack_require__(15);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _defaultSettings = __webpack_require__(310);

var _defaultSettings2 = _interopRequireDefault(_defaultSettings);

var _cellTypes = __webpack_require__(83);

var _i18n = __webpack_require__(311);

var _dictionariesManager = __webpack_require__(67);

var _utils = __webpack_require__(312);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var activeGuid = null;

/**
 * Handsontable constructor
 *
 * @core
 * @constructor Core
 * @description
 *
 * After Handsontable is constructed, you can modify the grid behavior using the available public methods.
 *
 * ---
 * ## How to call methods
 *
 * These are 2 equal ways to call a Handsontable method:
 *
 * ```js
 * // all following examples assume that you constructed Handsontable like this
 * var ht = new Handsontable(document.getElementById('example1'), options);
 *
 * // now, to use setDataAtCell method, you can either:
 * ht.setDataAtCell(0, 0, 'new value');
 * ```
 *
 * Alternatively, you can call the method using jQuery wrapper (__obsolete__, requires initialization using our jQuery guide
 * ```js
 *   $('#example1').handsontable('setDataAtCell', 0, 0, 'new value');
 * ```
 * ---
 */
function Core(rootElement, userSettings) {
  var rootInstanceSymbol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

  var priv,
      datamap,
      dataSource,
      grid,
      selection,
      editorManager,
      instance = this,
      GridSettings = function GridSettings() {},
      eventManager = new _eventManager2.default(instance);

  (0, _object.extend)(GridSettings.prototype, _defaultSettings2.default.prototype); // create grid settings as a copy of default settings
  (0, _object.extend)(GridSettings.prototype, userSettings); // overwrite defaults with user settings
  (0, _object.extend)(GridSettings.prototype, expandType(userSettings));

  (0, _utils.applyLanguageSetting)(GridSettings.prototype, userSettings.language);

  if ((0, _rootInstance.hasValidParameter)(rootInstanceSymbol)) {
    (0, _rootInstance.registerAsRootInstance)(this);
  }

  this.rootElement = rootElement;
  this.isHotTableEnv = (0, _element.isChildOfWebComponentTable)(this.rootElement);
  _eventManager2.default.isHotTableEnv = this.isHotTableEnv;

  this.container = document.createElement('div');
  this.renderCall = false;

  rootElement.insertBefore(this.container, rootElement.firstChild);

  if (false) {
    (0, _mixed._injectProductInfo)(userSettings.licenseKey, rootElement);
  }

  this.guid = 'ht_' + (0, _string.randomString)(); // this is the namespace for global events

  var recordTranslator = (0, _recordTranslator.getTranslator)(instance);

  dataSource = new _dataSource2.default(instance);

  if (!this.rootElement.id || this.rootElement.id.substring(0, 3) === 'ht_') {
    this.rootElement.id = this.guid; // if root element does not have an id, assign a random id
  }
  priv = {
    cellSettings: [],
    columnSettings: [],
    columnsSettingConflicts: ['data', 'width', 'language'],
    settings: new GridSettings(), // current settings instance
    selRange: null, // exposed by public method `getSelectedRange`
    isPopulated: null,
    scrollable: null,
    firstRun: true
  };

  grid = {
    /**
     * Inserts or removes rows and columns
     *
     * @memberof Core#
     * @function alter
     * @private
     * @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col"
     * @param {Number} index
     * @param {Number} amount
     * @param {String} [source] Optional. Source of hook runner.
     * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
     */
    alter: function alter(action, index, amount, source, keepEmptyRows) {
      var delta;

      amount = amount || 1;

      function spliceWith(data, index, count, toInject) {
        var valueFactory = function valueFactory() {
          var result = void 0;

          if (toInject === 'array') {
            result = [];
          } else if (toInject === 'object') {
            result = {};
          }

          return result;
        };
        var spliceArgs = (0, _array.arrayMap)(new Array(count), function () {
          return valueFactory();
        });

        spliceArgs.unshift(index, 0);
        data.splice.apply(data, _toConsumableArray(spliceArgs));
      }

      /* eslint-disable no-case-declarations */
      switch (action) {
        case 'insert_row':

          var numberOfSourceRows = instance.countSourceRows();

          if (instance.getSettings().maxRows === numberOfSourceRows) {
            return;
          }

          index = (0, _mixed.isDefined)(index) ? index : numberOfSourceRows;

          delta = datamap.createRow(index, amount, source);
          spliceWith(priv.cellSettings, index, amount, 'array');

          if (delta) {
            if (selection.isSelected() && priv.selRange.from.row >= index) {
              priv.selRange.from.row += delta;
              selection.transformEnd(delta, 0); // will call render() internally
            } else {
              selection.refreshBorders(); // it will call render and prepare methods
            }
          }
          break;

        case 'insert_col':
          delta = datamap.createCol(index, amount, source);

          for (var row = 0, len = instance.countSourceRows(); row < len; row++) {
            if (priv.cellSettings[row]) {
              spliceWith(priv.cellSettings[row], index, amount);
            }
          }

          if (delta) {
            if (Array.isArray(instance.getSettings().colHeaders)) {
              var spliceArray = [index, 0];
              spliceArray.length += delta; // inserts empty (undefined) elements at the end of an array
              Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); // inserts empty (undefined) elements into the colHeader array
            }

            if (selection.isSelected() && priv.selRange.from.col >= index) {
              priv.selRange.from.col += delta;
              selection.transformEnd(0, delta); // will call render() internally
            } else {
              selection.refreshBorders(); // it will call render and prepare methods
            }
          }
          break;

        case 'remove_row':
          datamap.removeRow(index, amount, source);
          priv.cellSettings.splice(index, amount);

          var totalRows = instance.countRows();
          var fixedRowsTop = instance.getSettings().fixedRowsTop;
          if (fixedRowsTop >= index + 1) {
            instance.getSettings().fixedRowsTop -= Math.min(amount, fixedRowsTop - index);
          }

          var fixedRowsBottom = instance.getSettings().fixedRowsBottom;
          if (fixedRowsBottom && index >= totalRows - fixedRowsBottom) {
            instance.getSettings().fixedRowsBottom -= Math.min(amount, fixedRowsBottom);
          }

          grid.adjustRowsAndCols();
          selection.refreshBorders(); // it will call render and prepare methods
          break;

        case 'remove_col':
          var visualColumnIndex = recordTranslator.toPhysicalColumn(index);

          datamap.removeCol(index, amount, source);

          for (var _row = 0, _len = instance.countSourceRows(); _row < _len; _row++) {
            if (priv.cellSettings[_row]) {
              // if row hasn't been rendered it wouldn't have cellSettings
              priv.cellSettings[_row].splice(visualColumnIndex, amount);
            }
          }
          var fixedColumnsLeft = instance.getSettings().fixedColumnsLeft;

          if (fixedColumnsLeft >= index + 1) {
            instance.getSettings().fixedColumnsLeft -= Math.min(amount, fixedColumnsLeft - index);
          }

          if (Array.isArray(instance.getSettings().colHeaders)) {
            if (typeof visualColumnIndex === 'undefined') {
              visualColumnIndex = -1;
            }
            instance.getSettings().colHeaders.splice(visualColumnIndex, amount);
          }

          grid.adjustRowsAndCols();
          selection.refreshBorders(); // it will call render and prepare methods

          break;
        default:
          throw new Error('There is no such action "' + action + '"');
      }

      if (!keepEmptyRows) {
        grid.adjustRowsAndCols(); // makes sure that we did not add rows that will be removed in next refresh
      }
    },


    /**
     * Makes sure there are empty rows at the bottom of the table
     */
    adjustRowsAndCols: function adjustRowsAndCols() {
      if (priv.settings.minRows) {
        // should I add empty rows to data source to meet minRows?
        var rows = instance.countRows();

        if (rows < priv.settings.minRows) {
          for (var r = 0, minRows = priv.settings.minRows; r < minRows - rows; r++) {
            datamap.createRow(instance.countRows(), 1, 'auto');
          }
        }
      }
      if (priv.settings.minSpareRows) {
        var emptyRows = instance.countEmptyRows(true);

        // should I add empty rows to meet minSpareRows?
        if (emptyRows < priv.settings.minSpareRows) {
          for (; emptyRows < priv.settings.minSpareRows && instance.countSourceRows() < priv.settings.maxRows; emptyRows++) {
            datamap.createRow(instance.countRows(), 1, 'auto');
          }
        }
      }
      {
        var emptyCols = void 0;

        // count currently empty cols
        if (priv.settings.minCols || priv.settings.minSpareCols) {
          emptyCols = instance.countEmptyCols(true);
        }

        // should I add empty cols to meet minCols?
        if (priv.settings.minCols && !priv.settings.columns && instance.countCols() < priv.settings.minCols) {
          for (; instance.countCols() < priv.settings.minCols; emptyCols++) {
            datamap.createCol(instance.countCols(), 1, 'auto');
          }
        }
        // should I add empty cols to meet minSpareCols?
        if (priv.settings.minSpareCols && !priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) {
          for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) {
            datamap.createCol(instance.countCols(), 1, 'auto');
          }
        }
      }
      var rowCount = instance.countRows();
      var colCount = instance.countCols();

      if (rowCount === 0 || colCount === 0) {
        selection.deselect();
      }

      if (selection.isSelected()) {
        var selectionChanged = false;
        var fromRow = priv.selRange.from.row;
        var fromCol = priv.selRange.from.col;
        var toRow = priv.selRange.to.row;
        var toCol = priv.selRange.to.col;

        // if selection is outside, move selection to last row
        if (fromRow > rowCount - 1) {
          fromRow = rowCount - 1;
          selectionChanged = true;

          if (toRow > fromRow) {
            toRow = fromRow;
          }
        } else if (toRow > rowCount - 1) {
          toRow = rowCount - 1;
          selectionChanged = true;

          if (fromRow > toRow) {
            fromRow = toRow;
          }
        }
        // if selection is outside, move selection to last row
        if (fromCol > colCount - 1) {
          fromCol = colCount - 1;
          selectionChanged = true;

          if (toCol > fromCol) {
            toCol = fromCol;
          }
        } else if (toCol > colCount - 1) {
          toCol = colCount - 1;
          selectionChanged = true;

          if (fromCol > toCol) {
            fromCol = toCol;
          }
        }

        if (selectionChanged) {
          instance.selectCell(fromRow, fromCol, toRow, toCol);
        }
      }
      if (instance.view) {
        instance.view.wt.wtOverlays.adjustElementsSize();
      }
    },


    /**
     * Populate the data from the provided 2d array from the given cell coordinates.
     *
     * @private
     * @param {Object} start Start selection position. Visual indexes.
     * @param {Array} input 2d data array.
     * @param {Object} [end] End selection position (only for drag-down mode). Visual indexes.
     * @param {String} [source="populateFromArray"] Source information string.
     * @param {String} [method="overwrite"] Populate method. Possible options: `shift_down`, `shift_right`, `overwrite`.
     * @param {String} direction (left|right|up|down) String specifying the direction.
     * @param {Array} deltas The deltas array. A difference between values of adjacent cells.
     *                       Useful **only** when the type of handled cells is `numeric`.
     * @returns {Object|undefined} ending td in pasted area (only if any cell was changed).
     */
    populateFromArray: function populateFromArray(start, input, end, source, method, direction, deltas) {
      // TODO: either remove or implement the `direction` argument. Currently it's not working at all.
      var r,
          rlen,
          c,
          clen,
          setData = [],
          current = {};

      rlen = input.length;

      if (rlen === 0) {
        return false;
      }

      var repeatCol,
          repeatRow,
          cmax,
          rmax,
          baseEnd = {
        row: end === null ? null : end.row,
        col: end === null ? null : end.col
      };

      /* eslint-disable no-case-declarations */
      // insert data with specified pasteMode method
      switch (method) {
        case 'shift_down':
          repeatCol = end ? end.col - start.col + 1 : 0;
          repeatRow = end ? end.row - start.row + 1 : 0;
          input = (0, _data.translateRowsToColumns)(input);
          for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) {
            if (c < clen) {
              var _instance;

              for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) {
                input[c].push(input[c][r % rlen]);
              }
              input[c].unshift(start.col + c, start.row, 0);
              (_instance = instance).spliceCol.apply(_instance, _toConsumableArray(input[c]));
            } else {
              var _instance2;

              input[c % clen][0] = start.col + c;
              (_instance2 = instance).spliceCol.apply(_instance2, _toConsumableArray(input[c % clen]));
            }
          }
          break;

        case 'shift_right':
          repeatCol = end ? end.col - start.col + 1 : 0;
          repeatRow = end ? end.row - start.row + 1 : 0;
          for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) {
            if (r < rlen) {
              var _instance3;

              for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) {
                input[r].push(input[r][c % clen]);
              }
              input[r].unshift(start.row + r, start.col, 0);
              (_instance3 = instance).spliceRow.apply(_instance3, _toConsumableArray(input[r]));
            } else {
              var _instance4;

              input[r % rlen][0] = start.row + r;
              (_instance4 = instance).spliceRow.apply(_instance4, _toConsumableArray(input[r % rlen]));
            }
          }
          break;

        case 'overwrite':
        default:
          // overwrite and other not specified options
          current.row = start.row;
          current.col = start.col;

          var selected = { // selected range
            row: end && start ? end.row - start.row + 1 : 1,
            col: end && start ? end.col - start.col + 1 : 1
          };
          var skippedRow = 0;
          var skippedColumn = 0;
          var pushData = true;
          var cellMeta = void 0;

          var getInputValue = function getInputValue(row) {
            var col = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

            var rowValue = input[row % input.length];

            if (col !== null) {
              return rowValue[col % rowValue.length];
            }

            return rowValue;
          };
          var rowInputLength = input.length;
          var rowSelectionLength = end ? end.row - start.row + 1 : 0;

          if (end) {
            rlen = rowSelectionLength;
          } else {
            rlen = Math.max(rowInputLength, rowSelectionLength);
          }
          for (r = 0; r < rlen; r++) {
            if (end && current.row > end.row && rowSelectionLength > rowInputLength || !priv.settings.allowInsertRow && current.row > instance.countRows() - 1 || current.row >= priv.settings.maxRows) {
              break;
            }
            var visualRow = r - skippedRow;
            var colInputLength = getInputValue(visualRow).length;
            var colSelectionLength = end ? end.col - start.col + 1 : 0;

            if (end) {
              clen = colSelectionLength;
            } else {
              clen = Math.max(colInputLength, colSelectionLength);
            }
            current.col = start.col;
            cellMeta = instance.getCellMeta(current.row, current.col);

            if ((source === 'CopyPaste.paste' || source === 'Autofill.autofill') && cellMeta.skipRowOnPaste) {
              skippedRow++;
              current.row++;
              rlen++;
              /* eslint-disable no-continue */
              continue;
            }
            skippedColumn = 0;

            for (c = 0; c < clen; c++) {
              if (end && current.col > end.col && colSelectionLength > colInputLength || !priv.settings.allowInsertColumn && current.col > instance.countCols() - 1 || current.col >= priv.settings.maxCols) {
                break;
              }
              cellMeta = instance.getCellMeta(current.row, current.col);

              if ((source === 'CopyPaste.paste' || source === 'Autofill.fill') && cellMeta.skipColumnOnPaste) {
                skippedColumn++;
                current.col++;
                clen++;
                continue;
              }
              if (cellMeta.readOnly) {
                current.col++;
                /* eslint-disable no-continue */
                continue;
              }
              var visualColumn = c - skippedColumn;
              var value = getInputValue(visualRow, visualColumn);
              var orgValue = instance.getDataAtCell(current.row, current.col);
              var index = {
                row: visualRow,
                col: visualColumn
              };

              if (source === 'Autofill.fill') {
                var result = instance.runHooks('beforeAutofillInsidePopulate', index, direction, input, deltas, {}, selected);

                if (result) {
                  value = (0, _mixed.isUndefined)(result.value) ? value : result.value;
                }
              }
              if (value !== null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
                if (orgValue === null || (typeof orgValue === 'undefined' ? 'undefined' : _typeof(orgValue)) !== 'object') {
                  pushData = false;
                } else {
                  var orgValueSchema = (0, _object.duckSchema)(orgValue[0] || orgValue);
                  var valueSchema = (0, _object.duckSchema)(value[0] || value);

                  /* eslint-disable max-depth */
                  if ((0, _object.isObjectEquals)(orgValueSchema, valueSchema)) {
                    value = (0, _object.deepClone)(value);
                  } else {
                    pushData = false;
                  }
                }
              } else if (orgValue !== null && (typeof orgValue === 'undefined' ? 'undefined' : _typeof(orgValue)) === 'object') {
                pushData = false;
              }
              if (pushData) {
                setData.push([current.row, current.col, value]);
              }
              pushData = true;
              current.col++;
            }
            current.row++;
          }
          instance.setDataAtCell(setData, null, null, source || 'populateFromArray');
          break;
      }
    }
  };

  /* eslint-disable no-multi-assign */
  this.selection = selection = { // this public assignment is only temporary
    inProgress: false,

    selectedHeader: {
      cols: false,
      rows: false
    },

    /**
     * @param {Boolean} [rows=false]
     * @param {Boolean} [cols=false]
     * @param {Boolean} [corner=false]
     */
    setSelectedHeaders: function setSelectedHeaders() {
      var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var cols = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      var corner = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

      instance.selection.selectedHeader.rows = rows;
      instance.selection.selectedHeader.cols = cols;
      instance.selection.selectedHeader.corner = corner;
    },


    /**
     * Sets inProgress to `true`. This enables onSelectionEnd and onSelectionEndByProp to function as desired.
     */
    begin: function begin() {
      instance.selection.inProgress = true;
    },


    /**
     * Sets inProgress to `false`. Triggers onSelectionEnd and onSelectionEndByProp.
     */
    finish: function finish() {
      var sel = instance.getSelected();
      instance.runHooks('afterSelectionEnd', sel[0], sel[1], sel[2], sel[3]);
      instance.runHooks('afterSelectionEndByProp', sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3]));
      instance.selection.inProgress = false;
    },


    /**
     * @returns {Boolean}
     */
    isInProgress: function isInProgress() {
      return instance.selection.inProgress;
    },


    /**
     * Starts selection range on given td object.
     *
     * @param {CellCoords} coords Visual coords.
     * @param keepEditorOpened
     */
    setRangeStart: function setRangeStart(coords, keepEditorOpened) {
      instance.runHooks('beforeSetRangeStart', coords);
      priv.selRange = new _src.CellRange(coords, coords, coords);
      selection.setRangeEnd(coords, null, keepEditorOpened);
    },


    /**
     * Starts selection range on given td object.
     *
     * @param {CellCoords} coords Visual coords.
     * @param keepEditorOpened
     */
    setRangeStartOnly: function setRangeStartOnly(coords) {
      instance.runHooks('beforeSetRangeStartOnly', coords);
      priv.selRange = new _src.CellRange(coords, coords, coords);
    },


    /**
     * Ends selection range on given td object.
     *
     * @param {CellCoords} coords Visual coords.
     * @param {Boolean} [scrollToCell=true] If `true`, viewport will be scrolled to range end
     * @param {Boolean} [keepEditorOpened] If `true`, cell editor will be still opened after changing selection range
     */
    setRangeEnd: function setRangeEnd(coords, scrollToCell, keepEditorOpened) {
      if (priv.selRange === null) {
        return;
      }
      var disableVisualSelection,
          isHeaderSelected = false,
          areCoordsPositive = true;

      var firstVisibleRow = instance.view.wt.wtTable.getFirstVisibleRow();
      var firstVisibleColumn = instance.view.wt.wtTable.getFirstVisibleColumn();
      var newRangeCoords = {
        row: null,
        col: null
      };

      // trigger handlers
      instance.runHooks('beforeSetRangeEnd', coords);
      instance.selection.begin();

      newRangeCoords.row = coords.row < 0 ? firstVisibleRow : coords.row;
      newRangeCoords.col = coords.col < 0 ? firstVisibleColumn : coords.col;

      priv.selRange.to = new _src.CellCoords(newRangeCoords.row, newRangeCoords.col);

      if (!priv.settings.multiSelect) {
        priv.selRange.from = coords;
      }
      // set up current selection
      instance.view.wt.selections.current.clear();

      disableVisualSelection = instance.getCellMeta(priv.selRange.highlight.row, priv.selRange.highlight.col).disableVisualSelection;

      if (typeof disableVisualSelection === 'string') {
        disableVisualSelection = [disableVisualSelection];
      }

      if (disableVisualSelection === false || Array.isArray(disableVisualSelection) && disableVisualSelection.indexOf('current') === -1) {
        instance.view.wt.selections.current.add(priv.selRange.highlight);
      }
      // set up area selection
      instance.view.wt.selections.area.clear();

      if ((disableVisualSelection === false || Array.isArray(disableVisualSelection) && disableVisualSelection.indexOf('area') === -1) && selection.isMultiple()) {
        instance.view.wt.selections.area.add(priv.selRange.from);
        instance.view.wt.selections.area.add(priv.selRange.to);
      }
      // set up highlight
      if (priv.settings.currentHeaderClassName || priv.settings.currentRowClassName || priv.settings.currentColClassName) {
        instance.view.wt.selections.highlight.clear();
        instance.view.wt.selections.highlight.add(priv.selRange.from);
        instance.view.wt.selections.highlight.add(priv.selRange.to);
      }

      var preventScrolling = (0, _object.createObjectPropListener)('value');

      // trigger handlers
      instance.runHooks('afterSelection', priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col, preventScrolling);
      instance.runHooks('afterSelectionByProp', priv.selRange.from.row, datamap.colToProp(priv.selRange.from.col), priv.selRange.to.row, datamap.colToProp(priv.selRange.to.col), preventScrolling);

      if (instance.selection.selectedHeader.cols || instance.selection.selectedHeader.rows) {
        isHeaderSelected = true;
      }

      if (coords.row < 0 || coords.col < 0) {
        areCoordsPositive = false;
      }

      if (preventScrolling.isTouched()) {
        scrollToCell = !preventScrolling.value;
      }

      if (scrollToCell !== false && !isHeaderSelected && areCoordsPositive) {
        if (priv.selRange.from && !selection.isMultiple()) {
          instance.view.scrollViewport(priv.selRange.from);
        } else {
          instance.view.scrollViewport(coords);
        }
      }

      if (selection.selectedHeader.rows && selection.selectedHeader.cols) {
        (0, _element.addClass)(instance.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
      } else if (selection.selectedHeader.rows) {
        (0, _element.removeClass)(instance.rootElement, 'ht__selection--columns');
        (0, _element.addClass)(instance.rootElement, 'ht__selection--rows');
      } else if (selection.selectedHeader.cols) {
        (0, _element.removeClass)(instance.rootElement, 'ht__selection--rows');
        (0, _element.addClass)(instance.rootElement, 'ht__selection--columns');
      } else {
        (0, _element.removeClass)(instance.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
      }

      selection.refreshBorders(null, keepEditorOpened);
    },


    /**
     * Destroys editor, redraws borders around cells, prepares editor.
     *
     * @param {Boolean} [revertOriginal]
     * @param {Boolean} [keepEditor]
     */
    refreshBorders: function refreshBorders(revertOriginal, keepEditor) {
      if (!keepEditor) {
        editorManager.destroyEditor(revertOriginal);
      }
      instance.view.render();

      if (selection.isSelected() && !keepEditor) {
        editorManager.prepareEditor();
      }
    },


    /**
     * Returns information if we have a multiselection.
     *
     * @returns {Boolean}
     */
    isMultiple: function isMultiple() {
      var isMultiple = !(priv.selRange.to.col === priv.selRange.from.col && priv.selRange.to.row === priv.selRange.from.row),
          modifier = instance.runHooks('afterIsMultipleSelection', isMultiple);

      if (isMultiple) {
        return modifier;
      }
    },


    /**
     * Selects cell relative to current cell (if possible).
     */
    transformStart: function transformStart(rowDelta, colDelta, force, keepEditorOpened) {
      var delta = new _src.CellCoords(rowDelta, colDelta),
          rowTransformDir = 0,
          colTransformDir = 0,
          totalRows,
          totalCols,
          coords,
          fixedRowsBottom;

      instance.runHooks('modifyTransformStart', delta);
      totalRows = instance.countRows();
      totalCols = instance.countCols();
      fixedRowsBottom = instance.getSettings().fixedRowsBottom;

      if (priv.selRange.highlight.row + rowDelta > totalRows - 1) {
        if (force && priv.settings.minSpareRows > 0 && !(fixedRowsBottom && priv.selRange.highlight.row >= totalRows - fixedRowsBottom - 1)) {
          instance.alter('insert_row', totalRows);
          totalRows = instance.countRows();
        } else if (priv.settings.autoWrapCol) {
          delta.row = 1 - totalRows;
          delta.col = priv.selRange.highlight.col + delta.col == totalCols - 1 ? 1 - totalCols : 1;
        }
      } else if (priv.settings.autoWrapCol && priv.selRange.highlight.row + delta.row < 0 && priv.selRange.highlight.col + delta.col >= 0) {
        delta.row = totalRows - 1;
        delta.col = priv.selRange.highlight.col + delta.col == 0 ? totalCols - 1 : -1;
      }

      if (priv.selRange.highlight.col + delta.col > totalCols - 1) {
        if (force && priv.settings.minSpareCols > 0) {
          instance.alter('insert_col', totalCols);
          totalCols = instance.countCols();
        } else if (priv.settings.autoWrapRow) {
          delta.row = priv.selRange.highlight.row + delta.row == totalRows - 1 ? 1 - totalRows : 1;
          delta.col = 1 - totalCols;
        }
      } else if (priv.settings.autoWrapRow && priv.selRange.highlight.col + delta.col < 0 && priv.selRange.highlight.row + delta.row >= 0) {
        delta.row = priv.selRange.highlight.row + delta.row == 0 ? totalRows - 1 : -1;
        delta.col = totalCols - 1;
      }

      coords = new _src.CellCoords(priv.selRange.highlight.row + delta.row, priv.selRange.highlight.col + delta.col);

      if (coords.row < 0) {
        rowTransformDir = -1;
        coords.row = 0;
      } else if (coords.row > 0 && coords.row >= totalRows) {
        rowTransformDir = 1;
        coords.row = totalRows - 1;
      }

      if (coords.col < 0) {
        colTransformDir = -1;
        coords.col = 0;
      } else if (coords.col > 0 && coords.col >= totalCols) {
        colTransformDir = 1;
        coords.col = totalCols - 1;
      }
      instance.runHooks('afterModifyTransformStart', coords, rowTransformDir, colTransformDir);
      selection.setRangeStart(coords, keepEditorOpened);
    },


    /**
     * Sets selection end cell relative to current selection end cell (if possible).
     */
    transformEnd: function transformEnd(rowDelta, colDelta) {
      var delta = new _src.CellCoords(rowDelta, colDelta),
          rowTransformDir = 0,
          colTransformDir = 0,
          totalRows,
          totalCols,
          coords;

      instance.runHooks('modifyTransformEnd', delta);

      totalRows = instance.countRows();
      totalCols = instance.countCols();
      coords = new _src.CellCoords(priv.selRange.to.row + delta.row, priv.selRange.to.col + delta.col);

      if (coords.row < 0) {
        rowTransformDir = -1;
        coords.row = 0;
      } else if (coords.row > 0 && coords.row >= totalRows) {
        rowTransformDir = 1;
        coords.row = totalRows - 1;
      }

      if (coords.col < 0) {
        colTransformDir = -1;
        coords.col = 0;
      } else if (coords.col > 0 && coords.col >= totalCols) {
        colTransformDir = 1;
        coords.col = totalCols - 1;
      }
      instance.runHooks('afterModifyTransformEnd', coords, rowTransformDir, colTransformDir);
      selection.setRangeEnd(coords, true);
    },


    /**
     * Returns `true` if currently there is a selection on screen, `false` otherwise.
     *
     * @returns {Boolean}
     */
    isSelected: function isSelected() {
      return priv.selRange !== null;
    },


    /**
     * Returns `true` if coords is within current selection coords.
     *
     * @param {CellCoords} coords
     * @returns {Boolean}
     */
    inInSelection: function inInSelection(coords) {
      if (!selection.isSelected()) {
        return false;
      }

      return priv.selRange.includes(coords);
    },


    /**
     * Deselects all selected cells
     */
    deselect: function deselect() {
      if (!selection.isSelected()) {
        return;
      }
      instance.selection.inProgress = false; // needed by HT inception
      priv.selRange = null;
      instance.view.wt.selections.current.clear();
      instance.view.wt.selections.area.clear();
      if (priv.settings.currentHeaderClassName || priv.settings.currentRowClassName || priv.settings.currentColClassName) {
        instance.view.wt.selections.highlight.clear();
      }
      editorManager.destroyEditor();
      selection.refreshBorders();
      (0, _element.removeClass)(instance.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
      instance.runHooks('afterDeselect');
    },


    /**
     * Select all cells
     */
    selectAll: function selectAll() {
      if (!priv.settings.multiSelect) {
        return;
      }
      selection.setSelectedHeaders(true, true, true);
      selection.setRangeStart(new _src.CellCoords(0, 0));
      selection.setRangeEnd(new _src.CellCoords(instance.countRows() - 1, instance.countCols() - 1), false);
    },


    /**
     * Deletes data from selected cells
     */
    empty: function empty() {
      if (!selection.isSelected()) {
        return;
      }
      var topLeft = priv.selRange.getTopLeftCorner();
      var bottomRight = priv.selRange.getBottomRightCorner();
      var r,
          c,
          changes = [];

      for (r = topLeft.row; r <= bottomRight.row; r++) {
        for (c = topLeft.col; c <= bottomRight.col; c++) {
          if (!instance.getCellMeta(r, c).readOnly) {
            changes.push([r, c, '']);
          }
        }
      }
      instance.setDataAtCell(changes);
    }
  };

  /**
   * Internal function to set `language` key of settings.
   *
   * @private
   * @param {String} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'
   * @fires Hooks#afterLanguageChange
   */
  function setLanguage(languageCode) {
    var normalizedLanguageCode = (0, _utils.normalizeLanguageCode)(languageCode);

    if ((0, _dictionariesManager.hasLanguageDictionary)(normalizedLanguageCode)) {
      instance.runHooks('beforeLanguageChange', normalizedLanguageCode);

      GridSettings.prototype.language = normalizedLanguageCode;

      instance.runHooks('afterLanguageChange', normalizedLanguageCode);
    } else {
      (0, _utils.warnUserAboutLanguageRegistration)(languageCode);
    }
  }

  this.init = function () {
    dataSource.setData(priv.settings.data);
    instance.runHooks('beforeInit');

    if ((0, _browser.isMobileBrowser)()) {
      (0, _element.addClass)(instance.rootElement, 'mobile');
    }

    this.updateSettings(priv.settings, true);

    this.view = new _tableView2.default(this);
    editorManager = new _editorManager2.default(instance, priv, selection, datamap);

    this.forceFullRender = true; // used when data was changed

    instance.runHooks('init');
    this.view.render();

    if (_typeof(priv.firstRun) === 'object') {
      instance.runHooks('afterChange', priv.firstRun[0], priv.firstRun[1]);
      priv.firstRun = false;
    }
    instance.runHooks('afterInit');
  };

  function ValidatorsQueue() {
    // moved this one level up so it can be used in any function here. Probably this should be moved to a separate file
    var resolved = false;

    return {
      validatorsInQueue: 0,
      valid: true,
      addValidatorToQueue: function addValidatorToQueue() {
        this.validatorsInQueue++;
        resolved = false;
      },
      removeValidatorFormQueue: function removeValidatorFormQueue() {
        this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1;
        this.checkIfQueueIsEmpty();
      },
      onQueueEmpty: function onQueueEmpty(valid) {},
      checkIfQueueIsEmpty: function checkIfQueueIsEmpty() {
        if (this.validatorsInQueue == 0 && resolved == false) {
          resolved = true;
          this.onQueueEmpty(this.valid);
        }
      }
    };
  }

  /**
   * Get parsed number from numeric string.
   *
   * @param {String} numericData Float (separated by a dot or a comma) or integer.
   * @returns {Number} Number if we get data in parsable format, not changed value otherwise.
   */
  function getParsedNumber(numericData) {
    // Unifying "float like" string. Change from value with comma determiner to value with dot determiner,
    // for example from `450,65` to `450.65`.
    var unifiedNumericData = numericData.replace(',', '.');

    if (isNaN(parseFloat(unifiedNumericData)) === false) {
      return parseFloat(unifiedNumericData);
    }

    return numericData;
  }

  function validateChanges(changes, source, callback) {
    var waitingForValidator = new ValidatorsQueue();
    var isNumericData = function isNumericData(value) {
      return value.length > 0 && /^-?[\d\s]*(\.|,)?\d*$/.test(value);
    };

    waitingForValidator.onQueueEmpty = resolve;

    for (var i = changes.length - 1; i >= 0; i--) {
      if (changes[i] === null) {
        changes.splice(i, 1);
      } else {
        var _changes$i = _slicedToArray(changes[i], 4),
            row = _changes$i[0],
            prop = _changes$i[1],
            newValue = _changes$i[3];

        var col = datamap.propToCol(prop);
        var cellProperties = instance.getCellMeta(row, col);

        if (cellProperties.type === 'numeric' && typeof newValue === 'string' && isNumericData(newValue)) {
          changes[i][3] = getParsedNumber(newValue);
        }

        /* eslint-disable no-loop-func */
        if (instance.getCellValidator(cellProperties)) {
          waitingForValidator.addValidatorToQueue();
          instance.validateCell(changes[i][3], cellProperties, function (i, cellProperties) {
            return function (result) {
              if (typeof result !== 'boolean') {
                throw new Error('Validation error: result is not boolean');
              }
              if (result === false && cellProperties.allowInvalid === false) {
                changes.splice(i, 1); // cancel the change
                cellProperties.valid = true; // we cancelled the change, so cell value is still valid
                var cell = instance.getCell(cellProperties.visualRow, cellProperties.visualCol);
                (0, _element.removeClass)(cell, instance.getSettings().invalidCellClassName);
                --i;
              }
              waitingForValidator.removeValidatorFormQueue();
            };
          }(i, cellProperties), source);
        }
      }
    }
    waitingForValidator.checkIfQueueIsEmpty();

    function resolve() {
      var beforeChangeResult;

      if (changes.length) {
        beforeChangeResult = instance.runHooks('beforeChange', changes, source);
        if ((0, _function.isFunction)(beforeChangeResult)) {
          console.warn('Your beforeChange callback returns a function. It\'s not supported since Handsontable 0.12.1 (and the returned function will not be executed).');
        } else if (beforeChangeResult === false) {
          changes.splice(0, changes.length); // invalidate all changes (remove everything from array)
        }
      }
      callback(); // called when async validators are resolved and beforeChange was not async
    }
  }

  /**
   * Internal function to apply changes. Called after validateChanges
   *
   * @private
   * @param {Array} changes Array in form of [row, prop, oldValue, newValue]
   * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
   * @fires Hooks#beforeChangeRender
   * @fires Hooks#afterChange
   */
  function applyChanges(changes, source) {
    var i = changes.length - 1;

    if (i < 0) {
      return;
    }

    for (; i >= 0; i--) {
      var skipThisChange = false;

      if (changes[i] === null) {
        changes.splice(i, 1);
        /* eslint-disable no-continue */
        continue;
      }

      if (changes[i][2] == null && changes[i][3] == null) {
        /* eslint-disable no-continue */
        continue;
      }

      if (priv.settings.allowInsertRow) {
        while (changes[i][0] > instance.countRows() - 1) {
          var numberOfCreatedRows = datamap.createRow(void 0, void 0, source);

          if (numberOfCreatedRows === 0) {
            skipThisChange = true;
            break;
          }
        }
      }

      if (skipThisChange) {
        /* eslint-disable no-continue */
        continue;
      }

      if (instance.dataType === 'array' && (!priv.settings.columns || priv.settings.columns.length === 0) && priv.settings.allowInsertColumn) {
        while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) {
          datamap.createCol(void 0, void 0, source);
        }
      }

      datamap.set(changes[i][0], changes[i][1], changes[i][3]);
    }

    instance.forceFullRender = true; // used when data was changed
    grid.adjustRowsAndCols();
    instance.runHooks('beforeChangeRender', changes, source);
    selection.refreshBorders(null, true);
    instance.view.wt.wtOverlays.adjustElementsSize();
    instance.runHooks('afterChange', changes, source || 'edit');

    var activeEditor = instance.getActiveEditor();

    if (activeEditor && (0, _mixed.isDefined)(activeEditor.refreshValue)) {
      activeEditor.refreshValue();
    }
  }

  this.validateCell = function (value, cellProperties, callback, source) {
    var validator = instance.getCellValidator(cellProperties);

    function done(valid) {
      var col = cellProperties.visualCol,
          row = cellProperties.visualRow,
          td = instance.getCell(row, col, true);

      if (td && td.nodeName != 'TH') {
        instance.view.wt.wtSettings.settings.cellRenderer(row, col, td);
      }
      callback(valid);
    }

    if ((0, _mixed.isRegExp)(validator)) {
      validator = function (validator) {
        return function (value, callback) {
          callback(validator.test(value));
        };
      }(validator);
    }

    if ((0, _function.isFunction)(validator)) {

      value = instance.runHooks('beforeValidate', value, cellProperties.visualRow, cellProperties.prop, source);

      // To provide consistent behaviour, validation should be always asynchronous
      instance._registerTimeout(setTimeout(function () {
        validator.call(cellProperties, value, function (valid) {
          valid = instance.runHooks('afterValidate', valid, value, cellProperties.visualRow, cellProperties.prop, source);
          cellProperties.valid = valid;

          done(valid);
          instance.runHooks('postAfterValidate', valid, value, cellProperties.visualRow, cellProperties.prop, source);
        });
      }, 0));
    } else {
      // resolve callback even if validator function was not found
      instance._registerTimeout(setTimeout(function () {
        cellProperties.valid = true;
        done(cellProperties.valid);
      }, 0));
    }
  };

  function setDataInputToArray(row, propOrCol, value) {
    if ((typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
      // is it an array of changes
      return row;
    }
    return [[row, propOrCol, value]];
  }

  /**
   * @description
   * Set new value to a cell. To change many cells at once, pass an array of `changes` in format `[[row, col, value], ...]` as
   * the only parameter. `col` is the index of a __visible__ column (note that if columns were reordered,
   * the current visible order will be used). `source` is a flag for before/afterChange events. If you pass only array of
   * changes then `source` could be set as second parameter.
   *
   * @memberof Core#
   * @function setDataAtCell
   * @param {Number|Array} row Visual row index or array of changes in format `[[row, col, value], ...]`.
   * @param {Number} col Visual column index.
   * @param {String} value New value.
   * @param {String} [source] String that identifies how this change will be described in the changes array (useful in onAfterChange or onBeforeChange callback).
   */
  this.setDataAtCell = function (row, col, value, source) {
    var input = setDataInputToArray(row, col, value),
        i,
        ilen,
        changes = [],
        prop;

    for (i = 0, ilen = input.length; i < ilen; i++) {
      if (_typeof(input[i]) !== 'object') {
        throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter');
      }
      if (typeof input[i][1] !== 'number') {
        throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`');
      }
      prop = datamap.colToProp(input[i][1]);
      changes.push([input[i][0], prop, dataSource.getAtCell(recordTranslator.toPhysicalRow(input[i][0]), input[i][1]), input[i][2]]);
    }

    if (!source && (typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
      source = col;
    }

    instance.runHooks('afterSetDataAtCell', changes, source);

    validateChanges(changes, source, function () {
      applyChanges(changes, source);
    });
  };

  /**
   * @description
   * Set new value to a cell. To change many cells at once, pass an array of `changes` in format `[[row, prop, value], ...]` as
   * the only parameter. `prop` is the name of the object property (e.g. `first.name`). `source` is a flag for before/afterChange events.
   * If you pass only array of changes then `source` could be set as second parameter.
   *
   * @memberof Core#
   * @function setDataAtRowProp
   * @param {Number|Array} row Visual row index or array of changes in format `[[row, prop, value], ...]`.
   * @param {String} prop Property name or the source string.
   * @param {String} value Value to be set.
   * @param {String} [source] String that identifies how this change will be described in changes array (useful in onChange callback).
   */
  this.setDataAtRowProp = function (row, prop, value, source) {
    var input = setDataInputToArray(row, prop, value),
        i,
        ilen,
        changes = [];

    for (i = 0, ilen = input.length; i < ilen; i++) {
      changes.push([input[i][0], input[i][1], dataSource.getAtCell(recordTranslator.toPhysicalRow(input[i][0]), input[i][1]), input[i][2]]);
    }

    if (!source && (typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
      source = prop;
    }

    instance.runHooks('afterSetDataAtRowProp', changes, source);

    validateChanges(changes, source, function () {
      applyChanges(changes, source);
    });
  };

  /**
   * Listen to the keyboard input on document body.
   *
   * @memberof Core#
   * @function listen
   * @since 0.11
   * @param {Boolean} [modifyDocumentFocus=true] If `true`, currently focused element will be blured (which returns focus
   *                                             to the document.body). Otherwise the active element does not lose its focus.
   */
  this.listen = function () {
    var modifyDocumentFocus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

    if (modifyDocumentFocus) {
      var invalidActiveElement = !document.activeElement || document.activeElement && document.activeElement.nodeName === void 0;

      if (document.activeElement && document.activeElement !== document.body && !invalidActiveElement) {
        document.activeElement.blur();
      } else if (invalidActiveElement) {
        // IE
        document.body.focus();
      }
    }

    if (instance && !instance.isListening()) {
      activeGuid = instance.guid;
      instance.runHooks('afterListen');
    }
  };

  /**
   * Stop listening to keyboard input on the document body.
   *
   * @memberof Core#
   * @function unlisten
   * @since 0.11
   */
  this.unlisten = function () {
    if (this.isListening()) {
      activeGuid = null;
      instance.runHooks('afterUnlisten');
    }
  };

  /**
   * Returns `true` if the current Handsontable instance is listening to keyboard input on document body.
   *
   * @memberof Core#
   * @function isListening
   * @since 0.11
   * @returns {Boolean} `true` if the instance is listening, `false` otherwise.
   */
  this.isListening = function () {
    return activeGuid === instance.guid;
  };

  /**
   * Destroys the current editor, renders and selects the current cell.
   *
   * @memberof Core#
   * @function destroyEditor
   * @param {Boolean} [revertOriginal] If != `true`, edited data is saved. Otherwise the previous value is restored.
   */
  this.destroyEditor = function (revertOriginal) {
    selection.refreshBorders(revertOriginal);
  };

  /**
   * Populate cells at position with 2D input array (e.g. `[[1, 2], [3, 4]]`).
   * Use `endRow`, `endCol` when you want to cut input when a certain row is reached.
   * Optional `source` parameter (default value "populateFromArray") is used to identify this call in the resulting events (beforeChange, afterChange).
   * Optional `populateMethod` parameter (default value "overwrite", possible values "shift_down" and "shift_right")
   * has the same effect as pasteMode option {@link Options#pasteMode}
   *
   * @memberof Core#
   * @function populateFromArray
   * @since 0.9.0
   * @param {Number} row Start visual row index.
   * @param {Number} col Start visual column index.
   * @param {Array} input 2d array
   * @param {Number} [endRow] End visual row index (use when you want to cut input when certain row is reached).
   * @param {Number} [endCol] End visual column index (use when you want to cut input when certain column is reached).
   * @param {String} [source="populateFromArray"] Source string.
   * @param {String} [method="overwrite"] Populate method. Possible options: `shift_down`, `shift_right`, `overwrite`.
   * @param {String} direction Populate direction. (left|right|up|down)
   * @param {Array} deltas Deltas array.
   * @returns {Object|undefined} The ending TD element in pasted area (only if any cells were changed).
   */
  this.populateFromArray = function (row, col, input, endRow, endCol, source, method, direction, deltas) {
    var c;

    if (!((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && _typeof(input[0]) === 'object')) {
      throw new Error('populateFromArray parameter `input` must be an array of arrays'); // API changed in 0.9-beta2, let's check if you use it correctly
    }
    c = typeof endRow === 'number' ? new _src.CellCoords(endRow, endCol) : null;

    return grid.populateFromArray(new _src.CellCoords(row, col), input, c, source, method, direction, deltas);
  };

  /**
   * Adds/removes data from the column. This function is modelled after Array.splice.
   * Parameter `col` is the index of the column in which do you want to do splice.
   * Parameter `index` is the row index at which to start changing the array.
   * If negative, will begin that many elements from the end. Parameter `amount`, is the number of the old array elements to remove.
   * If the amount is 0, no elements are removed. Fourth and further parameters are the `elements` to add to the array.
   * If you don't specify any elements, spliceCol simply removes elements from the array.
   * {@link DataMap#spliceCol}
   *
   * @memberof Core#
   * @function spliceCol
   * @since 0.9-beta2
   * @param {Number} col Index of the column in which do you want to do splice.
   * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
   * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed.
   * @param {*} [elements] The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array.
   */
  this.spliceCol = function (col, index, amount /* , elements... */) {
    var _datamap;

    return (_datamap = datamap).spliceCol.apply(_datamap, arguments);
  };

  /**
   * Adds/removes data from the row. This function works is modelled after Array.splice.
   * Parameter `row` is the index of row in which do you want to do splice.
   * Parameter `index` is the column index at which to start changing the array.
   * If negative, will begin that many elements from the end. Parameter `amount`, is the number of old array elements to remove.
   * If the amount is 0, no elements are removed. Fourth and further parameters are the `elements` to add to the array.
   * If you don't specify any elements, spliceCol simply removes elements from the array.
   * {@link DataMap#spliceRow}
   *
   * @memberof Core#
   * @function spliceRow
   * @since 0.11
   * @param {Number} row Index of column in which do you want to do splice.
   * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
   * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed.
   * @param {*} [elements] The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array.
   */
  this.spliceRow = function (row, index, amount /* , elements... */) {
    var _datamap2;

    return (_datamap2 = datamap).spliceRow.apply(_datamap2, arguments);
  };

  /**
   * Returns indexes of the currently selected cells as an array `[startRow, startCol, endRow, endCol]`.
   *
   * Start row and start col are the coordinates of the active cell (where the selection was started).
   *
   * @memberof Core#
   * @function getSelected
   * @returns {Array} Array of the selection's indexes.
   */
  this.getSelected = function () {
    // https://github.com/handsontable/handsontable/issues/44  //cjl
    if (selection.isSelected()) {
      return [priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col];
    }
  };

  /**
   * Returns the current selection as a CellRange object.
   *
   * @memberof Core#
   * @function getSelectedRange
   * @since 0.11
   * @returns {CellRange} Selected range object or undefined` if there is no selection.
   */
  this.getSelectedRange = function () {
    // https://github.com/handsontable/handsontable/issues/44  //cjl
    if (selection.isSelected()) {
      return priv.selRange;
    }
  };

  /**
   * Rerender the table.
   *
   * @memberof Core#
   * @function render
   */
  this.render = function () {
    if (instance.view) {
      instance.renderCall = true;
      instance.forceFullRender = true; // used when data was changed
      selection.refreshBorders(null, true);
    }
  };

  /**
   * Reset all cells in the grid to contain data from the data array.
   *
   * @memberof Core#
   * @function loadData
   * @param {Array} data Array of arrays or array of objects containing data.
   * @fires Hooks#afterLoadData
   * @fires Hooks#afterChange
   */
  this.loadData = function (data) {
    if (Array.isArray(priv.settings.dataSchema)) {
      instance.dataType = 'array';
    } else if ((0, _function.isFunction)(priv.settings.dataSchema)) {
      instance.dataType = 'function';
    } else {
      instance.dataType = 'object';
    }

    if (datamap) {
      datamap.destroy();
    }
    datamap = new _dataMap2.default(instance, priv, GridSettings);

    if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object' && data !== null) {
      if (!(data.push && data.splice)) {
        // check if data is array. Must use duck-type check so Backbone Collections also pass it
        // when data is not an array, attempt to make a single-row array of it
        data = [data];
      }
    } else if (data === null) {
      data = [];
      var row;
      var r = 0;
      var rlen = 0;
      var dataSchema = datamap.getSchema();

      for (r = 0, rlen = priv.settings.startRows; r < rlen; r++) {
        if ((instance.dataType === 'object' || instance.dataType === 'function') && priv.settings.dataSchema) {
          row = (0, _object.deepClone)(dataSchema);
          data.push(row);
        } else if (instance.dataType === 'array') {
          row = (0, _object.deepClone)(dataSchema[0]);
          data.push(row);
        } else {
          row = [];

          for (var c = 0, clen = priv.settings.startCols; c < clen; c++) {
            row.push(null);
          }

          data.push(row);
        }
      }
    } else {
      throw new Error('loadData only accepts array of objects or array of arrays (' + (typeof data === 'undefined' ? 'undefined' : _typeof(data)) + ' given)');
    }

    priv.isPopulated = false;
    GridSettings.prototype.data = data;

    if (Array.isArray(data[0])) {
      instance.dataType = 'array';
    }

    datamap.dataSource = data;
    dataSource.data = data;
    dataSource.dataType = instance.dataType;
    dataSource.colToProp = datamap.colToProp.bind(datamap);
    dataSource.propToCol = datamap.propToCol.bind(datamap);

    clearCellSettingCache();

    grid.adjustRowsAndCols();
    instance.runHooks('afterLoadData', priv.firstRun);

    if (priv.firstRun) {
      priv.firstRun = [null, 'loadData'];
    } else {
      instance.runHooks('afterChange', null, 'loadData');
      instance.render();
    }
    priv.isPopulated = true;

    function clearCellSettingCache() {
      priv.cellSettings.length = 0;
    }
  };

  /**
   * Returns the current data object (the same one that was passed by `data` configuration option or `loadData` method,
   * unless the `modifyRow` hook was used to trim some of the rows. If that's the case - use the {@link Core#getSourceData} method.).
   * Optionally you can provide cell range by defining `row`, `col`, `row2`, `col2` to get only a fragment of grid data.
   *
   * Note: getData functionality changed with the release of version 0.20. If you're looking for the previous functionality,
   * you should use the {@link Core#getSourceData} method.
   *
   * @memberof Core#
   * @function getData
   * @param {Number} [r] From visual row index.
   * @param {Number} [c] From visual column index.
   * @param {Number} [r2] To visual row index.
   * @param {Number} [c2] To visual column index.
   * @returns {Array} Array with the data.
   */
  this.getData = function (r, c, r2, c2) {
    if ((0, _mixed.isUndefined)(r)) {
      return datamap.getAll();
    }
    return datamap.getRange(new _src.CellCoords(r, c), new _src.CellCoords(r2, c2), datamap.DESTINATION_RENDERER);
  };

  /**
   * Returns a string value of the selected range. Each column is separated by tab, each row is separated by a new line character.
   * {@link DataMap#getCopyableText}
   *
   * @memberof Core#
   * @function getCopyableText
   * @since 0.11
   * @param {Number} startRow From visual row index.
   * @param {Number} startCol From visual column index.
   * @param {Number} endRow To visual row index.
   * @param {Number} endCol To visual column index.
   * @returns {String}
   */
  this.getCopyableText = function (startRow, startCol, endRow, endCol) {
    return datamap.getCopyableText(new _src.CellCoords(startRow, startCol), new _src.CellCoords(endRow, endCol));
  };

  /**
   * Returns the data's copyable value at specified row and column index ({@link DataMap#getCopyable}).
   *
   * @memberof Core#
   * @function getCopyableData
   * @since 0.19.0
   * @param {Number} row Visual row index.
   * @param {Number} column Visual column index.
   * @returns {String}
   */
  this.getCopyableData = function (row, column) {
    return datamap.getCopyable(row, datamap.colToProp(column));
  };

  /**
   * Returns schema provided by constructor settings. If it doesn't exist then it returns the schema based on the data
   * structure in the first row.
   *
   * @memberof Core#
   * @function getSchema
   * @since 0.13.2
   * @returns {Object} Schema object.
   */
  this.getSchema = function () {
    return datamap.getSchema();
  };

  /**
   * Use it if you need to change configuration after initialization. The `settings` parameter is an object containing the new
   * settings, declared the same way as in the initial settings object.
   * Note, that although the `updateSettings` method doesn't overwrite the previously declared settings, it might reset
   * the settings made post-initialization. (for example - ignore changes made using the columnResize feature).
   *
   * @memberof Core#
   * @function updateSettings
   * @param {Object} settings New settings object.
   * @param {Boolean} init Calls this method in the initialization mode. Internal use only.
   *                       Used by API could be cause of the unexpected behaviour of the Handsontable.
   * @example
   * ```js
   * hot.updateSettings({
   *    contextMenu: true,
   *    colHeaders: true,
   *    fixedRowsTop: 2
   * });
   * ```
   * @fires Hooks#afterCellMetaReset
   * @fires Hooks#afterUpdateSettings
   */
  this.updateSettings = function (settings, init) {
    var columnsAsFunc = false;
    var i = void 0;
    var j = void 0;
    var clen = void 0;

    if ((0, _mixed.isDefined)(settings.rows)) {
      throw new Error('"rows" setting is no longer supported. do you mean startRows, minRows or maxRows?');
    }
    if ((0, _mixed.isDefined)(settings.cols)) {
      throw new Error('"cols" setting is no longer supported. do you mean startCols, minCols or maxCols?');
    }

    for (i in settings) {
      if (i === 'data') {
        /* eslint-disable-next-line no-continue */
        continue; // loadData will be triggered later
      } else if (i === 'language') {
        setLanguage(settings.language);

        /* eslint-disable-next-line no-continue */
        continue;
      } else if (_pluginHooks2.default.getSingleton().getRegistered().indexOf(i) > -1) {
        if ((0, _function.isFunction)(settings[i]) || Array.isArray(settings[i])) {
          settings[i].initialHook = true;
          instance.addHook(i, settings[i]);
        }
      } else if (!init && (0, _object.hasOwnProperty)(settings, i)) {
        // Update settings
        GridSettings.prototype[i] = settings[i];
      }
    }

    // Load data or create data map
    if (settings.data === void 0 && priv.settings.data === void 0) {
      instance.loadData(null); // data source created just now
    } else if (settings.data !== void 0) {
      instance.loadData(settings.data); // data source given as option
    } else if (settings.columns !== void 0) {
      datamap.createMap();
    }

    clen = instance.countCols();

    var columnSetting = settings.columns || GridSettings.prototype.columns;

    // Init columns constructors configuration
    if (columnSetting && (0, _function.isFunction)(columnSetting)) {
      clen = instance.countSourceCols();
      columnsAsFunc = true;
    }

    // Clear cellSettings cache
    if (settings.cell !== void 0 || settings.cells !== void 0 || settings.columns !== void 0) {
      priv.cellSettings.length = 0;
    }

    if (clen > 0) {
      var proto = void 0;
      var column = void 0;

      for (i = 0, j = 0; i < clen; i++) {
        if (columnsAsFunc && !columnSetting(i)) {
          /* eslint-disable no-continue */
          continue;
        }
        priv.columnSettings[j] = (0, _setting.columnFactory)(GridSettings, priv.columnsSettingConflicts);

        // shortcut for prototype
        proto = priv.columnSettings[j].prototype;

        // Use settings provided by user
        if (columnSetting) {
          if (columnsAsFunc) {
            column = columnSetting(i);
          } else {
            column = columnSetting[j];
          }

          if (column) {
            (0, _object.extend)(proto, column);
            (0, _object.extend)(proto, expandType(column));
          }
        }

        j++;
      }
    }

    if ((0, _mixed.isDefined)(settings.cell)) {
      for (var key in settings.cell) {
        if ((0, _object.hasOwnProperty)(settings.cell, key)) {
          var cell = settings.cell[key];

          instance.setCellMetaObject(cell.row, cell.col, cell);
        }
      }
    }

    instance.runHooks('afterCellMetaReset');

    if ((0, _mixed.isDefined)(settings.className)) {
      if (GridSettings.prototype.className) {
        (0, _element.removeClass)(instance.rootElement, GridSettings.prototype.className);
      }
      if (settings.className) {
        (0, _element.addClass)(instance.rootElement, settings.className);
      }
    }

    var currentHeight = instance.rootElement.style.height;
    if (currentHeight !== '') {
      currentHeight = parseInt(instance.rootElement.style.height, 10);
    }

    var height = settings.height;
    if ((0, _function.isFunction)(height)) {
      height = height();
    }

    if (init) {
      var initialStyle = instance.rootElement.getAttribute('style');

      if (initialStyle) {
        instance.rootElement.setAttribute('data-initialstyle', instance.rootElement.getAttribute('style'));
      }
    }

    if (height === null) {
      var _initialStyle = instance.rootElement.getAttribute('data-initialstyle');

      if (_initialStyle && (_initialStyle.indexOf('height') > -1 || _initialStyle.indexOf('overflow') > -1)) {
        instance.rootElement.setAttribute('style', _initialStyle);
      } else {
        instance.rootElement.style.height = '';
        instance.rootElement.style.overflow = '';
      }
    } else if (height !== void 0) {
      instance.rootElement.style.height = height + 'px';
      instance.rootElement.style.overflow = 'hidden';
    }

    if (typeof settings.width !== 'undefined') {
      var width = settings.width;

      if ((0, _function.isFunction)(width)) {
        width = width();
      }

      instance.rootElement.style.width = width + 'px';
    }

    if (!init) {
      datamap.clearLengthCache(); // force clear cache length on updateSettings() #3416

      if (instance.view) {
        instance.view.wt.wtViewport.resetHasOversizedColumnHeadersMarked();
      }

      instance.runHooks('afterUpdateSettings', settings);
    }

    grid.adjustRowsAndCols();
    if (instance.view && !priv.firstRun) {
      instance.forceFullRender = true; // used when data was changed
      selection.refreshBorders(null, true);
    }

    if (!init && instance.view && (currentHeight === '' || height === '' || height === void 0) && currentHeight !== height) {
      instance.view.wt.wtOverlays.updateMainScrollableElements();
    }
  };

  /**
   * Get value from the selected cell.
   *
   * @memberof Core#
   * @function getValue
   * @since 0.11
   * @returns {*} Value of selected cell.
   */
  this.getValue = function () {
    var sel = instance.getSelected();
    if (GridSettings.prototype.getValue) {
      if ((0, _function.isFunction)(GridSettings.prototype.getValue)) {
        return GridSettings.prototype.getValue.call(instance);
      } else if (sel) {
        return instance.getData()[sel[0]][GridSettings.prototype.getValue];
      }
    } else if (sel) {
      return instance.getDataAtCell(sel[0], sel[1]);
    }
  };

  function expandType(obj) {
    if (!(0, _object.hasOwnProperty)(obj, 'type')) {
      // ignore obj.prototype.type
      return;
    }

    var type,
        expandedType = {};

    if (_typeof(obj.type) === 'object') {
      type = obj.type;
    } else if (typeof obj.type === 'string') {
      type = (0, _cellTypes.getCellType)(obj.type);
    }

    for (var i in type) {
      if ((0, _object.hasOwnProperty)(type, i) && !(0, _object.hasOwnProperty)(obj, i)) {
        expandedType[i] = type[i];
      }
    }

    return expandedType;
  }

  /**
   * Returns the object settings.
   *
   * @memberof Core#
   * @function getSettings
   * @returns {Object} Object containing the current grid settings.
   */
  this.getSettings = function () {
    return priv.settings;
  };

  /**
   * Clears the data from the grid. (The table settings remain intact.)
   *
   * @memberof Core#
   * @function clear
   * @since 0.11
   */
  this.clear = function () {
    selection.selectAll();
    selection.empty();
  };

  /**
   * @memberof Core#
   * @function alter
   * @param {String} action See grid.alter for possible values: `"insert_row"`, `"insert_col"`, `"remove_row"`, `"remove_col"`
   * @param {Number} index Visual index of the row/column before which the new row/column will be inserted/removed.
   * @param {Number} [amount = 1] Amound of rows/columns to be inserted/removed.
   * @param {String} [source] Source indicator.
   * @param {Boolean} [keepEmptyRows] Flag for preventing deletion of empty rows.
   * @description
   *
   * Allows altering the table structure by either inserting/removing rows or inserting/removing columns:
   *
   * Insert new row(s) above the row with a given `index`. If index is `null` or `undefined`, the new row will be
   * added after the last row.
   * ```js
   * var hot = new Handsontable(document.getElementById('example'));
   * hot.alter('insert_row', 10);
   * ```
   *
   * Insert new column(s) before the column with a given `index`. If index is `null` or `undefined`, the new column
   * will be added after the last column.
   * ```js
   * var hot = new Handsontable(document.getElementById('example'));
   * hot.alter('insert_col', 10);
   * ```
   *
   * Remove the row(s) at the given `index`.
   * ```js
   * var hot = new Handsontable(document.getElementById('example'));
   * hot.alter('remove_row', 10);
   * ```
   *
   * Remove the column(s) at the given `index`.
   * ```js
   * var hot = new Handsontable(document.getElementById('example'));
   * hot.alter('remove_col', 10);
   * ```
   */
  this.alter = function (action, index, amount, source, keepEmptyRows) {
    grid.alter(action, index, amount, source, keepEmptyRows);
  };

  /**
   * Returns a TD element for the given `row` and `col` arguments, if it is rendered on screen.
   * Returns `null` if the TD is not rendered on screen (probably because that part of the table is not visible).
   *
   * @memberof Core#
   * @function getCell
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @param {Boolean} topmost If set to true, it returns the TD element from the topmost overlay. For example,
   * if the wanted cell is in the range of fixed rows, it will return a TD element from the `top` overlay.
   * @returns {Element} The cell's TD element.
   */
  this.getCell = function (row, col, topmost) {
    return instance.view.getCellAtCoords(new _src.CellCoords(row, col), topmost);
  };

  /**
   * Returns the coordinates of the cell, provided as a HTML Element.
   *
   * @memberof Core#
   * @function getCoords
   * @param {Element} elem The HTML Element representing the cell.
   * @returns {CellCoords} Visual coordinates object.
   */
  this.getCoords = function (elem) {
    return this.view.wt.wtTable.getCoords.call(this.view.wt.wtTable, elem);
  };

  /**
   * Returns the property name that corresponds with the given column index. {@link DataMap#colToProp}
   * If the data source is an array of arrays, it returns the columns index.
   *
   * @memberof Core#
   * @function colToProp
   * @param {Number} col Visual column index.
   * @returns {String|Number} Column property or physical column index.
   */
  this.colToProp = function (col) {
    return datamap.colToProp(col);
  };

  /**
   * Returns column index that corresponds with the given property. {@link DataMap#propToCol}
   *
   * @memberof Core#
   * @function propToCol
   * @param {String|Number} prop Property name or physical column index.
   * @returns {Number} Visual column index.
   */
  this.propToCol = function (prop) {
    return datamap.propToCol(prop);
  };

  /**
   * Translate physical row index into visual.
   *
   * @since 0.29.0
   * @memberof Core#
   * @function toVisualRow
   * @param {Number} row Physical row index.
   * @returns {Number} Returns visual row index.
   */
  this.toVisualRow = function (row) {
    return recordTranslator.toVisualRow(row);
  };

  /**
   * Translate physical column index into visual.
   *
   * @since 0.29.0
   * @memberof Core#
   * @function toVisualColumn
   * @param {Number} column Physical column index.
   * @returns {Number} Returns visual column index.
   */
  this.toVisualColumn = function (column) {
    return recordTranslator.toVisualColumn(column);
  };

  /**
   * Translate visual row index into physical.
   * If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied)
   * to retrieve valid physical row index you can use this method.
   *
   * @since 0.29.0
   * @memberof Core#
   * @function toPhysicalRow
   * @param {Number} row Visual row index.
   * @returns {Number} Returns physical row index.
   */
  this.toPhysicalRow = function (row) {
    return recordTranslator.toPhysicalRow(row);
  };

  /**
   * Translate visual column index into physical.
   * If displayed columns order is different than the order of columns stored in memory (i.e. manual column move is applied)
   * to retrieve valid physical column index you can use this method.
   *
   * @since 0.29.0
   * @memberof Core#
   * @function toPhysicalColumn
   * @param {Number} column Visual column index.
   * @returns {Number} Returns physical column index.
   */
  this.toPhysicalColumn = function (column) {
    return recordTranslator.toPhysicalColumn(column);
  };

  /**
   * @description
   * Returns the cell value at `row`, `col`. `row` and `col` are the __visible__ indexes (note, that if columns were reordered or sorted,
   * the currently visible order will be used).
   *
   * @memberof Core#
   * @function getDataAtCell
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @returns {String|Boolean|null} Data at cell.
   */
  this.getDataAtCell = function (row, col) {
    return datamap.get(row, datamap.colToProp(col));
  };

  /**
   * Return value at `row`, `prop`. (Uses {@link DataMap#get})
   *
   * @memberof Core#
   * @function getDataAtRowProp
   * @param {Number} row Visual row index.
   * @param {String} prop Property name.
   * @returns {*} Cell value.
   */
  this.getDataAtRowProp = function (row, prop) {
    return datamap.get(row, prop);
  };

  /**
   * @description
   * Returns array of column values from the data source. `col` is the __visible__ index of the column.
   * Note, that if columns were reordered or sorted, the currently visible order will be used.
   *
   * @memberof Core#
   * @function getDataAtCol
   * @since 0.9-beta2
   * @param {Number} col Visual column index.
   * @returns {Array} Array of cell values.
   */
  this.getDataAtCol = function (col) {
    var out = [];
    return out.concat.apply(out, _toConsumableArray(datamap.getRange(new _src.CellCoords(0, col), new _src.CellCoords(priv.settings.data.length - 1, col), datamap.DESTINATION_RENDERER)));
  };

  /**
   * Given the object property name (e.g. `'first.name'`), returns an array of column's values from the data source.
   * You can also provide a column index as the first argument.
   *
   * @memberof Core#
   * @function getDataAtProp
   * @since 0.9-beta2
   * @param {String|Number} prop Property name / physical column index.
   * @returns {Array} Array of cell values.
   */
  // TODO: Getting data from `datamap` should work on visual indexes.
  this.getDataAtProp = function (prop) {
    var out = [],
        range;

    range = datamap.getRange(new _src.CellCoords(0, datamap.propToCol(prop)), new _src.CellCoords(priv.settings.data.length - 1, datamap.propToCol(prop)), datamap.DESTINATION_RENDERER);

    return out.concat.apply(out, _toConsumableArray(range));
  };

  /**
   * Returns the source data object (the same that was passed by `data` configuration option or `loadData` method).
   * Optionally you can provide a cell range by using the `row`, `col`, `row2`, `col2` arguments, to get only a fragment of grid data.
   *
   * @memberof Core#
   * @function getSourceData
   * @since 0.20.0
   * @param {Number} [r] From physical row index.
   * @param {Number} [c] From physical column index (or visual index, if data type is an array of objects).
   * @param {Number} [r2] To physical row index.
   * @param {Number} [c2] To physical column index (or visual index, if data type is an array of objects).
   * @returns {Array} Array of grid data.
   */
  this.getSourceData = function (r, c, r2, c2) {
    var data = void 0;

    if (r === void 0) {
      data = dataSource.getData();
    } else {
      data = dataSource.getByRange(new _src.CellCoords(r, c), new _src.CellCoords(r2, c2));
    }

    return data;
  };

  /**
   * Returns the source data object as an arrays of arrays format even when source data was provided in another format.
   * Optionally you can provide a cell range by using the `row`, `col`, `row2`, `col2` arguments, to get only a fragment of grid data.
   *
   * @memberof Core#
   * @function getSourceDataArray
   * @since 0.28.0
   * @param {Number} [r] From physical row index.
   * @param {Number} [c] From physical column index (or visual index, if data type is an array of objects).
   * @param {Number} [r2] To physical row index.
   * @param {Number} [c2] To physical column index (or visual index, if data type is an array of objects).
   * @returns {Array} An array of arrays.
   */
  this.getSourceDataArray = function (r, c, r2, c2) {
    var data = void 0;

    if (r === void 0) {
      data = dataSource.getData(true);
    } else {
      data = dataSource.getByRange(new _src.CellCoords(r, c), new _src.CellCoords(r2, c2), true);
    }

    return data;
  };

  /**
   * Returns an array of column values from the data source. `col` is the index of the row in the data source.
   *
   * @memberof Core#
   * @function getSourceDataAtCol
   * @since 0.11.0-beta3
   * @param {Number} column Visual column index.
   * @returns {Array} Array of the column's cell values.
   */
  // TODO: Getting data from `sourceData` should work always on physical indexes.
  this.getSourceDataAtCol = function (column) {
    return dataSource.getAtColumn(column);
  };

  /**
   * Returns a single row of the data (array or object, depending on what you have). `row` is the index of the row in the data source.
   *
   * @memberof Core#
   * @function getSourceDataAtRow
   * @since 0.11.0-beta3
   * @param {Number} row Physical row index.
   * @returns {Array|Object} Single row of data.
   */
  this.getSourceDataAtRow = function (row) {
    return dataSource.getAtRow(row);
  };

  /**
   * Returns a single value from the data source.
   *
   * @memberof Core#
   * @function getSourceDataAtCell
   * @param {Number} row Physical row index.
   * @param {Number} column Visual column index.
   * @returns {*} Cell data.
   * @since 0.20.0
   */
  // TODO: Getting data from `sourceData` should work always on physical indexes.
  this.getSourceDataAtCell = function (row, column) {
    return dataSource.getAtCell(row, column);
  };

  /**
   * @description
   * Returns a single row of the data. The `row` argument is the __visible__ index of the row.
   *
   * @memberof Core#
   * @function getDataAtRow
   * @param {Number} row Visual row index.
   * @returns {Array} Array of row's cell data.
   * @since 0.9-beta2
   */
  this.getDataAtRow = function (row) {
    var data = datamap.getRange(new _src.CellCoords(row, 0), new _src.CellCoords(row, this.countCols() - 1), datamap.DESTINATION_RENDERER);

    return data[0] || [];
  };

  /**
   * @description
   * Returns a data type defined in the Handsontable settings under the `type` key ([Options#type](http://docs.handsontable.com/Options.html#type)).
   * If there are cells with different types in the selected range, it returns `'mixed'`.
   *
   * @since 0.18.1
   * @memberof Core#
   * @function getDataType
   * @param {Number} rowFrom From visual row index.
   * @param {Number} columnFrom From visual column index.
   * @param {Number} rowTo To visual row index.
   * @param {Number} columnTo To visual column index.
   * @returns {String} Cell type (e.q: `'mixed'`, `'text'`, `'numeric'`, `'autocomplete'`).
   */
  this.getDataType = function (rowFrom, columnFrom, rowTo, columnTo) {
    var _this = this;

    var previousType = null;
    var currentType = null;

    if (rowFrom === void 0) {
      rowFrom = 0;
      rowTo = this.countRows();
      columnFrom = 0;
      columnTo = this.countCols();
    }
    if (rowTo === void 0) {
      rowTo = rowFrom;
    }
    if (columnTo === void 0) {
      columnTo = columnFrom;
    }
    var type = 'mixed';

    (0, _number.rangeEach)(Math.min(rowFrom, rowTo), Math.max(rowFrom, rowTo), function (row) {
      var isTypeEqual = true;

      (0, _number.rangeEach)(Math.min(columnFrom, columnTo), Math.max(columnFrom, columnTo), function (column) {
        var cellType = _this.getCellMeta(row, column);

        currentType = cellType.type;

        if (previousType) {
          isTypeEqual = previousType === currentType;
        } else {
          previousType = currentType;
        }

        return isTypeEqual;
      });
      type = isTypeEqual ? currentType : 'mixed';

      return isTypeEqual;
    });

    return type;
  };

  /**
   * Remove a property defined by the `key` argument from the cell meta object for the provided `row` and `col` coordinates.
   *
   * @memberof Core#
   * @function removeCellMeta
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @param {String} key Property name.
   * @fires Hooks#beforeRemoveCellMeta
   * @fires Hooks#afterRemoveCellMeta
   */
  this.removeCellMeta = function (row, col, key) {
    var _recordTranslator$toP = recordTranslator.toPhysical(row, col),
        _recordTranslator$toP2 = _slicedToArray(_recordTranslator$toP, 2),
        physicalRow = _recordTranslator$toP2[0],
        physicalColumn = _recordTranslator$toP2[1];

    var cachedValue = priv.cellSettings[physicalRow][physicalColumn][key];

    var hookResult = instance.runHooks('beforeRemoveCellMeta', row, col, key, cachedValue);

    if (hookResult !== false) {
      delete priv.cellSettings[physicalRow][physicalColumn][key];

      instance.runHooks('afterRemoveCellMeta', row, col, key, cachedValue);
    }

    cachedValue = null;
  };

  /**
   * Remove one or more rows from the cell meta object.
   *
   * @since 0.30.0
   * @param {Number} index An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.
   * @param {Number} deleteAmount The number of items to be removed. If set to 0, no items will be removed.
   * @param {Array} items The new items to be added to the array.
   */
  this.spliceCellsMeta = function (index, deleteAmount) {
    var _priv$cellSettings;

    for (var _len2 = arguments.length, items = Array(_len2 > 2 ? _len2 - 2 : 0), _key = 2; _key < _len2; _key++) {
      items[_key - 2] = arguments[_key];
    }

    (_priv$cellSettings = priv.cellSettings).splice.apply(_priv$cellSettings, [index, deleteAmount].concat(items));
  };

  /**
   * Set cell meta data object defined by `prop` to the corresponding params `row` and `col`.
   *
   * @memberof Core#
   * @function setCellMetaObject
   * @since 0.11
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @param {Object} prop Meta object.
   */
  this.setCellMetaObject = function (row, col, prop) {
    if ((typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) === 'object') {
      for (var key in prop) {
        if ((0, _object.hasOwnProperty)(prop, key)) {
          var value = prop[key];
          this.setCellMeta(row, col, key, value);
        }
      }
    }
  };

  /**
   * Sets a property defined by the `key` object to the meta object of a cell corresponding to params `row` and `col`.
   *
   * @memberof Core#
   * @function setCellMeta
   * @since 0.11
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @param {String} key Property name.
   * @param {String} val Property value.
   * @fires Hooks#afterSetCellMeta
   */
  this.setCellMeta = function (row, col, key, val) {
    var _recordTranslator$toP3 = recordTranslator.toPhysical(row, col),
        _recordTranslator$toP4 = _slicedToArray(_recordTranslator$toP3, 2),
        physicalRow = _recordTranslator$toP4[0],
        physicalColumn = _recordTranslator$toP4[1];

    if (!priv.columnSettings[physicalColumn]) {
      priv.columnSettings[physicalColumn] = (0, _setting.columnFactory)(GridSettings, priv.columnsSettingConflicts);
    }

    if (!priv.cellSettings[physicalRow]) {
      priv.cellSettings[physicalRow] = [];
    }
    if (!priv.cellSettings[physicalRow][physicalColumn]) {
      priv.cellSettings[physicalRow][physicalColumn] = new priv.columnSettings[physicalColumn]();
    }
    priv.cellSettings[physicalRow][physicalColumn][key] = val;
    instance.runHooks('afterSetCellMeta', row, col, key, val);
  };

  /**
   * Get all the cells meta settings at least once generated in the table (in order of cell initialization).
   *
   * @since 0.19.0
   * @returns {Array} Returns Array of ColumnSettings object.
   */
  this.getCellsMeta = function () {
    return (0, _array.arrayFlatten)(priv.cellSettings);
  };

  /**
   * Returns the cell properties object for the given `row` and `col` coordinates.
   *
   * @memberof Core#
   * @function getCellMeta
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @returns {Object} The cell properties object.
   * @fires Hooks#beforeGetCellMeta
   * @fires Hooks#afterGetCellMeta
   */
  this.getCellMeta = function (row, col) {
    var prop = datamap.colToProp(col);
    var cellProperties = void 0;

    var _recordTranslator$toP5 = recordTranslator.toPhysical(row, col),
        _recordTranslator$toP6 = _slicedToArray(_recordTranslator$toP5, 2),
        physicalRow = _recordTranslator$toP6[0],
        physicalColumn = _recordTranslator$toP6[1];

    // Workaround for #11. Connected also with #3849. It should be fixed within #4497.


    if (physicalRow === null) {
      physicalRow = row;
    }

    if (!priv.columnSettings[physicalColumn]) {
      priv.columnSettings[physicalColumn] = (0, _setting.columnFactory)(GridSettings, priv.columnsSettingConflicts);
    }

    if (!priv.cellSettings[physicalRow]) {
      priv.cellSettings[physicalRow] = [];
    }
    if (!priv.cellSettings[physicalRow][physicalColumn]) {
      priv.cellSettings[physicalRow][physicalColumn] = new priv.columnSettings[physicalColumn]();
    }

    cellProperties = priv.cellSettings[physicalRow][physicalColumn]; // retrieve cellProperties from cache

    cellProperties.row = physicalRow;
    cellProperties.col = physicalColumn;
    cellProperties.visualRow = row;
    cellProperties.visualCol = col;
    cellProperties.prop = prop;
    cellProperties.instance = instance;

    instance.runHooks('beforeGetCellMeta', row, col, cellProperties);
    (0, _object.extend)(cellProperties, expandType(cellProperties)); // for `type` added in beforeGetCellMeta

    if (cellProperties.cells) {
      var settings = cellProperties.cells.call(cellProperties, physicalRow, physicalColumn, prop);

      if (settings) {
        (0, _object.extend)(cellProperties, settings);
        (0, _object.extend)(cellProperties, expandType(settings)); // for `type` added in cells
      }
    }

    instance.runHooks('afterGetCellMeta', row, col, cellProperties);

    return cellProperties;
  };

  /**
   * Returns a row off the cell meta array.
   *
   * @memberof Core#
   * @function getCellMetaAtRow
   * @since 0.30.0
   * @param {Number} row Physical index of the row to return cell meta for.
   * @returns {Array}
   */
  this.getCellMetaAtRow = function (row) {
    return priv.cellSettings[row];
  };

  /**
   * Checks if the data format and config allows user to modify the column structure.
   * @returns {boolean}
   */
  this.isColumnModificationAllowed = function () {
    return !(instance.dataType === 'object' || instance.getSettings().columns);
  };

  var rendererLookup = (0, _data.cellMethodLookupFactory)('renderer');

  /**
   * Returns the cell renderer function by given `row` and `col` arguments.
   *
   * @memberof Core#
   * @function getCellRenderer
   * @since 0.11
   * @param {Number|Object} row Visual row index or cell meta object.
   * @param {Number} [col] Visual column index.
   * @returns {Function} The renderer function.
   */
  this.getCellRenderer = function (row, col) {
    return (0, _renderers.getRenderer)(rendererLookup.call(this, row, col));
  };

  /**
   * Returns the cell editor by the provided `row` and `col` arguments.
   *
   * @memberof Core#
   * @function getCellEditor
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @returns {Object} The Editor object.
   */
  this.getCellEditor = (0, _data.cellMethodLookupFactory)('editor');

  var validatorLookup = (0, _data.cellMethodLookupFactory)('validator');

  /**
   * Returns the cell validator by `row` and `col`, provided a validator is defined. If not - it doesn't return anything.
   *
   * @memberof Core#
   * @function getCellValidator
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @returns {Function|RegExp|undefined} The validator function.
   */
  this.getCellValidator = function (row, col) {
    var validator = validatorLookup.call(this, row, col);

    if (typeof validator === 'string') {
      validator = (0, _validators.getValidator)(validator);
    }

    return validator;
  };

  /**
   * Validates all cells using their validator functions and calls callback when finished.
   *
   * If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
   *
   * @memberof Core#
   * @function validateCells
   * @param {Function} [callback] The callback function.
   */
  this.validateCells = function (callback) {
    this._validateCells(callback);
  };

  /**
   * Validates rows using their validator functions and calls callback when finished.
   *
   * If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
   *
   * @memberof Core#
   * @function validateRows
   * @param {Array} [rows] Array of validation target visual row indexes.
   * @param {Function} [callback] The callback function.
   */
  this.validateRows = function (rows, callback) {
    if (!Array.isArray(rows)) {
      throw new Error('validateRows parameter `rows` must be an array');
    }
    this._validateCells(callback, rows);
  };

  /**
   * Validates columns using their validator functions and calls callback when finished.
   *
   * If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
   *
   * @memberof Core#
   * @function validateColumns
   * @param {Array} [columns] Array of validation target visual columns indexes.
   * @param {Function} [callback] The callback function.
   */
  this.validateColumns = function (columns, callback) {
    if (!Array.isArray(columns)) {
      throw new Error('validateColumns parameter `columns` must be an array');
    }
    this._validateCells(callback, undefined, columns);
  };

  /**
   * Validates all cells using their validator functions and calls callback when finished.
   *
   * If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
   *
   * Private use intended.
   *
   * @private
   * @memberof Core#
   * @function _validateCells
   * @param {Function} [callback] The callback function.
   * @param {Array} [rows] Optional. Array of validation target visual row indexes.
   * @param {Array} [columns] Optional. Array of validation target visual column indexes.
   */
  this._validateCells = function (callback, rows, columns) {
    var waitingForValidator = new ValidatorsQueue();

    if (callback) {
      waitingForValidator.onQueueEmpty = callback;
    }

    var i = instance.countRows() - 1;

    while (i >= 0) {
      if (rows !== undefined && rows.indexOf(i) === -1) {
        i--;
        continue;
      }
      var j = instance.countCols() - 1;

      while (j >= 0) {
        if (columns !== undefined && columns.indexOf(j) === -1) {
          j--;
          continue;
        }
        waitingForValidator.addValidatorToQueue();

        instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function (result) {
          if (typeof result !== 'boolean') {
            throw new Error('Validation error: result is not boolean');
          }
          if (result === false) {
            waitingForValidator.valid = false;
          }
          waitingForValidator.removeValidatorFormQueue();
        }, 'validateCells');
        j--;
      }
      i--;
    }
    waitingForValidator.checkIfQueueIsEmpty();
  };

  /**
   * Returns an array of row headers' values (if they are enabled). If param `row` was given, it returns the header of the given row as a string.
   *
   * @memberof Core#
   * @function getRowHeader
   * @param {Number} [row] Visual row index.
   * @fires Hooks#modifyRowHeader
   * @returns {Array|String} Array of header values / single header value.
   */
  this.getRowHeader = function (row) {
    var rowHeader = priv.settings.rowHeaders;

    if (row !== void 0) {
      row = instance.runHooks('modifyRowHeader', row);
    }
    if (row === void 0) {
      rowHeader = [];
      (0, _number.rangeEach)(instance.countRows() - 1, function (i) {
        rowHeader.push(instance.getRowHeader(i));
      });
    } else if (Array.isArray(rowHeader) && rowHeader[row] !== void 0) {
      rowHeader = rowHeader[row];
    } else if ((0, _function.isFunction)(rowHeader)) {
      rowHeader = rowHeader(row);
    } else if (rowHeader && typeof rowHeader !== 'string' && typeof rowHeader !== 'number') {
      rowHeader = row + 1;
    }

    return rowHeader;
  };

  /**
   * Returns information about if this table is configured to display row headers.
   *
   * @memberof Core#
   * @function hasRowHeaders
   * @returns {Boolean} `true` if the instance has the row headers enabled, `false` otherwise.
   * @since 0.11
   */
  this.hasRowHeaders = function () {
    return !!priv.settings.rowHeaders;
  };

  /**
   * Returns information about if this table is configured to display column headers.
   *
   * @memberof Core#
   * @function hasColHeaders
   * @since 0.11
   * @returns {Boolean} `True` if the instance has the column headers enabled, `false` otherwise.
   */
  this.hasColHeaders = function () {
    if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) {
      // Polymer has empty value = null
      return !!priv.settings.colHeaders;
    }
    for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
      if (instance.getColHeader(i)) {
        return true;
      }
    }

    return false;
  };

  /**
   * Returns an array of column headers (in string format, if they are enabled). If param `col` is given, it returns the header at the given column as a string.
   *
   * @memberof Core#
   * @function getColHeader
   * @param {Number} [col] Visual column index.
   * @fires Hooks#modifyColHeader
   * @returns {Array|String} The column header(s).
   */
  this.getColHeader = function (col) {
    var columnsAsFunc = priv.settings.columns && (0, _function.isFunction)(priv.settings.columns);
    var result = priv.settings.colHeaders;

    col = instance.runHooks('modifyColHeader', col);

    if (col === void 0) {
      var out = [];
      var ilen = columnsAsFunc ? instance.countSourceCols() : instance.countCols();

      for (var i = 0; i < ilen; i++) {
        out.push(instance.getColHeader(i));
      }

      result = out;
    } else {
      var translateVisualIndexToColumns = function translateVisualIndexToColumns(col) {
        var arr = [];
        var columnsLen = instance.countSourceCols();
        var index = 0;

        for (; index < columnsLen; index++) {
          if ((0, _function.isFunction)(instance.getSettings().columns) && instance.getSettings().columns(index)) {
            arr.push(index);
          }
        }

        return arr[col];
      };
      var baseCol = col;
      col = instance.runHooks('modifyCol', col);

      var prop = translateVisualIndexToColumns(col);

      if (priv.settings.columns && (0, _function.isFunction)(priv.settings.columns) && priv.settings.columns(prop) && priv.settings.columns(prop).title) {
        result = priv.settings.columns(prop).title;
      } else if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) {
        result = priv.settings.columns[col].title;
      } else if (Array.isArray(priv.settings.colHeaders) && priv.settings.colHeaders[col] !== void 0) {
        result = priv.settings.colHeaders[col];
      } else if ((0, _function.isFunction)(priv.settings.colHeaders)) {
        result = priv.settings.colHeaders(col);
      } else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') {
        result = (0, _data.spreadsheetColumnLabel)(baseCol); // see #1458
      }
    }

    return result;
  };

  /**
   * Return column width from settings (no guessing). Private use intended.
   *
   * @private
   * @memberof Core#
   * @function _getColWidthFromSettings
   * @param {Number} col Visual col index.
   * @returns {Number}
   */
  this._getColWidthFromSettings = function (col) {
    var cellProperties = instance.getCellMeta(0, col);
    var width = cellProperties.width;

    if (width === void 0 || width === priv.settings.width) {
      width = cellProperties.colWidths;
    }
    if (width !== void 0 && width !== null) {
      switch (typeof width === 'undefined' ? 'undefined' : _typeof(width)) {
        case 'object':
          // array
          width = width[col];
          break;

        case 'function':
          width = width(col);
          break;
        default:
          break;
      }
      if (typeof width === 'string') {
        width = parseInt(width, 10);
      }
    }

    return width;
  };

  /**
   * Returns the width of the requested column.
   *
   * @memberof Core#
   * @function getColWidth
   * @since 0.11
   * @param {Number} col Visual column index.
   * @returns {Number} Column width.
   * @fires Hooks#modifyColWidth
   */
  this.getColWidth = function (col) {
    var width = instance._getColWidthFromSettings(col);

    width = instance.runHooks('modifyColWidth', width, col);

    if (width === void 0) {
      width = _src.ViewportColumnsCalculator.DEFAULT_WIDTH;
    }

    return width;
  };

  /**
   * Return row height from settings (no guessing). Private use intended.
   *
   * @private
   * @memberof Core#
   * @function _getRowHeightFromSettings
   * @param {Number} row Visual row index.
   * @returns {Number}
   */
  this._getRowHeightFromSettings = function (row) {
    // let cellProperties = instance.getCellMeta(row, 0);
    // let height = cellProperties.height;
    //
    // if (height === void 0 || height === priv.settings.height) {
    //  height = cellProperties.rowHeights;
    // }
    var height = priv.settings.rowHeights;

    if (height !== void 0 && height !== null) {
      switch (typeof height === 'undefined' ? 'undefined' : _typeof(height)) {
        case 'object':
          // array
          height = height[row];
          break;

        case 'function':
          height = height(row);
          break;
        default:
          break;
      }
      if (typeof height === 'string') {
        height = parseInt(height, 10);
      }
    }

    return height;
  };

  /**
   * Returns the row height.
   *
   * @memberof Core#
   * @function getRowHeight
   * @since 0.11
   * @param {Number} row Visual row index.
   * @returns {Number} The given row's height.
   * @fires Hooks#modifyRowHeight
   */
  this.getRowHeight = function (row) {
    var height = instance._getRowHeightFromSettings(row);

    height = instance.runHooks('modifyRowHeight', height, row);

    return height;
  };

  /**
   * Returns the total number of rows in the data source.
   *
   * @memberof Core#
   * @function countSourceRows
   * @since 0.20.0
   * @returns {Number} Total number in rows in data source.
   */
  this.countSourceRows = function () {
    var sourceLength = instance.runHooks('modifySourceLength');
    return sourceLength || (instance.getSourceData() ? instance.getSourceData().length : 0);
  };

  /**
   * Returns the total number of columns in the data source.
   *
   * @memberof Core#
   * @function countSourceCols
   * @since 0.26.1
   * @returns {Number} Total number in columns in data source.
   */
  this.countSourceCols = function () {
    var len = 0;
    var obj = instance.getSourceData() && instance.getSourceData()[0] ? instance.getSourceData()[0] : [];

    if ((0, _object.isObject)(obj)) {
      len = (0, _object.deepObjectSize)(obj);
    } else {
      len = obj.length || 0;
    }

    return len;
  };

  /**
   * Returns the total number of rows in the grid.
   *
   * @memberof Core#
   * @function countRows
   * @returns {Number} Total number in rows the grid.
   */
  this.countRows = function () {
    return datamap.getLength();
  };

  /**
   * Returns the total number of columns in the grid.
   *
   * @memberof Core#
   * @function countCols
   * @returns {Number} Total number of columns.
   */
  this.countCols = function () {
    var maxCols = this.getSettings().maxCols;
    var dataHasLength = false;
    var dataLen = 0;

    if (instance.dataType === 'array') {
      dataHasLength = priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length;
    }

    if (dataHasLength) {
      dataLen = priv.settings.data[0].length;
    }

    if (priv.settings.columns) {
      var columnsIsFunction = (0, _function.isFunction)(priv.settings.columns);

      if (columnsIsFunction) {
        if (instance.dataType === 'array') {
          var columnLen = 0;

          for (var i = 0; i < dataLen; i++) {
            if (priv.settings.columns(i)) {
              columnLen++;
            }
          }

          dataLen = columnLen;
        } else if (instance.dataType === 'object' || instance.dataType === 'function') {
          dataLen = datamap.colToPropCache.length;
        }
      } else {
        dataLen = priv.settings.columns.length;
      }
    } else if (instance.dataType === 'object' || instance.dataType === 'function') {
      dataLen = datamap.colToPropCache.length;
    }

    return Math.min(maxCols, dataLen);
  };

  /**
   * Returns an visual index of the first rendered row.
   *
   * @memberof Core#
   * @function rowOffset
   * @returns {Number} Visual index of first rendered row.
   */
  this.rowOffset = function () {
    return instance.view.wt.wtTable.getFirstRenderedRow();
  };

  /**
   * Returns the visual index of the first rendered column.
   *
   * @memberof Core#
   * @function colOffset
   * @returns {Number} Visual index of the first visible column.
   */
  this.colOffset = function () {
    return instance.view.wt.wtTable.getFirstRenderedColumn();
  };

  /**
   * Returns the number of rendered rows (including rows partially or fully rendered outside viewport).
   *
   * @memberof Core#
   * @function countRenderedRows
   * @returns {Number} Returns -1 if table is not visible.
   */
  this.countRenderedRows = function () {
    return instance.view.wt.drawn ? instance.view.wt.wtTable.getRenderedRowsCount() : -1;
  };

  /**
   * Returns the number of visible rows (rendered rows that fully fit inside viewport).
   *
   * @memberof Core#
   * @function countVisibleRows
   * @returns {Number} Number of visible rows or -1.
   */
  this.countVisibleRows = function () {
    return instance.view.wt.drawn ? instance.view.wt.wtTable.getVisibleRowsCount() : -1;
  };

  /**
   * Returns the number of rendered columns (including columns partially or fully rendered outside viewport).
   *
   * @memberof Core#
   * @function countRenderedCols
   * @returns {Number} Returns -1 if table is not visible.
   */
  this.countRenderedCols = function () {
    return instance.view.wt.drawn ? instance.view.wt.wtTable.getRenderedColumnsCount() : -1;
  };

  /**
   * Returns the number of visible columns. Returns -1 if table is not visible
   *
   * @memberof Core#
   * @function countVisibleCols
   * @return {Number} Number of visible columns or -1.
   */
  this.countVisibleCols = function () {
    return instance.view.wt.drawn ? instance.view.wt.wtTable.getVisibleColumnsCount() : -1;
  };

  /**
   * Returns the number of empty rows. If the optional ending parameter is `true`, returns the
   * number of empty rows at the bottom of the table.
   *
   * @memberof Core#
   * @function countEmptyRows
   * @param {Boolean} [ending] If `true`, will only count empty rows at the end of the data source.
   * @returns {Number} Count empty rows
   * @fires Hooks#modifyRow
   */
  this.countEmptyRows = function (ending) {
    var i = instance.countRows() - 1,
        empty = 0,
        row;

    while (i >= 0) {
      row = instance.runHooks('modifyRow', i);

      if (instance.isEmptyRow(row)) {
        empty++;
      } else if (ending) {
        break;
      }
      i--;
    }

    return empty;
  };

  /**
   * Returns the number of empty columns. If the optional ending parameter is `true`, returns the number of empty
   * columns at right hand edge of the table.
   *
   * @memberof Core#
   * @function countEmptyCols
   * @param {Boolean} [ending] If `true`, will only count empty columns at the end of the data source row.
   * @returns {Number} Count empty cols
   */
  this.countEmptyCols = function (ending) {
    if (instance.countRows() < 1) {
      return 0;
    }
    var i = instance.countCols() - 1,
        empty = 0;

    while (i >= 0) {
      if (instance.isEmptyCol(i)) {
        empty++;
      } else if (ending) {
        break;
      }
      i--;
    }

    return empty;
  };

  /**
   * Check if all cells in the row declared by the `row` argument are empty.
   *
   * @memberof Core#
   * @function isEmptyRow
   * @param {Number} row Row index.
   * @returns {Boolean} `true` if the row at the given `row` is empty, `false` otherwise.
   */
  this.isEmptyRow = function (row) {
    return priv.settings.isEmptyRow.call(instance, row);
  };

  /**
   * Check if all cells in the the column declared by the `col` argument are empty.
   *
   * @memberof Core#
   * @function isEmptyCol
   * @param {Number} col Column index.
   * @returns {Boolean} `true` if the column at the given `col` is empty, `false` otherwise.
   */
  this.isEmptyCol = function (col) {
    return priv.settings.isEmptyCol.call(instance, col);
  };

  /**
   * Select cell specified by `row` and `col` values or a range of cells finishing at `endRow`, `endCol`.
   * By default, viewport will be scrolled to selection.
   * After the `selectCell` method had finished, the instance will be listening to keyboard input on the document.
   *
   * @memberof Core#
   * @function selectCell
   * @param {Number} row Visual row index.
   * @param {Number} col Visual column index.
   * @param {Number} [endRow] Visual end row index (if selecting a range).
   * @param {Number} [endCol] Visual end column index (if selecting a range).
   * @param {Boolean} [scrollToCell=true] If `true`, the viewport will be scrolled to the selection.
   * @param {Boolean} [changeListener=true] If `false`, Handsontable will not change keyboard events listener to himself.
   * @returns {Boolean} `true` if selection was successful, `false` otherwise.
   */
  this.selectCell = function (row, col, endRow, endCol, scrollToCell, changeListener) {
    var coords;

    changeListener = (0, _mixed.isUndefined)(changeListener) || changeListener === true;

    if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) {
      return false;
    }
    if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
      return false;
    }
    if ((0, _mixed.isDefined)(endRow)) {
      if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
        return false;
      }
      if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
        return false;
      }
    }
    coords = new _src.CellCoords(row, col);
    priv.selRange = new _src.CellRange(coords, coords, coords);

    if (changeListener) {
      instance.listen();
    }

    if ((0, _mixed.isUndefined)(endRow)) {
      selection.setRangeEnd(priv.selRange.from, scrollToCell);
    } else {
      selection.setRangeEnd(new _src.CellCoords(endRow, endCol), scrollToCell);
    }
    instance.selection.finish();
    return true;
  };

  /**
   * Select the cell specified by the `row` and `prop` arguments, or a range finishing at `endRow`, `endProp`.
   * By default, viewport will be scrolled to selection.
   *
   * @memberof Core#
   * @function selectCellByProp
   * @param {Number} row Visual row index.
   * @param {String} prop Property name.
   * @param {Number} [endRow] visual end row index (if selecting a range).
   * @param {String} [endProp] End property name (if selecting a range).
   * @param {Boolean} [scrollToCell=true] If `true`, viewport will be scrolled to the selection.
   * @returns {Boolean} `true` if selection was successful, `false` otherwise.
   */
  this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) {
    var _instance5;

    arguments[1] = datamap.propToCol(arguments[1]);

    if ((0, _mixed.isDefined)(arguments[3])) {
      arguments[3] = datamap.propToCol(arguments[3]);
    }

    return (_instance5 = instance).selectCell.apply(_instance5, arguments);
  };

  /**
   * Deselects the current cell selection on grid.
   *
   * @memberof Core#
   * @function deselectCell
   */
  this.deselectCell = function () {
    selection.deselect();
  };

  /**
   * Scroll viewport to coords specified by the `row` and `column` arguments.
   *
   * @since 0.24.3
   * @memberof Core#
   * @function scrollViewportTo
   * @param {Number} [row] Visual row index.
   * @param {Number} [column] Visual column index.
   * @param {Boolean} [snapToBottom = false] If `true`, viewport is scrolled to show the cell on the bottom of the table.
   * @param {Boolean} [snapToRight = false] If `true`, viewport is scrolled to show the cell on the right side of the table.
   * @returns {Boolean} `true` if scroll was successful, `false` otherwise.
   */
  this.scrollViewportTo = function (row, column) {
    var snapToBottom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    var snapToRight = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

    if (row !== void 0 && (row < 0 || row >= instance.countRows())) {
      return false;
    }
    if (column !== void 0 && (column < 0 || column >= instance.countCols())) {
      return false;
    }

    var result = false;

    if (row !== void 0 && column !== void 0) {
      instance.view.wt.wtOverlays.topOverlay.scrollTo(row, snapToBottom);
      instance.view.wt.wtOverlays.leftOverlay.scrollTo(column, snapToRight);

      result = true;
    }
    if (typeof row === 'number' && typeof column !== 'number') {
      instance.view.wt.wtOverlays.topOverlay.scrollTo(row, snapToBottom);

      result = true;
    }
    if (typeof column === 'number' && typeof row !== 'number') {
      instance.view.wt.wtOverlays.leftOverlay.scrollTo(column, snapToRight);

      result = true;
    }

    return result;
  };

  /**
   * Removes grid from the DOM.
   *
   * @memberof Core#
   * @function destroy
   * @fires Hooks#afterDestroy
   */
  this.destroy = function () {

    instance._clearTimeouts();
    if (instance.view) {
      // in case HT is destroyed before initialization has finished
      instance.view.destroy();
    }
    if (dataSource) {
      dataSource.destroy();
    }
    dataSource = null;

    if (false) {
      var licenseInfo = document.querySelector('#hot-display-license-info');

      if (licenseInfo) {
        licenseInfo.parentNode.removeChild(licenseInfo);
      }
    }
    (0, _element.empty)(instance.rootElement);
    eventManager.destroy();

    instance.runHooks('afterDestroy');
    _pluginHooks2.default.getSingleton().destroy(instance);

    for (var i in instance) {
      if ((0, _object.hasOwnProperty)(instance, i)) {
        // replace instance methods with post mortem
        if ((0, _function.isFunction)(instance[i])) {
          instance[i] = postMortem;
        } else if (i !== 'guid') {
          // replace instance properties with null (restores memory)
          // it should not be necessary but this prevents a memory leak side effects that show itself in Jasmine tests
          instance[i] = null;
        }
      }
    }

    // replace private properties with null (restores memory)
    // it should not be necessary but this prevents a memory leak side effects that show itself in Jasmine tests
    if (datamap) {
      datamap.destroy();
    }
    datamap = null;
    priv = null;
    grid = null;
    selection = null;
    editorManager = null;
    instance = null;
    GridSettings = null;
  };

  /**
   * Replacement for all methods after Handsotnable was destroyed.
   *
   * @private
   */
  function postMortem() {
    throw new Error('This method cannot be called because this Handsontable instance has been destroyed');
  }

  /**
   * Returns the active editor object.
   *
   * @memberof Core#
   * @function getActiveEditor
   * @returns {Object} The active editor object.
   */
  this.getActiveEditor = function () {
    return editorManager.getActiveEditor();
  };

  /**
   * Returns plugin instance using the plugin name provided.
   *
   * @memberof Core#
   * @function getPlugin
   * @param {String} pluginName The plugin name.
   * @returns {*} The plugin instance.
   * @since 0.15.0
   */
  this.getPlugin = function (pluginName) {
    return (0, _plugins.getPlugin)(this, pluginName);
  };

  /**
   * Returns the Handsontable instance.
   *
   * @memberof Core#
   * @function getInstance
   * @returns {Handsontable} The Handsontable instance.
   */
  this.getInstance = function () {
    return instance;
  };

  /**
   * Adds listener to the specified hook name (only for this Handsontable instance).
   *
   * @memberof Core#
   * @function addHook
   * @see Hooks#add
   * @param {String} key Hook name.
   * @param {Function|Array} callback Function or array of Functions.
   *
   * @example
   * ```js
   * hot.addHook('beforeInit', myCallback);
   * ```
   */
  this.addHook = function (key, callback) {
    _pluginHooks2.default.getSingleton().add(key, callback, instance);
  };

  /**
   * Check if for a specified hook name there are added listeners (only for this Handsontable instance).
   *
   * @memberof Core#
   * @function hasHook
   * @see Hooks#has
   * @param {String} key Hook name
   * @return {Boolean}
   *
   * @example
   * ```js
   * var hasBeforeInitListeners = hot.hasHook('beforeInit');
   * ```
   */
  this.hasHook = function (key) {
    return _pluginHooks2.default.getSingleton().has(key, instance);
  };

  /**
   * Adds listener to specified hook name (only for this Handsontable instance).
   * After the listener is triggered, it will be automatically removed.
   *
   * @memberof Core#
   * @function addHookOnce
   * @see Hooks#once
   * @param {String} key Hook name.
   * @param {Function|Array} callback Function or array of Functions.
   *
   * @example
   * ```js
   * hot.addHookOnce('beforeInit', myCallback);
   * ```
   */
  this.addHookOnce = function (key, callback) {
    _pluginHooks2.default.getSingleton().once(key, callback, instance);
  };

  /**
   * Removes the hook listener previously registered with {@link Core#addHook}.
   *
   * @memberof Core#
   * @function removeHook
   * @see Hooks#remove
   * @param {String} key Hook name.
   * @param {Function} callback Function which have been registered via {@link Core#addHook}.
   *
   * @example
   * ```js
   * hot.removeHook('beforeInit', myCallback);
   * ```
   */
  this.removeHook = function (key, callback) {
    _pluginHooks2.default.getSingleton().remove(key, callback, instance);
  };

  /**
   * Run the callbacks for the hook provided in the `key` argument using the parameters given in the other arguments.
   *
   * @memberof Core#
   * @function runHooks
   * @see Hooks#run
   * @param {String} key Hook name.
   * @param {*} [p1] Argument passed to the callback.
   * @param {*} [p2] Argument passed to the callback.
   * @param {*} [p3] Argument passed to the callback.
   * @param {*} [p4] Argument passed to the callback.
   * @param {*} [p5] Argument passed to the callback.
   * @param {*} [p6] Argument passed to the callback.
   * @returns {*}
   *
   * @example
   * ```js
   * hot.runHooks('beforeInit');
   * ```
   */
  this.runHooks = function (key, p1, p2, p3, p4, p5, p6) {
    return _pluginHooks2.default.getSingleton().run(instance, key, p1, p2, p3, p4, p5, p6);
  };

  /**
   * Get phrase for specified dictionary key.
   *
   * @memberof Core#
   * @function getTranslatedPhrase
   * @since 0.35.0
   * @param {String} dictionaryKey Constant which is dictionary key.
   * @param {*} extraArguments Arguments which will be handled by formatters.
   *
   * @returns {String}
   */
  this.getTranslatedPhrase = function (dictionaryKey, extraArguments) {
    return (0, _i18n.getTranslatedPhrase)(priv.settings.language, dictionaryKey, extraArguments);
  };

  this.timeouts = [];

  /**
   * Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called.
   *
   * @param {*} handle
   * @private
   */
  this._registerTimeout = function (handle) {
    this.timeouts.push(handle);
  };

  /**
   * Clears all known timeouts.
   *
   * @private
   */
  this._clearTimeouts = function () {
    for (var i = 0, ilen = this.timeouts.length; i < ilen; i++) {
      clearTimeout(this.timeouts[i]);
    }
  };

  _pluginHooks2.default.getSingleton().run(instance, 'construct');
};

/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.columnFactory = columnFactory;

var _object = __webpack_require__(1);

/* eslint-disable import/prefer-default-export */
/**
 * Factory for columns constructors.
 *
 * @param {Object} GridSettings
 * @param {Array} conflictList
 * @return {Object} ColumnSettings
 */
function columnFactory(GridSettings, conflictList) {
  function ColumnSettings() {};

  (0, _object.inherit)(ColumnSettings, GridSettings);

  // Clear conflict settings
  for (var i = 0, len = conflictList.length; i < len; i++) {
    ColumnSettings.prototype[conflictList[i]] = void 0;
  }

  return ColumnSettings;
}

/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.spreadsheetColumnLabel = spreadsheetColumnLabel;
exports.spreadsheetColumnIndex = spreadsheetColumnIndex;
exports.createSpreadsheetData = createSpreadsheetData;
exports.createSpreadsheetObjectData = createSpreadsheetObjectData;
exports.createEmptySpreadsheetData = createEmptySpreadsheetData;
exports.translateRowsToColumns = translateRowsToColumns;
exports.cellMethodLookupFactory = cellMethodLookupFactory;

var _cellTypes = __webpack_require__(83);

var _object = __webpack_require__(1);

var COLUMN_LABEL_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var COLUMN_LABEL_BASE_LENGTH = COLUMN_LABEL_BASE.length;

/**
 * Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc.
 *
 * @param {Number} index Column index.
 * @returns {String}
 */
function spreadsheetColumnLabel(index) {
  var dividend = index + 1;
  var columnLabel = '';
  var modulo = void 0;

  while (dividend > 0) {
    modulo = (dividend - 1) % COLUMN_LABEL_BASE_LENGTH;
    columnLabel = String.fromCharCode(65 + modulo) + columnLabel;
    dividend = parseInt((dividend - modulo) / COLUMN_LABEL_BASE_LENGTH, 10);
  }

  return columnLabel;
}

/**
 * Generates spreadsheet-like column index from theirs labels: A, B, C ...., Z, AA, AB, etc.
 *
 * @param {String} label Column label.
 * @returns {Number}
 */
function spreadsheetColumnIndex(label) {
  var result = 0;

  if (label) {
    for (var i = 0, j = label.length - 1; i < label.length; i += 1, j -= 1) {
      result += Math.pow(COLUMN_LABEL_BASE_LENGTH, j) * (COLUMN_LABEL_BASE.indexOf(label[i]) + 1);
    }
  }
  --result;

  return result;
}

/**
 * Creates 2D array of Excel-like values "A1", "A2", ...
 *
 * @param {Number} rows Number of rows to generate.
 * @param {Number} columns Number of columns to generate.
 * @returns {Array}
 */
function createSpreadsheetData() {
  var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;

  var _rows = [],
      i,
      j;

  for (i = 0; i < rows; i++) {
    var row = [];

    for (j = 0; j < columns; j++) {
      row.push(spreadsheetColumnLabel(j) + (i + 1));
    }
    _rows.push(row);
  }

  return _rows;
}

/**
 * Creates 2D array of Excel-like values "A1", "A2", as an array of objects.
 *
 * @param {Number} rows Number of rows to generate.
 * @param {Number} colCount Number of columns to generate.
 * @returns {Array}
 */
function createSpreadsheetObjectData() {
  var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100;
  var colCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;

  var _rows = [],
      i,
      j;

  for (i = 0; i < rows; i++) {
    var row = {};

    for (j = 0; j < colCount; j++) {
      row['prop' + j] = spreadsheetColumnLabel(j) + (i + 1);
    }
    _rows.push(row);
  }

  return _rows;
}

/**
 * Generates an empty data object.
 *
 * @param {Number} rows Number of rows to generate.
 * @param {Number} columns Number of columns to generate
 * @returns {Array}
 */
function createEmptySpreadsheetData(rows, columns) {
  var data = [];
  var row = void 0;

  for (var i = 0; i < rows; i++) {
    row = [];
    for (var j = 0; j < columns; j++) {
      row.push('');
    }
    data.push(row);
  }

  return data;
}

function translateRowsToColumns(input) {
  var i,
      ilen,
      j,
      jlen,
      output = [],
      olen = 0;

  for (i = 0, ilen = input.length; i < ilen; i++) {
    for (j = 0, jlen = input[i].length; j < jlen; j++) {
      if (j == olen) {
        output.push([]);
        olen++;
      }
      output[j].push(input[i][j]);
    }
  }

  return output;
}

/**
 * Factory that produces a function for searching methods (or any properties) which could be defined directly in
 * table configuration or implicitly, within cell type definition.
 *
 * For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be
 * defined implicitly using "type" property.
 *
 * Methods/properties defined explicitly always takes precedence over those defined through "type".
 *
 * If the method/property is not found in an object, searching is continued recursively through prototype chain, until
 * it reaches the Object.prototype.
 *
 *
 * @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable')
 * @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type"
 * @returns {Function}
 */
function cellMethodLookupFactory(methodName, allowUndefined) {

  allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined;

  return function cellMethodLookup(row, col) {
    return function getMethodFromProperties(properties) {

      if (!properties) {
        return; // method not found
      } else if ((0, _object.hasOwnProperty)(properties, methodName) && properties[methodName] !== void 0) {
        // check if it is own and is not empty
        return properties[methodName]; // method defined directly
      } else if ((0, _object.hasOwnProperty)(properties, 'type') && properties.type) {
        // check if it is own and is not empty
        var type;

        if (typeof properties.type != 'string') {
          throw new Error('Cell type must be a string ');
        }
        type = (0, _cellTypes.getCellType)(properties.type);

        if ((0, _object.hasOwnProperty)(type, methodName)) {
          return type[methodName]; // method defined in type.
        } else if (allowUndefined) {
          return; // method does not defined in type (eg. validator), returns undefined
        }
      }

      return getMethodFromProperties(Object.getPrototypeOf(properties));
    }(typeof row == 'number' ? this.getCellMeta(row, col) : row);
  };
}

/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _array = __webpack_require__(2);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class GhostTable
 * @util
 */
var GhostTable = function () {
  function GhostTable(hotInstance) {
    _classCallCheck(this, GhostTable);

    /**
     * Handsontable instance.
     *
     * @type {Core}
     */
    this.hot = hotInstance;
    /**
     * Container element where every table will be injected.
     *
     * @type {HTMLElement|null}
     */
    this.container = null;
    /**
     * Flag which determine is table was injected to DOM.
     *
     * @type {Boolean}
     */
    this.injected = false;
    /**
     * Added rows collection.
     *
     * @type {Array}
     */
    this.rows = [];
    /**
     * Added columns collection.
     *
     * @type {Array}
     */
    this.columns = [];
    /**
     * Samples prepared for calculations.
     *
     * @type {Map}
     * @default {null}
     */
    this.samples = null;
    /**
     * Ghost table settings.
     *
     * @type {Object}
     * @default {Object}
     */
    this.settings = {
      useHeaders: true
    };
  }

  /**
   * Add row.
   *
   * @param {Number} row Row index.
   * @param {Map} samples Samples Map object.
   */


  _createClass(GhostTable, [{
    key: 'addRow',
    value: function addRow(row, samples) {
      if (this.columns.length) {
        throw new Error('Doesn\'t support multi-dimensional table');
      }
      if (!this.rows.length) {
        this.container = this.createContainer(this.hot.rootElement.className);
      }
      var rowObject = { row: row };
      this.rows.push(rowObject);

      this.samples = samples;
      this.table = this.createTable(this.hot.table.className);
      this.table.colGroup.appendChild(this.createColGroupsCol());
      this.table.tr.appendChild(this.createRow(row));
      this.container.container.appendChild(this.table.fragment);

      rowObject.table = this.table.table;
    }

    /**
     * Add a row consisting of the column headers.
     */

  }, {
    key: 'addColumnHeadersRow',
    value: function addColumnHeadersRow(samples) {
      if (this.hot.getColHeader(0) != null) {
        var rowObject = { row: -1 };
        this.rows.push(rowObject);

        this.container = this.createContainer(this.hot.rootElement.className);

        this.samples = samples;
        this.table = this.createTable(this.hot.table.className);
        this.table.colGroup.appendChild(this.createColGroupsCol());
        this.table.tHead.appendChild(this.createColumnHeadersRow());
        this.container.container.appendChild(this.table.fragment);

        rowObject.table = this.table.table;
      }
    }

    /**
     * Add column.
     *
     * @param {Number} column Column index.
     * @param {Map} samples Samples Map object.
     */

  }, {
    key: 'addColumn',
    value: function addColumn(column, samples) {
      if (this.rows.length) {
        throw new Error('Doesn\'t support multi-dimensional table');
      }
      if (!this.columns.length) {
        this.container = this.createContainer(this.hot.rootElement.className);
      }
      var columnObject = { col: column };
      this.columns.push(columnObject);

      this.samples = samples;
      this.table = this.createTable(this.hot.table.className);

      if (this.getSetting('useHeaders') && this.hot.getColHeader(column) !== null) {
        this.hot.view.appendColHeader(column, this.table.th);
      }
      this.table.tBody.appendChild(this.createCol(column));
      this.container.container.appendChild(this.table.fragment);

      columnObject.table = this.table.table;
    }

    /**
     * Get calculated heights.
     *
     * @param {Function} callback Callback which will be fired for each calculated row.
     */

  }, {
    key: 'getHeights',
    value: function getHeights(callback) {
      if (!this.injected) {
        this.injectTable();
      }
      (0, _array.arrayEach)(this.rows, function (row) {
        // -1 <- reduce border-top from table
        callback(row.row, (0, _element.outerHeight)(row.table) - 1);
      });
    }

    /**
     * Get calculated widths.
     *
     * @param {Function} callback Callback which will be fired for each calculated column.
     */

  }, {
    key: 'getWidths',
    value: function getWidths(callback) {
      if (!this.injected) {
        this.injectTable();
      }
      (0, _array.arrayEach)(this.columns, function (column) {
        callback(column.col, (0, _element.outerWidth)(column.table));
      });
    }

    /**
     * Set the Ghost Table settings to the provided object.
     *
     * @param {Object} settings New Ghost Table Settings
     */

  }, {
    key: 'setSettings',
    value: function setSettings(settings) {
      this.settings = settings;
    }

    /**
     * Set a single setting of the Ghost Table.
     *
     * @param {String} name Setting name.
     * @param {*} value Setting value.
     */

  }, {
    key: 'setSetting',
    value: function setSetting(name, value) {
      if (!this.settings) {
        this.settings = {};
      }

      this.settings[name] = value;
    }

    /**
     * Get the Ghost Table settings.
     *
     * @returns {Object|null}
     */

  }, {
    key: 'getSettings',
    value: function getSettings() {
      return this.settings;
    }

    /**
     * Get a single Ghost Table setting.
     *
     * @param {String} name
     * @returns {Boolean|null}
     */

  }, {
    key: 'getSetting',
    value: function getSetting(name) {
      if (this.settings) {
        return this.settings[name];
      }
      return null;
    }

    /**
     * Create colgroup col elements.
     *
     * @returns {DocumentFragment}
     */

  }, {
    key: 'createColGroupsCol',
    value: function createColGroupsCol() {
      var _this = this;

      var d = document;
      var fragment = d.createDocumentFragment();

      if (this.hot.hasRowHeaders()) {
        fragment.appendChild(this.createColElement(-1));
      }

      this.samples.forEach(function (sample) {
        (0, _array.arrayEach)(sample.strings, function (string) {
          fragment.appendChild(_this.createColElement(string.col));
        });
      });

      return fragment;
    }

    /**
     * Create table row element.
     *
     * @param {Number} row Row index.
     * @returns {DocumentFragment} Returns created table row elements.
     */

  }, {
    key: 'createRow',
    value: function createRow(row) {
      var _this2 = this;

      var d = document;
      var fragment = d.createDocumentFragment();
      var th = d.createElement('th');

      if (this.hot.hasRowHeaders()) {
        this.hot.view.appendRowHeader(row, th);

        fragment.appendChild(th);
      }

      this.samples.forEach(function (sample) {
        (0, _array.arrayEach)(sample.strings, function (string) {
          var column = string.col;
          var cellProperties = _this2.hot.getCellMeta(row, column);

          cellProperties.col = column;
          cellProperties.row = row;

          var renderer = _this2.hot.getCellRenderer(cellProperties);
          var td = d.createElement('td');

          renderer(_this2.hot, td, row, column, _this2.hot.colToProp(column), string.value, cellProperties);
          fragment.appendChild(td);
        });
      });

      return fragment;
    }
  }, {
    key: 'createColumnHeadersRow',
    value: function createColumnHeadersRow() {
      var _this3 = this;

      var d = document;
      var fragment = d.createDocumentFragment();

      if (this.hot.hasRowHeaders()) {
        var th = d.createElement('th');
        this.hot.view.appendColHeader(-1, th);
        fragment.appendChild(th);
      }

      this.samples.forEach(function (sample) {
        (0, _array.arrayEach)(sample.strings, function (string) {
          var column = string.col;

          var th = d.createElement('th');

          _this3.hot.view.appendColHeader(column, th);
          fragment.appendChild(th);
        });
      });

      return fragment;
    }

    /**
     * Create table column elements.
     *
     * @param {Number} column Column index.
     * @returns {DocumentFragment} Returns created column table column elements.
     */

  }, {
    key: 'createCol',
    value: function createCol(column) {
      var _this4 = this;

      var d = document;
      var fragment = d.createDocumentFragment();

      this.samples.forEach(function (sample) {
        (0, _array.arrayEach)(sample.strings, function (string) {
          var row = string.row;
          var cellProperties = _this4.hot.getCellMeta(row, column);

          cellProperties.col = column;
          cellProperties.row = row;

          var renderer = _this4.hot.getCellRenderer(cellProperties);
          var td = d.createElement('td');
          var tr = d.createElement('tr');

          renderer(_this4.hot, td, row, column, _this4.hot.colToProp(column), string.value, cellProperties);
          tr.appendChild(td);
          fragment.appendChild(tr);
        });
      });

      return fragment;
    }

    /**
     * Remove table from document and reset internal state.
     */

  }, {
    key: 'clean',
    value: function clean() {
      this.rows.length = 0;
      this.rows[-1] = void 0;
      this.columns.length = 0;

      if (this.samples) {
        this.samples.clear();
      }
      this.samples = null;
      this.removeTable();
    }

    /**
     * Inject generated table into document.
     *
     * @param {HTMLElement} [parent=null]
     */

  }, {
    key: 'injectTable',
    value: function injectTable() {
      var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

      if (!this.injected) {
        (parent || this.hot.rootElement).appendChild(this.container.fragment);
        this.injected = true;
      }
    }

    /**
     * Remove table from document.
     */

  }, {
    key: 'removeTable',
    value: function removeTable() {
      if (this.injected && this.container.container.parentNode) {
        this.container.container.parentNode.removeChild(this.container.container);
        this.container = null;
        this.injected = false;
      }
    }

    /**
     * Create col element.
     *
     * @param {Number} column Column index.
     * @returns {HTMLElement}
     */

  }, {
    key: 'createColElement',
    value: function createColElement(column) {
      var d = document;
      var col = d.createElement('col');

      col.style.width = this.hot.view.wt.wtTable.getStretchedColumnWidth(column) + 'px';

      return col;
    }

    /**
     * Create table element.
     *
     * @param {String} className
     * @returns {Object}
     */

  }, {
    key: 'createTable',
    value: function createTable() {
      var className = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

      var d = document;
      var fragment = d.createDocumentFragment();
      var table = d.createElement('table');
      var tHead = d.createElement('thead');
      var tBody = d.createElement('tbody');
      var colGroup = d.createElement('colgroup');
      var tr = d.createElement('tr');
      var th = d.createElement('th');

      if (this.isVertical()) {
        table.appendChild(colGroup);
      }
      if (this.isHorizontal()) {
        tr.appendChild(th);
        tHead.appendChild(tr);
        table.style.tableLayout = 'auto';
        table.style.width = 'auto';
      }
      table.appendChild(tHead);

      if (this.isVertical()) {
        tBody.appendChild(tr);
      }
      table.appendChild(tBody);
      (0, _element.addClass)(table, className);
      fragment.appendChild(table);

      return { fragment: fragment, table: table, tHead: tHead, tBody: tBody, colGroup: colGroup, tr: tr, th: th };
    }

    /**
     * Create container for tables.
     *
     * @param {String} className
     * @returns {Object}
     */

  }, {
    key: 'createContainer',
    value: function createContainer() {
      var className = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

      var d = document;
      var fragment = d.createDocumentFragment();
      var container = d.createElement('div');

      className = 'htGhostTable htAutoSize ' + className.trim();
      (0, _element.addClass)(container, className);
      fragment.appendChild(container);

      return { fragment: fragment, container: container };
    }

    /**
     * Checks if table is raised vertically (checking rows).
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isVertical',
    value: function isVertical() {
      return !!(this.rows.length && !this.columns.length);
    }

    /**
     * Checks if table is raised horizontally (checking columns).
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isHorizontal',
    value: function isHorizontal() {
      return !!(this.columns.length && !this.rows.length);
    }
  }]);

  return GhostTable;
}();

exports.default = GhostTable;

/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = separatorItem;
var KEY = exports.KEY = '---------';

function separatorItem() {
  return {
    name: KEY
  };
}

/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _array = __webpack_require__(2);

var _object = __webpack_require__(1);

var MIXIN_NAME = 'localHooks';

/**
 * Mixin object to extend objects functionality for local hooks.
 *
 * @type {Object}
 */
var localHooks = {
  /**
   * Internal hooks storage.
   */
  _localHooks: Object.create(null),

  /**
   * Add hook to the collection.
   *
   * @param {String} key Hook name.
   * @param {Function} callback Hook callback
   */
  addLocalHook: function addLocalHook(key, callback) {
    if (!this._localHooks[key]) {
      this._localHooks[key] = [];
    }
    this._localHooks[key].push(callback);
  },


  /**
   * Run hooks.
   *
   * @param {String} key Hook name.
   * @param {*} params
   */
  runLocalHooks: function runLocalHooks(key) {
    var _this = this;

    for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      params[_key - 1] = arguments[_key];
    }

    if (this._localHooks[key]) {
      (0, _array.arrayEach)(this._localHooks[key], function (callback) {
        return callback.apply(_this, params);
      });
    }
  },


  /**
   * Clear all added hooks.
   */
  clearLocalHooks: function clearLocalHooks() {
    this._localHooks = {};
  }
};

(0, _object.defineGetter)(localHooks, 'MIXIN_NAME', MIXIN_NAME, {
  writable: false,
  enumerable: false
});

exports.default = localHooks;

/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.ITEMS = exports.UNDO = exports.SEPARATOR = exports.ROW_BELOW = exports.ROW_ABOVE = exports.REMOVE_ROW = exports.REMOVE_COLUMN = exports.REDO = exports.READ_ONLY = exports.COLUMN_RIGHT = exports.COLUMN_LEFT = exports.CLEAR_COLUMN = exports.ALIGNMENT = undefined;

var _predefinedItems2;

var _alignment = __webpack_require__(403);

Object.defineProperty(exports, 'ALIGNMENT', {
  enumerable: true,
  get: function get() {
    return _alignment.KEY;
  }
});

var _clearColumn = __webpack_require__(404);

Object.defineProperty(exports, 'CLEAR_COLUMN', {
  enumerable: true,
  get: function get() {
    return _clearColumn.KEY;
  }
});

var _columnLeft = __webpack_require__(405);

Object.defineProperty(exports, 'COLUMN_LEFT', {
  enumerable: true,
  get: function get() {
    return _columnLeft.KEY;
  }
});

var _columnRight = __webpack_require__(406);

Object.defineProperty(exports, 'COLUMN_RIGHT', {
  enumerable: true,
  get: function get() {
    return _columnRight.KEY;
  }
});

var _readOnly = __webpack_require__(407);

Object.defineProperty(exports, 'READ_ONLY', {
  enumerable: true,
  get: function get() {
    return _readOnly.KEY;
  }
});

var _redo = __webpack_require__(408);

Object.defineProperty(exports, 'REDO', {
  enumerable: true,
  get: function get() {
    return _redo.KEY;
  }
});

var _removeColumn = __webpack_require__(409);

Object.defineProperty(exports, 'REMOVE_COLUMN', {
  enumerable: true,
  get: function get() {
    return _removeColumn.KEY;
  }
});

var _removeRow = __webpack_require__(410);

Object.defineProperty(exports, 'REMOVE_ROW', {
  enumerable: true,
  get: function get() {
    return _removeRow.KEY;
  }
});

var _rowAbove = __webpack_require__(411);

Object.defineProperty(exports, 'ROW_ABOVE', {
  enumerable: true,
  get: function get() {
    return _rowAbove.KEY;
  }
});

var _rowBelow = __webpack_require__(412);

Object.defineProperty(exports, 'ROW_BELOW', {
  enumerable: true,
  get: function get() {
    return _rowBelow.KEY;
  }
});

var _separator = __webpack_require__(88);

Object.defineProperty(exports, 'SEPARATOR', {
  enumerable: true,
  get: function get() {
    return _separator.KEY;
  }
});

var _undo = __webpack_require__(413);

Object.defineProperty(exports, 'UNDO', {
  enumerable: true,
  get: function get() {
    return _undo.KEY;
  }
});
exports.predefinedItems = predefinedItems;
exports.addItem = addItem;

var _object = __webpack_require__(1);

var _alignment2 = _interopRequireDefault(_alignment);

var _clearColumn2 = _interopRequireDefault(_clearColumn);

var _columnLeft2 = _interopRequireDefault(_columnLeft);

var _columnRight2 = _interopRequireDefault(_columnRight);

var _readOnly2 = _interopRequireDefault(_readOnly);

var _redo2 = _interopRequireDefault(_redo);

var _removeColumn2 = _interopRequireDefault(_removeColumn);

var _removeRow2 = _interopRequireDefault(_removeRow);

var _rowAbove2 = _interopRequireDefault(_rowAbove);

var _rowBelow2 = _interopRequireDefault(_rowBelow);

var _separator2 = _interopRequireDefault(_separator);

var _undo2 = _interopRequireDefault(_undo);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var ITEMS = exports.ITEMS = [_rowAbove.KEY, _rowBelow.KEY, _columnLeft.KEY, _columnRight.KEY, _clearColumn.KEY, _removeRow.KEY, _removeColumn.KEY, _undo.KEY, _redo.KEY, _readOnly.KEY, _alignment.KEY, _separator.KEY];

var _predefinedItems = (_predefinedItems2 = {}, _defineProperty(_predefinedItems2, _separator.KEY, _separator2.default), _defineProperty(_predefinedItems2, _rowAbove.KEY, _rowAbove2.default), _defineProperty(_predefinedItems2, _rowBelow.KEY, _rowBelow2.default), _defineProperty(_predefinedItems2, _columnLeft.KEY, _columnLeft2.default), _defineProperty(_predefinedItems2, _columnRight.KEY, _columnRight2.default), _defineProperty(_predefinedItems2, _clearColumn.KEY, _clearColumn2.default), _defineProperty(_predefinedItems2, _removeRow.KEY, _removeRow2.default), _defineProperty(_predefinedItems2, _removeColumn.KEY, _removeColumn2.default), _defineProperty(_predefinedItems2, _undo.KEY, _undo2.default), _defineProperty(_predefinedItems2, _redo.KEY, _redo2.default), _defineProperty(_predefinedItems2, _readOnly.KEY, _readOnly2.default), _defineProperty(_predefinedItems2, _alignment.KEY, _alignment2.default), _predefinedItems2);

/**
 * Gets new object with all predefined menu items.
 *
 * @returns {Object}
 */
function predefinedItems() {
  var items = {};

  (0, _object.objectEach)(_predefinedItems, function (itemFactory, key) {
    items[key] = itemFactory();
  });

  return items;
}

/**
 * Add new predefined menu item to the collection.
 *
 * @param {String} key Menu command id.
 * @param {Object} item Object command descriptor.
 */
function addItem(key, item) {
  if (ITEMS.indexOf(key) === -1) {
    _predefinedItems[key] = item;
  }
}

/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var strong = __webpack_require__(92);
var validate = __webpack_require__(44);
var MAP = 'Map';

// 23.1 Map Objects
module.exports = __webpack_require__(62)(MAP, function (get) {
  return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
  // 23.1.3.6 Map.prototype.get(key)
  get: function get(key) {
    var entry = strong.getEntry(validate(this, MAP), key);
    return entry && entry.v;
  },
  // 23.1.3.9 Map.prototype.set(key, value)
  set: function set(key, value) {
    return strong.def(validate(this, MAP), key === 0 ? 0 : key, value);
  }
}, strong, true);


/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var dP = __webpack_require__(19).f;
var create = __webpack_require__(70);
var redefineAll = __webpack_require__(57);
var ctx = __webpack_require__(32);
var anInstance = __webpack_require__(59);
var forOf = __webpack_require__(60);
var $iterDefine = __webpack_require__(101);
var step = __webpack_require__(103);
var setSpecies = __webpack_require__(104);
var DESCRIPTORS = __webpack_require__(22);
var fastKey = __webpack_require__(34).fastKey;
var validate = __webpack_require__(44);
var SIZE = DESCRIPTORS ? '_s' : 'size';

var getEntry = function (that, key) {
  // fast case
  var index = fastKey(key);
  var entry;
  if (index !== 'F') return that._i[index];
  // frozen object case
  for (entry = that._f; entry; entry = entry.n) {
    if (entry.k == key) return entry;
  }
};

module.exports = {
  getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
    var C = wrapper(function (that, iterable) {
      anInstance(that, C, NAME, '_i');
      that._t = NAME;         // collection type
      that._i = create(null); // index
      that._f = undefined;    // first entry
      that._l = undefined;    // last entry
      that[SIZE] = 0;         // size
      if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
    });
    redefineAll(C.prototype, {
      // 23.1.3.1 Map.prototype.clear()
      // 23.2.3.2 Set.prototype.clear()
      clear: function clear() {
        for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
          entry.r = true;
          if (entry.p) entry.p = entry.p.n = undefined;
          delete data[entry.i];
        }
        that._f = that._l = undefined;
        that[SIZE] = 0;
      },
      // 23.1.3.3 Map.prototype.delete(key)
      // 23.2.3.4 Set.prototype.delete(value)
      'delete': function (key) {
        var that = validate(this, NAME);
        var entry = getEntry(that, key);
        if (entry) {
          var next = entry.n;
          var prev = entry.p;
          delete that._i[entry.i];
          entry.r = true;
          if (prev) prev.n = next;
          if (next) next.p = prev;
          if (that._f == entry) that._f = next;
          if (that._l == entry) that._l = prev;
          that[SIZE]--;
        } return !!entry;
      },
      // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
      // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
      forEach: function forEach(callbackfn /* , that = undefined */) {
        validate(this, NAME);
        var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
        var entry;
        while (entry = entry ? entry.n : this._f) {
          f(entry.v, entry.k, this);
          // revert to the last existing entry
          while (entry && entry.r) entry = entry.p;
        }
      },
      // 23.1.3.7 Map.prototype.has(key)
      // 23.2.3.7 Set.prototype.has(value)
      has: function has(key) {
        return !!getEntry(validate(this, NAME), key);
      }
    });
    if (DESCRIPTORS) dP(C.prototype, 'size', {
      get: function () {
        return validate(this, NAME)[SIZE];
      }
    });
    return C;
  },
  def: function (that, key, value) {
    var entry = getEntry(that, key);
    var prev, index;
    // change existing entry
    if (entry) {
      entry.v = value;
    // create new entry
    } else {
      that._l = entry = {
        i: index = fastKey(key, true), // <- index
        k: key,                        // <- key
        v: value,                      // <- value
        p: prev = that._l,             // <- previous entry
        n: undefined,                  // <- next entry
        r: false                       // <- removed
      };
      if (!that._f) that._f = entry;
      if (prev) prev.n = entry;
      that[SIZE]++;
      // add to index
      if (index !== 'F') that._i[index] = entry;
    } return that;
  },
  getEntry: getEntry,
  setStrong: function (C, NAME, IS_MAP) {
    // add .keys, .values, .entries, [@@iterator]
    // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
    $iterDefine(C, NAME, function (iterated, kind) {
      this._t = validate(iterated, NAME); // target
      this._k = kind;                     // kind
      this._l = undefined;                // previous
    }, function () {
      var that = this;
      var kind = that._k;
      var entry = that._l;
      // revert to the last existing entry
      while (entry && entry.r) entry = entry.p;
      // get next entry
      if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
        // or finish the iteration
        that._t = undefined;
        return step(1);
      }
      // return step by kind
      if (kind == 'keys') return step(0, entry.k);
      if (kind == 'values') return step(0, entry.v);
      return step(0, [entry.k, entry.v]);
    }, IS_MAP ? 'entries' : 'values', !IS_MAP, true);

    // add [@@species], 23.1.2.2, 23.2.2.2
    setSpecies(NAME);
  }
};


/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = !__webpack_require__(22) && !__webpack_require__(23)(function () {
  return Object.defineProperty(__webpack_require__(68)('div'), 'a', { get: function () { return 7; } }).a != 7;
});


/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {

var has = __webpack_require__(27);
var toIObject = __webpack_require__(24);
var arrayIndexOf = __webpack_require__(95)(false);
var IE_PROTO = __webpack_require__(72)('IE_PROTO');

module.exports = function (object, names) {
  var O = toIObject(object);
  var i = 0;
  var result = [];
  var key;
  for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
  // Don't enum bug & hidden keys
  while (names.length > i) if (has(O, key = names[i++])) {
    ~arrayIndexOf(result, key) || result.push(key);
  }
  return result;
};


/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {

// false -> Array#indexOf
// true  -> Array#includes
var toIObject = __webpack_require__(24);
var toLength = __webpack_require__(25);
var toAbsoluteIndex = __webpack_require__(56);
module.exports = function (IS_INCLUDES) {
  return function ($this, el, fromIndex) {
    var O = toIObject($this);
    var length = toLength(O.length);
    var index = toAbsoluteIndex(fromIndex, length);
    var value;
    // Array#includes uses SameValueZero equality algorithm
    // eslint-disable-next-line no-self-compare
    if (IS_INCLUDES && el != el) while (length > index) {
      value = O[index++];
      // eslint-disable-next-line no-self-compare
      if (value != value) return true;
    // Array#indexOf ignores holes, Array#includes - not
    } else for (;length > index; index++) if (IS_INCLUDES || index in O) {
      if (O[index] === el) return IS_INCLUDES || index || 0;
    } return !IS_INCLUDES && -1;
  };
};


/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {

var document = __webpack_require__(13).document;
module.exports = document && document.documentElement;


/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {

// call something on iterator step with safe closing on error
var anObject = __webpack_require__(18);
module.exports = function (iterator, fn, value, entries) {
  try {
    return entries ? fn(anObject(value)[0], value[1]) : fn(value);
  // 7.4.6 IteratorClose(iterator, completion)
  } catch (e) {
    var ret = iterator['return'];
    if (ret !== undefined) anObject(ret.call(iterator));
    throw e;
  }
};


/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {

// check on default Array iterator
var Iterators = __webpack_require__(50);
var ITERATOR = __webpack_require__(10)('iterator');
var ArrayProto = Array.prototype;

module.exports = function (it) {
  return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};


/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {

var classof = __webpack_require__(100);
var ITERATOR = __webpack_require__(10)('iterator');
var Iterators = __webpack_require__(50);
module.exports = __webpack_require__(43).getIteratorMethod = function (it) {
  if (it != undefined) return it[ITERATOR]
    || it['@@iterator']
    || Iterators[classof(it)];
};


/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {

// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(42);
var TAG = __webpack_require__(10)('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';

// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
  try {
    return it[key];
  } catch (e) { /* empty */ }
};

module.exports = function (it) {
  var O, T, B;
  return it === undefined ? 'Undefined' : it === null ? 'Null'
    // @@toStringTag case
    : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
    // builtinTag case
    : ARG ? cof(O)
    // ES3 arguments fallback
    : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};


/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var LIBRARY = __webpack_require__(61);
var $export = __webpack_require__(3);
var redefine = __webpack_require__(30);
var hide = __webpack_require__(31);
var has = __webpack_require__(27);
var Iterators = __webpack_require__(50);
var $iterCreate = __webpack_require__(320);
var setToStringTag = __webpack_require__(51);
var getPrototypeOf = __webpack_require__(102);
var ITERATOR = __webpack_require__(10)('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';

var returnThis = function () { return this; };

module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
  $iterCreate(Constructor, NAME, next);
  var getMethod = function (kind) {
    if (!BUGGY && kind in proto) return proto[kind];
    switch (kind) {
      case KEYS: return function keys() { return new Constructor(this, kind); };
      case VALUES: return function values() { return new Constructor(this, kind); };
    } return function entries() { return new Constructor(this, kind); };
  };
  var TAG = NAME + ' Iterator';
  var DEF_VALUES = DEFAULT == VALUES;
  var VALUES_BUG = false;
  var proto = Base.prototype;
  var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
  var $default = (!BUGGY && $native) || getMethod(DEFAULT);
  var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
  var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
  var methods, key, IteratorPrototype;
  // Fix native
  if ($anyNative) {
    IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
    if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
      // Set @@toStringTag to native iterators
      setToStringTag(IteratorPrototype, TAG, true);
      // fix for some old engines
      if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis);
    }
  }
  // fix Array#{values, @@iterator}.name in V8 / FF
  if (DEF_VALUES && $native && $native.name !== VALUES) {
    VALUES_BUG = true;
    $default = function values() { return $native.call(this); };
  }
  // Define iterator
  if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
    hide(proto, ITERATOR, $default);
  }
  // Plug for library
  Iterators[NAME] = $default;
  Iterators[TAG] = returnThis;
  if (DEFAULT) {
    methods = {
      values: DEF_VALUES ? $default : getMethod(VALUES),
      keys: IS_SET ? $default : getMethod(KEYS),
      entries: $entries
    };
    if (FORCED) for (key in methods) {
      if (!(key in proto)) redefine(proto, key, methods[key]);
    } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
  }
  return methods;
};


/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(27);
var toObject = __webpack_require__(33);
var IE_PROTO = __webpack_require__(72)('IE_PROTO');
var ObjectProto = Object.prototype;

module.exports = Object.getPrototypeOf || function (O) {
  O = toObject(O);
  if (has(O, IE_PROTO)) return O[IE_PROTO];
  if (typeof O.constructor == 'function' && O instanceof O.constructor) {
    return O.constructor.prototype;
  } return O instanceof Object ? ObjectProto : null;
};


/***/ }),
/* 103 */
/***/ (function(module, exports) {

module.exports = function (done, value) {
  return { value: value, done: !!done };
};


/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var global = __webpack_require__(13);
var dP = __webpack_require__(19);
var DESCRIPTORS = __webpack_require__(22);
var SPECIES = __webpack_require__(10)('species');

module.exports = function (KEY) {
  var C = global[KEY];
  if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
    configurable: true,
    get: function () { return this; }
  });
};


/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {

// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(5);
var anObject = __webpack_require__(18);
var check = function (O, proto) {
  anObject(O);
  if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
  set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
    function (test, buggy, set) {
      try {
        set = __webpack_require__(32)(Function.call, __webpack_require__(63).f(Object.prototype, '__proto__').set, 2);
        set(test, []);
        buggy = !(test instanceof Array);
      } catch (e) { buggy = true; }
      return function setPrototypeOf(O, proto) {
        check(O, proto);
        if (buggy) O.__proto__ = proto;
        else set(O, proto);
        return O;
      };
    }({}, false) : undefined),
  check: check
};


/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var strong = __webpack_require__(92);
var validate = __webpack_require__(44);
var SET = 'Set';

// 23.2 Set Objects
module.exports = __webpack_require__(62)(SET, function (get) {
  return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
  // 23.2.3.1 Set.prototype.add(value)
  add: function add(value) {
    return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
  }
}, strong);


/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var each = __webpack_require__(64)(0);
var redefine = __webpack_require__(30);
var meta = __webpack_require__(34);
var assign = __webpack_require__(109);
var weak = __webpack_require__(110);
var isObject = __webpack_require__(5);
var fails = __webpack_require__(23);
var validate = __webpack_require__(44);
var WEAK_MAP = 'WeakMap';
var getWeak = meta.getWeak;
var isExtensible = Object.isExtensible;
var uncaughtFrozenStore = weak.ufstore;
var tmp = {};
var InternalMap;

var wrapper = function (get) {
  return function WeakMap() {
    return get(this, arguments.length > 0 ? arguments[0] : undefined);
  };
};

var methods = {
  // 23.3.3.3 WeakMap.prototype.get(key)
  get: function get(key) {
    if (isObject(key)) {
      var data = getWeak(key);
      if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);
      return data ? data[this._i] : undefined;
    }
  },
  // 23.3.3.5 WeakMap.prototype.set(key, value)
  set: function set(key, value) {
    return weak.def(validate(this, WEAK_MAP), key, value);
  }
};

// 23.3 WeakMap Objects
var $WeakMap = module.exports = __webpack_require__(62)(WEAK_MAP, wrapper, methods, weak, true, true);

// IE11 WeakMap frozen keys fix
if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) {
  InternalMap = weak.getConstructor(wrapper, WEAK_MAP);
  assign(InternalMap.prototype, methods);
  meta.NEED = true;
  each(['delete', 'has', 'get', 'set'], function (key) {
    var proto = $WeakMap.prototype;
    var method = proto[key];
    redefine(proto, key, function (a, b) {
      // store frozen objects on internal weakmap shim
      if (isObject(a) && !isExtensible(a)) {
        if (!this._f) this._f = new InternalMap();
        var result = this._f[key](a, b);
        return key == 'set' ? this : result;
      // store all the rest on native weakmap
      } return method.call(this, a, b);
    });
  });
}


/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {

// 7.2.2 IsArray(argument)
var cof = __webpack_require__(42);
module.exports = Array.isArray || function isArray(arg) {
  return cof(arg) == 'Array';
};


/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(37);
var gOPS = __webpack_require__(65);
var pIE = __webpack_require__(52);
var toObject = __webpack_require__(33);
var IObject = __webpack_require__(71);
var $assign = Object.assign;

// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(23)(function () {
  var A = {};
  var B = {};
  // eslint-disable-next-line no-undef
  var S = Symbol();
  var K = 'abcdefghijklmnopqrst';
  A[S] = 7;
  K.split('').forEach(function (k) { B[k] = k; });
  return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
  var T = toObject(target);
  var aLen = arguments.length;
  var index = 1;
  var getSymbols = gOPS.f;
  var isEnum = pIE.f;
  while (aLen > index) {
    var S = IObject(arguments[index++]);
    var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
    var length = keys.length;
    var j = 0;
    var key;
    while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
  } return T;
} : $assign;


/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var redefineAll = __webpack_require__(57);
var getWeak = __webpack_require__(34).getWeak;
var anObject = __webpack_require__(18);
var isObject = __webpack_require__(5);
var anInstance = __webpack_require__(59);
var forOf = __webpack_require__(60);
var createArrayMethod = __webpack_require__(64);
var $has = __webpack_require__(27);
var validate = __webpack_require__(44);
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var id = 0;

// fallback for uncaught frozen keys
var uncaughtFrozenStore = function (that) {
  return that._l || (that._l = new UncaughtFrozenStore());
};
var UncaughtFrozenStore = function () {
  this.a = [];
};
var findUncaughtFrozen = function (store, key) {
  return arrayFind(store.a, function (it) {
    return it[0] === key;
  });
};
UncaughtFrozenStore.prototype = {
  get: function (key) {
    var entry = findUncaughtFrozen(this, key);
    if (entry) return entry[1];
  },
  has: function (key) {
    return !!findUncaughtFrozen(this, key);
  },
  set: function (key, value) {
    var entry = findUncaughtFrozen(this, key);
    if (entry) entry[1] = value;
    else this.a.push([key, value]);
  },
  'delete': function (key) {
    var index = arrayFindIndex(this.a, function (it) {
      return it[0] === key;
    });
    if (~index) this.a.splice(index, 1);
    return !!~index;
  }
};

module.exports = {
  getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
    var C = wrapper(function (that, iterable) {
      anInstance(that, C, NAME, '_i');
      that._t = NAME;      // collection type
      that._i = id++;      // collection id
      that._l = undefined; // leak store for uncaught frozen objects
      if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
    });
    redefineAll(C.prototype, {
      // 23.3.3.2 WeakMap.prototype.delete(key)
      // 23.4.3.3 WeakSet.prototype.delete(value)
      'delete': function (key) {
        if (!isObject(key)) return false;
        var data = getWeak(key);
        if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);
        return data && $has(data, this._i) && delete data[this._i];
      },
      // 23.3.3.4 WeakMap.prototype.has(key)
      // 23.4.3.4 WeakSet.prototype.has(value)
      has: function has(key) {
        if (!isObject(key)) return false;
        var data = getWeak(key);
        if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);
        return data && $has(data, this._i);
      }
    });
    return C;
  },
  def: function (that, key, value) {
    var data = getWeak(anObject(key), true);
    if (data === true) uncaughtFrozenStore(that).set(key, value);
    else data[that._i] = value;
    return that;
  },
  ufstore: uncaughtFrozenStore
};


/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var weak = __webpack_require__(110);
var validate = __webpack_require__(44);
var WEAK_SET = 'WeakSet';

// 23.4 WeakSet Objects
__webpack_require__(62)(WEAK_SET, function (get) {
  return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
  // 23.4.3.1 WeakSet.prototype.add(value)
  add: function add(value) {
    return weak.def(validate(this, WEAK_SET), value, true);
  }
}, weak, false, true);


/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var LIBRARY = __webpack_require__(61);
var global = __webpack_require__(13);
var ctx = __webpack_require__(32);
var classof = __webpack_require__(100);
var $export = __webpack_require__(3);
var isObject = __webpack_require__(5);
var aFunction = __webpack_require__(58);
var anInstance = __webpack_require__(59);
var forOf = __webpack_require__(60);
var speciesConstructor = __webpack_require__(324);
var task = __webpack_require__(76).set;
var microtask = __webpack_require__(326)();
var newPromiseCapabilityModule = __webpack_require__(113);
var perform = __webpack_require__(327);
var promiseResolve = __webpack_require__(328);
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;

var USE_NATIVE = !!function () {
  try {
    // correct subclassing with @@species support
    var promise = $Promise.resolve(1);
    var FakePromise = (promise.constructor = {})[__webpack_require__(10)('species')] = function (exec) {
      exec(empty, empty);
    };
    // unhandled rejections tracking support, NodeJS Promise without it fails @@species test
    return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
  } catch (e) { /* empty */ }
}();

// helpers
var isThenable = function (it) {
  var then;
  return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
  if (promise._n) return;
  promise._n = true;
  var chain = promise._c;
  microtask(function () {
    var value = promise._v;
    var ok = promise._s == 1;
    var i = 0;
    var run = function (reaction) {
      var handler = ok ? reaction.ok : reaction.fail;
      var resolve = reaction.resolve;
      var reject = reaction.reject;
      var domain = reaction.domain;
      var result, then;
      try {
        if (handler) {
          if (!ok) {
            if (promise._h == 2) onHandleUnhandled(promise);
            promise._h = 1;
          }
          if (handler === true) result = value;
          else {
            if (domain) domain.enter();
            result = handler(value);
            if (domain) domain.exit();
          }
          if (result === reaction.promise) {
            reject(TypeError('Promise-chain cycle'));
          } else if (then = isThenable(result)) {
            then.call(result, resolve, reject);
          } else resolve(result);
        } else reject(value);
      } catch (e) {
        reject(e);
      }
    };
    while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
    promise._c = [];
    promise._n = false;
    if (isReject && !promise._h) onUnhandled(promise);
  });
};
var onUnhandled = function (promise) {
  task.call(global, function () {
    var value = promise._v;
    var unhandled = isUnhandled(promise);
    var result, handler, console;
    if (unhandled) {
      result = perform(function () {
        if (isNode) {
          process.emit('unhandledRejection', value, promise);
        } else if (handler = global.onunhandledrejection) {
          handler({ promise: promise, reason: value });
        } else if ((console = global.console) && console.error) {
          console.error('Unhandled promise rejection', value);
        }
      });
      // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
      promise._h = isNode || isUnhandled(promise) ? 2 : 1;
    } promise._a = undefined;
    if (unhandled && result.e) throw result.v;
  });
};
var isUnhandled = function (promise) {
  return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
  task.call(global, function () {
    var handler;
    if (isNode) {
      process.emit('rejectionHandled', promise);
    } else if (handler = global.onrejectionhandled) {
      handler({ promise: promise, reason: promise._v });
    }
  });
};
var $reject = function (value) {
  var promise = this;
  if (promise._d) return;
  promise._d = true;
  promise = promise._w || promise; // unwrap
  promise._v = value;
  promise._s = 2;
  if (!promise._a) promise._a = promise._c.slice();
  notify(promise, true);
};
var $resolve = function (value) {
  var promise = this;
  var then;
  if (promise._d) return;
  promise._d = true;
  promise = promise._w || promise; // unwrap
  try {
    if (promise === value) throw TypeError("Promise can't be resolved itself");
    if (then = isThenable(value)) {
      microtask(function () {
        var wrapper = { _w: promise, _d: false }; // wrap
        try {
          then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
        } catch (e) {
          $reject.call(wrapper, e);
        }
      });
    } else {
      promise._v = value;
      promise._s = 1;
      notify(promise, false);
    }
  } catch (e) {
    $reject.call({ _w: promise, _d: false }, e); // wrap
  }
};

// constructor polyfill
if (!USE_NATIVE) {
  // 25.4.3.1 Promise(executor)
  $Promise = function Promise(executor) {
    anInstance(this, $Promise, PROMISE, '_h');
    aFunction(executor);
    Internal.call(this);
    try {
      executor(ctx($resolve, this, 1), ctx($reject, this, 1));
    } catch (err) {
      $reject.call(this, err);
    }
  };
  // eslint-disable-next-line no-unused-vars
  Internal = function Promise(executor) {
    this._c = [];             // <- awaiting reactions
    this._a = undefined;      // <- checked in isUnhandled reactions
    this._s = 0;              // <- state
    this._d = false;          // <- done
    this._v = undefined;      // <- value
    this._h = 0;              // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
    this._n = false;          // <- notify
  };
  Internal.prototype = __webpack_require__(57)($Promise.prototype, {
    // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
    then: function then(onFulfilled, onRejected) {
      var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
      reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
      reaction.fail = typeof onRejected == 'function' && onRejected;
      reaction.domain = isNode ? process.domain : undefined;
      this._c.push(reaction);
      if (this._a) this._a.push(reaction);
      if (this._s) notify(this, false);
      return reaction.promise;
    },
    // 25.4.5.1 Promise.prototype.catch(onRejected)
    'catch': function (onRejected) {
      return this.then(undefined, onRejected);
    }
  });
  OwnPromiseCapability = function () {
    var promise = new Internal();
    this.promise = promise;
    this.resolve = ctx($resolve, promise, 1);
    this.reject = ctx($reject, promise, 1);
  };
  newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
    return C === $Promise || C === Wrapper
      ? new OwnPromiseCapability(C)
      : newGenericPromiseCapability(C);
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
__webpack_require__(51)($Promise, PROMISE);
__webpack_require__(104)(PROMISE);
Wrapper = __webpack_require__(43)[PROMISE];

// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
  // 25.4.4.5 Promise.reject(r)
  reject: function reject(r) {
    var capability = newPromiseCapability(this);
    var $$reject = capability.reject;
    $$reject(r);
    return capability.promise;
  }
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
  // 25.4.4.6 Promise.resolve(x)
  resolve: function resolve(x) {
    return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
  }
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(75)(function (iter) {
  $Promise.all(iter)['catch'](empty);
})), PROMISE, {
  // 25.4.4.1 Promise.all(iterable)
  all: function all(iterable) {
    var C = this;
    var capability = newPromiseCapability(C);
    var resolve = capability.resolve;
    var reject = capability.reject;
    var result = perform(function () {
      var values = [];
      var index = 0;
      var remaining = 1;
      forOf(iterable, false, function (promise) {
        var $index = index++;
        var alreadyCalled = false;
        values.push(undefined);
        remaining++;
        C.resolve(promise).then(function (value) {
          if (alreadyCalled) return;
          alreadyCalled = true;
          values[$index] = value;
          --remaining || resolve(values);
        }, reject);
      });
      --remaining || resolve(values);
    });
    if (result.e) reject(result.v);
    return capability.promise;
  },
  // 25.4.4.4 Promise.race(iterable)
  race: function race(iterable) {
    var C = this;
    var capability = newPromiseCapability(C);
    var reject = capability.reject;
    var result = perform(function () {
      forOf(iterable, false, function (promise) {
        C.resolve(promise).then(capability.resolve, reject);
      });
    });
    if (result.e) reject(result.v);
    return capability.promise;
  }
});


/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// 25.4.1.5 NewPromiseCapability(C)
var aFunction = __webpack_require__(58);

function PromiseCapability(C) {
  var resolve, reject;
  this.promise = new C(function ($$resolve, $$reject) {
    if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
    resolve = $$resolve;
    reject = $$reject;
  });
  this.resolve = aFunction(resolve);
  this.reject = aFunction(reject);
}

module.exports.f = function (C) {
  return new PromiseCapability(C);
};


/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// ECMAScript 6 symbols shim
var global = __webpack_require__(13);
var has = __webpack_require__(27);
var DESCRIPTORS = __webpack_require__(22);
var $export = __webpack_require__(3);
var redefine = __webpack_require__(30);
var META = __webpack_require__(34).KEY;
var $fails = __webpack_require__(23);
var shared = __webpack_require__(73);
var setToStringTag = __webpack_require__(51);
var uid = __webpack_require__(48);
var wks = __webpack_require__(10);
var wksExt = __webpack_require__(115);
var wksDefine = __webpack_require__(329);
var enumKeys = __webpack_require__(330);
var isArray = __webpack_require__(108);
var anObject = __webpack_require__(18);
var isObject = __webpack_require__(5);
var toIObject = __webpack_require__(24);
var toPrimitive = __webpack_require__(69);
var createDesc = __webpack_require__(49);
var _create = __webpack_require__(70);
var gOPNExt = __webpack_require__(116);
var $GOPD = __webpack_require__(63);
var $DP = __webpack_require__(19);
var $keys = __webpack_require__(37);
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function';
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;

// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
  return _create(dP({}, 'a', {
    get: function () { return dP(this, 'a', { value: 7 }).a; }
  })).a != 7;
}) ? function (it, key, D) {
  var protoDesc = gOPD(ObjectProto, key);
  if (protoDesc) delete ObjectProto[key];
  dP(it, key, D);
  if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;

var wrap = function (tag) {
  var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
  sym._k = tag;
  return sym;
};

var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
  return typeof it == 'symbol';
} : function (it) {
  return it instanceof $Symbol;
};

var $defineProperty = function defineProperty(it, key, D) {
  if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
  anObject(it);
  key = toPrimitive(key, true);
  anObject(D);
  if (has(AllSymbols, key)) {
    if (!D.enumerable) {
      if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
      it[HIDDEN][key] = true;
    } else {
      if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
      D = _create(D, { enumerable: createDesc(0, false) });
    } return setSymbolDesc(it, key, D);
  } return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
  anObject(it);
  var keys = enumKeys(P = toIObject(P));
  var i = 0;
  var l = keys.length;
  var key;
  while (l > i) $defineProperty(it, key = keys[i++], P[key]);
  return it;
};
var $create = function create(it, P) {
  return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
  var E = isEnum.call(this, key = toPrimitive(key, true));
  if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
  return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
  it = toIObject(it);
  key = toPrimitive(key, true);
  if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
  var D = gOPD(it, key);
  if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
  return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
  var names = gOPN(toIObject(it));
  var result = [];
  var i = 0;
  var key;
  while (names.length > i) {
    if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
  } return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
  var IS_OP = it === ObjectProto;
  var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
  var result = [];
  var i = 0;
  var key;
  while (names.length > i) {
    if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
  } return result;
};

// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
  $Symbol = function Symbol() {
    if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
    var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
    var $set = function (value) {
      if (this === ObjectProto) $set.call(OPSymbols, value);
      if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
      setSymbolDesc(this, tag, createDesc(1, value));
    };
    if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
    return wrap(tag);
  };
  redefine($Symbol[PROTOTYPE], 'toString', function toString() {
    return this._k;
  });

  $GOPD.f = $getOwnPropertyDescriptor;
  $DP.f = $defineProperty;
  __webpack_require__(77).f = gOPNExt.f = $getOwnPropertyNames;
  __webpack_require__(52).f = $propertyIsEnumerable;
  __webpack_require__(65).f = $getOwnPropertySymbols;

  if (DESCRIPTORS && !__webpack_require__(61)) {
    redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
  }

  wksExt.f = function (name) {
    return wrap(wks(name));
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });

for (var es6Symbols = (
  // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
  'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);

for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);

$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
  // 19.4.2.1 Symbol.for(key)
  'for': function (key) {
    return has(SymbolRegistry, key += '')
      ? SymbolRegistry[key]
      : SymbolRegistry[key] = $Symbol(key);
  },
  // 19.4.2.5 Symbol.keyFor(sym)
  keyFor: function keyFor(sym) {
    if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
    for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
  },
  useSetter: function () { setter = true; },
  useSimple: function () { setter = false; }
});

$export($export.S + $export.F * !USE_NATIVE, 'Object', {
  // 19.1.2.2 Object.create(O [, Properties])
  create: $create,
  // 19.1.2.4 Object.defineProperty(O, P, Attributes)
  defineProperty: $defineProperty,
  // 19.1.2.3 Object.defineProperties(O, Properties)
  defineProperties: $defineProperties,
  // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
  getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
  // 19.1.2.7 Object.getOwnPropertyNames(O)
  getOwnPropertyNames: $getOwnPropertyNames,
  // 19.1.2.8 Object.getOwnPropertySymbols(O)
  getOwnPropertySymbols: $getOwnPropertySymbols
});

// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
  var S = $Symbol();
  // MS Edge converts symbol values to JSON as {}
  // WebKit converts symbol values to JSON as null
  // V8 throws on boxed symbols
  return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
  stringify: function stringify(it) {
    var args = [it];
    var i = 1;
    var replacer, $replacer;
    while (arguments.length > i) args.push(arguments[i++]);
    $replacer = replacer = args[1];
    if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
    if (!isArray(replacer)) replacer = function (key, value) {
      if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
      if (!isSymbol(value)) return value;
    };
    args[1] = replacer;
    return _stringify.apply($JSON, args);
  }
});

// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(31)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);


/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {

exports.f = __webpack_require__(10);


/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {

// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(24);
var gOPN = __webpack_require__(77).f;
var toString = {}.toString;

var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
  ? Object.getOwnPropertyNames(window) : [];

var getWindowNames = function (it) {
  try {
    return gOPN(it);
  } catch (e) {
    return windowNames.slice();
  }
};

module.exports.f = function getOwnPropertyNames(it) {
  return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};


/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(5);
var meta = __webpack_require__(34).onFreeze;

__webpack_require__(26)('freeze', function ($freeze) {
  return function freeze(it) {
    return $freeze && isObject(it) ? $freeze(meta(it)) : it;
  };
});


/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(5);
var meta = __webpack_require__(34).onFreeze;

__webpack_require__(26)('seal', function ($seal) {
  return function seal(it) {
    return $seal && isObject(it) ? $seal(meta(it)) : it;
  };
});


/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(5);
var meta = __webpack_require__(34).onFreeze;

__webpack_require__(26)('preventExtensions', function ($preventExtensions) {
  return function preventExtensions(it) {
    return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
  };
});


/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(5);

__webpack_require__(26)('isFrozen', function ($isFrozen) {
  return function isFrozen(it) {
    return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
  };
});


/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(5);

__webpack_require__(26)('isSealed', function ($isSealed) {
  return function isSealed(it) {
    return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
  };
});


/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(5);

__webpack_require__(26)('isExtensible', function ($isExtensible) {
  return function isExtensible(it) {
    return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
  };
});


/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(24);
var $getOwnPropertyDescriptor = __webpack_require__(63).f;

__webpack_require__(26)('getOwnPropertyDescriptor', function () {
  return function getOwnPropertyDescriptor(it, key) {
    return $getOwnPropertyDescriptor(toIObject(it), key);
  };
});


/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(33);
var $getPrototypeOf = __webpack_require__(102);

__webpack_require__(26)('getPrototypeOf', function () {
  return function getPrototypeOf(it) {
    return $getPrototypeOf(toObject(it));
  };
});


/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(33);
var $keys = __webpack_require__(37);

__webpack_require__(26)('keys', function () {
  return function keys(it) {
    return $keys(toObject(it));
  };
});


/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(26)('getOwnPropertyNames', function () {
  return __webpack_require__(116).f;
});


/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(3);

$export($export.S + $export.F, 'Object', { assign: __webpack_require__(109) });


/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(3);
$export($export.S, 'Object', { is: __webpack_require__(331) });


/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(3);
$export($export.S, 'Object', { setPrototypeOf: __webpack_require__(105).set });


/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {

var dP = __webpack_require__(19).f;
var FProto = Function.prototype;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name';

// 19.2.4.2 name
NAME in FProto || __webpack_require__(22) && dP(FProto, NAME, {
  configurable: true,
  get: function () {
    try {
      return ('' + this).match(nameRE)[1];
    } catch (e) {
      return '';
    }
  }
});


/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {

var $export = __webpack_require__(3);
var toIObject = __webpack_require__(24);
var toLength = __webpack_require__(25);

$export($export.S, 'String', {
  // 21.1.2.4 String.raw(callSite, ...substitutions)
  raw: function raw(callSite) {
    var tpl = toIObject(callSite.raw);
    var len = toLength(tpl.length);
    var aLen = arguments.length;
    var res = [];
    var i = 0;
    while (len > i) {
      res.push(String(tpl[i++]));
      if (i < aLen) res.push(String(arguments[i]));
    } return res.join('');
  }
});


/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {

var $export = __webpack_require__(3);
var toAbsoluteIndex = __webpack_require__(56);
var fromCharCode = String.fromCharCode;
var $fromCodePoint = String.fromCodePoint;

// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
  // 21.1.2.2 String.fromCodePoint(...codePoints)
  fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars
    var res = [];
    var aLen = arguments.length;
    var i = 0;
    var code;
    while (aLen > i) {
      code = +arguments[i++];
      if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');
      res.push(code < 0x10000
        ? fromCharCode(code)
        : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
      );
    } return res.join('');
  }
});


/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var $export = __webpack_require__(3);
var $at = __webpack_require__(332)(false);
$export($export.P, 'String', {
  // 21.1.3.3 String.prototype.codePointAt(pos)
  codePointAt: function codePointAt(pos) {
    return $at(this, pos);
  }
});


/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {

var $export = __webpack_require__(3);

$export($export.P, 'String', {
  // 21.1.3.13 String.prototype.repeat(count)
  repeat: __webpack_require__(135)
});


/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var toInteger = __webpack_require__(55);
var defined = __webpack_require__(38);

module.exports = function repeat(count) {
  var str = String(defined(this));
  var res = '';
  var n = toInteger(count);
  if (n < 0 || n == Infinity) throw RangeError("Count can't be negative");
  for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str;
  return res;
};


/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])

var $export = __webpack_require__(3);
var toLength = __webpack_require__(25);
var context = __webpack_require__(78);
var STARTS_WITH = 'startsWith';
var $startsWith = ''[STARTS_WITH];

$export($export.P + $export.F * __webpack_require__(79)(STARTS_WITH), 'String', {
  startsWith: function startsWith(searchString /* , position = 0 */) {
    var that = context(this, searchString, STARTS_WITH);
    var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
    var search = String(searchString);
    return $startsWith
      ? $startsWith.call(that, search, index)
      : that.slice(index, index + search.length) === search;
  }
});


/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {

// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(5);
var cof = __webpack_require__(42);
var MATCH = __webpack_require__(10)('match');
module.exports = function (it) {
  var isRegExp;
  return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};


/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])

var $export = __webpack_require__(3);
var toLength = __webpack_require__(25);
var context = __webpack_require__(78);
var ENDS_WITH = 'endsWith';
var $endsWith = ''[ENDS_WITH];

$export($export.P + $export.F * __webpack_require__(79)(ENDS_WITH), 'String', {
  endsWith: function endsWith(searchString /* , endPosition = @length */) {
    var that = context(this, searchString, ENDS_WITH);
    var endPosition = arguments.length > 1 ? arguments[1] : undefined;
    var len = toLength(that.length);
    var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);
    var search = String(searchString);
    return $endsWith
      ? $endsWith.call(that, search, end)
      : that.slice(end - search.length, end) === search;
  }
});


/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// 21.1.3.7 String.prototype.includes(searchString, position = 0)

var $export = __webpack_require__(3);
var context = __webpack_require__(78);
var INCLUDES = 'includes';

$export($export.P + $export.F * __webpack_require__(79)(INCLUDES), 'String', {
  includes: function includes(searchString /* , position = 0 */) {
    return !!~context(this, searchString, INCLUDES)
      .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
  }
});


/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {

// 21.2.5.3 get RegExp.prototype.flags()
if (__webpack_require__(22) && /./g.flags != 'g') __webpack_require__(19).f(RegExp.prototype, 'flags', {
  configurable: true,
  get: __webpack_require__(333)
});


/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {

// @@match logic
__webpack_require__(66)('match', 1, function (defined, MATCH, $match) {
  // 21.1.3.11 String.prototype.match(regexp)
  return [function match(regexp) {
    'use strict';
    var O = defined(this);
    var fn = regexp == undefined ? undefined : regexp[MATCH];
    return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
  }, $match];
});


/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {

// @@replace logic
__webpack_require__(66)('replace', 2, function (defined, REPLACE, $replace) {
  // 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
  return [function replace(searchValue, replaceValue) {
    'use strict';
    var O = defined(this);
    var fn = searchValue == undefined ? undefined : searchValue[REPLACE];
    return fn !== undefined
      ? fn.call(searchValue, O, replaceValue)
      : $replace.call(String(O), searchValue, replaceValue);
  }, $replace];
});


/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {

// @@split logic
__webpack_require__(66)('split', 2, function (defined, SPLIT, $split) {
  'use strict';
  var isRegExp = __webpack_require__(137);
  var _split = $split;
  var $push = [].push;
  var $SPLIT = 'split';
  var LENGTH = 'length';
  var LAST_INDEX = 'lastIndex';
  if (
    'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
    'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
    'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
    '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
    '.'[$SPLIT](/()()/)[LENGTH] > 1 ||
    ''[$SPLIT](/.?/)[LENGTH]
  ) {
    var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
    // based on es5-shim implementation, need to rework it
    $split = function (separator, limit) {
      var string = String(this);
      if (separator === undefined && limit === 0) return [];
      // If `separator` is not a regex, use native split
      if (!isRegExp(separator)) return _split.call(string, separator, limit);
      var output = [];
      var flags = (separator.ignoreCase ? 'i' : '') +
                  (separator.multiline ? 'm' : '') +
                  (separator.unicode ? 'u' : '') +
                  (separator.sticky ? 'y' : '');
      var lastLastIndex = 0;
      var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
      // Make `global` and avoid `lastIndex` issues by working with a copy
      var separatorCopy = new RegExp(separator.source, flags + 'g');
      var separator2, match, lastIndex, lastLength, i;
      // Doesn't need flags gy, but they don't hurt
      if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
      while (match = separatorCopy.exec(string)) {
        // `separatorCopy.lastIndex` is not reliable cross-browser
        lastIndex = match.index + match[0][LENGTH];
        if (lastIndex > lastLastIndex) {
          output.push(string.slice(lastLastIndex, match.index));
          // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
          // eslint-disable-next-line no-loop-func
          if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () {
            for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined;
          });
          if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1));
          lastLength = match[0][LENGTH];
          lastLastIndex = lastIndex;
          if (output[LENGTH] >= splitLimit) break;
        }
        if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
      }
      if (lastLastIndex === string[LENGTH]) {
        if (lastLength || !separatorCopy.test('')) output.push('');
      } else output.push(string.slice(lastLastIndex));
      return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
    };
  // Chakra, V8
  } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) {
    $split = function (separator, limit) {
      return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
    };
  }
  // 21.1.3.17 String.prototype.split(separator, limit)
  return [function split(separator, limit) {
    var O = defined(this);
    var fn = separator == undefined ? undefined : separator[SPLIT];
    return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
  }, $split];
});


/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {

// @@search logic
__webpack_require__(66)('search', 1, function (defined, SEARCH, $search) {
  // 21.1.3.15 String.prototype.search(regexp)
  return [function search(regexp) {
    'use strict';
    var O = defined(this);
    var fn = regexp == undefined ? undefined : regexp[SEARCH];
    return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
  }, $search];
});


/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var ctx = __webpack_require__(32);
var $export = __webpack_require__(3);
var toObject = __webpack_require__(33);
var call = __webpack_require__(97);
var isArrayIter = __webpack_require__(98);
var toLength = __webpack_require__(25);
var createProperty = __webpack_require__(80);
var getIterFn = __webpack_require__(99);

$export($export.S + $export.F * !__webpack_require__(75)(function (iter) { Array.from(iter); }), 'Array', {
  // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
  from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
    var O = toObject(arrayLike);
    var C = typeof this == 'function' ? this : Array;
    var aLen = arguments.length;
    var mapfn = aLen > 1 ? arguments[1] : undefined;
    var mapping = mapfn !== undefined;
    var index = 0;
    var iterFn = getIterFn(O);
    var length, result, step, iterator;
    if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
    // if object isn't iterable or it's array with default iterator - use simple case
    if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
      for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
        createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
      }
    } else {
      length = toLength(O.length);
      for (result = new C(length); length > index; index++) {
        createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
      }
    }
    result.length = index;
    return result;
  }
});


/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var $export = __webpack_require__(3);
var createProperty = __webpack_require__(80);

// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(23)(function () {
  function F() { /* empty */ }
  return !(Array.of.call(F) instanceof F);
}), 'Array', {
  // 22.1.2.3 Array.of( ...items)
  of: function of(/* ...args */) {
    var index = 0;
    var aLen = arguments.length;
    var result = new (typeof this == 'function' ? this : Array)(aLen);
    while (aLen > index) createProperty(result, index, arguments[index++]);
    result.length = aLen;
    return result;
  }
});


/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {

// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(3);

$export($export.P, 'Array', { copyWithin: __webpack_require__(334) });

__webpack_require__(45)('copyWithin');


/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(3);
var $find = __webpack_require__(64)(5);
var KEY = 'find';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
  find: function find(callbackfn /* , that = undefined */) {
    return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  }
});
__webpack_require__(45)(KEY);


/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(3);
var $find = __webpack_require__(64)(6);
var KEY = 'findIndex';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
  findIndex: function findIndex(callbackfn /* , that = undefined */) {
    return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
  }
});
__webpack_require__(45)(KEY);


/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {

// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(3);

$export($export.P, 'Array', { fill: __webpack_require__(335) });

__webpack_require__(45)('fill');


/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(3);
var _isFinite = __webpack_require__(13).isFinite;

$export($export.S, 'Number', {
  isFinite: function isFinite(it) {
    return typeof it == 'number' && _isFinite(it);
  }
});


/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(3);

$export($export.S, 'Number', { isInteger: __webpack_require__(153) });


/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(5);
var floor = Math.floor;
module.exports = function isInteger(it) {
  return !isObject(it) && isFinite(it) && floor(it) === it;
};


/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(3);
var isInteger = __webpack_require__(153);
var abs = Math.abs;

$export($export.S, 'Number', {
  isSafeInteger: function isSafeInteger(number) {
    return isInteger(number) && abs(number) <= 0x1fffffffffffff;
  }
});


/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(3);

$export($export.S, 'Number', {
  isNaN: function isNaN(number) {
    // eslint-disable-next-line no-self-compare
    return number != number;
  }
});


/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(3);

$export($export.S, 'Number', { EPSILON: Math.pow(2, -52) });


/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(3);

$export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff });


/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {

// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(3);

$export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff });


/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__(3);
var $includes = __webpack_require__(95)(true);

$export($export.P, 'Array', {
  includes: function includes(el /* , fromIndex = 0 */) {
    return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
  }
});

__webpack_require__(45)('includes');


/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {

// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(3);
var $values = __webpack_require__(161)(false);

$export($export.S, 'Object', {
  values: function values(it) {
    return $values(it);
  }
});


/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {

var getKeys = __webpack_require__(37);
var toIObject = __webpack_require__(24);
var isEnum = __webpack_require__(52).f;
module.exports = function (isEntries) {
  return function (it) {
    var O = toIObject(it);
    var keys = getKeys(O);
    var length = keys.length;
    var i = 0;
    var result = [];
    var key;
    while (length > i) if (isEnum.call(O, key = keys[i++])) {
      result.push(isEntries ? [key, O[key]] : O[key]);
    } return result;
  };
};


/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {

// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(3);
var $entries = __webpack_require__(161)(true);

$export($export.S, 'Object', {
  entries: function entries(it) {
    return $entries(it);
  }
});


/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {

// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = __webpack_require__(3);
var ownKeys = __webpack_require__(336);
var toIObject = __webpack_require__(24);
var gOPD = __webpack_require__(63);
var createProperty = __webpack_require__(80);

$export($export.S, 'Object', {
  getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
    var O = toIObject(object);
    var getDesc = gOPD.f;
    var keys = ownKeys(O);
    var result = {};
    var i = 0;
    var key, desc;
    while (keys.length > i) {
      desc = getDesc(O, key = keys[i++]);
      if (desc !== undefined) createProperty(result, key, desc);
    }
    return result;
  }
});


/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(3);
var $pad = __webpack_require__(165);
var userAgent = __webpack_require__(166);

// https://github.com/zloirock/core-js/issues/280
$export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', {
  padStart: function padStart(maxLength /* , fillString = ' ' */) {
    return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
  }
});


/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {

// https://github.com/tc39/proposal-string-pad-start-end
var toLength = __webpack_require__(25);
var repeat = __webpack_require__(135);
var defined = __webpack_require__(38);

module.exports = function (that, maxLength, fillString, left) {
  var S = String(defined(that));
  var stringLength = S.length;
  var fillStr = fillString === undefined ? ' ' : String(fillString);
  var intMaxLength = toLength(maxLength);
  if (intMaxLength <= stringLength || fillStr == '') return S;
  var fillLen = intMaxLength - stringLength;
  var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
  if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);
  return left ? stringFiller + S : S + stringFiller;
};


/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(13);
var navigator = global.navigator;

module.exports = navigator && navigator.userAgent || '';


/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(3);
var $pad = __webpack_require__(165);
var userAgent = __webpack_require__(166);

// https://github.com/zloirock/core-js/issues/280
$export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', {
  padEnd: function padEnd(maxLength /* , fillString = ' ' */) {
    return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
  }
});


/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {

var $export = __webpack_require__(3);
var $task = __webpack_require__(76);
$export($export.G + $export.B, {
  setImmediate: $task.set,
  clearImmediate: $task.clear
});


/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {

var $iterators = __webpack_require__(81);
var getKeys = __webpack_require__(37);
var redefine = __webpack_require__(30);
var global = __webpack_require__(13);
var hide = __webpack_require__(31);
var Iterators = __webpack_require__(50);
var wks = __webpack_require__(10);
var ITERATOR = wks('iterator');
var TO_STRING_TAG = wks('toStringTag');
var ArrayValues = Iterators.Array;

var DOMIterables = {
  CSSRuleList: true, // TODO: Not spec compliant, should be false.
  CSSStyleDeclaration: false,
  CSSValueList: false,
  ClientRectList: false,
  DOMRectList: false,
  DOMStringList: false,
  DOMTokenList: true,
  DataTransferItemList: false,
  FileList: false,
  HTMLAllCollection: false,
  HTMLCollection: false,
  HTMLFormElement: false,
  HTMLSelectElement: false,
  MediaList: true, // TODO: Not spec compliant, should be false.
  MimeTypeArray: false,
  NamedNodeMap: false,
  NodeList: true,
  PaintRequestList: false,
  Plugin: false,
  PluginArray: false,
  SVGLengthList: false,
  SVGNumberList: false,
  SVGPathSegList: false,
  SVGPointList: false,
  SVGStringList: false,
  SVGTransformList: false,
  SourceBufferList: false,
  StyleSheetList: true, // TODO: Not spec compliant, should be false.
  TextTrackCueList: false,
  TextTrackList: false,
  TouchList: false
};

for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {
  var NAME = collections[i];
  var explicit = DOMIterables[NAME];
  var Collection = global[NAME];
  var proto = Collection && Collection.prototype;
  var key;
  if (proto) {
    if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);
    if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
    Iterators[NAME] = ArrayValues;
    if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true);
  }
}


/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var privatePool = new WeakMap();

/**
 * Calculates indexes of columns to render OR columns that are visible.
 * To redo the calculation, you need to create a new calculator.
 *
 * @class ViewportColumnsCalculator
 */

var ViewportColumnsCalculator = function () {
  _createClass(ViewportColumnsCalculator, null, [{
    key: 'DEFAULT_WIDTH',

    /**
     * Default column width
     *
     * @type {Number}
     */
    get: function get() {
      return 50;
    }

    /**
     * @param {Number} viewportWidth Width of the viewport
     * @param {Number} scrollOffset Current horizontal scroll position of the viewport
     * @param {Number} totalColumns Total number of rows
     * @param {Function} columnWidthFn Function that returns the width of the column at a given index (in px)
     * @param {Function} overrideFn Function that changes calculated this.startRow, this.endRow (used by MergeCells plugin)
     * @param {Boolean} onlyFullyVisible if `true`, only startRow and endRow will be indexes of rows that are fully in viewport
     * @param {Boolean} stretchH
     * @param {Function} [stretchingColumnWidthFn] Function that returns the new width of the stretched column.
     */

  }]);

  function ViewportColumnsCalculator(viewportWidth, scrollOffset, totalColumns, columnWidthFn, overrideFn, onlyFullyVisible, stretchH) {
    var stretchingColumnWidthFn = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : function (width) {
      return width;
    };

    _classCallCheck(this, ViewportColumnsCalculator);

    privatePool.set(this, {
      viewportWidth: viewportWidth,
      scrollOffset: scrollOffset,
      totalColumns: totalColumns,
      columnWidthFn: columnWidthFn,
      overrideFn: overrideFn,
      onlyFullyVisible: onlyFullyVisible,
      stretchingColumnWidthFn: stretchingColumnWidthFn
    });

    /**
     * Number of rendered/visible columns
     *
     * @type {Number}
     */
    this.count = 0;

    /**
     * Index of the first rendered/visible column (can be overwritten using overrideFn)
     *
     * @type {Number|null}
     */
    this.startColumn = null;

    /**
     * Index of the last rendered/visible column (can be overwritten using overrideFn)
     *
     * @type {null}
     */
    this.endColumn = null;

    /**
     * Position of the first rendered/visible column (in px)
     *
     * @type {Number|null}
     */
    this.startPosition = null;

    this.stretchAllRatio = 0;
    this.stretchLastWidth = 0;
    this.stretch = stretchH;
    this.totalTargetWidth = 0;
    this.needVerifyLastColumnWidth = true;
    this.stretchAllColumnsWidth = [];

    this.calculate();
  }

  /**
   * Calculates viewport
   */


  _createClass(ViewportColumnsCalculator, [{
    key: 'calculate',
    value: function calculate() {
      var sum = 0;
      var needReverse = true;
      var startPositions = [];
      var columnWidth = void 0;

      var priv = privatePool.get(this);
      var onlyFullyVisible = priv.onlyFullyVisible;
      var overrideFn = priv.overrideFn;
      var scrollOffset = priv.scrollOffset;
      var totalColumns = priv.totalColumns;
      var viewportWidth = priv.viewportWidth;

      for (var i = 0; i < totalColumns; i++) {
        columnWidth = this._getColumnWidth(i);

        if (sum <= scrollOffset && !onlyFullyVisible) {
          this.startColumn = i;
        }

        // +1 pixel for row header width compensation for horizontal scroll > 0
        var compensatedViewportWidth = scrollOffset > 0 ? viewportWidth + 1 : viewportWidth;

        if (sum >= scrollOffset && sum + columnWidth <= scrollOffset + compensatedViewportWidth) {
          if (this.startColumn == null) {
            this.startColumn = i;
          }
          this.endColumn = i;
        }
        startPositions.push(sum);
        sum += columnWidth;

        if (!onlyFullyVisible) {
          this.endColumn = i;
        }
        if (sum >= scrollOffset + viewportWidth) {
          needReverse = false;
          break;
        }
      }

      if (this.endColumn === totalColumns - 1 && needReverse) {
        this.startColumn = this.endColumn;

        while (this.startColumn > 0) {
          var viewportSum = startPositions[this.endColumn] + columnWidth - startPositions[this.startColumn - 1];

          if (viewportSum <= viewportWidth || !onlyFullyVisible) {
            this.startColumn--;
          }
          if (viewportSum > viewportWidth) {
            break;
          }
        }
      }

      if (this.startColumn !== null && overrideFn) {
        overrideFn(this);
      }
      this.startPosition = startPositions[this.startColumn];

      if (this.startPosition == void 0) {
        this.startPosition = null;
      }
      if (this.startColumn !== null) {
        this.count = this.endColumn - this.startColumn + 1;
      }
    }

    /**
     * Recalculate columns stretching.
     *
     * @param {Number} totalWidth
     */

  }, {
    key: 'refreshStretching',
    value: function refreshStretching(totalWidth) {
      if (this.stretch === 'none') {
        return;
      }
      this.totalTargetWidth = totalWidth;

      var priv = privatePool.get(this);
      var totalColumns = priv.totalColumns;
      var sumAll = 0;

      for (var i = 0; i < totalColumns; i++) {
        var columnWidth = this._getColumnWidth(i);
        var permanentColumnWidth = priv.stretchingColumnWidthFn(void 0, i);

        if (typeof permanentColumnWidth === 'number') {
          totalWidth -= permanentColumnWidth;
        } else {
          sumAll += columnWidth;
        }
      }
      var remainingSize = totalWidth - sumAll;

      if (this.stretch === 'all' && remainingSize > 0) {
        this.stretchAllRatio = totalWidth / sumAll;
        this.stretchAllColumnsWidth = [];
        this.needVerifyLastColumnWidth = true;
      } else if (this.stretch === 'last' && totalWidth !== Infinity) {
        var _columnWidth = this._getColumnWidth(totalColumns - 1);
        var lastColumnWidth = remainingSize + _columnWidth;

        this.stretchLastWidth = lastColumnWidth >= 0 ? lastColumnWidth : _columnWidth;
      }
    }

    /**
     * Get stretched column width based on stretchH (all or last) setting passed in handsontable instance.
     *
     * @param {Number} column
     * @param {Number} baseWidth
     * @returns {Number|null}
     */

  }, {
    key: 'getStretchedColumnWidth',
    value: function getStretchedColumnWidth(column, baseWidth) {
      var result = null;

      if (this.stretch === 'all' && this.stretchAllRatio !== 0) {
        result = this._getStretchedAllColumnWidth(column, baseWidth);
      } else if (this.stretch === 'last' && this.stretchLastWidth !== 0) {
        result = this._getStretchedLastColumnWidth(column);
      }

      return result;
    }

    /**
     * @param {Number} column
     * @param {Number} baseWidth
     * @returns {Number}
     * @private
     */

  }, {
    key: '_getStretchedAllColumnWidth',
    value: function _getStretchedAllColumnWidth(column, baseWidth) {
      var sumRatioWidth = 0;
      var priv = privatePool.get(this);
      var totalColumns = priv.totalColumns;

      if (!this.stretchAllColumnsWidth[column]) {
        var stretchedWidth = Math.round(baseWidth * this.stretchAllRatio);
        var newStretchedWidth = priv.stretchingColumnWidthFn(stretchedWidth, column);

        if (newStretchedWidth === void 0) {
          this.stretchAllColumnsWidth[column] = stretchedWidth;
        } else {
          this.stretchAllColumnsWidth[column] = isNaN(newStretchedWidth) ? this._getColumnWidth(column) : newStretchedWidth;
        }
      }

      if (this.stretchAllColumnsWidth.length === totalColumns && this.needVerifyLastColumnWidth) {
        this.needVerifyLastColumnWidth = false;

        for (var i = 0; i < this.stretchAllColumnsWidth.length; i++) {
          sumRatioWidth += this.stretchAllColumnsWidth[i];
        }
        if (sumRatioWidth !== this.totalTargetWidth) {
          this.stretchAllColumnsWidth[this.stretchAllColumnsWidth.length - 1] += this.totalTargetWidth - sumRatioWidth;
        }
      }

      return this.stretchAllColumnsWidth[column];
    }

    /**
     * @param {Number} column
     * @returns {Number|null}
     * @private
     */

  }, {
    key: '_getStretchedLastColumnWidth',
    value: function _getStretchedLastColumnWidth(column) {
      var priv = privatePool.get(this);
      var totalColumns = priv.totalColumns;

      if (column === totalColumns - 1) {
        return this.stretchLastWidth;
      }

      return null;
    }

    /**
     * @param {Number} column Column index.
     * @returns {Number}
     * @private
     */

  }, {
    key: '_getColumnWidth',
    value: function _getColumnWidth(column) {
      var width = privatePool.get(this).columnWidthFn(column);

      if (width === void 0) {
        width = ViewportColumnsCalculator.DEFAULT_WIDTH;
      }

      return width;
    }
  }]);

  return ViewportColumnsCalculator;
}();

exports.default = ViewportColumnsCalculator;

/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var privatePool = new WeakMap();

/**
 * Calculates indexes of rows to render OR rows that are visible.
 * To redo the calculation, you need to create a new calculator.
 *
 * @class ViewportRowsCalculator
 */

var ViewportRowsCalculator = function () {
  _createClass(ViewportRowsCalculator, null, [{
    key: "DEFAULT_HEIGHT",

    /**
     * Default row height
     *
     * @type {Number}
     */
    get: function get() {
      return 23;
    }

    /**
     * @param {Number} viewportHeight Height of the viewport
     * @param {Number} scrollOffset Current vertical scroll position of the viewport
     * @param {Number} totalRows Total number of rows
     * @param {Function} rowHeightFn Function that returns the height of the row at a given index (in px)
     * @param {Function} overrideFn Function that changes calculated this.startRow, this.endRow (used by MergeCells plugin)
     * @param {Boolean} onlyFullyVisible if `true`, only startRow and endRow will be indexes of rows that are fully in viewport
     * @param {Number} horizontalScrollbarHeight
     */

  }]);

  function ViewportRowsCalculator(viewportHeight, scrollOffset, totalRows, rowHeightFn, overrideFn, onlyFullyVisible, horizontalScrollbarHeight) {
    _classCallCheck(this, ViewportRowsCalculator);

    privatePool.set(this, {
      viewportHeight: viewportHeight,
      scrollOffset: scrollOffset,
      totalRows: totalRows,
      rowHeightFn: rowHeightFn,
      overrideFn: overrideFn,
      onlyFullyVisible: onlyFullyVisible,
      horizontalScrollbarHeight: horizontalScrollbarHeight
    });

    /**
     * Number of rendered/visible rows
     *
     * @type {Number}
     */
    this.count = 0;

    /**
     * Index of the first rendered/visible row (can be overwritten using overrideFn)
     *
     * @type {Number|null}
     */
    this.startRow = null;

    /**
     * Index of the last rendered/visible row (can be overwritten using overrideFn)
     *
     * @type {null}
     */
    this.endRow = null;

    /**
     * Position of the first rendered/visible row (in px)
     *
     * @type {Number|null}
     */
    this.startPosition = null;

    this.calculate();
  }

  /**
   * Calculates viewport
   */


  _createClass(ViewportRowsCalculator, [{
    key: "calculate",
    value: function calculate() {
      var sum = 0;
      var needReverse = true;
      var startPositions = [];

      var priv = privatePool.get(this);
      var onlyFullyVisible = priv.onlyFullyVisible;
      var overrideFn = priv.overrideFn;
      var rowHeightFn = priv.rowHeightFn;
      var scrollOffset = priv.scrollOffset;
      var totalRows = priv.totalRows;
      var viewportHeight = priv.viewportHeight;
      var horizontalScrollbarHeight = priv.horizontalScrollbarHeight || 0;
      var rowHeight = void 0;

      // Calculate the number (start and end index) of rows needed
      for (var i = 0; i < totalRows; i++) {
        rowHeight = rowHeightFn(i);

        if (rowHeight === undefined) {
          rowHeight = ViewportRowsCalculator.DEFAULT_HEIGHT;
        }
        if (sum <= scrollOffset && !onlyFullyVisible) {
          this.startRow = i;
        }

        // the row is within the "visible range"
        if (sum >= scrollOffset && sum + rowHeight <= scrollOffset + viewportHeight - horizontalScrollbarHeight) {
          if (this.startRow === null) {
            this.startRow = i;
          }
          this.endRow = i;
        }
        startPositions.push(sum);
        sum += rowHeight;

        if (!onlyFullyVisible) {
          this.endRow = i;
        }
        if (sum >= scrollOffset + viewportHeight - horizontalScrollbarHeight) {
          needReverse = false;
          break;
        }
      }

      // If the estimation has reached the last row and there is still some space available in the viewport,
      // we need to render in reverse in order to fill the whole viewport with rows
      if (this.endRow === totalRows - 1 && needReverse) {
        this.startRow = this.endRow;

        while (this.startRow > 0) {
          // rowHeight is the height of the last row
          var viewportSum = startPositions[this.endRow] + rowHeight - startPositions[this.startRow - 1];

          if (viewportSum <= viewportHeight - horizontalScrollbarHeight || !onlyFullyVisible) {
            this.startRow--;
          }
          if (viewportSum >= viewportHeight - horizontalScrollbarHeight) {
            break;
          }
        }
      }

      if (this.startRow !== null && overrideFn) {
        overrideFn(this);
      }
      this.startPosition = startPositions[this.startRow];

      if (this.startPosition == void 0) {
        this.startPosition = null;
      }
      if (this.startRow !== null) {
        this.count = this.endRow - this.startRow + 1;
      }
    }
  }]);

  return ViewportRowsCalculator;
}();

exports.default = ViewportRowsCalculator;

/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class ColumnFilter
 */
var ColumnFilter = function () {
  /**
   * @param {Number} offset
   * @param {Number} total
   * @param {Number} countTH
   */
  function ColumnFilter(offset, total, countTH) {
    _classCallCheck(this, ColumnFilter);

    this.offset = offset;
    this.total = total;
    this.countTH = countTH;
  }

  /**
   * @param index
   * @returns {Number}
   */


  _createClass(ColumnFilter, [{
    key: "offsetted",
    value: function offsetted(index) {
      return index + this.offset;
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "unOffsetted",
    value: function unOffsetted(index) {
      return index - this.offset;
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "renderedToSource",
    value: function renderedToSource(index) {
      return this.offsetted(index);
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "sourceToRendered",
    value: function sourceToRendered(index) {
      return this.unOffsetted(index);
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "offsettedTH",
    value: function offsettedTH(index) {
      return index - this.countTH;
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "unOffsettedTH",
    value: function unOffsettedTH(index) {
      return index + this.countTH;
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "visibleRowHeadedColumnToSourceColumn",
    value: function visibleRowHeadedColumnToSourceColumn(index) {
      return this.renderedToSource(this.offsettedTH(index));
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "sourceColumnToVisibleRowHeadedColumn",
    value: function sourceColumnToVisibleRowHeadedColumn(index) {
      return this.unOffsettedTH(this.sourceToRendered(index));
    }
  }]);

  return ColumnFilter;
}();

exports.default = ColumnFilter;

/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class RowFilter
 */
var RowFilter = function () {
  /**
   * @param {Number} offset
   * @param {Number} total
   * @param {Number} countTH
   */
  function RowFilter(offset, total, countTH) {
    _classCallCheck(this, RowFilter);

    this.offset = offset;
    this.total = total;
    this.countTH = countTH;
  }

  /**
   * @param index
   * @returns {Number}
   */


  _createClass(RowFilter, [{
    key: "offsetted",
    value: function offsetted(index) {
      return index + this.offset;
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "unOffsetted",
    value: function unOffsetted(index) {
      return index - this.offset;
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "renderedToSource",
    value: function renderedToSource(index) {
      return this.offsetted(index);
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "sourceToRendered",
    value: function sourceToRendered(index) {
      return this.unOffsetted(index);
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "offsettedTH",
    value: function offsettedTH(index) {
      return index - this.countTH;
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "unOffsettedTH",
    value: function unOffsettedTH(index) {
      return index + this.countTH;
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "visibleColHeadedRowToSourceRow",
    value: function visibleColHeadedRowToSourceRow(index) {
      return this.renderedToSource(this.offsettedTH(index));
    }

    /**
     * @param index
     * @returns {Number}
     */

  }, {
    key: "sourceRowToVisibleColHeadedRow",
    value: function sourceRowToVisibleColHeadedRow(index) {
      return this.unOffsettedTH(this.sourceToRendered(index));
    }
  }]);

  return RowFilter;
}();

exports.default = RowFilter;

/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _object = __webpack_require__(1);

var _string = __webpack_require__(36);

var _event = __webpack_require__(295);

var _event2 = _interopRequireDefault(_event);

var _overlays = __webpack_require__(296);

var _overlays2 = _interopRequireDefault(_overlays);

var _scroll = __webpack_require__(297);

var _scroll2 = _interopRequireDefault(_scroll);

var _settings = __webpack_require__(298);

var _settings2 = _interopRequireDefault(_settings);

var _table = __webpack_require__(299);

var _table2 = _interopRequireDefault(_table);

var _viewport = __webpack_require__(301);

var _viewport2 = _interopRequireDefault(_viewport);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Walkontable
 */
var Walkontable = function () {
  /**
   * @param {Object} settings
   */
  function Walkontable(settings) {
    _classCallCheck(this, Walkontable);

    var originalHeaders = [];

    // this is the namespace for global events
    this.guid = 'wt_' + (0, _string.randomString)();

    // bootstrap from settings
    if (settings.cloneSource) {
      this.cloneSource = settings.cloneSource;
      this.cloneOverlay = settings.cloneOverlay;
      this.wtSettings = settings.cloneSource.wtSettings;
      this.wtTable = new _table2.default(this, settings.table, settings.wtRootElement);
      this.wtScroll = new _scroll2.default(this);
      this.wtViewport = settings.cloneSource.wtViewport;
      this.wtEvent = new _event2.default(this);
      this.selections = this.cloneSource.selections;
    } else {
      this.wtSettings = new _settings2.default(this, settings);
      this.wtTable = new _table2.default(this, settings.table);
      this.wtScroll = new _scroll2.default(this);
      this.wtViewport = new _viewport2.default(this);
      this.wtEvent = new _event2.default(this);
      this.selections = this.getSetting('selections');
      this.wtOverlays = new _overlays2.default(this);
      this.exportSettingsAsClassNames();
    }

    // find original headers
    if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) {
      for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) {
        originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML);
      }
      if (!this.getSetting('columnHeaders').length) {
        this.update('columnHeaders', [function (column, TH) {
          (0, _element.fastInnerText)(TH, originalHeaders[column]);
        }]);
      }
    }
    this.drawn = false;
    this.drawInterrupted = false;
  }

  /**
   * Force rerender of Walkontable
   *
   * @param {Boolean} [fastDraw=false] When `true`, try to refresh only the positions of borders without rerendering
   *                                   the data. It will only work if Table.draw() does not force
   *                                   rendering anyway
   * @returns {Walkontable}
   */


  _createClass(Walkontable, [{
    key: 'draw',
    value: function draw() {
      var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      this.drawInterrupted = false;

      if (!fastDraw && !(0, _element.isVisible)(this.wtTable.TABLE)) {
        // draw interrupted because TABLE is not visible
        this.drawInterrupted = true;
      } else {
        this.wtTable.draw(fastDraw);
      }

      return this;
    }

    /**
     * Returns the TD at coords. If topmost is set to true, returns TD from the topmost overlay layer,
     * if not set or set to false, returns TD from the master table.
     *
     * @param {CellCoords} coords
     * @param {Boolean} [topmost=false]
     * @returns {Object}
     */

  }, {
    key: 'getCell',
    value: function getCell(coords) {
      var topmost = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      if (!topmost) {
        return this.wtTable.getCell(coords);
      }

      var totalRows = this.wtSettings.getSetting('totalRows');
      var fixedRowsTop = this.wtSettings.getSetting('fixedRowsTop');
      var fixedRowsBottom = this.wtSettings.getSetting('fixedRowsBottom');
      var fixedColumns = this.wtSettings.getSetting('fixedColumnsLeft');

      if (coords.row < fixedRowsTop && coords.col < fixedColumns) {
        return this.wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell(coords);
      } else if (coords.row < fixedRowsTop) {
        return this.wtOverlays.topOverlay.clone.wtTable.getCell(coords);
      } else if (coords.col < fixedColumns && coords.row >= totalRows - fixedRowsBottom) {
        if (this.wtOverlays.bottomLeftCornerOverlay && this.wtOverlays.bottomLeftCornerOverlay.clone) {
          return this.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.getCell(coords);
        }
      } else if (coords.col < fixedColumns) {
        return this.wtOverlays.leftOverlay.clone.wtTable.getCell(coords);
      } else if (coords.row < totalRows && coords.row > totalRows - fixedRowsBottom) {
        if (this.wtOverlays.bottomOverlay && this.wtOverlays.bottomOverlay.clone) {
          return this.wtOverlays.bottomOverlay.clone.wtTable.getCell(coords);
        }
      }

      return this.wtTable.getCell(coords);
    }

    /**
     * @param {Object} settings
     * @param {*} value
     * @returns {Walkontable}
     */

  }, {
    key: 'update',
    value: function update(settings, value) {
      return this.wtSettings.update(settings, value);
    }

    /**
     * Scroll the viewport to a row at the given index in the data source
     *
     * @param {Number} row
     * @returns {Walkontable}
     */

  }, {
    key: 'scrollVertical',
    value: function scrollVertical(row) {
      this.wtOverlays.topOverlay.scrollTo(row);
      this.getSetting('onScrollVertically');

      return this;
    }

    /**
     * Scroll the viewport to a column at the given index in the data source
     *
     * @param {Number} column
     * @returns {Walkontable}
     */

  }, {
    key: 'scrollHorizontal',
    value: function scrollHorizontal(column) {
      this.wtOverlays.leftOverlay.scrollTo(column);
      this.getSetting('onScrollHorizontally');

      return this;
    }

    /**
     * Scrolls the viewport to a cell (rerenders if needed)
     *
     * @param {CellCoords} coords
     * @returns {Walkontable}
     */

  }, {
    key: 'scrollViewport',
    value: function scrollViewport(coords) {
      this.wtScroll.scrollViewport(coords);

      return this;
    }

    /**
     * @returns {Array}
     */

  }, {
    key: 'getViewport',
    value: function getViewport() {
      return [this.wtTable.getFirstVisibleRow(), this.wtTable.getFirstVisibleColumn(), this.wtTable.getLastVisibleRow(), this.wtTable.getLastVisibleColumn()];
    }

    /**
     * Get overlay name
     *
     * @returns {String}
     */

  }, {
    key: 'getOverlayName',
    value: function getOverlayName() {
      return this.cloneOverlay ? this.cloneOverlay.type : 'master';
    }

    /**
     * Check overlay type of this Walkontable instance.
     *
     * @param {String} name Clone type @see {Overlay.CLONE_TYPES}.
     * @returns {Boolean}
     */

  }, {
    key: 'isOverlayName',
    value: function isOverlayName(name) {
      if (this.cloneOverlay) {
        return this.cloneOverlay.type === name;
      }

      return false;
    }

    /**
     * Export settings as class names added to the parent element of the table.
     */

  }, {
    key: 'exportSettingsAsClassNames',
    value: function exportSettingsAsClassNames() {
      var _this = this;

      var toExport = {
        rowHeaders: ['array'],
        columnHeaders: ['array']
      };
      var allClassNames = [];
      var newClassNames = [];

      (0, _object.objectEach)(toExport, function (optionType, key) {
        if (optionType.indexOf('array') > -1 && _this.getSetting(key).length) {
          newClassNames.push('ht' + (0, _string.toUpperCaseFirst)(key));
        }
        allClassNames.push('ht' + (0, _string.toUpperCaseFirst)(key));
      });
      (0, _element.removeClass)(this.wtTable.wtRootElement.parentNode, allClassNames);
      (0, _element.addClass)(this.wtTable.wtRootElement.parentNode, newClassNames);
    }

    /**
     * Get/Set Walkontable instance setting
     *
     * @param {String} key
     * @param {*} [param1]
     * @param {*} [param2]
     * @param {*} [param3]
     * @param {*} [param4]
     * @returns {*}
     */

  }, {
    key: 'getSetting',
    value: function getSetting(key, param1, param2, param3, param4) {
      // this is faster than .apply - https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
      return this.wtSettings.getSetting(key, param1, param2, param3, param4);
    }

    /**
     * Checks if setting exists
     *
     * @param {String} key
     * @returns {Boolean}
     */

  }, {
    key: 'hasSetting',
    value: function hasSetting(key) {
      return this.wtSettings.has(key);
    }

    /**
     * Destroy instance
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.wtOverlays.destroy();
      this.wtEvent.destroy();
    }
  }]);

  return Walkontable;
}();

exports.default = Walkontable;

/***/ }),
/* 175 */
/***/ (function(module, exports) {



/***/ }),
/* 176 */
/***/ (function(module, exports) {



/***/ }),
/* 177 */
/***/ (function(module, exports) {



/***/ }),
/* 178 */
/***/ (function(module, exports) {



/***/ }),
/* 179 */
/***/ (function(module, exports) {



/***/ }),
/* 180 */
/***/ (function(module, exports) {



/***/ }),
/* 181 */
/***/ (function(module, exports) {



/***/ }),
/* 182 */
/***/ (function(module, exports) {



/***/ }),
/* 183 */
/***/ (function(module, exports) {



/***/ }),
/* 184 */
/***/ (function(module, exports) {



/***/ }),
/* 185 */
/***/ (function(module, exports) {



/***/ }),
/* 186 */
/***/ (function(module, exports) {



/***/ }),
/* 187 */
/***/ (function(module, exports) {



/***/ }),
/* 188 */
/***/ (function(module, exports) {



/***/ }),
/* 189 */
/***/ (function(module, exports) {



/***/ }),
/* 190 */
/***/ (function(module, exports) {



/***/ }),
/* 191 */
/***/ (function(module, exports) {



/***/ }),
/* 192 */
/***/ (function(module, exports) {



/***/ }),
/* 193 */
/***/ (function(module, exports) {



/***/ }),
/* 194 */
/***/ (function(module, exports) {



/***/ }),
/* 195 */
/***/ (function(module, exports) {



/***/ }),
/* 196 */
/***/ (function(module, exports) {



/***/ }),
/* 197 */
/***/ (function(module, exports) {



/***/ }),
/* 198 */
/***/ (function(module, exports) {



/***/ }),
/* 199 */
/***/ (function(module, exports) {



/***/ }),
/* 200 */
/***/ (function(module, exports) {



/***/ }),
/* 201 */
/***/ (function(module, exports) {



/***/ }),
/* 202 */
/***/ (function(module, exports) {



/***/ }),
/* 203 */
/***/ (function(module, exports) {



/***/ }),
/* 204 */
/***/ (function(module, exports) {



/***/ }),
/* 205 */
/***/ (function(module, exports) {



/***/ }),
/* 206 */
/***/ (function(module, exports) {



/***/ }),
/* 207 */
/***/ (function(module, exports) {



/***/ }),
/* 208 */
/***/ (function(module, exports) {



/***/ }),
/* 209 */
/***/ (function(module, exports) {



/***/ }),
/* 210 */
/***/ (function(module, exports) {



/***/ }),
/* 211 */
/***/ (function(module, exports) {



/***/ }),
/* 212 */
/***/ (function(module, exports) {



/***/ }),
/* 213 */
/***/ (function(module, exports) {



/***/ }),
/* 214 */
/***/ (function(module, exports) {



/***/ }),
/* 215 */
/***/ (function(module, exports) {



/***/ }),
/* 216 */
/***/ (function(module, exports) {



/***/ }),
/* 217 */
/***/ (function(module, exports) {



/***/ }),
/* 218 */
/***/ (function(module, exports) {



/***/ }),
/* 219 */
/***/ (function(module, exports) {



/***/ }),
/* 220 */
/***/ (function(module, exports) {



/***/ }),
/* 221 */
/***/ (function(module, exports) {



/***/ }),
/* 222 */
/***/ (function(module, exports) {



/***/ }),
/* 223 */
/***/ (function(module, exports) {



/***/ }),
/* 224 */
/***/ (function(module, exports) {



/***/ }),
/* 225 */
/***/ (function(module, exports) {



/***/ }),
/* 226 */
/***/ (function(module, exports) {



/***/ }),
/* 227 */
/***/ (function(module, exports) {



/***/ }),
/* 228 */
/***/ (function(module, exports) {



/***/ }),
/* 229 */
/***/ (function(module, exports) {



/***/ }),
/* 230 */
/***/ (function(module, exports) {



/***/ }),
/* 231 */
/***/ (function(module, exports) {



/***/ }),
/* 232 */
/***/ (function(module, exports) {



/***/ }),
/* 233 */
/***/ (function(module, exports) {



/***/ }),
/* 234 */
/***/ (function(module, exports) {



/***/ }),
/* 235 */
/***/ (function(module, exports) {



/***/ }),
/* 236 */
/***/ (function(module, exports) {



/***/ }),
/* 237 */
/***/ (function(module, exports) {



/***/ }),
/* 238 */
/***/ (function(module, exports) {



/***/ }),
/* 239 */
/***/ (function(module, exports) {



/***/ }),
/* 240 */
/***/ (function(module, exports) {



/***/ }),
/* 241 */
/***/ (function(module, exports) {



/***/ }),
/* 242 */
/***/ (function(module, exports) {



/***/ }),
/* 243 */
/***/ (function(module, exports) {



/***/ }),
/* 244 */
/***/ (function(module, exports) {



/***/ }),
/* 245 */
/***/ (function(module, exports) {



/***/ }),
/* 246 */
/***/ (function(module, exports) {



/***/ }),
/* 247 */
/***/ (function(module, exports) {



/***/ }),
/* 248 */
/***/ (function(module, exports) {



/***/ }),
/* 249 */
/***/ (function(module, exports) {



/***/ }),
/* 250 */
/***/ (function(module, exports) {



/***/ }),
/* 251 */
/***/ (function(module, exports) {



/***/ }),
/* 252 */
/***/ (function(module, exports) {



/***/ }),
/* 253 */
/***/ (function(module, exports) {



/***/ }),
/* 254 */
/***/ (function(module, exports) {



/***/ }),
/* 255 */
/***/ (function(module, exports) {



/***/ }),
/* 256 */
/***/ (function(module, exports) {



/***/ }),
/* 257 */
/***/ (function(module, exports) {



/***/ }),
/* 258 */
/***/ (function(module, exports) {



/***/ }),
/* 259 */
/***/ (function(module, exports) {



/***/ }),
/* 260 */
/***/ (function(module, exports) {



/***/ }),
/* 261 */
/***/ (function(module, exports) {



/***/ }),
/* 262 */
/***/ (function(module, exports) {



/***/ }),
/* 263 */
/***/ (function(module, exports) {



/***/ }),
/* 264 */
/***/ (function(module, exports) {



/***/ }),
/* 265 */
/***/ (function(module, exports) {



/***/ }),
/* 266 */
/***/ (function(module, exports) {



/***/ }),
/* 267 */
/***/ (function(module, exports) {



/***/ }),
/* 268 */
/***/ (function(module, exports) {



/***/ }),
/* 269 */
/***/ (function(module, exports) {



/***/ }),
/* 270 */
/***/ (function(module, exports) {



/***/ }),
/* 271 */
/***/ (function(module, exports) {



/***/ }),
/* 272 */
/***/ (function(module, exports) {



/***/ }),
/* 273 */
/***/ (function(module, exports) {



/***/ }),
/* 274 */
/***/ (function(module, exports) {



/***/ }),
/* 275 */
/***/ (function(module, exports) {



/***/ }),
/* 276 */
/***/ (function(module, exports) {



/***/ }),
/* 277 */
/***/ (function(module, exports) {



/***/ }),
/* 278 */
/***/ (function(module, exports) {



/***/ }),
/* 279 */
/***/ (function(module, exports) {



/***/ }),
/* 280 */
/***/ (function(module, exports) {



/***/ }),
/* 281 */
/***/ (function(module, exports) {



/***/ }),
/* 282 */
/***/ (function(module, exports) {



/***/ }),
/* 283 */
/***/ (function(module, exports) {



/***/ }),
/* 284 */
/***/ (function(module, exports) {



/***/ }),
/* 285 */
/***/ (function(module, exports) {



/***/ }),
/* 286 */
/***/ (function(module, exports) {



/***/ }),
/* 287 */
/***/ (function(module, exports) {



/***/ }),
/* 288 */
/***/ (function(module, exports) {



/***/ }),
/* 289 */
/***/ (function(module, exports) {



/***/ }),
/* 290 */
/***/ (function(module, exports) {



/***/ }),
/* 291 */
/***/ (function(module, exports) {



/***/ }),
/* 292 */
/***/ (function(module, exports) {



/***/ }),
/* 293 */
/***/ (function(module, exports) {



/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.toSingleLine = toSingleLine;

var _array = __webpack_require__(2);

/**
 * Tags a multiline string and return new one without line break characters and following spaces.
 *
 * @param {Array} strings Parts of the entire string without expressions.
 * @param {...String} expressions Expressions converted to strings, which are added to the entire string.
 * @returns {String}
 */
function toSingleLine(strings) {
  for (var _len = arguments.length, expressions = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    expressions[_key - 1] = arguments[_key];
  }

  var result = (0, _array.arrayReduce)(strings, function (previousValue, currentValue, index) {

    var valueWithoutWhiteSpaces = currentValue.replace(/(?:\r?\n\s+)/g, '');
    var expressionForIndex = expressions[index] ? expressions[index] : '';

    return previousValue + valueWithoutWhiteSpaces + expressionForIndex;
  }, '');

  return result.trim();
} /* eslint-disable import/prefer-default-export */

/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

var _function = __webpack_require__(41);

var _browser = __webpack_require__(28);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 *
 */
function Event(instance) {
  var that = this;
  var eventManager = new _eventManager2.default(instance);

  this.instance = instance;

  var dblClickOrigin = [null, null];
  this.dblClickTimeout = [null, null];

  var onMouseDown = function onMouseDown(event) {
    var activeElement = document.activeElement;
    var getParentNode = (0, _function.partial)(_element.getParent, event.realTarget);
    var realTarget = event.realTarget;

    // ignore focusable element from mouse down processing (https://github.com/handsontable/handsontable/issues/3555)
    if (realTarget === activeElement || getParentNode(0) === activeElement || getParentNode(1) === activeElement) {
      return;
    }

    var cell = that.parentCell(realTarget);

    if ((0, _element.hasClass)(realTarget, 'corner')) {
      that.instance.getSetting('onCellCornerMouseDown', event, realTarget);
    } else if (cell.TD) {
      if (that.instance.hasSetting('onCellMouseDown')) {
        that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD, that.instance);
      }
    }

    if (event.button !== 2) {
      // if not right mouse button
      if (cell.TD) {
        dblClickOrigin[0] = cell.TD;
        clearTimeout(that.dblClickTimeout[0]);
        that.dblClickTimeout[0] = setTimeout(function () {
          dblClickOrigin[0] = null;
        }, 1000);
      }
    }
  };

  var onTouchMove = function onTouchMove(event) {
    that.instance.touchMoving = true;
  };

  var longTouchTimeout;

  var onTouchStart = function onTouchStart(event) {
    var container = this;

    eventManager.addEventListener(this, 'touchmove', onTouchMove);

    // Prevent cell selection when scrolling with touch event - not the best solution performance-wise
    that.checkIfTouchMove = setTimeout(function () {
      if (that.instance.touchMoving === true) {
        that.instance.touchMoving = void 0;

        eventManager.removeEventListener('touchmove', onTouchMove, false);
      }

      onMouseDown(event);
    }, 30);
  };

  var onMouseOver = function onMouseOver(event) {
    var table, td, mainWOT;

    if (that.instance.hasSetting('onCellMouseOver')) {
      table = that.instance.wtTable.TABLE;
      td = (0, _element.closestDown)(event.realTarget, ['TD', 'TH'], table);
      mainWOT = that.instance.cloneSource || that.instance;

      if (td && td !== mainWOT.lastMouseOver && (0, _element.isChildOf)(td, table)) {
        mainWOT.lastMouseOver = td;

        that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(td), td, that.instance);
      }
    }
  };

  var onMouseOut = function onMouseOut(event) {
    var table = void 0;
    var lastTD = void 0;
    var nextTD = void 0;

    if (that.instance.hasSetting('onCellMouseOut')) {
      table = that.instance.wtTable.TABLE;
      lastTD = (0, _element.closestDown)(event.realTarget, ['TD', 'TH'], table);
      nextTD = (0, _element.closestDown)(event.relatedTarget, ['TD', 'TH'], table);

      if (lastTD && lastTD !== nextTD && (0, _element.isChildOf)(lastTD, table)) {
        that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(lastTD), lastTD, that.instance);
      }
    }
  };

  var onMouseUp = function onMouseUp(event) {
    if (event.button !== 2) {
      // if not right mouse button
      var cell = that.parentCell(event.realTarget);

      if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) {
        if ((0, _element.hasClass)(event.realTarget, 'corner')) {
          that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD, that.instance);
        } else {
          that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD, that.instance);
        }

        dblClickOrigin[0] = null;
        dblClickOrigin[1] = null;
      } else if (cell.TD === dblClickOrigin[0]) {
        that.instance.getSetting('onCellMouseUp', event, cell.coords, cell.TD, that.instance);

        dblClickOrigin[1] = cell.TD;
        clearTimeout(that.dblClickTimeout[1]);
        that.dblClickTimeout[1] = setTimeout(function () {
          dblClickOrigin[1] = null;
        }, 500);
      } else if (cell.TD && that.instance.hasSetting('onCellMouseUp')) {
        that.instance.getSetting('onCellMouseUp', event, cell.coords, cell.TD, that.instance);
      }
    }
  };

  var onTouchEnd = function onTouchEnd(event) {
    clearTimeout(longTouchTimeout);
    // that.instance.longTouch == void 0;

    event.preventDefault();
    onMouseUp(event);

    // eventManager.removeEventListener(that.instance.wtTable.holder, "mouseup", onMouseUp);
  };

  eventManager.addEventListener(this.instance.wtTable.holder, 'mousedown', onMouseDown);
  eventManager.addEventListener(this.instance.wtTable.TABLE, 'mouseover', onMouseOver);
  eventManager.addEventListener(this.instance.wtTable.TABLE, 'mouseout', onMouseOut);
  eventManager.addEventListener(this.instance.wtTable.holder, 'mouseup', onMouseUp);

  // check if full HOT instance, or detached WOT AND run on mobile device
  if (this.instance.wtTable.holder.parentNode.parentNode && (0, _browser.isMobileBrowser)() && !that.instance.wtTable.isWorkingOnClone()) {
    var classSelector = '.' + this.instance.wtTable.holder.parentNode.className.split(' ').join('.');

    eventManager.addEventListener(this.instance.wtTable.holder, 'touchstart', function (event) {
      that.instance.touchApplied = true;
      if ((0, _element.isChildOf)(event.target, classSelector)) {
        onTouchStart.call(event.target, event);
      }
    });
    eventManager.addEventListener(this.instance.wtTable.holder, 'touchend', function (event) {
      that.instance.touchApplied = false;
      if ((0, _element.isChildOf)(event.target, classSelector)) {
        onTouchEnd.call(event.target, event);
      }
    });

    if (!that.instance.momentumScrolling) {
      that.instance.momentumScrolling = {};
    }
    eventManager.addEventListener(this.instance.wtTable.holder, 'scroll', function (event) {
      clearTimeout(that.instance.momentumScrolling._timeout);

      if (!that.instance.momentumScrolling.ongoing) {
        that.instance.getSetting('onBeforeTouchScroll');
      }
      that.instance.momentumScrolling.ongoing = true;

      that.instance.momentumScrolling._timeout = setTimeout(function () {
        if (!that.instance.touchApplied) {
          that.instance.momentumScrolling.ongoing = false;

          that.instance.getSetting('onAfterMomentumScroll');
        }
      }, 200);
    });
  }

  eventManager.addEventListener(window, 'resize', function () {
    if (that.instance.getSetting('stretchH') !== 'none') {
      that.instance.draw();
    }
  });

  this.destroy = function () {
    clearTimeout(this.dblClickTimeout[0]);
    clearTimeout(this.dblClickTimeout[1]);

    eventManager.destroy();
  };
}

Event.prototype.parentCell = function (elem) {
  var cell = {};
  var TABLE = this.instance.wtTable.TABLE;
  var TD = (0, _element.closestDown)(elem, ['TD', 'TH'], TABLE);

  if (TD) {
    cell.coords = this.instance.wtTable.getCoords(TD);
    cell.TD = TD;
  } else if ((0, _element.hasClass)(elem, 'wtBorder') && (0, _element.hasClass)(elem, 'current')) {
    cell.coords = this.instance.selections.current.cellRange.highlight; // selections.current is current selected cell
    cell.TD = this.instance.wtTable.getCell(cell.coords);
  } else if ((0, _element.hasClass)(elem, 'wtBorder') && (0, _element.hasClass)(elem, 'area')) {
    if (this.instance.selections.area.cellRange) {
      cell.coords = this.instance.selections.area.cellRange.to; // selections.area is area selected cells
      cell.TD = this.instance.wtTable.getCell(cell.coords);
    }
  }

  return cell;
};

exports.default = Event;

/***/ }),
/* 296 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _array = __webpack_require__(2);

var _unicode = __webpack_require__(20);

var _browser = __webpack_require__(28);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _base = __webpack_require__(35);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Overlays
 */
var Overlays = function () {
  /**
   * @param {Walkontable} wotInstance
   */
  function Overlays(wotInstance) {
    _classCallCheck(this, Overlays);

    this.wot = wotInstance;

    // legacy support
    this.instance = this.wot;
    this.eventManager = new _eventManager2.default(this.wot);

    this.wot.update('scrollbarWidth', (0, _element.getScrollbarWidth)());
    this.wot.update('scrollbarHeight', (0, _element.getScrollbarWidth)());

    this.scrollableElement = (0, _element.getScrollableElement)(this.wot.wtTable.TABLE);

    this.prepareOverlays();

    this.destroyed = false;
    this.keyPressed = false;
    this.spreaderLastSize = {
      width: null,
      height: null
    };
    this.overlayScrollPositions = {
      master: {
        top: 0,
        left: 0
      },
      top: {
        top: null,
        left: 0
      },
      bottom: {
        top: null,
        left: 0
      },
      left: {
        top: 0,
        left: null
      }
    };

    this.pendingScrollCallbacks = {
      master: {
        top: 0,
        left: 0
      },
      top: {
        left: 0
      },
      bottom: {
        left: 0
      },
      left: {
        top: 0
      }
    };

    this.verticalScrolling = false;
    this.horizontalScrolling = false;
    this.delegatedScrollCallback = false;

    this.registeredListeners = [];

    this.registerListeners();
  }

  /**
   * Prepare overlays based on user settings.
   *
   * @returns {Boolean} Returns `true` if changes applied to overlay needs scroll synchronization.
   */


  _createClass(Overlays, [{
    key: 'prepareOverlays',
    value: function prepareOverlays() {
      var syncScroll = false;

      if (this.topOverlay) {
        syncScroll = this.topOverlay.updateStateOfRendering() || syncScroll;
      } else {
        this.topOverlay = _base2.default.createOverlay(_base2.default.CLONE_TOP, this.wot);
      }

      if (!_base2.default.hasOverlay(_base2.default.CLONE_BOTTOM)) {
        this.bottomOverlay = {
          needFullRender: false,
          updateStateOfRendering: function updateStateOfRendering() {
            return false;
          }
        };
      }
      if (!_base2.default.hasOverlay(_base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
        this.bottomLeftCornerOverlay = {
          needFullRender: false,
          updateStateOfRendering: function updateStateOfRendering() {
            return false;
          }
        };
      }

      if (this.bottomOverlay) {
        syncScroll = this.bottomOverlay.updateStateOfRendering() || syncScroll;
      } else {
        this.bottomOverlay = _base2.default.createOverlay(_base2.default.CLONE_BOTTOM, this.wot);
      }

      if (this.leftOverlay) {
        syncScroll = this.leftOverlay.updateStateOfRendering() || syncScroll;
      } else {
        this.leftOverlay = _base2.default.createOverlay(_base2.default.CLONE_LEFT, this.wot);
      }

      if (this.topOverlay.needFullRender && this.leftOverlay.needFullRender) {
        if (this.topLeftCornerOverlay) {
          syncScroll = this.topLeftCornerOverlay.updateStateOfRendering() || syncScroll;
        } else {
          this.topLeftCornerOverlay = _base2.default.createOverlay(_base2.default.CLONE_TOP_LEFT_CORNER, this.wot);
        }
      }

      if (this.bottomOverlay.needFullRender && this.leftOverlay.needFullRender) {
        if (this.bottomLeftCornerOverlay) {
          syncScroll = this.bottomLeftCornerOverlay.updateStateOfRendering() || syncScroll;
        } else {
          this.bottomLeftCornerOverlay = _base2.default.createOverlay(_base2.default.CLONE_BOTTOM_LEFT_CORNER, this.wot);
        }
      }

      if (this.wot.getSetting('debug') && !this.debug) {
        this.debug = _base2.default.createOverlay(_base2.default.CLONE_DEBUG, this.wot);
      }

      return syncScroll;
    }

    /**
     * Refresh and redraw table
     */

  }, {
    key: 'refreshAll',
    value: function refreshAll() {
      if (!this.wot.drawn) {
        return;
      }
      if (!this.wot.wtTable.holder.parentNode) {
        // Walkontable was detached from DOM, but this handler was not removed
        this.destroy();

        return;
      }
      this.wot.draw(true);

      if (this.verticalScrolling) {
        this.leftOverlay.onScroll();
      }

      if (this.horizontalScrolling) {
        this.topOverlay.onScroll();
      }

      this.verticalScrolling = false;
      this.horizontalScrolling = false;
    }

    /**
     * Register all necessary event listeners.
     */

  }, {
    key: 'registerListeners',
    value: function registerListeners() {
      var _this = this;

      var topOverlayScrollable = this.topOverlay.mainTableScrollableElement;
      var leftOverlayScrollable = this.leftOverlay.mainTableScrollableElement;

      var listenersToRegister = [];
      listenersToRegister.push([document.documentElement, 'keydown', function (event) {
        return _this.onKeyDown(event);
      }]);
      listenersToRegister.push([document.documentElement, 'keyup', function () {
        return _this.onKeyUp();
      }]);
      listenersToRegister.push([document, 'visibilitychange', function () {
        return _this.onKeyUp();
      }]);
      listenersToRegister.push([topOverlayScrollable, 'scroll', function (event) {
        return _this.onTableScroll(event);
      }]);

      if (topOverlayScrollable !== leftOverlayScrollable) {
        listenersToRegister.push([leftOverlayScrollable, 'scroll', function (event) {
          return _this.onTableScroll(event);
        }]);
      }

      if (this.topOverlay.needFullRender) {
        listenersToRegister.push([this.topOverlay.clone.wtTable.holder, 'scroll', function (event) {
          return _this.onTableScroll(event);
        }]);
        listenersToRegister.push([this.topOverlay.clone.wtTable.holder, 'wheel', function (event) {
          return _this.onTableScroll(event);
        }]);
      }

      if (this.bottomOverlay.needFullRender) {
        listenersToRegister.push([this.bottomOverlay.clone.wtTable.holder, 'scroll', function (event) {
          return _this.onTableScroll(event);
        }]);
        listenersToRegister.push([this.bottomOverlay.clone.wtTable.holder, 'wheel', function (event) {
          return _this.onTableScroll(event);
        }]);
      }

      if (this.leftOverlay.needFullRender) {
        listenersToRegister.push([this.leftOverlay.clone.wtTable.holder, 'scroll', function (event) {
          return _this.onTableScroll(event);
        }]);
        listenersToRegister.push([this.leftOverlay.clone.wtTable.holder, 'wheel', function (event) {
          return _this.onTableScroll(event);
        }]);
      }

      if (this.topLeftCornerOverlay && this.topLeftCornerOverlay.needFullRender) {
        listenersToRegister.push([this.topLeftCornerOverlay.clone.wtTable.holder, 'wheel', function (event) {
          return _this.onTableScroll(event);
        }]);
      }

      if (this.bottomLeftCornerOverlay && this.bottomLeftCornerOverlay.needFullRender) {
        listenersToRegister.push([this.bottomLeftCornerOverlay.clone.wtTable.holder, 'wheel', function (event) {
          return _this.onTableScroll(event);
        }]);
      }

      if (this.topOverlay.trimmingContainer !== window && this.leftOverlay.trimmingContainer !== window) {
        // This is necessary?
        // eventManager.addEventListener(window, 'scroll', (event) => this.refreshAll(event));
        listenersToRegister.push([window, 'wheel', function (event) {
          var overlay = void 0;
          var deltaY = event.wheelDeltaY || event.deltaY;
          var deltaX = event.wheelDeltaX || event.deltaX;

          if (_this.topOverlay.clone.wtTable.holder.contains(event.realTarget)) {
            overlay = 'top';
          } else if (_this.bottomOverlay.clone && _this.bottomOverlay.clone.wtTable.holder.contains(event.realTarget)) {
            overlay = 'bottom';
          } else if (_this.leftOverlay.clone.wtTable.holder.contains(event.realTarget)) {
            overlay = 'left';
          } else if (_this.topLeftCornerOverlay && _this.topLeftCornerOverlay.clone && _this.topLeftCornerOverlay.clone.wtTable.holder.contains(event.realTarget)) {
            overlay = 'topLeft';
          } else if (_this.bottomLeftCornerOverlay && _this.bottomLeftCornerOverlay.clone && _this.bottomLeftCornerOverlay.clone.wtTable.holder.contains(event.realTarget)) {
            overlay = 'bottomLeft';
          }

          if (overlay == 'top' && deltaY !== 0 || overlay == 'left' && deltaX !== 0 || overlay == 'bottom' && deltaY !== 0 || (overlay === 'topLeft' || overlay === 'bottomLeft') && (deltaY !== 0 || deltaX !== 0)) {

            event.preventDefault();
          }
        }]);
      }

      while (listenersToRegister.length) {
        var listener = listenersToRegister.pop();
        this.eventManager.addEventListener(listener[0], listener[1], listener[2]);

        this.registeredListeners.push(listener);
      }
    }

    /**
     * Deregister all previously registered listeners.
     */

  }, {
    key: 'deregisterListeners',
    value: function deregisterListeners() {
      while (this.registeredListeners.length) {
        var listener = this.registeredListeners.pop();
        this.eventManager.removeEventListener(listener[0], listener[1], listener[2]);
      }
    }

    /**
     * Scroll listener
     *
     * @param {Event} event
     */

  }, {
    key: 'onTableScroll',
    value: function onTableScroll(event) {
      // if mobile browser, do not update scroll positions, as the overlays are hidden during the scroll
      if ((0, _browser.isMobileBrowser)()) {
        return;
      }
      var masterHorizontal = this.leftOverlay.mainTableScrollableElement;
      var masterVertical = this.topOverlay.mainTableScrollableElement;
      var target = event.target;

      // For key press, sync only master -> overlay position because while pressing Walkontable.render is triggered
      // by hot.refreshBorder
      if (this.keyPressed) {
        if (masterVertical !== window && target !== window && !event.target.contains(masterVertical) || masterHorizontal !== window && target !== window && !event.target.contains(masterHorizontal)) {
          return;
        }
      }

      if (event.type === 'scroll') {
        this.syncScrollPositions(event);
      } else {
        this.translateMouseWheelToScroll(event);
      }
    }

    /**
     * Key down listener
     */

  }, {
    key: 'onKeyDown',
    value: function onKeyDown(event) {
      this.keyPressed = (0, _unicode.isKey)(event.keyCode, 'ARROW_UP|ARROW_RIGHT|ARROW_DOWN|ARROW_LEFT');
    }

    /**
     * Key up listener
     */

  }, {
    key: 'onKeyUp',
    value: function onKeyUp() {
      this.keyPressed = false;
    }

    /**
     * Translate wheel event into scroll event and sync scroll overlays position
     *
     * @private
     * @param {Event} event
     * @returns {Boolean}
     */

  }, {
    key: 'translateMouseWheelToScroll',
    value: function translateMouseWheelToScroll(event) {
      var topOverlay = this.topOverlay.clone.wtTable.holder;
      var bottomOverlay = this.bottomOverlay.clone ? this.bottomOverlay.clone.wtTable.holder : null;
      var leftOverlay = this.leftOverlay.clone.wtTable.holder;
      var topLeftCornerOverlay = this.topLeftCornerOverlay && this.topLeftCornerOverlay.clone ? this.topLeftCornerOverlay.clone.wtTable.holder : null;
      var bottomLeftCornerOverlay = this.bottomLeftCornerOverlay && this.bottomLeftCornerOverlay.clone ? this.bottomLeftCornerOverlay.clone.wtTable.holder : null;
      var mouseWheelSpeedRatio = -0.2;
      var deltaY = event.wheelDeltaY || -1 * event.deltaY;
      var deltaX = event.wheelDeltaX || -1 * event.deltaX;
      var parentHolder = null;
      var eventMockup = { type: 'wheel' };
      var tempElem = event.target;
      var delta = null;

      // Fix for extremely slow header scrolling with a mousewheel on Firefox
      if (event.deltaMode === 1) {
        deltaY *= 120;
        deltaX *= 120;
      }

      while (tempElem != document && tempElem != null) {
        if (tempElem.className.indexOf('wtHolder') > -1) {
          parentHolder = tempElem;
          break;
        }
        tempElem = tempElem.parentNode;
      }
      eventMockup.target = parentHolder;

      if (parentHolder === topLeftCornerOverlay || parentHolder === bottomLeftCornerOverlay) {
        this.syncScrollPositions(eventMockup, mouseWheelSpeedRatio * deltaX, 'x');
        this.syncScrollPositions(eventMockup, mouseWheelSpeedRatio * deltaY, 'y');
      } else {
        if (parentHolder === topOverlay || parentHolder === bottomOverlay) {
          delta = deltaY;
        } else if (parentHolder === leftOverlay) {
          delta = deltaX;
        }

        this.syncScrollPositions(eventMockup, mouseWheelSpeedRatio * delta);
      }

      return false;
    }

    /**
     * Synchronize scroll position between master table and overlay table.
     *
     * @private
     * @param {Event|Object} event
     * @param {Number} [fakeScrollValue=null]
     * @param {String} [fakeScrollDirection=null] `x` or `y`.
     */

  }, {
    key: 'syncScrollPositions',
    value: function syncScrollPositions(event) {
      var fakeScrollValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
      var fakeScrollDirection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

      if (this.destroyed) {
        return;
      }
      if (arguments.length === 0) {
        this.syncScrollWithMaster();

        return;
      }

      var masterHorizontal = this.leftOverlay.mainTableScrollableElement;
      var masterVertical = this.topOverlay.mainTableScrollableElement;
      var target = event.target;
      var tempScrollValue = 0;
      var scrollValueChanged = false;
      var topOverlay = void 0;
      var leftOverlay = void 0;
      var topLeftCornerOverlay = void 0;
      var bottomLeftCornerOverlay = void 0;
      var bottomOverlay = void 0;
      var delegatedScroll = false;
      var preventOverflow = this.wot.getSetting('preventOverflow');

      if (this.topOverlay.needFullRender) {
        topOverlay = this.topOverlay.clone.wtTable.holder;
      }

      if (this.bottomOverlay.needFullRender) {
        bottomOverlay = this.bottomOverlay.clone.wtTable.holder;
      }

      if (this.leftOverlay.needFullRender) {
        leftOverlay = this.leftOverlay.clone.wtTable.holder;
      }

      if (this.leftOverlay.needFullRender && this.topOverlay.needFullRender) {
        topLeftCornerOverlay = this.topLeftCornerOverlay.clone.wtTable.holder;
      }

      if (this.leftOverlay.needFullRender && this.bottomOverlay.needFullRender) {
        bottomLeftCornerOverlay = this.bottomLeftCornerOverlay.clone.wtTable.holder;
      }

      if (target === document) {
        target = window;
      }

      if (target === masterHorizontal || target === masterVertical) {
        if (preventOverflow) {
          tempScrollValue = (0, _element.getScrollLeft)(this.scrollableElement);
        } else {
          tempScrollValue = (0, _element.getScrollLeft)(target);
        }

        // if scrolling the master table - populate the scroll values to both top and left overlays
        this.horizontalScrolling = this.overlayScrollPositions.master.left !== tempScrollValue;
        this.overlayScrollPositions.master.left = tempScrollValue;
        scrollValueChanged = true;

        if (this.pendingScrollCallbacks.master.left > 0) {
          this.pendingScrollCallbacks.master.left--;
        } else {
          if (topOverlay && topOverlay.scrollLeft !== tempScrollValue) {

            if (fakeScrollValue == null) {
              this.pendingScrollCallbacks.top.left++;
            }

            topOverlay.scrollLeft = tempScrollValue;
            delegatedScroll = masterHorizontal !== window;
          }

          if (bottomOverlay && bottomOverlay.scrollLeft !== tempScrollValue) {

            if (fakeScrollValue == null) {
              this.pendingScrollCallbacks.bottom.left++;
            }

            bottomOverlay.scrollLeft = tempScrollValue;
            delegatedScroll = masterHorizontal !== window;
          }
        }

        tempScrollValue = (0, _element.getScrollTop)(target);

        this.verticalScrolling = this.overlayScrollPositions.master.top !== tempScrollValue;
        this.overlayScrollPositions.master.top = tempScrollValue;
        scrollValueChanged = true;

        if (this.pendingScrollCallbacks.master.top > 0) {
          this.pendingScrollCallbacks.master.top--;
        } else if (leftOverlay && leftOverlay.scrollTop !== tempScrollValue) {
          if (fakeScrollValue == null) {
            this.pendingScrollCallbacks.left.top++;
          }

          leftOverlay.scrollTop = tempScrollValue;
          delegatedScroll = masterVertical !== window;
        }
      } else if (target === bottomOverlay) {
        tempScrollValue = (0, _element.getScrollLeft)(target);

        // if scrolling the bottom overlay - populate the horizontal scroll to the master table
        this.overlayScrollPositions.bottom.left = tempScrollValue;
        scrollValueChanged = true;

        if (this.pendingScrollCallbacks.bottom.left > 0) {
          this.pendingScrollCallbacks.bottom.left--;
        } else {
          if (fakeScrollValue == null) {
            this.pendingScrollCallbacks.master.left++;
          }

          masterHorizontal.scrollLeft = tempScrollValue;

          if (topOverlay && topOverlay.scrollLeft !== tempScrollValue) {
            if (fakeScrollValue == null) {
              this.pendingScrollCallbacks.top.left++;
            }

            topOverlay.scrollLeft = tempScrollValue;
            delegatedScroll = masterVertical !== window;
          }
        }

        // "fake" scroll value calculated from the mousewheel event
        if (fakeScrollValue !== null) {
          scrollValueChanged = true;
          masterVertical.scrollTop += fakeScrollValue;
        }
      } else if (target === topOverlay) {
        tempScrollValue = (0, _element.getScrollLeft)(target);

        // if scrolling the top overlay - populate the horizontal scroll to the master table
        this.overlayScrollPositions.top.left = tempScrollValue;
        scrollValueChanged = true;

        if (this.pendingScrollCallbacks.top.left > 0) {
          this.pendingScrollCallbacks.top.left--;
        } else {

          if (fakeScrollValue == null) {
            this.pendingScrollCallbacks.master.left++;
          }

          masterHorizontal.scrollLeft = tempScrollValue;
        }

        // "fake" scroll value calculated from the mousewheel event
        if (fakeScrollValue !== null) {
          scrollValueChanged = true;
          masterVertical.scrollTop += fakeScrollValue;
        }

        if (bottomOverlay && bottomOverlay.scrollLeft !== tempScrollValue) {
          if (fakeScrollValue == null) {
            this.pendingScrollCallbacks.bottom.left++;
          }

          bottomOverlay.scrollLeft = tempScrollValue;
          delegatedScroll = masterVertical !== window;
        }
      } else if (target === leftOverlay) {
        tempScrollValue = (0, _element.getScrollTop)(target);

        // if scrolling the left overlay - populate the vertical scroll to the master table
        if (this.overlayScrollPositions.left.top !== tempScrollValue) {
          this.overlayScrollPositions.left.top = tempScrollValue;
          scrollValueChanged = true;

          if (this.pendingScrollCallbacks.left.top > 0) {
            this.pendingScrollCallbacks.left.top--;
          } else {
            if (fakeScrollValue == null) {
              this.pendingScrollCallbacks.master.top++;
            }

            masterVertical.scrollTop = tempScrollValue;
          }
        }

        // "fake" scroll value calculated from the mousewheel event
        if (fakeScrollValue !== null) {
          scrollValueChanged = true;
          masterVertical.scrollLeft += fakeScrollValue;
        }
      } else if (target === topLeftCornerOverlay || target === bottomLeftCornerOverlay) {
        if (fakeScrollValue !== null) {
          scrollValueChanged = true;

          if (fakeScrollDirection === 'x') {
            masterVertical.scrollLeft += fakeScrollValue;
          } else if (fakeScrollDirection === 'y') {
            masterVertical.scrollTop += fakeScrollValue;
          }
        }
      }

      if (!this.keyPressed && scrollValueChanged && event.type === 'scroll') {
        if (this.delegatedScrollCallback) {
          this.delegatedScrollCallback = false;
        } else {
          this.refreshAll();
        }

        if (delegatedScroll) {
          this.delegatedScrollCallback = true;
        }
      }
    }

    /**
     * Synchronize overlay scrollbars with the master scrollbar
     */

  }, {
    key: 'syncScrollWithMaster',
    value: function syncScrollWithMaster() {
      var master = this.topOverlay.mainTableScrollableElement;
      var scrollLeft = master.scrollLeft,
          scrollTop = master.scrollTop;


      if (this.topOverlay.needFullRender) {
        this.topOverlay.clone.wtTable.holder.scrollLeft = scrollLeft;
      }
      if (this.bottomOverlay.needFullRender) {
        this.bottomOverlay.clone.wtTable.holder.scrollLeft = scrollLeft;
      }
      if (this.leftOverlay.needFullRender) {
        this.leftOverlay.clone.wtTable.holder.scrollTop = scrollTop;
      }
    }

    /**
     * Update the main scrollable elements for all the overlays.
     */

  }, {
    key: 'updateMainScrollableElements',
    value: function updateMainScrollableElements() {
      this.deregisterListeners();

      this.leftOverlay.updateMainScrollableElement();
      this.topOverlay.updateMainScrollableElement();

      if (this.bottomOverlay.needFullRender) {
        this.bottomOverlay.updateMainScrollableElement();
      }

      this.scrollableElement = (0, _element.getScrollableElement)(this.wot.wtTable.TABLE);

      this.registerListeners();
    }

    /**
     *
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.eventManager.destroy();
      this.topOverlay.destroy();

      if (this.bottomOverlay.clone) {
        this.bottomOverlay.destroy();
      }
      this.leftOverlay.destroy();

      if (this.topLeftCornerOverlay) {
        this.topLeftCornerOverlay.destroy();
      }

      if (this.bottomLeftCornerOverlay && this.bottomLeftCornerOverlay.clone) {
        this.bottomLeftCornerOverlay.destroy();
      }

      if (this.debug) {
        this.debug.destroy();
      }
      this.destroyed = true;
    }

    /**
     * @param {Boolean} [fastDraw=false]
     */

  }, {
    key: 'refresh',
    value: function refresh() {
      var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.topOverlay.areElementSizesAdjusted && this.leftOverlay.areElementSizesAdjusted) {
        var container = this.wot.wtTable.wtRootElement.parentNode || this.wot.wtTable.wtRootElement;
        var width = container.clientWidth;
        var height = container.clientHeight;

        if (width !== this.spreaderLastSize.width || height !== this.spreaderLastSize.height) {
          this.spreaderLastSize.width = width;
          this.spreaderLastSize.height = height;
          this.adjustElementsSize();
        }
      }

      if (this.bottomOverlay.clone) {
        this.bottomOverlay.refresh(fastDraw);
      }

      this.leftOverlay.refresh(fastDraw);
      this.topOverlay.refresh(fastDraw);

      if (this.topLeftCornerOverlay) {
        this.topLeftCornerOverlay.refresh(fastDraw);
      }

      if (this.bottomLeftCornerOverlay && this.bottomLeftCornerOverlay.clone) {
        this.bottomLeftCornerOverlay.refresh(fastDraw);
      }

      if (this.debug) {
        this.debug.refresh(fastDraw);
      }
    }

    /**
     * Adjust overlays elements size and master table size
     *
     * @param {Boolean} [force=false]
     */

  }, {
    key: 'adjustElementsSize',
    value: function adjustElementsSize() {
      var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var totalColumns = this.wot.getSetting('totalColumns');
      var totalRows = this.wot.getSetting('totalRows');
      var headerRowSize = this.wot.wtViewport.getRowHeaderWidth();
      var headerColumnSize = this.wot.wtViewport.getColumnHeaderHeight();
      var hiderStyle = this.wot.wtTable.hider.style;

      hiderStyle.width = headerRowSize + this.leftOverlay.sumCellSizes(0, totalColumns) + 'px';
      hiderStyle.height = headerColumnSize + this.topOverlay.sumCellSizes(0, totalRows) + 1 + 'px';

      this.topOverlay.adjustElementsSize(force);
      this.leftOverlay.adjustElementsSize(force);

      if (this.bottomOverlay.clone) {
        this.bottomOverlay.adjustElementsSize(force);
      }
    }

    /**
     *
     */

  }, {
    key: 'applyToDOM',
    value: function applyToDOM() {
      if (!this.topOverlay.areElementSizesAdjusted || !this.leftOverlay.areElementSizesAdjusted) {
        this.adjustElementsSize();
      }
      this.topOverlay.applyToDOM();

      if (this.bottomOverlay.clone) {
        this.bottomOverlay.applyToDOM();
      }

      this.leftOverlay.applyToDOM();
    }

    /**
     * Get the parent overlay of the provided element.
     *
     * @param {HTMLElement} element
     * @returns {Object|null}
     */

  }, {
    key: 'getParentOverlay',
    value: function getParentOverlay(element) {
      if (!element) {
        return null;
      }

      var overlays = [this.topOverlay, this.leftOverlay, this.bottomOverlay, this.topLeftCornerOverlay, this.bottomLeftCornerOverlay];
      var result = null;

      (0, _array.arrayEach)(overlays, function (elem, i) {
        if (!elem) {
          return;
        }

        if (elem.clone && elem.clone.wtTable.TABLE.contains(element)) {
          result = elem.clone;
        }
      });

      return result;
    }
  }]);

  return Overlays;
}();

exports.default = Overlays;

/***/ }),
/* 297 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _number = __webpack_require__(6);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Scroll
 */
var Scroll = function () {
  /**
   * @param {Walkontable} wotInstance
   */
  function Scroll(wotInstance) {
    _classCallCheck(this, Scroll);

    this.wot = wotInstance;

    // legacy support
    this.instance = wotInstance;
  }

  /**
   * Scrolls viewport to a cell by minimum number of cells
   *
   * @param {CellCoords} coords
   */


  _createClass(Scroll, [{
    key: 'scrollViewport',
    value: function scrollViewport(coords) {
      if (!this.wot.drawn) {
        return;
      }

      var _getVariables2 = this._getVariables(),
          topOverlay = _getVariables2.topOverlay,
          leftOverlay = _getVariables2.leftOverlay,
          totalRows = _getVariables2.totalRows,
          totalColumns = _getVariables2.totalColumns,
          fixedRowsTop = _getVariables2.fixedRowsTop,
          fixedRowsBottom = _getVariables2.fixedRowsBottom,
          fixedColumnsLeft = _getVariables2.fixedColumnsLeft;

      if (coords.row < 0 || coords.row > Math.max(totalRows - 1, 0)) {
        throw new Error('row ' + coords.row + ' does not exist');
      }

      if (coords.col < 0 || coords.col > Math.max(totalColumns - 1, 0)) {
        throw new Error('column ' + coords.col + ' does not exist');
      }

      if (coords.row >= fixedRowsTop && coords.row < this.getFirstVisibleRow()) {
        topOverlay.scrollTo(coords.row);
      } else if (coords.row > this.getLastVisibleRow() && coords.row < totalRows - fixedRowsBottom) {
        topOverlay.scrollTo(coords.row, true);
      }

      if (coords.col >= fixedColumnsLeft && coords.col < this.getFirstVisibleColumn()) {
        leftOverlay.scrollTo(coords.col);
      } else if (coords.col > this.getLastVisibleColumn()) {
        leftOverlay.scrollTo(coords.col, true);
      }
    }

    /**
     * Get first visible row based on virtual dom and how table is visible in browser window viewport.
     *
     * @returns {Number}
     */

  }, {
    key: 'getFirstVisibleRow',
    value: function getFirstVisibleRow() {
      var _getVariables3 = this._getVariables(),
          topOverlay = _getVariables3.topOverlay,
          wtTable = _getVariables3.wtTable,
          wtViewport = _getVariables3.wtViewport,
          totalRows = _getVariables3.totalRows,
          fixedRowsTop = _getVariables3.fixedRowsTop;

      var firstVisibleRow = wtTable.getFirstVisibleRow();

      if (topOverlay.mainTableScrollableElement === window) {
        var rootElementOffset = (0, _element.offset)(wtTable.wtRootElement);
        var totalTableHeight = (0, _element.innerHeight)(wtTable.hider);
        var windowHeight = (0, _element.innerHeight)(window);
        var windowScrollTop = (0, _element.getScrollTop)(window);

        // Only calculate firstVisibleRow when table didn't filled (from up) whole viewport space
        if (rootElementOffset.top + totalTableHeight - windowHeight <= windowScrollTop) {
          var rowsHeight = wtViewport.getColumnHeaderHeight();

          rowsHeight += topOverlay.sumCellSizes(0, fixedRowsTop);

          (0, _number.rangeEachReverse)(totalRows, 1, function (row) {
            rowsHeight += topOverlay.sumCellSizes(row - 1, row);

            if (rootElementOffset.top + totalTableHeight - rowsHeight <= windowScrollTop) {
              // Return physical row + 1
              firstVisibleRow = row;

              return false;
            }
          });
        }
      }

      return firstVisibleRow;
    }

    /**
     * Get last visible row based on virtual dom and how table is visible in browser window viewport.
     *
     * @returns {Number}
     */

  }, {
    key: 'getLastVisibleRow',
    value: function getLastVisibleRow() {
      var _getVariables4 = this._getVariables(),
          topOverlay = _getVariables4.topOverlay,
          wtTable = _getVariables4.wtTable,
          wtViewport = _getVariables4.wtViewport,
          totalRows = _getVariables4.totalRows;

      var lastVisibleRow = wtTable.getLastVisibleRow();

      if (topOverlay.mainTableScrollableElement === window) {
        var rootElementOffset = (0, _element.offset)(wtTable.wtRootElement);
        var windowHeight = (0, _element.innerHeight)(window);
        var windowScrollTop = (0, _element.getScrollTop)(window);

        // Only calculate lastVisibleRow when table didn't filled (from bottom) whole viewport space
        if (rootElementOffset.top > windowScrollTop) {
          var rowsHeight = wtViewport.getColumnHeaderHeight();

          (0, _number.rangeEach)(1, totalRows, function (row) {
            rowsHeight += topOverlay.sumCellSizes(row - 1, row);

            if (rootElementOffset.top + rowsHeight - windowScrollTop >= windowHeight) {
              // Return physical row - 1 (-2 because rangeEach gives row index + 1 - sumCellSizes requirements)
              lastVisibleRow = row - 2;

              return false;
            }
          });
        }
      }

      return lastVisibleRow;
    }

    /**
     * Get first visible column based on virtual dom and how table is visible in browser window viewport.
     *
     * @returns {Number}
     */

  }, {
    key: 'getFirstVisibleColumn',
    value: function getFirstVisibleColumn() {
      var _getVariables5 = this._getVariables(),
          leftOverlay = _getVariables5.leftOverlay,
          wtTable = _getVariables5.wtTable,
          wtViewport = _getVariables5.wtViewport,
          totalColumns = _getVariables5.totalColumns,
          fixedColumnsLeft = _getVariables5.fixedColumnsLeft;

      var firstVisibleColumn = wtTable.getFirstVisibleColumn();

      if (leftOverlay.mainTableScrollableElement === window) {
        var rootElementOffset = (0, _element.offset)(wtTable.wtRootElement);
        var totalTableWidth = (0, _element.innerWidth)(wtTable.hider);
        var windowWidth = (0, _element.innerWidth)(window);
        var windowScrollLeft = (0, _element.getScrollLeft)(window);

        // Only calculate firstVisibleColumn when table didn't filled (from left) whole viewport space
        if (rootElementOffset.left + totalTableWidth - windowWidth <= windowScrollLeft) {
          var columnsWidth = wtViewport.getRowHeaderWidth();

          (0, _number.rangeEachReverse)(totalColumns, 1, function (column) {
            columnsWidth += leftOverlay.sumCellSizes(column - 1, column);

            if (rootElementOffset.left + totalTableWidth - columnsWidth <= windowScrollLeft) {
              // Return physical column + 1
              firstVisibleColumn = column;

              return false;
            }
          });
        }
      }

      return firstVisibleColumn;
    }

    /**
     * Get last visible column based on virtual dom and how table is visible in browser window viewport.
     *
     * @returns {Number}
     */

  }, {
    key: 'getLastVisibleColumn',
    value: function getLastVisibleColumn() {
      var _getVariables6 = this._getVariables(),
          leftOverlay = _getVariables6.leftOverlay,
          wtTable = _getVariables6.wtTable,
          wtViewport = _getVariables6.wtViewport,
          totalColumns = _getVariables6.totalColumns;

      var lastVisibleColumn = wtTable.getLastVisibleColumn();

      if (leftOverlay.mainTableScrollableElement === window) {
        var rootElementOffset = (0, _element.offset)(wtTable.wtRootElement);
        var windowWidth = (0, _element.innerWidth)(window);
        var windowScrollLeft = (0, _element.getScrollLeft)(window);

        // Only calculate lastVisibleColumn when table didn't filled (from right) whole viewport space
        if (rootElementOffset.left > windowScrollLeft) {
          var columnsWidth = wtViewport.getRowHeaderWidth();

          (0, _number.rangeEach)(1, totalColumns, function (column) {
            columnsWidth += leftOverlay.sumCellSizes(column - 1, column);

            if (rootElementOffset.left + columnsWidth - windowScrollLeft >= windowWidth) {
              // Return physical column - 1 (-2 because rangeEach gives column index + 1 - sumCellSizes requirements)
              lastVisibleColumn = column - 2;

              return false;
            }
          });
        }
      }

      return lastVisibleColumn;
    }

    /**
     * Returns collection of variables used to rows and columns visibility calculations.
     *
     * @returns {Object}
     * @private
     */

  }, {
    key: '_getVariables',
    value: function _getVariables() {
      var wot = this.wot;
      var topOverlay = wot.wtOverlays.topOverlay;
      var leftOverlay = wot.wtOverlays.leftOverlay;
      var wtTable = wot.wtTable;
      var wtViewport = wot.wtViewport;
      var totalRows = wot.getSetting('totalRows');
      var totalColumns = wot.getSetting('totalColumns');
      var fixedRowsTop = wot.getSetting('fixedRowsTop');
      var fixedRowsBottom = wot.getSetting('fixedRowsBottom');
      var fixedColumnsLeft = wot.getSetting('fixedColumnsLeft');

      return {
        topOverlay: topOverlay,
        leftOverlay: leftOverlay,
        wtTable: wtTable,
        wtViewport: wtViewport,
        totalRows: totalRows,
        totalColumns: totalColumns,
        fixedRowsTop: fixedRowsTop,
        fixedRowsBottom: fixedRowsBottom,
        fixedColumnsLeft: fixedColumnsLeft
      };
    }
  }]);

  return Scroll;
}();

exports.default = Scroll;

/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _object = __webpack_require__(1);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Settings
 */
var Settings = function () {
  /**
   * @param {Walkontable} wotInstance
   * @param {Object} settings
   */
  function Settings(wotInstance, settings) {
    var _this = this;

    _classCallCheck(this, Settings);

    this.wot = wotInstance;

    // legacy support
    this.instance = wotInstance;

    // default settings. void 0 means it is required, null means it can be empty
    this.defaults = {
      table: void 0,
      debug: false, // shows WalkontableDebugOverlay

      // presentation mode
      externalRowCalculator: false,
      stretchH: 'none', // values: all, last, none
      currentRowClassName: null,
      currentColumnClassName: null,
      preventOverflow: function preventOverflow() {
        return false;
      },


      // data source
      data: void 0,
      freezeOverlays: false,
      fixedColumnsLeft: 0,
      fixedRowsTop: 0,
      fixedRowsBottom: 0,
      minSpareRows: 0,

      // this must be array of functions: [function (row, TH) {}]
      rowHeaders: function rowHeaders() {
        return [];
      },


      // this must be array of functions: [function (column, TH) {}]
      columnHeaders: function columnHeaders() {
        return [];
      },

      totalRows: void 0,
      totalColumns: void 0,
      cellRenderer: function cellRenderer(row, column, TD) {
        var cellData = _this.getSetting('data', row, column);

        (0, _element.fastInnerText)(TD, cellData === void 0 || cellData === null ? '' : cellData);
      },

      // columnWidth: 50,
      columnWidth: function columnWidth(col) {
        // return undefined means use default size for the rendered cell content
      },
      rowHeight: function rowHeight(row) {
        // return undefined means use default size for the rendered cell content
      },

      defaultRowHeight: 23,
      defaultColumnWidth: 50,
      selections: null,
      hideBorderOnMouseDownOver: false,
      viewportRowCalculatorOverride: null,
      viewportColumnCalculatorOverride: null,

      // callbacks
      onCellMouseDown: null,
      onCellMouseOver: null,
      onCellMouseOut: null,
      onCellMouseUp: null,

      //    onCellMouseOut: null,
      onCellDblClick: null,
      onCellCornerMouseDown: null,
      onCellCornerDblClick: null,
      beforeDraw: null,
      onDraw: null,
      onBeforeDrawBorders: null,
      onScrollVertically: null,
      onScrollHorizontally: null,
      onBeforeTouchScroll: null,
      onAfterMomentumScroll: null,
      onBeforeStretchingColumnWidth: function onBeforeStretchingColumnWidth(width) {
        return width;
      },
      onModifyRowHeaderWidth: null,

      // constants
      scrollbarWidth: 10,
      scrollbarHeight: 10,

      renderAllRows: false,
      groups: false,
      rowHeaderWidth: null,
      columnHeaderHeight: null,
      headerClassName: null
    };

    // reference to settings
    this.settings = {};

    for (var i in this.defaults) {
      if ((0, _object.hasOwnProperty)(this.defaults, i)) {
        if (settings[i] !== void 0) {
          this.settings[i] = settings[i];
        } else if (this.defaults[i] === void 0) {
          throw new Error('A required setting "' + i + '" was not provided');
        } else {
          this.settings[i] = this.defaults[i];
        }
      }
    }
  }

  /**
   * Update settings
   *
   * @param {Object} settings
   * @param {*} value
   * @returns {Walkontable}
   */


  _createClass(Settings, [{
    key: 'update',
    value: function update(settings, value) {
      if (value === void 0) {
        // settings is object
        for (var i in settings) {
          if ((0, _object.hasOwnProperty)(settings, i)) {
            this.settings[i] = settings[i];
          }
        }
      } else {
        // if value is defined then settings is the key
        this.settings[settings] = value;
      }
      return this.wot;
    }

    /**
     * Get setting by name
     *
     * @param {String} key
     * @param {*} param1
     * @param {*} param2
     * @param {*} param3
     * @param {*} param4
     * @returns {*}
     */

  }, {
    key: 'getSetting',
    value: function getSetting(key, param1, param2, param3, param4) {
      if (typeof this.settings[key] === 'function') {
        // this is faster than .apply - https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
        return this.settings[key](param1, param2, param3, param4);
      } else if (param1 !== void 0 && Array.isArray(this.settings[key])) {
        // perhaps this can be removed, it is only used in tests
        return this.settings[key][param1];
      }

      return this.settings[key];
    }

    /**
     * Checks if setting exists
     *
     * @param {Boolean} key
     * @returns {Boolean}
     */

  }, {
    key: 'has',
    value: function has(key) {
      return !!this.settings[key];
    }
  }]);

  return Settings;
}();

exports.default = Settings;

/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _function = __webpack_require__(41);

var _coords = __webpack_require__(53);

var _coords2 = _interopRequireDefault(_coords);

var _range = __webpack_require__(82);

var _range2 = _interopRequireDefault(_range);

var _column = __webpack_require__(172);

var _column2 = _interopRequireDefault(_column);

var _row = __webpack_require__(173);

var _row2 = _interopRequireDefault(_row);

var _tableRenderer = __webpack_require__(300);

var _tableRenderer2 = _interopRequireDefault(_tableRenderer);

var _base = __webpack_require__(35);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 *
 */
var Table = function () {
  /**
   * @param {Walkontable} wotInstance
   * @param {HTMLTableElement} table
   */
  function Table(wotInstance, table) {
    var _this = this;

    _classCallCheck(this, Table);

    this.wot = wotInstance;

    // legacy support
    this.instance = this.wot;
    this.TABLE = table;
    this.TBODY = null;
    this.THEAD = null;
    this.COLGROUP = null;
    this.tableOffset = 0;
    this.holderOffset = 0;

    (0, _element.removeTextNodes)(this.TABLE);

    this.spreader = this.createSpreader(this.TABLE);
    this.hider = this.createHider(this.spreader);
    this.holder = this.createHolder(this.hider);

    this.wtRootElement = this.holder.parentNode;
    this.alignOverlaysWithTrimmingContainer();
    this.fixTableDomTree();

    this.colgroupChildrenLength = this.COLGROUP.childNodes.length;
    this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0;
    this.tbodyChildrenLength = this.TBODY.childNodes.length;

    this.rowFilter = null;
    this.columnFilter = null;
    this.correctHeaderWidth = false;

    var origRowHeaderWidth = this.wot.wtSettings.settings.rowHeaderWidth;

    // Fix for jumping row headers (https://github.com/handsontable/handsontable/issues/3850)
    this.wot.wtSettings.settings.rowHeaderWidth = function () {
      return _this._modifyRowHeaderWidth(origRowHeaderWidth);
    };
  }

  /**
   *
   */


  _createClass(Table, [{
    key: 'fixTableDomTree',
    value: function fixTableDomTree() {
      this.TBODY = this.TABLE.querySelector('tbody');

      if (!this.TBODY) {
        this.TBODY = document.createElement('tbody');
        this.TABLE.appendChild(this.TBODY);
      }
      this.THEAD = this.TABLE.querySelector('thead');

      if (!this.THEAD) {
        this.THEAD = document.createElement('thead');
        this.TABLE.insertBefore(this.THEAD, this.TBODY);
      }
      this.COLGROUP = this.TABLE.querySelector('colgroup');

      if (!this.COLGROUP) {
        this.COLGROUP = document.createElement('colgroup');
        this.TABLE.insertBefore(this.COLGROUP, this.THEAD);
      }

      if (this.wot.getSetting('columnHeaders').length && !this.THEAD.childNodes.length) {
        this.THEAD.appendChild(document.createElement('TR'));
      }
    }

    /**
     * @param table
     * @returns {HTMLElement}
     */

  }, {
    key: 'createSpreader',
    value: function createSpreader(table) {
      var parent = table.parentNode;
      var spreader = void 0;

      if (!parent || parent.nodeType !== 1 || !(0, _element.hasClass)(parent, 'wtHolder')) {
        spreader = document.createElement('div');
        spreader.className = 'wtSpreader';

        if (parent) {
          // if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
          parent.insertBefore(spreader, table);
        }
        spreader.appendChild(table);
      }
      spreader.style.position = 'relative';

      return spreader;
    }

    /**
     * @param spreader
     * @returns {HTMLElement}
     */

  }, {
    key: 'createHider',
    value: function createHider(spreader) {
      var parent = spreader.parentNode;
      var hider = void 0;

      if (!parent || parent.nodeType !== 1 || !(0, _element.hasClass)(parent, 'wtHolder')) {
        hider = document.createElement('div');
        hider.className = 'wtHider';

        if (parent) {
          // if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
          parent.insertBefore(hider, spreader);
        }
        hider.appendChild(spreader);
      }

      return hider;
    }

    /**
     *
     * @param hider
     * @returns {HTMLElement}
     */

  }, {
    key: 'createHolder',
    value: function createHolder(hider) {
      var parent = hider.parentNode;
      var holder = void 0;

      if (!parent || parent.nodeType !== 1 || !(0, _element.hasClass)(parent, 'wtHolder')) {
        holder = document.createElement('div');
        holder.style.position = 'relative';
        holder.className = 'wtHolder';

        if (parent) {
          // if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
          parent.insertBefore(holder, hider);
        }
        if (!this.isWorkingOnClone()) {
          holder.parentNode.className += 'ht_master handsontable';
        }
        holder.appendChild(hider);
      }

      return holder;
    }
  }, {
    key: 'alignOverlaysWithTrimmingContainer',
    value: function alignOverlaysWithTrimmingContainer() {
      var trimmingElement = (0, _element.getTrimmingContainer)(this.wtRootElement);

      if (!this.isWorkingOnClone()) {
        this.holder.parentNode.style.position = 'relative';

        if (trimmingElement === window) {
          var preventOverflow = this.wot.getSetting('preventOverflow');

          if (!preventOverflow) {
            this.holder.style.overflow = 'visible';
            this.wtRootElement.style.overflow = 'visible';
          }
        } else {
          this.holder.style.width = (0, _element.getStyle)(trimmingElement, 'width');
          this.holder.style.height = (0, _element.getStyle)(trimmingElement, 'height');
          this.holder.style.overflow = '';
        }
      }
    }
  }, {
    key: 'isWorkingOnClone',
    value: function isWorkingOnClone() {
      return !!this.wot.cloneSource;
    }

    /**
     * Redraws the table
     *
     * @param {Boolean} fastDraw If TRUE, will try to avoid full redraw and only update the border positions. If FALSE or UNDEFINED, will perform a full redraw
     * @returns {Table}
     */

  }, {
    key: 'draw',
    value: function draw(fastDraw) {
      var _wot = this.wot,
          wtOverlays = _wot.wtOverlays,
          wtViewport = _wot.wtViewport;

      var totalRows = this.instance.getSetting('totalRows');
      var rowHeaders = this.wot.getSetting('rowHeaders').length;
      var columnHeaders = this.wot.getSetting('columnHeaders').length;
      var syncScroll = false;

      if (!this.isWorkingOnClone()) {
        this.holderOffset = (0, _element.offset)(this.holder);
        fastDraw = wtViewport.createRenderCalculators(fastDraw);

        if (rowHeaders && !this.wot.getSetting('fixedColumnsLeft')) {
          var leftScrollPos = wtOverlays.leftOverlay.getScrollPosition();
          var previousState = this.correctHeaderWidth;

          this.correctHeaderWidth = leftScrollPos > 0;

          if (previousState !== this.correctHeaderWidth) {
            fastDraw = false;
          }
        }
      }

      if (!this.isWorkingOnClone()) {
        syncScroll = wtOverlays.prepareOverlays();
      }

      if (fastDraw) {
        if (!this.isWorkingOnClone()) {
          // in case we only scrolled without redraw, update visible rows information in oldRowsCalculator
          wtViewport.createVisibleCalculators();
        }
        if (wtOverlays) {
          wtOverlays.refresh(true);
        }
      } else {
        if (this.isWorkingOnClone()) {
          this.tableOffset = this.wot.cloneSource.wtTable.tableOffset;
        } else {
          this.tableOffset = (0, _element.offset)(this.TABLE);
        }
        var startRow = void 0;

        if (_base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_DEBUG) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_TOP) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_TOP_LEFT_CORNER)) {
          startRow = 0;
        } else if (_base2.default.isOverlayTypeOf(this.instance.cloneOverlay, _base2.default.CLONE_BOTTOM) || _base2.default.isOverlayTypeOf(this.instance.cloneOverlay, _base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
          startRow = Math.max(totalRows - this.wot.getSetting('fixedRowsBottom'), 0);
        } else {
          startRow = wtViewport.rowsRenderCalculator.startRow;
        }
        var startColumn = void 0;

        if (_base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_DEBUG) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_LEFT) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_TOP_LEFT_CORNER) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
          startColumn = 0;
        } else {
          startColumn = wtViewport.columnsRenderCalculator.startColumn;
        }
        this.rowFilter = new _row2.default(startRow, totalRows, columnHeaders);
        this.columnFilter = new _column2.default(startColumn, this.wot.getSetting('totalColumns'), rowHeaders);

        this.alignOverlaysWithTrimmingContainer();
        this._doDraw(); // creates calculator after draw
      }
      this.refreshSelections(fastDraw);

      if (!this.isWorkingOnClone()) {
        wtOverlays.topOverlay.resetFixedPosition();

        if (wtOverlays.bottomOverlay.clone) {
          wtOverlays.bottomOverlay.resetFixedPosition();
        }

        wtOverlays.leftOverlay.resetFixedPosition();

        if (wtOverlays.topLeftCornerOverlay) {
          wtOverlays.topLeftCornerOverlay.resetFixedPosition();
        }

        if (wtOverlays.bottomLeftCornerOverlay && wtOverlays.bottomLeftCornerOverlay.clone) {
          wtOverlays.bottomLeftCornerOverlay.resetFixedPosition();
        }
      }
      if (syncScroll) {
        wtOverlays.syncScrollWithMaster();
      }
      this.wot.drawn = true;

      return this;
    }
  }, {
    key: '_doDraw',
    value: function _doDraw() {
      var wtRenderer = new _tableRenderer2.default(this);

      wtRenderer.render();
    }
  }, {
    key: 'removeClassFromCells',
    value: function removeClassFromCells(className) {
      var nodes = this.TABLE.querySelectorAll('.' + className);

      for (var i = 0, len = nodes.length; i < len; i++) {
        (0, _element.removeClass)(nodes[i], className);
      }
    }
  }, {
    key: 'refreshSelections',
    value: function refreshSelections(fastDraw) {
      if (!this.wot.selections) {
        return;
      }
      var len = this.wot.selections.length;

      if (fastDraw) {
        for (var i = 0; i < len; i++) {
          // there was no rerender, so we need to remove classNames by ourselves
          if (this.wot.selections[i].settings.className) {
            this.removeClassFromCells(this.wot.selections[i].settings.className);
          }
          if (this.wot.selections[i].settings.highlightHeaderClassName) {
            this.removeClassFromCells(this.wot.selections[i].settings.highlightHeaderClassName);
          }
          if (this.wot.selections[i].settings.highlightRowClassName) {
            this.removeClassFromCells(this.wot.selections[i].settings.highlightRowClassName);
          }
          if (this.wot.selections[i].settings.highlightColumnClassName) {
            this.removeClassFromCells(this.wot.selections[i].settings.highlightColumnClassName);
          }
        }
      }
      for (var _i = 0; _i < len; _i++) {
        this.wot.selections[_i].draw(this.wot, fastDraw);
      }
    }

    /**
     * Get cell element at coords.
     *
     * @param {CellCoords} coords
     * @returns {HTMLElement|Number} HTMLElement on success or Number one of the exit codes on error:
     *  -1 row before viewport
     *  -2 row after viewport
     */

  }, {
    key: 'getCell',
    value: function getCell(coords) {
      if (this.isRowBeforeRenderedRows(coords.row)) {
        // row before rendered rows
        return -1;
      } else if (this.isRowAfterRenderedRows(coords.row)) {
        // row after rendered rows
        return -2;
      }

      var TR = this.TBODY.childNodes[this.rowFilter.sourceToRendered(coords.row)];

      if (TR) {
        return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords.col)];
      }
    }

    /**
     * getColumnHeader
     *
     * @param {Number} col Column index
     * @param {Number} [level=0] Header level (0 = most distant to the table)
     * @returns {Object} HTMLElement on success or undefined on error
     */

  }, {
    key: 'getColumnHeader',
    value: function getColumnHeader(col) {
      var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

      var TR = this.THEAD.childNodes[level];

      if (TR) {
        return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(col)];
      }
    }

    /**
     * getRowHeader
     *
     * @param {Number} row Row index
     * @returns {HTMLElement} HTMLElement on success or Number one of the exit codes on error: `null table doesn't have row headers`
     */

  }, {
    key: 'getRowHeader',
    value: function getRowHeader(row) {
      if (this.columnFilter.sourceColumnToVisibleRowHeadedColumn(0) === 0) {
        return null;
      }
      var TR = this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)];

      if (TR) {
        return TR.childNodes[0];
      }
    }

    /**
     * Returns cell coords object for a given TD (or a child element of a TD element).
     *
     * @param {HTMLTableCellElement} TD A cell DOM element (or a child of one).
     * @returns {CellCoords|null} The coordinates of the provided TD element (or the closest TD element) or null, if the provided element is not applicable.
     */

  }, {
    key: 'getCoords',
    value: function getCoords(TD) {
      if (TD.nodeName !== 'TD' && TD.nodeName !== 'TH') {
        TD = (0, _element.closest)(TD, ['TD', 'TH']);
      }

      if (TD === null) {
        return null;
      }

      var TR = TD.parentNode;
      var CONTAINER = TR.parentNode;
      var row = (0, _element.index)(TR);
      var col = TD.cellIndex;

      if ((0, _element.overlayContainsElement)(_base2.default.CLONE_TOP_LEFT_CORNER, TD) || (0, _element.overlayContainsElement)(_base2.default.CLONE_TOP, TD)) {
        if (CONTAINER.nodeName === 'THEAD') {
          row -= CONTAINER.childNodes.length;
        }
      } else if (CONTAINER === this.THEAD) {
        row = this.rowFilter.visibleColHeadedRowToSourceRow(row);
      } else {
        row = this.rowFilter.renderedToSource(row);
      }

      if ((0, _element.overlayContainsElement)(_base2.default.CLONE_TOP_LEFT_CORNER, TD) || (0, _element.overlayContainsElement)(_base2.default.CLONE_LEFT, TD)) {
        col = this.columnFilter.offsettedTH(col);
      } else {
        col = this.columnFilter.visibleRowHeadedColumnToSourceColumn(col);
      }

      return new _coords2.default(row, col);
    }
  }, {
    key: 'getTrForRow',
    value: function getTrForRow(row) {
      return this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)];
    }
  }, {
    key: 'getFirstRenderedRow',
    value: function getFirstRenderedRow() {
      return this.wot.wtViewport.rowsRenderCalculator.startRow;
    }
  }, {
    key: 'getFirstVisibleRow',
    value: function getFirstVisibleRow() {
      return this.wot.wtViewport.rowsVisibleCalculator.startRow;
    }
  }, {
    key: 'getFirstRenderedColumn',
    value: function getFirstRenderedColumn() {
      return this.wot.wtViewport.columnsRenderCalculator.startColumn;
    }

    /**
     * @returns {Number} Returns -1 if no row is visible
     */

  }, {
    key: 'getFirstVisibleColumn',
    value: function getFirstVisibleColumn() {
      return this.wot.wtViewport.columnsVisibleCalculator.startColumn;
    }

    /**
     * @returns {Number} Returns -1 if no row is visible
     */

  }, {
    key: 'getLastRenderedRow',
    value: function getLastRenderedRow() {
      return this.wot.wtViewport.rowsRenderCalculator.endRow;
    }
  }, {
    key: 'getLastVisibleRow',
    value: function getLastVisibleRow() {
      return this.wot.wtViewport.rowsVisibleCalculator.endRow;
    }
  }, {
    key: 'getLastRenderedColumn',
    value: function getLastRenderedColumn() {
      return this.wot.wtViewport.columnsRenderCalculator.endColumn;
    }

    /**
     * @returns {Number} Returns -1 if no column is visible
     */

  }, {
    key: 'getLastVisibleColumn',
    value: function getLastVisibleColumn() {
      return this.wot.wtViewport.columnsVisibleCalculator.endColumn;
    }
  }, {
    key: 'isRowBeforeRenderedRows',
    value: function isRowBeforeRenderedRows(row) {
      return this.rowFilter && this.rowFilter.sourceToRendered(row) < 0 && row >= 0;
    }
  }, {
    key: 'isRowAfterViewport',
    value: function isRowAfterViewport(row) {
      return this.rowFilter && this.rowFilter.sourceToRendered(row) > this.getLastVisibleRow();
    }
  }, {
    key: 'isRowAfterRenderedRows',
    value: function isRowAfterRenderedRows(row) {
      return this.rowFilter && this.rowFilter.sourceToRendered(row) > this.getLastRenderedRow();
    }
  }, {
    key: 'isColumnBeforeViewport',
    value: function isColumnBeforeViewport(column) {
      return this.columnFilter && this.columnFilter.sourceToRendered(column) < 0 && column >= 0;
    }
  }, {
    key: 'isColumnAfterViewport',
    value: function isColumnAfterViewport(column) {
      return this.columnFilter && this.columnFilter.sourceToRendered(column) > this.getLastVisibleColumn();
    }
  }, {
    key: 'isLastRowFullyVisible',
    value: function isLastRowFullyVisible() {
      return this.getLastVisibleRow() === this.getLastRenderedRow();
    }
  }, {
    key: 'isLastColumnFullyVisible',
    value: function isLastColumnFullyVisible() {
      return this.getLastVisibleColumn() === this.getLastRenderedColumn();
    }
  }, {
    key: 'getRenderedColumnsCount',
    value: function getRenderedColumnsCount() {
      var columnsCount = this.wot.wtViewport.columnsRenderCalculator.count;
      var totalColumns = this.wot.getSetting('totalColumns');

      if (this.wot.isOverlayName(_base2.default.CLONE_DEBUG)) {
        columnsCount = totalColumns;
      } else if (this.wot.isOverlayName(_base2.default.CLONE_LEFT) || this.wot.isOverlayName(_base2.default.CLONE_TOP_LEFT_CORNER) || this.wot.isOverlayName(_base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
        return Math.min(this.wot.getSetting('fixedColumnsLeft'), totalColumns);
      }

      return columnsCount;
    }
  }, {
    key: 'getRenderedRowsCount',
    value: function getRenderedRowsCount() {
      var rowsCount = this.wot.wtViewport.rowsRenderCalculator.count;
      var totalRows = this.wot.getSetting('totalRows');

      if (this.wot.isOverlayName(_base2.default.CLONE_DEBUG)) {
        rowsCount = totalRows;
      } else if (this.wot.isOverlayName(_base2.default.CLONE_TOP) || this.wot.isOverlayName(_base2.default.CLONE_TOP_LEFT_CORNER)) {
        rowsCount = Math.min(this.wot.getSetting('fixedRowsTop'), totalRows);
      } else if (this.wot.isOverlayName(_base2.default.CLONE_BOTTOM) || this.wot.isOverlayName(_base2.default.CLONE_BOTTOM_LEFT_CORNER)) {
        rowsCount = Math.min(this.wot.getSetting('fixedRowsBottom'), totalRows);
      }

      return rowsCount;
    }
  }, {
    key: 'getVisibleRowsCount',
    value: function getVisibleRowsCount() {
      return this.wot.wtViewport.rowsVisibleCalculator.count;
    }
  }, {
    key: 'allRowsInViewport',
    value: function allRowsInViewport() {
      return this.wot.getSetting('totalRows') == this.getVisibleRowsCount();
    }

    /**
     * Checks if any of the row's cells content exceeds its initial height, and if so, returns the oversized height
     *
     * @param {Number} sourceRow
     * @returns {Number}
     */

  }, {
    key: 'getRowHeight',
    value: function getRowHeight(sourceRow) {
      var height = this.wot.wtSettings.settings.rowHeight(sourceRow);
      var oversizedHeight = this.wot.wtViewport.oversizedRows[sourceRow];

      if (oversizedHeight !== void 0) {
        height = height === void 0 ? oversizedHeight : Math.max(height, oversizedHeight);
      }

      return height;
    }
  }, {
    key: 'getColumnHeaderHeight',
    value: function getColumnHeaderHeight(level) {
      var height = this.wot.wtSettings.settings.defaultRowHeight;
      var oversizedHeight = this.wot.wtViewport.oversizedColumnHeaders[level];

      if (oversizedHeight !== void 0) {
        height = height ? Math.max(height, oversizedHeight) : oversizedHeight;
      }

      return height;
    }
  }, {
    key: 'getVisibleColumnsCount',
    value: function getVisibleColumnsCount() {
      return this.wot.wtViewport.columnsVisibleCalculator.count;
    }
  }, {
    key: 'allColumnsInViewport',
    value: function allColumnsInViewport() {
      return this.wot.getSetting('totalColumns') == this.getVisibleColumnsCount();
    }
  }, {
    key: 'getColumnWidth',
    value: function getColumnWidth(sourceColumn) {
      var width = this.wot.wtSettings.settings.columnWidth;

      if (typeof width === 'function') {
        width = width(sourceColumn);
      } else if ((typeof width === 'undefined' ? 'undefined' : _typeof(width)) === 'object') {
        width = width[sourceColumn];
      }

      return width || this.wot.wtSettings.settings.defaultColumnWidth;
    }
  }, {
    key: 'getStretchedColumnWidth',
    value: function getStretchedColumnWidth(sourceColumn) {
      var columnWidth = this.getColumnWidth(sourceColumn);
      var width = columnWidth == null ? this.instance.wtSettings.settings.defaultColumnWidth : columnWidth;
      var calculator = this.wot.wtViewport.columnsRenderCalculator;

      if (calculator) {
        var stretchedWidth = calculator.getStretchedColumnWidth(sourceColumn, width);

        if (stretchedWidth) {
          width = stretchedWidth;
        }
      }

      return width;
    }

    /**
     * Modify row header widths provided by user in class contructor.
     *
     * @private
     */

  }, {
    key: '_modifyRowHeaderWidth',
    value: function _modifyRowHeaderWidth(rowHeaderWidthFactory) {
      var widths = (0, _function.isFunction)(rowHeaderWidthFactory) ? rowHeaderWidthFactory() : null;

      if (Array.isArray(widths)) {
        widths = [].concat(_toConsumableArray(widths));
        widths[widths.length - 1] = this._correctRowHeaderWidth(widths[widths.length - 1]);
      } else {
        widths = this._correctRowHeaderWidth(widths);
      }

      return widths;
    }

    /**
     * Correct row header width if necessary.
     *
     * @private
     */

  }, {
    key: '_correctRowHeaderWidth',
    value: function _correctRowHeaderWidth(width) {
      if (typeof width !== 'number') {
        width = this.wot.getSetting('defaultColumnWidth');
      }
      if (this.correctHeaderWidth) {
        width++;
      }

      return width;
    }
  }]);

  return Table;
}();

exports.default = Table;

/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _base = __webpack_require__(35);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var performanceWarningAppeared = false;

/**
 * @class TableRenderer
 */

var TableRenderer = function () {
  /**
   * @param {WalkontableTable} wtTable
   */
  function TableRenderer(wtTable) {
    _classCallCheck(this, TableRenderer);

    this.wtTable = wtTable;
    this.wot = wtTable.instance;

    // legacy support
    this.instance = wtTable.instance;

    this.rowFilter = wtTable.rowFilter;
    this.columnFilter = wtTable.columnFilter;

    this.TABLE = wtTable.TABLE;
    this.THEAD = wtTable.THEAD;
    this.TBODY = wtTable.TBODY;
    this.COLGROUP = wtTable.COLGROUP;

    this.rowHeaders = [];
    this.rowHeaderCount = 0;
    this.columnHeaders = [];
    this.columnHeaderCount = 0;
    this.fixedRowsTop = 0;
    this.fixedRowsBottom = 0;
  }

  /**
   *
   */


  _createClass(TableRenderer, [{
    key: 'render',
    value: function render() {
      if (!this.wtTable.isWorkingOnClone()) {
        var skipRender = {};
        this.wot.getSetting('beforeDraw', true, skipRender);

        if (skipRender.skipRender === true) {
          return;
        }
      }

      this.rowHeaders = this.wot.getSetting('rowHeaders');
      this.rowHeaderCount = this.rowHeaders.length;
      this.fixedRowsTop = this.wot.getSetting('fixedRowsTop');
      this.fixedRowsBottom = this.wot.getSetting('fixedRowsBottom');
      this.columnHeaders = this.wot.getSetting('columnHeaders');
      this.columnHeaderCount = this.columnHeaders.length;

      var columnsToRender = this.wtTable.getRenderedColumnsCount();
      var rowsToRender = this.wtTable.getRenderedRowsCount();
      var totalColumns = this.wot.getSetting('totalColumns');
      var totalRows = this.wot.getSetting('totalRows');
      var workspaceWidth = void 0;
      var adjusted = false;

      if (_base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_BOTTOM) || _base2.default.isOverlayTypeOf(this.wot.cloneOverlay, _base2.default.CLONE_BOTTOM_LEFT_CORNER)) {

        // do NOT render headers on the bottom or bottom-left corner overlay
        this.columnHeaders = [];
        this.columnHeaderCount = 0;
      }

      if (totalColumns >= 0) {
        // prepare COL and TH elements for rendering
        this.adjustAvailableNodes();
        adjusted = true;

        // adjust column widths according to user widths settings
        this.renderColumnHeaders();

        // Render table rows
        this.renderRows(totalRows, rowsToRender, columnsToRender);

        if (!this.wtTable.isWorkingOnClone()) {
          workspaceWidth = this.wot.wtViewport.getWorkspaceWidth();
          this.wot.wtViewport.containerWidth = null;
        }

        this.adjustColumnWidths(columnsToRender);
        this.markOversizedColumnHeaders();
        this.adjustColumnHeaderHeights();
      }

      if (!adjusted) {
        this.adjustAvailableNodes();
      }
      this.removeRedundantRows(rowsToRender);

      if (!this.wtTable.isWorkingOnClone() || this.wot.isOverlayName(_base2.default.CLONE_BOTTOM)) {
        this.markOversizedRows();
      }
      if (!this.wtTable.isWorkingOnClone()) {
        this.wot.wtViewport.createVisibleCalculators();
        this.wot.wtOverlays.refresh(false);

        this.wot.wtOverlays.applyToDOM();

        var hiderWidth = (0, _element.outerWidth)(this.wtTable.hider);
        var tableWidth = (0, _element.outerWidth)(this.wtTable.TABLE);

        if (hiderWidth !== 0 && tableWidth !== hiderWidth) {
          // Recalculate the column widths, if width changes made in the overlays removed the scrollbar, thus changing the viewport width.
          this.adjustColumnWidths(columnsToRender);
        }

        if (workspaceWidth !== this.wot.wtViewport.getWorkspaceWidth()) {
          // workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching
          this.wot.wtViewport.containerWidth = null;

          var firstRendered = this.wtTable.getFirstRenderedColumn();
          var lastRendered = this.wtTable.getLastRenderedColumn();
          var defaultColumnWidth = this.wot.getSetting('defaultColumnWidth');
          var rowHeaderWidthSetting = this.wot.getSetting('rowHeaderWidth');

          rowHeaderWidthSetting = this.instance.getSetting('onModifyRowHeaderWidth', rowHeaderWidthSetting);

          if (rowHeaderWidthSetting != null) {
            for (var i = 0; i < this.rowHeaderCount; i++) {
              var width = Array.isArray(rowHeaderWidthSetting) ? rowHeaderWidthSetting[i] : rowHeaderWidthSetting;

              width = width == null ? defaultColumnWidth : width;

              this.COLGROUP.childNodes[i].style.width = width + 'px';
            }
          }

          for (var _i = firstRendered; _i < lastRendered; _i++) {
            var _width = this.wtTable.getStretchedColumnWidth(_i);
            var renderedIndex = this.columnFilter.sourceToRendered(_i);

            this.COLGROUP.childNodes[renderedIndex + this.rowHeaderCount].style.width = _width + 'px';
          }
        }

        this.wot.getSetting('onDraw', true);
      } else if (this.wot.isOverlayName(_base2.default.CLONE_BOTTOM)) {
        this.wot.cloneSource.wtOverlays.adjustElementsSize();
      }
    }

    /**
     * @param {Number} renderedRowsCount
     */

  }, {
    key: 'removeRedundantRows',
    value: function removeRedundantRows(renderedRowsCount) {
      while (this.wtTable.tbodyChildrenLength > renderedRowsCount) {
        this.TBODY.removeChild(this.TBODY.lastChild);
        this.wtTable.tbodyChildrenLength--;
      }
    }

    /**
     * @param {Number} totalRows
     * @param {Number} rowsToRender
     * @param {Number} columnsToRender
     */

  }, {
    key: 'renderRows',
    value: function renderRows(totalRows, rowsToRender, columnsToRender) {
      var lastTD = void 0,
          TR = void 0;
      var visibleRowIndex = 0;
      var sourceRowIndex = this.rowFilter.renderedToSource(visibleRowIndex);
      var isWorkingOnClone = this.wtTable.isWorkingOnClone();

      while (sourceRowIndex < totalRows && sourceRowIndex >= 0) {
        if (!performanceWarningAppeared && visibleRowIndex > 1000) {
          performanceWarningAppeared = true;
          console.warn('Performance tip: Handsontable rendered more than 1000 visible rows. Consider limiting the number ' + 'of rendered rows by specifying the table height and/or turning off the "renderAllRows" option.');
        }
        if (rowsToRender !== void 0 && visibleRowIndex === rowsToRender) {
          // We have as much rows as needed for this clone
          break;
        }
        TR = this.getOrCreateTrForRow(visibleRowIndex, TR);

        // Render row headers
        this.renderRowHeaders(sourceRowIndex, TR);
        // Add and/or remove TDs to TR to match the desired number
        this.adjustColumns(TR, columnsToRender + this.rowHeaderCount);

        lastTD = this.renderCells(sourceRowIndex, TR, columnsToRender);

        if (!isWorkingOnClone ||
        // Necessary to refresh oversized row heights after editing cell in overlays
        this.wot.isOverlayName(_base2.default.CLONE_BOTTOM)) {
          // Reset the oversized row cache for this row
          this.resetOversizedRow(sourceRowIndex);
        }

        if (TR.firstChild) {
          // if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is
          // the way to make sure that the overlay will has same row height
          var height = this.wot.wtTable.getRowHeight(sourceRowIndex);

          if (height) {
            // Decrease height. 1 pixel will be "replaced" by 1px border top
            height--;
            TR.firstChild.style.height = height + 'px';
          } else {
            TR.firstChild.style.height = '';
          }
        }
        visibleRowIndex++;
        sourceRowIndex = this.rowFilter.renderedToSource(visibleRowIndex);
      }
    }

    /**
     * Reset the oversized row cache for the provided index
     *
     * @param {Number} sourceRow Row index
     */

  }, {
    key: 'resetOversizedRow',
    value: function resetOversizedRow(sourceRow) {
      if (this.wot.getSetting('externalRowCalculator')) {
        return;
      }
      if (this.wot.wtViewport.oversizedRows && this.wot.wtViewport.oversizedRows[sourceRow]) {
        this.wot.wtViewport.oversizedRows[sourceRow] = void 0;
      }
    }

    /**
     * Check if any of the rendered rows is higher than expected, and if so, cache them
     */

  }, {
    key: 'markOversizedRows',
    value: function markOversizedRows() {
      if (this.wot.getSetting('externalRowCalculator')) {
        return;
      }
      var rowCount = this.instance.wtTable.TBODY.childNodes.length;
      var expectedTableHeight = rowCount * this.instance.wtSettings.settings.defaultRowHeight;
      var actualTableHeight = (0, _element.innerHeight)(this.instance.wtTable.TBODY) - 1;
      var previousRowHeight = void 0;
      var rowInnerHeight = void 0;
      var sourceRowIndex = void 0;
      var currentTr = void 0;
      var rowHeader = void 0;
      var totalRows = this.instance.getSetting('totalRows');

      if (expectedTableHeight === actualTableHeight && !this.instance.getSetting('fixedRowsBottom')) {
        // If the actual table height equals rowCount * default single row height, no row is oversized -> no need to iterate over them
        return;
      }

      while (rowCount) {
        rowCount--;
        sourceRowIndex = this.instance.wtTable.rowFilter.renderedToSource(rowCount);
        previousRowHeight = this.instance.wtTable.getRowHeight(sourceRowIndex);
        currentTr = this.instance.wtTable.getTrForRow(sourceRowIndex);
        rowHeader = currentTr.querySelector('th');

        if (rowHeader) {
          rowInnerHeight = (0, _element.innerHeight)(rowHeader);
        } else {
          rowInnerHeight = (0, _element.innerHeight)(currentTr) - 1;
        }

        if (!previousRowHeight && this.instance.wtSettings.settings.defaultRowHeight < rowInnerHeight || previousRowHeight < rowInnerHeight) {
          this.instance.wtViewport.oversizedRows[sourceRowIndex] = ++rowInnerHeight;
        }
      }
    }

    /**
     * Check if any of the rendered columns is higher than expected, and if so, cache them.
     */

  }, {
    key: 'markOversizedColumnHeaders',
    value: function markOversizedColumnHeaders() {
      var overlayName = this.wot.getOverlayName();

      if (!this.columnHeaderCount || this.wot.wtViewport.hasOversizedColumnHeadersMarked[overlayName] || this.wtTable.isWorkingOnClone()) {
        return;
      }
      var columnCount = this.wtTable.getRenderedColumnsCount();

      for (var i = 0; i < this.columnHeaderCount; i++) {
        for (var renderedColumnIndex = -1 * this.rowHeaderCount; renderedColumnIndex < columnCount; renderedColumnIndex++) {
          this.markIfOversizedColumnHeader(renderedColumnIndex);
        }
      }
      this.wot.wtViewport.hasOversizedColumnHeadersMarked[overlayName] = true;
    }

    /**
     *
     */

  }, {
    key: 'adjustColumnHeaderHeights',
    value: function adjustColumnHeaderHeights() {
      var columnHeaders = this.wot.getSetting('columnHeaders');
      var children = this.wot.wtTable.THEAD.childNodes;
      var oversizedColumnHeaders = this.wot.wtViewport.oversizedColumnHeaders;

      for (var i = 0, len = columnHeaders.length; i < len; i++) {
        if (oversizedColumnHeaders[i]) {
          if (!children[i] || children[i].childNodes.length === 0) {
            return;
          }
          children[i].childNodes[0].style.height = oversizedColumnHeaders[i] + 'px';
        }
      }
    }

    /**
     * Check if column header for the specified column is higher than expected, and if so, cache it
     *
     * @param {Number} col Index of column
     */

  }, {
    key: 'markIfOversizedColumnHeader',
    value: function markIfOversizedColumnHeader(col) {
      var sourceColIndex = this.wot.wtTable.columnFilter.renderedToSource(col);
      var level = this.columnHeaderCount;
      var defaultRowHeight = this.wot.wtSettings.settings.defaultRowHeight;
      var previousColHeaderHeight = void 0;
      var currentHeader = void 0;
      var currentHeaderHeight = void 0;
      var columnHeaderHeightSetting = this.wot.getSetting('columnHeaderHeight') || [];

      while (level) {
        level--;

        previousColHeaderHeight = this.wot.wtTable.getColumnHeaderHeight(level);
        currentHeader = this.wot.wtTable.getColumnHeader(sourceColIndex, level);

        if (!currentHeader) {
          /* eslint-disable no-continue */
          continue;
        }
        currentHeaderHeight = (0, _element.innerHeight)(currentHeader);

        if (!previousColHeaderHeight && defaultRowHeight < currentHeaderHeight || previousColHeaderHeight < currentHeaderHeight) {
          this.wot.wtViewport.oversizedColumnHeaders[level] = currentHeaderHeight;
        }

        if (Array.isArray(columnHeaderHeightSetting)) {
          if (columnHeaderHeightSetting[level] != null) {
            this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting[level];
          }
        } else if (!isNaN(columnHeaderHeightSetting)) {
          this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting;
        }

        if (this.wot.wtViewport.oversizedColumnHeaders[level] < (columnHeaderHeightSetting[level] || columnHeaderHeightSetting)) {
          this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting[level] || columnHeaderHeightSetting;
        }
      }
    }

    /**
     * @param {Number} sourceRowIndex
     * @param {HTMLTableRowElement} TR
     * @param {Number} columnsToRender
     * @returns {HTMLTableCellElement}
     */

  }, {
    key: 'renderCells',
    value: function renderCells(sourceRowIndex, TR, columnsToRender) {
      var TD = void 0;
      var sourceColIndex = void 0;

      for (var visibleColIndex = 0; visibleColIndex < columnsToRender; visibleColIndex++) {
        sourceColIndex = this.columnFilter.renderedToSource(visibleColIndex);

        if (visibleColIndex === 0) {
          TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(sourceColIndex)];
        } else {
          TD = TD.nextSibling; // http://jsperf.com/nextsibling-vs-indexed-childnodes
        }
        // If the number of headers has been reduced, we need to replace excess TH with TD
        if (TD.nodeName == 'TH') {
          TD = replaceThWithTd(TD, TR);
        }
        if (!(0, _element.hasClass)(TD, 'hide')) {
          TD.className = '';
        }
        TD.removeAttribute('style');
        this.wot.wtSettings.settings.cellRenderer(sourceRowIndex, sourceColIndex, TD);
      }

      return TD;
    }

    /**
     * @param {Number} columnsToRender Number of columns to render.
     */

  }, {
    key: 'adjustColumnWidths',
    value: function adjustColumnWidths(columnsToRender) {
      var scrollbarCompensation = 0;
      var sourceInstance = this.wot.cloneSource ? this.wot.cloneSource : this.wot;
      var mainHolder = sourceInstance.wtTable.holder;
      var defaultColumnWidth = this.wot.getSetting('defaultColumnWidth');
      var rowHeaderWidthSetting = this.wot.getSetting('rowHeaderWidth');

      if (mainHolder.offsetHeight < mainHolder.scrollHeight) {
        scrollbarCompensation = (0, _element.getScrollbarWidth)();
      }
      this.wot.wtViewport.columnsRenderCalculator.refreshStretching(this.wot.wtViewport.getViewportWidth() - scrollbarCompensation);

      rowHeaderWidthSetting = this.instance.getSetting('onModifyRowHeaderWidth', rowHeaderWidthSetting);

      if (rowHeaderWidthSetting != null) {
        for (var i = 0; i < this.rowHeaderCount; i++) {
          var width = Array.isArray(rowHeaderWidthSetting) ? rowHeaderWidthSetting[i] : rowHeaderWidthSetting;

          width = width == null ? defaultColumnWidth : width;

          this.COLGROUP.childNodes[i].style.width = width + 'px';
        }
      }

      for (var renderedColIndex = 0; renderedColIndex < columnsToRender; renderedColIndex++) {
        var _width2 = this.wtTable.getStretchedColumnWidth(this.columnFilter.renderedToSource(renderedColIndex));

        this.COLGROUP.childNodes[renderedColIndex + this.rowHeaderCount].style.width = _width2 + 'px';
      }
    }

    /**
     * @param {HTMLTableCellElement} TR
     */

  }, {
    key: 'appendToTbody',
    value: function appendToTbody(TR) {
      this.TBODY.appendChild(TR);
      this.wtTable.tbodyChildrenLength++;
    }

    /**
     * @param {Number} rowIndex
     * @param {HTMLTableRowElement} currentTr
     * @returns {HTMLTableCellElement}
     */

  }, {
    key: 'getOrCreateTrForRow',
    value: function getOrCreateTrForRow(rowIndex, currentTr) {
      var TR = void 0;

      if (rowIndex >= this.wtTable.tbodyChildrenLength) {
        TR = this.createRow();
        this.appendToTbody(TR);
      } else if (rowIndex === 0) {
        TR = this.TBODY.firstChild;
      } else {
        // http://jsperf.com/nextsibling-vs-indexed-childnodes
        TR = currentTr.nextSibling;
      }
      if (TR.className) {
        TR.removeAttribute('class');
      }

      return TR;
    }

    /**
     * @returns {HTMLTableCellElement}
     */

  }, {
    key: 'createRow',
    value: function createRow() {
      var TR = document.createElement('TR');

      for (var visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) {
        TR.appendChild(document.createElement('TH'));
      }

      return TR;
    }

    /**
     * @param {Number} row
     * @param {Number} col
     * @param {HTMLTableCellElement} TH
     */

  }, {
    key: 'renderRowHeader',
    value: function renderRowHeader(row, col, TH) {
      TH.className = '';
      TH.removeAttribute('style');
      this.rowHeaders[col](row, TH, col);
    }

    /**
     * @param {Number} row
     * @param {HTMLTableCellElement} TR
     */

  }, {
    key: 'renderRowHeaders',
    value: function renderRowHeaders(row, TR) {
      for (var TH = TR.firstChild, visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) {
        // If the number of row headers increased we need to create TH or replace an existing TD node with TH
        if (!TH) {
          TH = document.createElement('TH');
          TR.appendChild(TH);
        } else if (TH.nodeName == 'TD') {
          TH = replaceTdWithTh(TH, TR);
        }
        this.renderRowHeader(row, visibleColIndex, TH);
        // http://jsperf.com/nextsibling-vs-indexed-childnodes
        TH = TH.nextSibling;
      }
    }

    /**
     * Adjust the number of COL and TH elements to match the number of columns and headers that need to be rendered
     */

  }, {
    key: 'adjustAvailableNodes',
    value: function adjustAvailableNodes() {
      this.adjustColGroups();
      this.adjustThead();
    }

    /**
     * Renders the column headers
     */

  }, {
    key: 'renderColumnHeaders',
    value: function renderColumnHeaders() {
      if (!this.columnHeaderCount) {
        return;
      }
      var columnCount = this.wtTable.getRenderedColumnsCount();

      for (var i = 0; i < this.columnHeaderCount; i++) {
        var TR = this.getTrForColumnHeaders(i);

        for (var renderedColumnIndex = -1 * this.rowHeaderCount; renderedColumnIndex < columnCount; renderedColumnIndex++) {
          var sourceCol = this.columnFilter.renderedToSource(renderedColumnIndex);

          this.renderColumnHeader(i, sourceCol, TR.childNodes[renderedColumnIndex + this.rowHeaderCount]);
        }
      }
    }

    /**
     * Adjusts the number of COL elements to match the number of columns that need to be rendered
     */

  }, {
    key: 'adjustColGroups',
    value: function adjustColGroups() {
      var columnCount = this.wtTable.getRenderedColumnsCount();

      while (this.wtTable.colgroupChildrenLength < columnCount + this.rowHeaderCount) {
        this.COLGROUP.appendChild(document.createElement('COL'));
        this.wtTable.colgroupChildrenLength++;
      }
      while (this.wtTable.colgroupChildrenLength > columnCount + this.rowHeaderCount) {
        this.COLGROUP.removeChild(this.COLGROUP.lastChild);
        this.wtTable.colgroupChildrenLength--;
      }
      if (this.rowHeaderCount) {
        (0, _element.addClass)(this.COLGROUP.childNodes[0], 'rowHeader');
      }
    }

    /**
     * Adjusts the number of TH elements in THEAD to match the number of headers and columns that need to be rendered
     */

  }, {
    key: 'adjustThead',
    value: function adjustThead() {
      var columnCount = this.wtTable.getRenderedColumnsCount();
      var TR = this.THEAD.firstChild;

      if (this.columnHeaders.length) {
        for (var i = 0, len = this.columnHeaders.length; i < len; i++) {
          TR = this.THEAD.childNodes[i];

          if (!TR) {
            TR = document.createElement('TR');
            this.THEAD.appendChild(TR);
          }
          this.theadChildrenLength = TR.childNodes.length;

          while (this.theadChildrenLength < columnCount + this.rowHeaderCount) {
            TR.appendChild(document.createElement('TH'));
            this.theadChildrenLength++;
          }
          while (this.theadChildrenLength > columnCount + this.rowHeaderCount) {
            TR.removeChild(TR.lastChild);
            this.theadChildrenLength--;
          }
        }
        var theadChildrenLength = this.THEAD.childNodes.length;

        if (theadChildrenLength > this.columnHeaders.length) {
          for (var _i2 = this.columnHeaders.length; _i2 < theadChildrenLength; _i2++) {
            this.THEAD.removeChild(this.THEAD.lastChild);
          }
        }
      } else if (TR) {
        (0, _element.empty)(TR);
      }
    }

    /**
     * @param {Number} index
     * @returns {HTMLTableCellElement}
     */

  }, {
    key: 'getTrForColumnHeaders',
    value: function getTrForColumnHeaders(index) {
      return this.THEAD.childNodes[index];
    }

    /**
     * @param {Number} row
     * @param {Number} col
     * @param {HTMLTableCellElement} TH
     * @returns {*}
     */

  }, {
    key: 'renderColumnHeader',
    value: function renderColumnHeader(row, col, TH) {
      TH.className = '';
      TH.removeAttribute('style');

      return this.columnHeaders[row](col, TH, row);
    }

    /**
     * Add and/or remove the TDs to match the desired number
     *
     * @param {HTMLTableCellElement} TR Table row in question
     * @param {Number} desiredCount The desired number of TDs in the TR
     */

  }, {
    key: 'adjustColumns',
    value: function adjustColumns(TR, desiredCount) {
      var count = TR.childNodes.length;

      while (count < desiredCount) {
        var TD = document.createElement('TD');

        TR.appendChild(TD);
        count++;
      }
      while (count > desiredCount) {
        TR.removeChild(TR.lastChild);
        count--;
      }
    }

    /**
     * @param {Number} columnsToRender
     */

  }, {
    key: 'removeRedundantColumns',
    value: function removeRedundantColumns(columnsToRender) {
      while (this.wtTable.tbodyChildrenLength > columnsToRender) {
        this.TBODY.removeChild(this.TBODY.lastChild);
        this.wtTable.tbodyChildrenLength--;
      }
    }
  }]);

  return TableRenderer;
}();

function replaceTdWithTh(TD, TR) {
  var TH = document.createElement('TH');

  TR.insertBefore(TH, TD);
  TR.removeChild(TD);

  return TH;
}

function replaceThWithTd(TH, TR) {
  var TD = document.createElement('TD');

  TR.insertBefore(TD, TH);
  TR.removeChild(TH);

  return TD;
}

exports.default = TableRenderer;

/***/ }),
/* 301 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _object = __webpack_require__(1);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _viewportColumns = __webpack_require__(170);

var _viewportColumns2 = _interopRequireDefault(_viewportColumns);

var _viewportRows = __webpack_require__(171);

var _viewportRows2 = _interopRequireDefault(_viewportRows);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Viewport
 */
var Viewport = function () {
  /**
   * @param wotInstance
   */
  function Viewport(wotInstance) {
    var _this = this;

    _classCallCheck(this, Viewport);

    this.wot = wotInstance;
    // legacy support
    this.instance = this.wot;

    this.oversizedRows = [];
    this.oversizedColumnHeaders = [];
    this.hasOversizedColumnHeadersMarked = {};
    this.clientHeight = 0;
    this.containerWidth = NaN;
    this.rowHeaderWidth = NaN;
    this.rowsVisibleCalculator = null;
    this.columnsVisibleCalculator = null;

    this.eventManager = new _eventManager2.default(this.wot);
    this.eventManager.addEventListener(window, 'resize', function () {
      _this.clientHeight = _this.getWorkspaceHeight();
    });
  }

  /**
   * @returns {number}
   */


  _createClass(Viewport, [{
    key: 'getWorkspaceHeight',
    value: function getWorkspaceHeight() {
      var trimmingContainer = this.instance.wtOverlays.topOverlay.trimmingContainer;
      var elemHeight = void 0;
      var height = 0;

      if (trimmingContainer === window) {
        height = document.documentElement.clientHeight;
      } else {
        elemHeight = (0, _element.outerHeight)(trimmingContainer);
        // returns height without DIV scrollbar
        height = elemHeight > 0 && trimmingContainer.clientHeight > 0 ? trimmingContainer.clientHeight : Infinity;
      }

      return height;
    }
  }, {
    key: 'getWorkspaceWidth',
    value: function getWorkspaceWidth() {
      var width = void 0;
      var totalColumns = this.wot.getSetting('totalColumns');
      var trimmingContainer = this.instance.wtOverlays.leftOverlay.trimmingContainer;
      var overflow = void 0;
      var stretchSetting = this.wot.getSetting('stretchH');
      var docOffsetWidth = document.documentElement.offsetWidth;
      var preventOverflow = this.wot.getSetting('preventOverflow');

      if (preventOverflow) {
        return (0, _element.outerWidth)(this.instance.wtTable.wtRootElement);
      }

      if (this.wot.getSetting('freezeOverlays')) {
        width = Math.min(docOffsetWidth - this.getWorkspaceOffset().left, docOffsetWidth);
      } else {
        width = Math.min(this.getContainerFillWidth(), docOffsetWidth - this.getWorkspaceOffset().left, docOffsetWidth);
      }

      if (trimmingContainer === window && totalColumns > 0 && this.sumColumnWidths(0, totalColumns - 1) > width) {
        // in case sum of column widths is higher than available stylesheet width, let's assume using the whole window
        // otherwise continue below, which will allow stretching
        // this is used in `scroll_window.html`
        // TODO test me
        return document.documentElement.clientWidth;
      }

      if (trimmingContainer !== window) {
        overflow = (0, _element.getStyle)(this.instance.wtOverlays.leftOverlay.trimmingContainer, 'overflow');

        if (overflow == 'scroll' || overflow == 'hidden' || overflow == 'auto') {
          // this is used in `scroll.html`
          // TODO test me
          return Math.max(width, trimmingContainer.clientWidth);
        }
      }

      if (stretchSetting === 'none' || !stretchSetting) {
        // if no stretching is used, return the maximum used workspace width
        return Math.max(width, (0, _element.outerWidth)(this.instance.wtTable.TABLE));
      }

      // if stretching is used, return the actual container width, so the columns can fit inside it
      return width;
    }

    /**
     * Checks if viewport has vertical scroll
     *
     * @returns {Boolean}
     */

  }, {
    key: 'hasVerticalScroll',
    value: function hasVerticalScroll() {
      return this.getWorkspaceActualHeight() > this.getWorkspaceHeight();
    }

    /**
     * Checks if viewport has horizontal scroll
     *
     * @returns {Boolean}
     */

  }, {
    key: 'hasHorizontalScroll',
    value: function hasHorizontalScroll() {
      return this.getWorkspaceActualWidth() > this.getWorkspaceWidth();
    }

    /**
     * @param from
     * @param length
     * @returns {Number}
     */

  }, {
    key: 'sumColumnWidths',
    value: function sumColumnWidths(from, length) {
      var sum = 0;

      while (from < length) {
        sum += this.wot.wtTable.getColumnWidth(from);
        from++;
      }

      return sum;
    }

    /**
     * @returns {Number}
     */

  }, {
    key: 'getContainerFillWidth',
    value: function getContainerFillWidth() {
      if (this.containerWidth) {
        return this.containerWidth;
      }
      var mainContainer = this.instance.wtTable.holder;
      var fillWidth = void 0;
      var dummyElement = void 0;

      dummyElement = document.createElement('div');
      dummyElement.style.width = '100%';
      dummyElement.style.height = '1px';
      mainContainer.appendChild(dummyElement);
      fillWidth = dummyElement.offsetWidth;

      this.containerWidth = fillWidth;
      mainContainer.removeChild(dummyElement);

      return fillWidth;
    }

    /**
     * @returns {Number}
     */

  }, {
    key: 'getWorkspaceOffset',
    value: function getWorkspaceOffset() {
      return (0, _element.offset)(this.wot.wtTable.TABLE);
    }

    /**
     * @returns {Number}
     */

  }, {
    key: 'getWorkspaceActualHeight',
    value: function getWorkspaceActualHeight() {
      return (0, _element.outerHeight)(this.wot.wtTable.TABLE);
    }

    /**
     * @returns {Number}
     */

  }, {
    key: 'getWorkspaceActualWidth',
    value: function getWorkspaceActualWidth() {
      return (0, _element.outerWidth)(this.wot.wtTable.TABLE) || (0, _element.outerWidth)(this.wot.wtTable.TBODY) || (0, _element.outerWidth)(this.wot.wtTable.THEAD); // IE8 reports 0 as <table> offsetWidth;
    }

    /**
     * @returns {Number}
     */

  }, {
    key: 'getColumnHeaderHeight',
    value: function getColumnHeaderHeight() {
      if (isNaN(this.columnHeaderHeight)) {
        this.columnHeaderHeight = (0, _element.outerHeight)(this.wot.wtTable.THEAD);
      }

      return this.columnHeaderHeight;
    }

    /**
     * @returns {Number}
     */

  }, {
    key: 'getViewportHeight',
    value: function getViewportHeight() {
      var containerHeight = this.getWorkspaceHeight();
      var columnHeaderHeight = void 0;

      if (containerHeight === Infinity) {
        return containerHeight;
      }
      columnHeaderHeight = this.getColumnHeaderHeight();

      if (columnHeaderHeight > 0) {
        containerHeight -= columnHeaderHeight;
      }

      return containerHeight;
    }

    /**
     * @returns {Number}
     */

  }, {
    key: 'getRowHeaderWidth',
    value: function getRowHeaderWidth() {
      var rowHeadersHeightSetting = this.instance.getSetting('rowHeaderWidth');
      var rowHeaders = this.instance.getSetting('rowHeaders');

      if (rowHeadersHeightSetting) {
        this.rowHeaderWidth = 0;

        for (var i = 0, len = rowHeaders.length; i < len; i++) {
          this.rowHeaderWidth += rowHeadersHeightSetting[i] || rowHeadersHeightSetting;
        }
      }

      if (this.wot.cloneSource) {
        return this.wot.cloneSource.wtViewport.getRowHeaderWidth();
      }

      if (isNaN(this.rowHeaderWidth)) {

        if (rowHeaders.length) {
          var TH = this.instance.wtTable.TABLE.querySelector('TH');
          this.rowHeaderWidth = 0;

          for (var _i = 0, _len = rowHeaders.length; _i < _len; _i++) {
            if (TH) {
              this.rowHeaderWidth += (0, _element.outerWidth)(TH);
              TH = TH.nextSibling;
            } else {
              // yes this is a cheat but it worked like that before, just taking assumption from CSS instead of measuring.
              // TODO: proper fix
              this.rowHeaderWidth += 50;
            }
          }
        } else {
          this.rowHeaderWidth = 0;
        }
      }

      this.rowHeaderWidth = this.instance.getSetting('onModifyRowHeaderWidth', this.rowHeaderWidth) || this.rowHeaderWidth;

      return this.rowHeaderWidth;
    }

    /**
     * @returns {Number}
     */

  }, {
    key: 'getViewportWidth',
    value: function getViewportWidth() {
      var containerWidth = this.getWorkspaceWidth();
      var rowHeaderWidth = void 0;

      if (containerWidth === Infinity) {
        return containerWidth;
      }
      rowHeaderWidth = this.getRowHeaderWidth();

      if (rowHeaderWidth > 0) {
        return containerWidth - rowHeaderWidth;
      }

      return containerWidth;
    }

    /**
     * Creates:
     *  - rowsRenderCalculator (before draw, to qualify rows for rendering)
     *  - rowsVisibleCalculator (after draw, to measure which rows are actually visible)
     *
     * @returns {ViewportRowsCalculator}
     */

  }, {
    key: 'createRowsCalculator',
    value: function createRowsCalculator() {
      var _this2 = this;

      var visible = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var height = void 0;
      var pos = void 0;
      var fixedRowsTop = void 0;
      var scrollbarHeight = void 0;
      var fixedRowsBottom = void 0;
      var fixedRowsHeight = void 0;
      var totalRows = void 0;

      this.rowHeaderWidth = NaN;

      if (this.wot.wtSettings.settings.renderAllRows && !visible) {
        height = Infinity;
      } else {
        height = this.getViewportHeight();
      }
      pos = this.wot.wtOverlays.topOverlay.getScrollPosition() - this.wot.wtOverlays.topOverlay.getTableParentOffset();

      if (pos < 0) {
        pos = 0;
      }
      fixedRowsTop = this.wot.getSetting('fixedRowsTop');
      fixedRowsBottom = this.wot.getSetting('fixedRowsBottom');
      totalRows = this.wot.getSetting('totalRows');

      if (fixedRowsTop) {
        fixedRowsHeight = this.wot.wtOverlays.topOverlay.sumCellSizes(0, fixedRowsTop);
        pos += fixedRowsHeight;
        height -= fixedRowsHeight;
      }

      if (fixedRowsBottom && this.wot.wtOverlays.bottomOverlay.clone) {
        fixedRowsHeight = this.wot.wtOverlays.bottomOverlay.sumCellSizes(totalRows - fixedRowsBottom, totalRows);

        height -= fixedRowsHeight;
      }

      if (this.wot.wtTable.holder.clientHeight === this.wot.wtTable.holder.offsetHeight) {
        scrollbarHeight = 0;
      } else {
        scrollbarHeight = (0, _element.getScrollbarWidth)();
      }

      return new _viewportRows2.default(height, pos, this.wot.getSetting('totalRows'), function (sourceRow) {
        return _this2.wot.wtTable.getRowHeight(sourceRow);
      }, visible ? null : this.wot.wtSettings.settings.viewportRowCalculatorOverride, visible, scrollbarHeight);
    }

    /**
     * Creates:
     *  - columnsRenderCalculator (before draw, to qualify columns for rendering)
     *  - columnsVisibleCalculator (after draw, to measure which columns are actually visible)
     *
     * @returns {ViewportRowsCalculator}
     */

  }, {
    key: 'createColumnsCalculator',
    value: function createColumnsCalculator() {
      var _this3 = this;

      var visible = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var width = this.getViewportWidth();
      var pos = void 0;
      var fixedColumnsLeft = void 0;

      this.columnHeaderHeight = NaN;

      pos = this.wot.wtOverlays.leftOverlay.getScrollPosition() - this.wot.wtOverlays.leftOverlay.getTableParentOffset();

      if (pos < 0) {
        pos = 0;
      }
      fixedColumnsLeft = this.wot.getSetting('fixedColumnsLeft');

      if (fixedColumnsLeft) {
        var fixedColumnsWidth = this.wot.wtOverlays.leftOverlay.sumCellSizes(0, fixedColumnsLeft);
        pos += fixedColumnsWidth;
        width -= fixedColumnsWidth;
      }
      if (this.wot.wtTable.holder.clientWidth !== this.wot.wtTable.holder.offsetWidth) {
        width -= (0, _element.getScrollbarWidth)();
      }

      return new _viewportColumns2.default(width, pos, this.wot.getSetting('totalColumns'), function (sourceCol) {
        return _this3.wot.wtTable.getColumnWidth(sourceCol);
      }, visible ? null : this.wot.wtSettings.settings.viewportColumnCalculatorOverride, visible, this.wot.getSetting('stretchH'), function (stretchedWidth, column) {
        return _this3.wot.getSetting('onBeforeStretchingColumnWidth', stretchedWidth, column);
      });
    }

    /**
     * Creates rowsRenderCalculator and columnsRenderCalculator (before draw, to determine what rows and
     * cols should be rendered)
     *
     * @param fastDraw {Boolean} If `true`, will try to avoid full redraw and only update the border positions.
     *                           If `false` or `undefined`, will perform a full redraw
     * @returns fastDraw {Boolean} The fastDraw value, possibly modified
     */

  }, {
    key: 'createRenderCalculators',
    value: function createRenderCalculators() {
      var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (fastDraw) {
        var proposedRowsVisibleCalculator = this.createRowsCalculator(true);
        var proposedColumnsVisibleCalculator = this.createColumnsCalculator(true);

        if (!(this.areAllProposedVisibleRowsAlreadyRendered(proposedRowsVisibleCalculator) && this.areAllProposedVisibleColumnsAlreadyRendered(proposedColumnsVisibleCalculator))) {
          fastDraw = false;
        }
      }

      if (!fastDraw) {
        this.rowsRenderCalculator = this.createRowsCalculator();
        this.columnsRenderCalculator = this.createColumnsCalculator();
      }
      // delete temporarily to make sure that renderers always use rowsRenderCalculator, not rowsVisibleCalculator
      this.rowsVisibleCalculator = null;
      this.columnsVisibleCalculator = null;

      return fastDraw;
    }

    /**
     * Creates rowsVisibleCalculator and columnsVisibleCalculator (after draw, to determine what are
     * the actually visible rows and columns)
     */

  }, {
    key: 'createVisibleCalculators',
    value: function createVisibleCalculators() {
      this.rowsVisibleCalculator = this.createRowsCalculator(true);
      this.columnsVisibleCalculator = this.createColumnsCalculator(true);
    }

    /**
     * Returns information whether proposedRowsVisibleCalculator viewport
     * is contained inside rows rendered in previous draw (cached in rowsRenderCalculator)
     *
     * @param {Object} proposedRowsVisibleCalculator
     * @returns {Boolean} Returns `true` if all proposed visible rows are already rendered (meaning: redraw is not needed).
     *                    Returns `false` if at least one proposed visible row is not already rendered (meaning: redraw is needed)
     */

  }, {
    key: 'areAllProposedVisibleRowsAlreadyRendered',
    value: function areAllProposedVisibleRowsAlreadyRendered(proposedRowsVisibleCalculator) {
      if (this.rowsVisibleCalculator) {
        if (proposedRowsVisibleCalculator.startRow < this.rowsRenderCalculator.startRow || proposedRowsVisibleCalculator.startRow === this.rowsRenderCalculator.startRow && proposedRowsVisibleCalculator.startRow > 0) {
          return false;
        } else if (proposedRowsVisibleCalculator.endRow > this.rowsRenderCalculator.endRow || proposedRowsVisibleCalculator.endRow === this.rowsRenderCalculator.endRow && proposedRowsVisibleCalculator.endRow < this.wot.getSetting('totalRows') - 1) {
          return false;
        }
        return true;
      }

      return false;
    }

    /**
     * Returns information whether proposedColumnsVisibleCalculator viewport
     * is contained inside column rendered in previous draw (cached in columnsRenderCalculator)
     *
     * @param {Object} proposedColumnsVisibleCalculator
     * @returns {Boolean} Returns `true` if all proposed visible columns are already rendered (meaning: redraw is not needed).
     *                    Returns `false` if at least one proposed visible column is not already rendered (meaning: redraw is needed)
     */

  }, {
    key: 'areAllProposedVisibleColumnsAlreadyRendered',
    value: function areAllProposedVisibleColumnsAlreadyRendered(proposedColumnsVisibleCalculator) {
      if (this.columnsVisibleCalculator) {
        if (proposedColumnsVisibleCalculator.startColumn < this.columnsRenderCalculator.startColumn || proposedColumnsVisibleCalculator.startColumn === this.columnsRenderCalculator.startColumn && proposedColumnsVisibleCalculator.startColumn > 0) {
          return false;
        } else if (proposedColumnsVisibleCalculator.endColumn > this.columnsRenderCalculator.endColumn || proposedColumnsVisibleCalculator.endColumn === this.columnsRenderCalculator.endColumn && proposedColumnsVisibleCalculator.endColumn < this.wot.getSetting('totalColumns') - 1) {
          return false;
        }
        return true;
      }

      return false;
    }

    /**
     * Resets values in keys of the hasOversizedColumnHeadersMarked object after updateSettings.
     */

  }, {
    key: 'resetHasOversizedColumnHeadersMarked',
    value: function resetHasOversizedColumnHeadersMarked() {
      (0, _object.objectEach)(this.hasOversizedColumnHeadersMarked, function (value, key, object) {
        object[key] = void 0;
      });
    }
  }]);

  return Viewport;
}();

exports.default = Viewport;

/***/ }),
/* 302 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _event = __webpack_require__(12);

var _object = __webpack_require__(1);

var _browser = __webpack_require__(28);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _coords = __webpack_require__(53);

var _coords2 = _interopRequireDefault(_coords);

var _base = __webpack_require__(35);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 *
 */
var Border = function () {
  /**
   * @param {Walkontable} wotInstance
   * @param {Object} settings
   */
  function Border(wotInstance, settings) {
    _classCallCheck(this, Border);

    if (!settings) {
      return;
    }
    this.eventManager = new _eventManager2.default(wotInstance);
    this.instance = wotInstance;
    this.wot = wotInstance;
    this.settings = settings;
    this.mouseDown = false;
    this.main = null;

    this.top = null;
    this.left = null;
    this.bottom = null;
    this.right = null;

    this.topStyle = null;
    this.leftStyle = null;
    this.bottomStyle = null;
    this.rightStyle = null;

    this.cornerDefaultStyle = {
      width: '5px',
      height: '5px',
      borderWidth: '2px',
      borderStyle: 'solid',
      borderColor: '#FFF'
    };
    this.corner = null;
    this.cornerStyle = null;

    this.createBorders(settings);
    this.registerListeners();
  }

  /**
   * Register all necessary events
   */


  _createClass(Border, [{
    key: 'registerListeners',
    value: function registerListeners() {
      var _this2 = this;

      this.eventManager.addEventListener(document.body, 'mousedown', function () {
        return _this2.onMouseDown();
      });
      this.eventManager.addEventListener(document.body, 'mouseup', function () {
        return _this2.onMouseUp();
      });

      var _loop = function _loop(c, len) {
        _this2.eventManager.addEventListener(_this2.main.childNodes[c], 'mouseenter', function (event) {
          return _this2.onMouseEnter(event, _this2.main.childNodes[c]);
        });
      };

      for (var c = 0, len = this.main.childNodes.length; c < len; c++) {
        _loop(c, len);
      }
    }

    /**
     * Mouse down listener
     *
     * @private
     */

  }, {
    key: 'onMouseDown',
    value: function onMouseDown() {
      this.mouseDown = true;
    }

    /**
     * Mouse up listener
     *
     * @private
     */

  }, {
    key: 'onMouseUp',
    value: function onMouseUp() {
      this.mouseDown = false;
    }

    /**
     * Mouse enter listener for fragment selection functionality.
     *
     * @private
     * @param {Event} event Dom event
     * @param {HTMLElement} parentElement Part of border element.
     */

  }, {
    key: 'onMouseEnter',
    value: function onMouseEnter(event, parentElement) {
      if (!this.mouseDown || !this.wot.getSetting('hideBorderOnMouseDownOver')) {
        return;
      }
      event.preventDefault();
      (0, _event.stopImmediatePropagation)(event);

      var _this = this;
      var bounds = parentElement.getBoundingClientRect();
      // Hide border to prevents selection jumping when fragmentSelection is enabled.
      parentElement.style.display = 'none';

      function isOutside(event) {
        if (event.clientY < Math.floor(bounds.top)) {
          return true;
        }
        if (event.clientY > Math.ceil(bounds.top + bounds.height)) {
          return true;
        }
        if (event.clientX < Math.floor(bounds.left)) {
          return true;
        }
        if (event.clientX > Math.ceil(bounds.left + bounds.width)) {
          return true;
        }
      }

      function handler(event) {
        if (isOutside(event)) {
          _this.eventManager.removeEventListener(document.body, 'mousemove', handler);
          parentElement.style.display = 'block';
        }
      }

      this.eventManager.addEventListener(document.body, 'mousemove', handler);
    }

    /**
     * Create border elements
     *
     * @param {Object} settings
     */

  }, {
    key: 'createBorders',
    value: function createBorders(settings) {
      this.main = document.createElement('div');

      var borderDivs = ['top', 'left', 'bottom', 'right', 'corner'];
      var style = this.main.style;
      style.position = 'absolute';
      style.top = 0;
      style.left = 0;

      for (var i = 0; i < 5; i++) {
        var position = borderDivs[i];
        var div = document.createElement('div');
        div.className = 'wtBorder ' + (this.settings.className || ''); // + borderDivs[i];

        if (this.settings[position] && this.settings[position].hide) {
          div.className += ' hidden';
        }
        style = div.style;
        style.backgroundColor = this.settings[position] && this.settings[position].color ? this.settings[position].color : settings.border.color;
        style.height = this.settings[position] && this.settings[position].width ? this.settings[position].width + 'px' : settings.border.width + 'px';
        style.width = this.settings[position] && this.settings[position].width ? this.settings[position].width + 'px' : settings.border.width + 'px';

        this.main.appendChild(div);
      }
      this.top = this.main.childNodes[0];
      this.left = this.main.childNodes[1];
      this.bottom = this.main.childNodes[2];
      this.right = this.main.childNodes[3];

      this.topStyle = this.top.style;
      this.leftStyle = this.left.style;
      this.bottomStyle = this.bottom.style;
      this.rightStyle = this.right.style;

      this.corner = this.main.childNodes[4];
      this.corner.className += ' corner';
      this.cornerStyle = this.corner.style;
      this.cornerStyle.width = this.cornerDefaultStyle.width;
      this.cornerStyle.height = this.cornerDefaultStyle.height;
      this.cornerStyle.border = [this.cornerDefaultStyle.borderWidth, this.cornerDefaultStyle.borderStyle, this.cornerDefaultStyle.borderColor].join(' ');

      if ((0, _browser.isMobileBrowser)()) {
        this.createMultipleSelectorHandles();
      }
      this.disappear();

      if (!this.wot.wtTable.bordersHolder) {
        this.wot.wtTable.bordersHolder = document.createElement('div');
        this.wot.wtTable.bordersHolder.className = 'htBorders';
        this.wot.wtTable.spreader.appendChild(this.wot.wtTable.bordersHolder);
      }
      this.wot.wtTable.bordersHolder.insertBefore(this.main, this.wot.wtTable.bordersHolder.firstChild);
    }

    /**
     * Create multiple selector handler for mobile devices
     */

  }, {
    key: 'createMultipleSelectorHandles',
    value: function createMultipleSelectorHandles() {
      this.selectionHandles = {
        topLeft: document.createElement('DIV'),
        topLeftHitArea: document.createElement('DIV'),
        bottomRight: document.createElement('DIV'),
        bottomRightHitArea: document.createElement('DIV')
      };
      var width = 10;
      var hitAreaWidth = 40;

      this.selectionHandles.topLeft.className = 'topLeftSelectionHandle';
      this.selectionHandles.topLeftHitArea.className = 'topLeftSelectionHandle-HitArea';
      this.selectionHandles.bottomRight.className = 'bottomRightSelectionHandle';
      this.selectionHandles.bottomRightHitArea.className = 'bottomRightSelectionHandle-HitArea';

      this.selectionHandles.styles = {
        topLeft: this.selectionHandles.topLeft.style,
        topLeftHitArea: this.selectionHandles.topLeftHitArea.style,
        bottomRight: this.selectionHandles.bottomRight.style,
        bottomRightHitArea: this.selectionHandles.bottomRightHitArea.style
      };

      var hitAreaStyle = {
        position: 'absolute',
        height: hitAreaWidth + 'px',
        width: hitAreaWidth + 'px',
        'border-radius': parseInt(hitAreaWidth / 1.5, 10) + 'px'
      };

      for (var prop in hitAreaStyle) {
        if ((0, _object.hasOwnProperty)(hitAreaStyle, prop)) {
          this.selectionHandles.styles.bottomRightHitArea[prop] = hitAreaStyle[prop];
          this.selectionHandles.styles.topLeftHitArea[prop] = hitAreaStyle[prop];
        }
      }

      var handleStyle = {
        position: 'absolute',
        height: width + 'px',
        width: width + 'px',
        'border-radius': parseInt(width / 1.5, 10) + 'px',
        background: '#F5F5FF',
        border: '1px solid #4285c8'
      };

      for (var _prop in handleStyle) {
        if ((0, _object.hasOwnProperty)(handleStyle, _prop)) {
          this.selectionHandles.styles.bottomRight[_prop] = handleStyle[_prop];
          this.selectionHandles.styles.topLeft[_prop] = handleStyle[_prop];
        }
      }
      this.main.appendChild(this.selectionHandles.topLeft);
      this.main.appendChild(this.selectionHandles.bottomRight);
      this.main.appendChild(this.selectionHandles.topLeftHitArea);
      this.main.appendChild(this.selectionHandles.bottomRightHitArea);
    }
  }, {
    key: 'isPartRange',
    value: function isPartRange(row, col) {
      if (this.wot.selections.area.cellRange) {
        if (row != this.wot.selections.area.cellRange.to.row || col != this.wot.selections.area.cellRange.to.col) {
          return true;
        }
      }

      return false;
    }
  }, {
    key: 'updateMultipleSelectionHandlesPosition',
    value: function updateMultipleSelectionHandlesPosition(row, col, top, left, width, height) {
      var handleWidth = parseInt(this.selectionHandles.styles.topLeft.width, 10);
      var hitAreaWidth = parseInt(this.selectionHandles.styles.topLeftHitArea.width, 10);

      this.selectionHandles.styles.topLeft.top = parseInt(top - handleWidth, 10) + 'px';
      this.selectionHandles.styles.topLeft.left = parseInt(left - handleWidth, 10) + 'px';

      this.selectionHandles.styles.topLeftHitArea.top = parseInt(top - hitAreaWidth / 4 * 3, 10) + 'px';
      this.selectionHandles.styles.topLeftHitArea.left = parseInt(left - hitAreaWidth / 4 * 3, 10) + 'px';

      this.selectionHandles.styles.bottomRight.top = parseInt(top + height, 10) + 'px';
      this.selectionHandles.styles.bottomRight.left = parseInt(left + width, 10) + 'px';

      this.selectionHandles.styles.bottomRightHitArea.top = parseInt(top + height - hitAreaWidth / 4, 10) + 'px';
      this.selectionHandles.styles.bottomRightHitArea.left = parseInt(left + width - hitAreaWidth / 4, 10) + 'px';

      if (this.settings.border.multipleSelectionHandlesVisible && this.settings.border.multipleSelectionHandlesVisible()) {
        this.selectionHandles.styles.topLeft.display = 'block';
        this.selectionHandles.styles.topLeftHitArea.display = 'block';

        if (this.isPartRange(row, col)) {
          this.selectionHandles.styles.bottomRight.display = 'none';
          this.selectionHandles.styles.bottomRightHitArea.display = 'none';
        } else {
          this.selectionHandles.styles.bottomRight.display = 'block';
          this.selectionHandles.styles.bottomRightHitArea.display = 'block';
        }
      } else {
        this.selectionHandles.styles.topLeft.display = 'none';
        this.selectionHandles.styles.bottomRight.display = 'none';
        this.selectionHandles.styles.topLeftHitArea.display = 'none';
        this.selectionHandles.styles.bottomRightHitArea.display = 'none';
      }

      if (row == this.wot.wtSettings.getSetting('fixedRowsTop') || col == this.wot.wtSettings.getSetting('fixedColumnsLeft')) {
        this.selectionHandles.styles.topLeft.zIndex = '9999';
        this.selectionHandles.styles.topLeftHitArea.zIndex = '9999';
      } else {
        this.selectionHandles.styles.topLeft.zIndex = '';
        this.selectionHandles.styles.topLeftHitArea.zIndex = '';
      }
    }

    /**
     * Show border around one or many cells
     *
     * @param {Array} corners
     */

  }, {
    key: 'appear',
    value: function appear(corners) {
      if (this.disabled) {
        return;
      }
      var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width, fromRow, fromColumn, toRow, toColumn, trimmingContainer, cornerOverlappingContainer, ilen;

      ilen = this.wot.wtTable.getRenderedRowsCount();

      for (var i = 0; i < ilen; i++) {
        var s = this.wot.wtTable.rowFilter.renderedToSource(i);

        if (s >= corners[0] && s <= corners[2]) {
          fromRow = s;
          break;
        }
      }

      for (var _i = ilen - 1; _i >= 0; _i--) {
        var _s = this.wot.wtTable.rowFilter.renderedToSource(_i);

        if (_s >= corners[0] && _s <= corners[2]) {
          toRow = _s;
          break;
        }
      }

      ilen = this.wot.wtTable.getRenderedColumnsCount();

      for (var _i2 = 0; _i2 < ilen; _i2++) {
        var _s2 = this.wot.wtTable.columnFilter.renderedToSource(_i2);

        if (_s2 >= corners[1] && _s2 <= corners[3]) {
          fromColumn = _s2;
          break;
        }
      }

      for (var _i3 = ilen - 1; _i3 >= 0; _i3--) {
        var _s3 = this.wot.wtTable.columnFilter.renderedToSource(_i3);

        if (_s3 >= corners[1] && _s3 <= corners[3]) {
          toColumn = _s3;
          break;
        }
      }
      if (fromRow === void 0 || fromColumn === void 0) {
        this.disappear();

        return;
      }
      isMultiple = fromRow !== toRow || fromColumn !== toColumn;
      fromTD = this.wot.wtTable.getCell(new _coords2.default(fromRow, fromColumn));
      toTD = isMultiple ? this.wot.wtTable.getCell(new _coords2.default(toRow, toColumn)) : fromTD;
      fromOffset = (0, _element.offset)(fromTD);
      toOffset = isMultiple ? (0, _element.offset)(toTD) : fromOffset;
      containerOffset = (0, _element.offset)(this.wot.wtTable.TABLE);

      minTop = fromOffset.top;
      height = toOffset.top + (0, _element.outerHeight)(toTD) - minTop;
      minLeft = fromOffset.left;
      width = toOffset.left + (0, _element.outerWidth)(toTD) - minLeft;

      top = minTop - containerOffset.top - 1;
      left = minLeft - containerOffset.left - 1;
      var style = (0, _element.getComputedStyle)(fromTD);

      if (parseInt(style.borderTopWidth, 10) > 0) {
        top += 1;
        height = height > 0 ? height - 1 : 0;
      }
      if (parseInt(style.borderLeftWidth, 10) > 0) {
        left += 1;
        width = width > 0 ? width - 1 : 0;
      }

      this.topStyle.top = top + 'px';
      this.topStyle.left = left + 'px';
      this.topStyle.width = width + 'px';
      this.topStyle.display = 'block';

      this.leftStyle.top = top + 'px';
      this.leftStyle.left = left + 'px';
      this.leftStyle.height = height + 'px';
      this.leftStyle.display = 'block';

      var delta = Math.floor(this.settings.border.width / 2);

      this.bottomStyle.top = top + height - delta + 'px';
      this.bottomStyle.left = left + 'px';
      this.bottomStyle.width = width + 'px';
      this.bottomStyle.display = 'block';

      this.rightStyle.top = top + 'px';
      this.rightStyle.left = left + width - delta + 'px';
      this.rightStyle.height = height + 1 + 'px';
      this.rightStyle.display = 'block';

      if ((0, _browser.isMobileBrowser)() || !this.hasSetting(this.settings.border.cornerVisible) || this.isPartRange(toRow, toColumn)) {
        this.cornerStyle.display = 'none';
      } else {
        this.cornerStyle.top = top + height - 4 + 'px';
        this.cornerStyle.left = left + width - 4 + 'px';
        this.cornerStyle.borderRightWidth = this.cornerDefaultStyle.borderWidth;
        this.cornerStyle.width = this.cornerDefaultStyle.width;

        // Hide the fill handle, so the possible further adjustments won't force unneeded scrollbars.
        this.cornerStyle.display = 'none';

        trimmingContainer = (0, _element.getTrimmingContainer)(this.wot.wtTable.TABLE);

        if (toColumn === this.wot.getSetting('totalColumns') - 1) {
          cornerOverlappingContainer = toTD.offsetLeft + (0, _element.outerWidth)(toTD) + parseInt(this.cornerDefaultStyle.width, 10) / 2 >= (0, _element.innerWidth)(trimmingContainer);

          if (cornerOverlappingContainer) {
            this.cornerStyle.left = Math.floor(left + width - 3 - parseInt(this.cornerDefaultStyle.width, 10) / 2) + 'px';
            this.cornerStyle.borderRightWidth = 0;
          }
        }

        if (toRow === this.wot.getSetting('totalRows') - 1) {
          cornerOverlappingContainer = toTD.offsetTop + (0, _element.outerHeight)(toTD) + parseInt(this.cornerDefaultStyle.height, 10) / 2 >= (0, _element.innerHeight)(trimmingContainer);

          if (cornerOverlappingContainer) {
            this.cornerStyle.top = Math.floor(top + height - 3 - parseInt(this.cornerDefaultStyle.height, 10) / 2) + 'px';
            this.cornerStyle.borderBottomWidth = 0;
          }
        }

        this.cornerStyle.display = 'block';
      }

      if ((0, _browser.isMobileBrowser)()) {
        this.updateMultipleSelectionHandlesPosition(fromRow, fromColumn, top, left, width, height);
      }
    }

    /**
     * Hide border
     */

  }, {
    key: 'disappear',
    value: function disappear() {
      this.topStyle.display = 'none';
      this.leftStyle.display = 'none';
      this.bottomStyle.display = 'none';
      this.rightStyle.display = 'none';
      this.cornerStyle.display = 'none';

      if ((0, _browser.isMobileBrowser)()) {
        this.selectionHandles.styles.topLeft.display = 'none';
        this.selectionHandles.styles.bottomRight.display = 'none';
      }
    }

    /**
     * @param {Function} setting
     * @returns {*}
     */

  }, {
    key: 'hasSetting',
    value: function hasSetting(setting) {
      if (typeof setting === 'function') {
        return setting();
      }

      return !!setting;
    }
  }]);

  return Border;
}();

exports.default = Border;

/***/ }),
/* 303 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _unicode = __webpack_require__(20);

var _mixed = __webpack_require__(17);

var _string = __webpack_require__(36);

var _array = __webpack_require__(2);

var _element = __webpack_require__(0);

var _handsontableEditor = __webpack_require__(304);

var _handsontableEditor2 = _interopRequireDefault(_handsontableEditor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var AutocompleteEditor = _handsontableEditor2.default.prototype.extend();

/**
 * @private
 * @editor AutocompleteEditor
 * @class AutocompleteEditor
 * @dependencies HandsontableEditor
 */
AutocompleteEditor.prototype.init = function () {
  _handsontableEditor2.default.prototype.init.apply(this, arguments);
  this.query = null;
  this.strippedChoices = [];
  this.rawChoices = [];
};

AutocompleteEditor.prototype.getValue = function () {
  var _this2 = this;

  var selectedValue = this.rawChoices.find(function (value) {
    var strippedValue = _this2.stripValueIfNeeded(value);

    return strippedValue === _this2.TEXTAREA.value;
  });

  if ((0, _mixed.isDefined)(selectedValue)) {
    return selectedValue;
  }

  return this.TEXTAREA.value;
};

AutocompleteEditor.prototype.createElements = function () {
  _handsontableEditor2.default.prototype.createElements.apply(this, arguments);

  (0, _element.addClass)(this.htContainer, 'autocompleteEditor');
  (0, _element.addClass)(this.htContainer, window.navigator.platform.indexOf('Mac') === -1 ? '' : 'htMacScroll');
};

var skipOne = false;
function onBeforeKeyDown(event) {
  skipOne = false;
  var editor = this.getActiveEditor();

  if ((0, _unicode.isPrintableChar)(event.keyCode) || event.keyCode === _unicode.KEY_CODES.BACKSPACE || event.keyCode === _unicode.KEY_CODES.DELETE || event.keyCode === _unicode.KEY_CODES.INSERT) {
    var timeOffset = 0;

    // on ctl+c / cmd+c don't update suggestion list
    if (event.keyCode === _unicode.KEY_CODES.C && (event.ctrlKey || event.metaKey)) {
      return;
    }
    if (!editor.isOpened()) {
      timeOffset += 10;
    }

    if (editor.htEditor) {
      editor.instance._registerTimeout(setTimeout(function () {
        editor.queryChoices(editor.TEXTAREA.value);
        skipOne = true;
      }, timeOffset));
    }
  }
}

AutocompleteEditor.prototype.prepare = function () {
  this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
  _handsontableEditor2.default.prototype.prepare.apply(this, arguments);
};

AutocompleteEditor.prototype.open = function () {
  // Ugly fix for handsontable which grab window object for autocomplete scroll listener instead table element.
  this.TEXTAREA_PARENT.style.overflow = 'auto';
  _handsontableEditor2.default.prototype.open.apply(this, arguments);
  this.TEXTAREA_PARENT.style.overflow = '';

  var choicesListHot = this.htEditor.getInstance();
  var _this = this;
  var trimDropdown = this.cellProperties.trimDropdown === void 0 ? true : this.cellProperties.trimDropdown;

  this.TEXTAREA.style.visibility = 'visible';
  this.focus();

  choicesListHot.updateSettings({
    colWidths: trimDropdown ? [(0, _element.outerWidth)(this.TEXTAREA) - 2] : void 0,
    width: trimDropdown ? (0, _element.outerWidth)(this.TEXTAREA) + (0, _element.getScrollbarWidth)() + 2 : void 0,
    afterRenderer: function afterRenderer(TD, row, col, prop, value, cellProperties) {
      var _this$cellProperties = _this.cellProperties,
          filteringCaseSensitive = _this$cellProperties.filteringCaseSensitive,
          allowHtml = _this$cellProperties.allowHtml;

      var indexOfMatch = void 0;
      var match = void 0;

      value = (0, _mixed.stringify)(value);

      if (value && !allowHtml) {
        indexOfMatch = filteringCaseSensitive === true ? value.indexOf(this.query) : value.toLowerCase().indexOf(_this.query.toLowerCase());

        if (indexOfMatch !== -1) {
          match = value.substr(indexOfMatch, _this.query.length);
          value = value.replace(match, '<strong>' + match + '</strong>');
        }
      }
      TD.innerHTML = value;
    },

    autoColumnSize: true,
    modifyColWidth: function modifyColWidth(width, col) {
      // workaround for <strong> text overlapping the dropdown, not really accurate
      var autoWidths = this.getPlugin('autoColumnSize').widths;

      if (autoWidths[col]) {
        width = autoWidths[col];
      }

      return trimDropdown ? width : width + 15;
    }
  });

  // Add additional space for autocomplete holder
  this.htEditor.view.wt.wtTable.holder.parentNode.style['padding-right'] = (0, _element.getScrollbarWidth)() + 2 + 'px';

  if (skipOne) {
    skipOne = false;
  }

  _this.instance._registerTimeout(setTimeout(function () {
    _this.queryChoices(_this.TEXTAREA.value);
  }, 0));
};

AutocompleteEditor.prototype.close = function () {
  _handsontableEditor2.default.prototype.close.apply(this, arguments);
};
AutocompleteEditor.prototype.queryChoices = function (query) {
  var _this3 = this;

  this.query = query;
  var source = this.cellProperties.source;

  if (typeof source == 'function') {
    source.call(this.cellProperties, query, function (choices) {
      _this3.rawChoices = choices;
      _this3.updateChoicesList(_this3.stripValuesIfNeeded(choices));
    });
  } else if (Array.isArray(source)) {
    this.rawChoices = source;
    this.updateChoicesList(this.stripValuesIfNeeded(source));
  } else {
    this.updateChoicesList([]);
  }
};

AutocompleteEditor.prototype.updateChoicesList = function (choices) {
  var pos = (0, _element.getCaretPosition)(this.TEXTAREA);
  var endPos = (0, _element.getSelectionEndPosition)(this.TEXTAREA);
  var sortByRelevanceSetting = this.cellProperties.sortByRelevance;
  var filterSetting = this.cellProperties.filter;
  var orderByRelevance = null;
  var highlightIndex = null;

  if (sortByRelevanceSetting) {
    orderByRelevance = AutocompleteEditor.sortByRelevance(this.stripValueIfNeeded(this.getValue()), choices, this.cellProperties.filteringCaseSensitive);
  }
  var orderByRelevanceLength = Array.isArray(orderByRelevance) ? orderByRelevance.length : 0;

  if (filterSetting === false) {
    if (orderByRelevanceLength) {
      highlightIndex = orderByRelevance[0];
    }
  } else {
    var sorted = [];

    for (var i = 0, choicesCount = choices.length; i < choicesCount; i++) {
      if (sortByRelevanceSetting && orderByRelevanceLength <= i) {
        break;
      }
      if (orderByRelevanceLength) {
        sorted.push(choices[orderByRelevance[i]]);
      } else {
        sorted.push(choices[i]);
      }
    }

    highlightIndex = 0;
    choices = sorted;
  }

  this.strippedChoices = choices;
  this.htEditor.loadData((0, _array.pivot)([choices]));

  this.updateDropdownHeight();

  this.flipDropdownIfNeeded();

  if (this.cellProperties.strict === true) {
    this.highlightBestMatchingChoice(highlightIndex);
  }

  this.instance.listen(false);

  (0, _element.setCaretPosition)(this.TEXTAREA, pos, pos === endPos ? void 0 : endPos);
};

AutocompleteEditor.prototype.flipDropdownIfNeeded = function () {
  var textareaOffset = (0, _element.offset)(this.TEXTAREA);
  var textareaHeight = (0, _element.outerHeight)(this.TEXTAREA);
  var dropdownHeight = this.getDropdownHeight();
  var trimmingContainer = (0, _element.getTrimmingContainer)(this.instance.view.wt.wtTable.TABLE);
  var trimmingContainerScrollTop = trimmingContainer.scrollTop;
  var headersHeight = (0, _element.outerHeight)(this.instance.view.wt.wtTable.THEAD);
  var containerOffset = {
    row: 0,
    col: 0
  };

  if (trimmingContainer !== window) {
    containerOffset = (0, _element.offset)(trimmingContainer);
  }

  var spaceAbove = textareaOffset.top - containerOffset.top - headersHeight + trimmingContainerScrollTop;
  var spaceBelow = trimmingContainer.scrollHeight - spaceAbove - headersHeight - textareaHeight;
  var flipNeeded = dropdownHeight > spaceBelow && spaceAbove > spaceBelow;

  if (flipNeeded) {
    this.flipDropdown(dropdownHeight);
  } else {
    this.unflipDropdown();
  }

  this.limitDropdownIfNeeded(flipNeeded ? spaceAbove : spaceBelow, dropdownHeight);

  return flipNeeded;
};

AutocompleteEditor.prototype.limitDropdownIfNeeded = function (spaceAvailable, dropdownHeight) {
  if (dropdownHeight > spaceAvailable) {
    var tempHeight = 0;
    var i = 0;
    var lastRowHeight = 0;
    var height = null;

    do {
      lastRowHeight = this.htEditor.getRowHeight(i) || this.htEditor.view.wt.wtSettings.settings.defaultRowHeight;
      tempHeight += lastRowHeight;
      i++;
    } while (tempHeight < spaceAvailable);

    height = tempHeight - lastRowHeight;

    if (this.htEditor.flipped) {
      this.htEditor.rootElement.style.top = parseInt(this.htEditor.rootElement.style.top, 10) + dropdownHeight - height + 'px';
    }

    this.setDropdownHeight(tempHeight - lastRowHeight);
  }
};

AutocompleteEditor.prototype.flipDropdown = function (dropdownHeight) {
  var dropdownStyle = this.htEditor.rootElement.style;

  dropdownStyle.position = 'absolute';
  dropdownStyle.top = -dropdownHeight + 'px';

  this.htEditor.flipped = true;
};

AutocompleteEditor.prototype.unflipDropdown = function () {
  var dropdownStyle = this.htEditor.rootElement.style;

  if (dropdownStyle.position === 'absolute') {
    dropdownStyle.position = '';
    dropdownStyle.top = '';
  }

  this.htEditor.flipped = void 0;
};

AutocompleteEditor.prototype.updateDropdownHeight = function () {
  var currentDropdownWidth = this.htEditor.getColWidth(0) + (0, _element.getScrollbarWidth)() + 2;
  var trimDropdown = this.cellProperties.trimDropdown;

  this.htEditor.updateSettings({
    height: this.getDropdownHeight(),
    width: trimDropdown ? void 0 : currentDropdownWidth
  });

  this.htEditor.view.wt.wtTable.alignOverlaysWithTrimmingContainer();
};

AutocompleteEditor.prototype.setDropdownHeight = function (height) {
  this.htEditor.updateSettings({
    height: height
  });
};

AutocompleteEditor.prototype.finishEditing = function (restoreOriginalValue) {
  if (!restoreOriginalValue) {
    this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
  }
  _handsontableEditor2.default.prototype.finishEditing.apply(this, arguments);
};

AutocompleteEditor.prototype.highlightBestMatchingChoice = function (index) {
  if (typeof index === 'number') {
    this.htEditor.selectCell(index, 0, void 0, void 0, void 0, false);
  } else {
    this.htEditor.deselectCell();
  }
};

/**
 * Filters and sorts by relevance
 * @param value
 * @param choices
 * @param caseSensitive
 * @returns {Array} array of indexes in original choices array
 */
AutocompleteEditor.sortByRelevance = function (value, choices, caseSensitive) {
  var choicesRelevance = [];
  var currentItem = void 0;
  var valueLength = value.length;
  var valueIndex = void 0;
  var charsLeft = void 0;
  var result = [];
  var i = void 0;
  var choicesCount = choices.length;

  if (valueLength === 0) {
    for (i = 0; i < choicesCount; i++) {
      result.push(i);
    }
    return result;
  }

  for (i = 0; i < choicesCount; i++) {
    currentItem = (0, _string.stripTags)((0, _mixed.stringify)(choices[i]));

    if (caseSensitive) {
      valueIndex = currentItem.indexOf(value);
    } else {
      valueIndex = currentItem.toLowerCase().indexOf(value.toLowerCase());
    }

    if (valueIndex !== -1) {
      charsLeft = currentItem.length - valueIndex - valueLength;

      choicesRelevance.push({
        baseIndex: i,
        index: valueIndex,
        charsLeft: charsLeft,
        value: currentItem
      });
    }
  }

  choicesRelevance.sort(function (a, b) {

    if (b.index === -1) {
      return -1;
    }
    if (a.index === -1) {
      return 1;
    }

    if (a.index < b.index) {
      return -1;
    } else if (b.index < a.index) {
      return 1;
    } else if (a.index === b.index) {
      if (a.charsLeft < b.charsLeft) {
        return -1;
      } else if (a.charsLeft > b.charsLeft) {
        return 1;
      }
    }

    return 0;
  });

  for (i = 0, choicesCount = choicesRelevance.length; i < choicesCount; i++) {
    result.push(choicesRelevance[i].baseIndex);
  }

  return result;
};

AutocompleteEditor.prototype.getDropdownHeight = function () {
  var firstRowHeight = this.htEditor.getInstance().getRowHeight(0) || 23;
  var visibleRows = this.cellProperties.visibleRows;

  return this.strippedChoices.length >= visibleRows ? visibleRows * firstRowHeight : this.strippedChoices.length * firstRowHeight + 8;
};

AutocompleteEditor.prototype.stripValueIfNeeded = function (value) {
  return this.stripValuesIfNeeded([value])[0];
};

AutocompleteEditor.prototype.stripValuesIfNeeded = function (values) {
  var allowHtml = this.cellProperties.allowHtml;


  var stringifiedValues = (0, _array.arrayMap)(values, function (value) {
    return (0, _mixed.stringify)(value);
  });
  var strippedValues = (0, _array.arrayMap)(stringifiedValues, function (value) {
    return allowHtml ? value : (0, _string.stripTags)(value);
  });

  return strippedValues;
};

AutocompleteEditor.prototype.allowKeyEventPropagation = function (keyCode) {
  var selected = { row: this.htEditor.getSelectedRange() ? this.htEditor.getSelectedRange().from.row : -1 };
  var allowed = false;

  if (keyCode === _unicode.KEY_CODES.ARROW_DOWN && selected.row > 0 && selected.row < this.htEditor.countRows() - 1) {
    allowed = true;
  }
  if (keyCode === _unicode.KEY_CODES.ARROW_UP && selected.row > -1) {
    allowed = true;
  }

  return allowed;
};

AutocompleteEditor.prototype.discardEditor = function (result) {
  _handsontableEditor2.default.prototype.discardEditor.apply(this, arguments);

  this.instance.view.render();
};

exports.default = AutocompleteEditor;

/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _unicode = __webpack_require__(20);

var _object = __webpack_require__(1);

var _element = __webpack_require__(0);

var _event = __webpack_require__(12);

var _textEditor = __webpack_require__(54);

var _textEditor2 = _interopRequireDefault(_textEditor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var HandsontableEditor = _textEditor2.default.prototype.extend();

/**
 * @private
 * @editor HandsontableEditor
 * @class HandsontableEditor
 * @dependencies TextEditor
 */
HandsontableEditor.prototype.createElements = function () {
  _textEditor2.default.prototype.createElements.apply(this, arguments);

  var DIV = document.createElement('DIV');
  DIV.className = 'handsontableEditor';
  this.TEXTAREA_PARENT.appendChild(DIV);

  this.htContainer = DIV;
  this.assignHooks();
};

HandsontableEditor.prototype.prepare = function (td, row, col, prop, value, cellProperties) {
  _textEditor2.default.prototype.prepare.apply(this, arguments);

  var parent = this;
  var options = {
    startRows: 0,
    startCols: 0,
    minRows: 0,
    minCols: 0,
    className: 'listbox',
    copyPaste: false,
    autoColumnSize: false,
    autoRowSize: false,
    readOnly: true,
    fillHandle: false,
    afterOnCellMouseDown: function afterOnCellMouseDown(_, coords) {
      var value = this.getSourceData(coords.row, coords.col);

      // if the value is undefined then it means we don't want to set the value
      if (value !== void 0) {
        parent.setValue(value);
      }
      parent.instance.destroyEditor();
    }
  };

  if (this.cellProperties.handsontable) {
    (0, _object.extend)(options, cellProperties.handsontable);
  }
  this.htOptions = options;
};

var onBeforeKeyDown = function onBeforeKeyDown(event) {
  if ((0, _event.isImmediatePropagationStopped)(event)) {
    return;
  }
  var editor = this.getActiveEditor();

  var innerHOT = editor.htEditor.getInstance();

  var rowToSelect;
  var selectedRow;

  if (event.keyCode == _unicode.KEY_CODES.ARROW_DOWN) {
    if (!innerHOT.getSelected() && !innerHOT.flipped) {
      rowToSelect = 0;
    } else if (innerHOT.getSelected()) {
      if (innerHOT.flipped) {
        rowToSelect = innerHOT.getSelected()[0] + 1;
      } else if (!innerHOT.flipped) {
        selectedRow = innerHOT.getSelected()[0];
        var lastRow = innerHOT.countRows() - 1;
        rowToSelect = Math.min(lastRow, selectedRow + 1);
      }
    }
  } else if (event.keyCode == _unicode.KEY_CODES.ARROW_UP) {
    if (!innerHOT.getSelected() && innerHOT.flipped) {
      rowToSelect = innerHOT.countRows() - 1;
    } else if (innerHOT.getSelected()) {
      if (innerHOT.flipped) {
        selectedRow = innerHOT.getSelected()[0];
        rowToSelect = Math.max(0, selectedRow - 1);
      } else {
        selectedRow = innerHOT.getSelected()[0];
        rowToSelect = selectedRow - 1;
      }
    }
  }

  if (rowToSelect !== void 0) {
    if (rowToSelect < 0 || innerHOT.flipped && rowToSelect > innerHOT.countRows() - 1) {
      innerHOT.deselectCell();
    } else {
      innerHOT.selectCell(rowToSelect, 0);
    }
    if (innerHOT.getData().length) {
      event.preventDefault();
      (0, _event.stopImmediatePropagation)(event);

      editor.instance.listen();
      editor.TEXTAREA.focus();
    }
  }
};

HandsontableEditor.prototype.open = function () {
  this.instance.addHook('beforeKeyDown', onBeforeKeyDown);

  _textEditor2.default.prototype.open.apply(this, arguments);

  if (this.htEditor) {
    this.htEditor.destroy();
  }
  // Construct and initialise a new Handsontable
  this.htEditor = new this.instance.constructor(this.htContainer, this.htOptions);
  this.htEditor.init();

  if (this.cellProperties.strict) {
    this.htEditor.selectCell(0, 0);
    this.TEXTAREA.style.visibility = 'hidden';
  } else {
    this.htEditor.deselectCell();
    this.TEXTAREA.style.visibility = 'visible';
  }

  (0, _element.setCaretPosition)(this.TEXTAREA, 0, this.TEXTAREA.value.length);
};

HandsontableEditor.prototype.close = function () {
  this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
  this.instance.listen();

  _textEditor2.default.prototype.close.apply(this, arguments);
};

HandsontableEditor.prototype.focus = function () {
  this.instance.listen();
  _textEditor2.default.prototype.focus.apply(this, arguments);
};

HandsontableEditor.prototype.beginEditing = function (initialValue) {
  var onBeginEditing = this.instance.getSettings().onBeginEditing;

  if (onBeginEditing && onBeginEditing() === false) {
    return;
  }
  _textEditor2.default.prototype.beginEditing.apply(this, arguments);
};

HandsontableEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
  if (this.htEditor && this.htEditor.isListening()) {
    // if focus is still in the HOT editor

    this.instance.listen(); // return the focus to the parent HOT instance
  }

  if (this.htEditor && this.htEditor.getSelected()) {
    var value = this.htEditor.getInstance().getValue();

    if (value !== void 0) {
      // if the value is undefined then it means we don't want to set the value
      this.setValue(value);
    }
  }

  return _textEditor2.default.prototype.finishEditing.apply(this, arguments);
};

HandsontableEditor.prototype.assignHooks = function () {
  var _this = this;

  this.instance.addHook('afterDestroy', function () {
    if (_this.htEditor) {
      _this.htEditor.destroy();
    }
  });
};

exports.default = HandsontableEditor;

/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * numbro.js
 * version : 1.11.0
 * author : Företagsplatsen AB
 * license : MIT
 * http://www.foretagsplatsen.se
 */

(function () {
    'use strict';

    /************************************
        Constants
    ************************************/

    var numbro,
        VERSION = '1.11.0',
        binarySuffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
        decimalSuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        bytes = {
            general: { scale: 1024, suffixes: decimalSuffixes, marker: 'bd' },
            binary:  { scale: 1024, suffixes: binarySuffixes, marker: 'b' },
            decimal: { scale: 1000, suffixes: decimalSuffixes, marker: 'd' }
        },
        // general must be before the others because it reuses their characters!
        byteFormatOrder = [ bytes.general, bytes.binary, bytes.decimal ],
    // internal storage for culture config files
        cultures = {},
    // Todo: Remove in 2.0.0
        languages = cultures,
        currentCulture = 'en-US',
        zeroFormat = null,
        defaultFormat = '0,0',
        defaultCurrencyFormat = '0$',
        // check for nodeJS
        hasModule = (typeof module !== 'undefined' && module.exports),
    // default culture
        enUS = {
            delimiters: {
                thousands: ',',
                decimal: '.'
            },
            abbreviations: {
                thousand: 'k',
                million: 'm',
                billion: 'b',
                trillion: 't'
            },
            ordinal: function(number) {
                var b = number % 10;
                return (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            },
            currency: {
                symbol: '$',
                position: 'prefix'
            },
            defaults: {
                currencyFormat: ',0000 a'
            },
            formats: {
                fourDigits: '0000 a',
                fullWithTwoDecimals: '$ ,0.00',
                fullWithTwoDecimalsNoCurrency: ',0.00'
            }
        };

    /************************************
        Constructors
    ************************************/


    // Numbro prototype object
    function Numbro(number) {
        this._value = number;
    }

    function numberLength(number) {
        if (number === 0) { return 1; }
        return Math.floor(Math.log(Math.abs(number)) / Math.LN10) + 1;
    }

    function zeroes(count) {
        var i, ret = '';

        for (i = 0; i < count; i++) {
            ret += '0';
        }

        return ret;
    }
    /**
     * Implementation of toFixed() for numbers with exponents
     * This function may return negative representations for zero values e.g. "-0.0"
     */
    function toFixedLargeSmall(value, precision) {
        var mantissa,
            beforeDec,
            afterDec,
            exponent,
            prefix,
            endStr,
            zerosStr,
            str;

        str = value.toString();

        mantissa = str.split('e')[0];
        exponent = str.split('e')[1];

        beforeDec = mantissa.split('.')[0];
        afterDec = mantissa.split('.')[1] || '';

        if (+exponent > 0) {
            // exponent is positive - add zeros after the numbers
            str = beforeDec + afterDec + zeroes(exponent - afterDec.length);
        } else {
            // exponent is negative

            if (+beforeDec < 0) {
                prefix = '-0';
            } else {
                prefix = '0';
            }

            // tack on the decimal point if needed
            if (precision > 0) {
                prefix += '.';
            }

            zerosStr = zeroes((-1 * exponent) - 1);
            // substring off the end to satisfy the precision
            endStr = (zerosStr + Math.abs(beforeDec) + afterDec).substr(0, precision);
            str = prefix + endStr;
        }

        // only add percision 0's if the exponent is positive
        if (+exponent > 0 && precision > 0) {
            str += '.' + zeroes(precision);
        }

        return str;
    }

    /**
     * Implementation of toFixed() that treats floats more like decimals
     *
     * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
     * problems for accounting- and finance-related software.
     *
     * Also removes negative signs for zero-formatted numbers. e.g. -0.01 w/ precision 1 -> 0.0
     */
    function toFixed(value, precision, roundingFunction, optionals) {
        var power = Math.pow(10, precision),
            optionalsRegExp,
            output;

        if (value.toString().indexOf('e') > -1) {
            // toFixed returns scientific notation for numbers above 1e21 and below 1e-7
            output = toFixedLargeSmall(value, precision);
            // remove the leading negative sign if it exists and should not be present (e.g. -0.00)
            if (output.charAt(0) === '-' && +output >= 0) {
                output = output.substr(1); // chop off the '-'
            }
        }
        else {
            // Multiply up by precision, round accurately, then divide and use native toFixed():
            output = (roundingFunction(value + 'e+' + precision) / power).toFixed(precision);
        }

        if (optionals) {
            optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
            output = output.replace(optionalsRegExp, '');
        }

        return output;
    }

    /************************************
        Formatting
    ************************************/

    // determine what type of formatting we need to do
    function formatNumbro(n, format, roundingFunction) {
        var output,
            escapedFormat = format.replace(/\{[^\{\}]*\}/g, '');

        // figure out what kind of format we are dealing with
        if (escapedFormat.indexOf('$') > -1) { // currency!!!!!
            output = formatCurrency(n, cultures[currentCulture].currency.symbol, format, roundingFunction);
        } else if (escapedFormat.indexOf('%') > -1) { // percentage
            output = formatPercentage(n, format, roundingFunction);
        } else if (escapedFormat.indexOf(':') > -1) { // time
            output = formatTime(n, format);
        } else { // plain ol' numbers or bytes
            output = formatNumber(n._value, format, roundingFunction);
        }

        // return string
        return output;
    }

    // revert to number
    function unformatNumbro(n, string) {
        var stringOriginal = string,
            thousandRegExp,
            millionRegExp,
            billionRegExp,
            trillionRegExp,
            bytesMultiplier = false,
            power;

        if (string.indexOf(':') > -1) {
            n._value = unformatTime(string);
        } else {
            if (string === zeroFormat) {
                n._value = 0;
            } else {
                if (cultures[currentCulture].delimiters.decimal !== '.') {
                    string = string.replace(/\./g, '').replace(cultures[currentCulture].delimiters.decimal, '.');
                }

                // see if abbreviations are there so that we can multiply to the correct number
                thousandRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.thousand +
                    '(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
                millionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.million +
                    '(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
                billionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.billion +
                    '(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
                trillionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.trillion +
                    '(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');

                // see if bytes are there so that we can multiply to the correct number
                for (power = 1; power < binarySuffixes.length && !bytesMultiplier; ++power) {
                    if (string.indexOf(binarySuffixes[power]) > -1) {
                        bytesMultiplier = Math.pow(1024, power);
                    } else if (string.indexOf(decimalSuffixes[power]) > -1) {
                        bytesMultiplier = Math.pow(1000, power);
                    }
                }

                var str = string.replace(/[^0-9\.]+/g, '');
                if (str === '') {
                    // An empty string is not a number.
                    n._value = NaN;

                } else {
                    // do some math to create our number
                    n._value = ((bytesMultiplier) ? bytesMultiplier : 1) *
                        ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) *
                        ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) *
                        ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) *
                        ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) *
                        ((string.indexOf('%') > -1) ? 0.01 : 1) *
                        (((string.split('-').length +
                            Math.min(string.split('(').length - 1, string.split(')').length - 1)) % 2) ? 1 : -1) *
                        Number(str);

                    // round if we are talking about bytes
                    n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value;
                }
            }
        }
        return n._value;
    }

    function formatCurrency(n, currencySymbol, originalFormat, roundingFunction) {
        var format = originalFormat,
            symbolIndex = format.indexOf('$'),
            openParenIndex = format.indexOf('('),
            plusSignIndex = format.indexOf('+'),
            minusSignIndex = format.indexOf('-'),
            space = '',
            decimalSeparator = '',
            spliceIndex,
            output;

        if(format.indexOf('$') === -1){
            // Use defaults instead of the format provided
            if (cultures[currentCulture].currency.position === 'infix') {
                decimalSeparator = currencySymbol;
                if (cultures[currentCulture].currency.spaceSeparated) {
                    decimalSeparator = ' ' + decimalSeparator + ' ';
                }
            } else if (cultures[currentCulture].currency.spaceSeparated) {
                space = ' ';
            }
        } else {
            // check for space before or after currency
            if (format.indexOf(' $') > -1) {
                space = ' ';
                format = format.replace(' $', '');
            } else if (format.indexOf('$ ') > -1) {
                space = ' ';
                format = format.replace('$ ', '');
            } else {
                format = format.replace('$', '');
            }
        }

        // Format The Number
        output = formatNumber(n._value, format, roundingFunction, decimalSeparator);

        if (originalFormat.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            switch (cultures[currentCulture].currency.position) {
                case 'postfix':
                    if (output.indexOf(')') > -1) {
                        output = output.split('');
                        output.splice(-1, 0, space + currencySymbol);
                        output = output.join('');
                    } else {
                        output = output + space + currencySymbol;
                    }
                    break;
                case 'infix':
                    break;
                case 'prefix':
                    if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
                        output = output.split('');
                        spliceIndex = Math.max(openParenIndex, minusSignIndex) + 1;

                        output.splice(spliceIndex, 0, currencySymbol + space);
                        output = output.join('');
                    } else {
                        output = currencySymbol + space + output;
                    }
                    break;
                default:
                    throw Error('Currency position should be among ["prefix", "infix", "postfix"]');
            }
        } else {
            // position the symbol
            if (symbolIndex <= 1) {
                if (output.indexOf('(') > -1 || output.indexOf('+') > -1 || output.indexOf('-') > -1) {
                    output = output.split('');
                    spliceIndex = 1;
                    if (symbolIndex < openParenIndex || symbolIndex < plusSignIndex || symbolIndex < minusSignIndex) {
                        // the symbol appears before the "(", "+" or "-"
                        spliceIndex = 0;
                    }
                    output.splice(spliceIndex, 0, currencySymbol + space);
                    output = output.join('');
                } else {
                    output = currencySymbol + space + output;
                }
            } else {
                if (output.indexOf(')') > -1) {
                    output = output.split('');
                    output.splice(-1, 0, space + currencySymbol);
                    output = output.join('');
                } else {
                    output = output + space + currencySymbol;
                }
            }
        }

        return output;
    }

    function formatForeignCurrency(n, foreignCurrencySymbol, originalFormat, roundingFunction) {
        return formatCurrency(n, foreignCurrencySymbol, originalFormat, roundingFunction);
    }

    function formatPercentage(n, format, roundingFunction) {
        var space = '',
            output,
            value = n._value * 100;

        // check for space before %
        if (format.indexOf(' %') > -1) {
            space = ' ';
            format = format.replace(' %', '');
        } else {
            format = format.replace('%', '');
        }

        output = formatNumber(value, format, roundingFunction);

        if (output.indexOf(')') > -1) {
            output = output.split('');
            output.splice(-1, 0, space + '%');
            output = output.join('');
        } else {
            output = output + space + '%';
        }

        return output;
    }

    function formatTime(n) {
        var hours = Math.floor(n._value / 60 / 60),
            minutes = Math.floor((n._value - (hours * 60 * 60)) / 60),
            seconds = Math.round(n._value - (hours * 60 * 60) - (minutes * 60));
        return hours + ':' +
            ((minutes < 10) ? '0' + minutes : minutes) + ':' +
            ((seconds < 10) ? '0' + seconds : seconds);
    }

    function unformatTime(string) {
        var timeArray = string.split(':'),
            seconds = 0;
        // turn hours and minutes into seconds and add them all up
        if (timeArray.length === 3) {
            // hours
            seconds = seconds + (Number(timeArray[0]) * 60 * 60);
            // minutes
            seconds = seconds + (Number(timeArray[1]) * 60);
            // seconds
            seconds = seconds + Number(timeArray[2]);
        } else if (timeArray.length === 2) {
            // minutes
            seconds = seconds + (Number(timeArray[0]) * 60);
            // seconds
            seconds = seconds + Number(timeArray[1]);
        }
        return Number(seconds);
    }

    function formatByteUnits (value, suffixes, scale) {
        var suffix = suffixes[0],
            power,
            min,
            max,
            abs = Math.abs(value);

        if (abs >= scale) {
            for (power = 1; power < suffixes.length; ++power) {
                min = Math.pow(scale, power);
                max = Math.pow(scale, power + 1);

                if (abs >= min && abs < max) {
                    suffix = suffixes[power];
                    value = value / min;
                    break;
                }
            }

            // values greater than or equal to [scale] YB never set the suffix
            if (suffix === suffixes[0]) {
                value = value / Math.pow(scale, suffixes.length - 1);
                suffix = suffixes[suffixes.length - 1];
            }
        }

        return { value: value, suffix: suffix };
    }

    function formatNumber (value, format, roundingFunction, sep) {
        var negP = false,
            signed = false,
            optDec = false,
            abbr = '',
            abbrK = false, // force abbreviation to thousands
            abbrM = false, // force abbreviation to millions
            abbrB = false, // force abbreviation to billions
            abbrT = false, // force abbreviation to trillions
            abbrForce = false, // force abbreviation
            bytes = '',
            byteFormat,
            units,
            ord = '',
            abs = Math.abs(value),
            totalLength,
            length,
            minimumPrecision,
            pow,
            w,
            intPrecision,
            precision,
            prefix,
            postfix,
            thousands,
            d = '',
            forcedNeg = false,
            neg = false,
            indexOpenP,
            indexMinus,
            paren = '',
            minlen,
            i;

        // check if number is zero and a custom zero format has been set
        if (value === 0 && zeroFormat !== null) {
            return zeroFormat;
        }

        if (!isFinite(value)) {
            return '' + value;
        }

        if (format.indexOf('{') === 0) {
            var end = format.indexOf('}');
            if (end === -1) {
                throw Error('Format should also contain a "}"');
            }
            prefix = format.slice(1, end);
            format = format.slice(end + 1);
        } else {
            prefix = '';
        }

        if (format.indexOf('}') === format.length - 1 && format.length) {
            var start = format.indexOf('{');
            if (start === -1) {
                throw Error('Format should also contain a "{"');
            }
            postfix = format.slice(start + 1, -1);
            format = format.slice(0, start + 1);
        } else {
            postfix = '';
        }

        // check for min length
        var info;
        if (format.indexOf('.') === -1) {
            info = format.match(/([0-9]+).*/);
        } else {
            info = format.match(/([0-9]+)\..*/);
        }
        minlen = info === null ? -1 : info[1].length;

        // see if we should use parentheses for negative number or if we should prefix with a sign
        // if both are present we default to parentheses
        if (format.indexOf('-') !== -1) {
            forcedNeg = true;
        }
        if (format.indexOf('(') > -1) {
            negP = true;
            format = format.slice(1, -1);
        } else if (format.indexOf('+') > -1) {
            signed = true;
            format = format.replace(/\+/g, '');
        }

        // see if abbreviation is wanted
        if (format.indexOf('a') > -1) {
            intPrecision = format.split('.')[0].match(/[0-9]+/g) || ['0'];
            intPrecision = parseInt(intPrecision[0], 10);

            // check if abbreviation is specified
            abbrK = format.indexOf('aK') >= 0;
            abbrM = format.indexOf('aM') >= 0;
            abbrB = format.indexOf('aB') >= 0;
            abbrT = format.indexOf('aT') >= 0;
            abbrForce = abbrK || abbrM || abbrB || abbrT;

            // check for space before abbreviation
            if (format.indexOf(' a') > -1) {
                abbr = ' ';
                format = format.replace(' a', '');
            } else {
                format = format.replace('a', '');
            }

            totalLength = numberLength(value);
            minimumPrecision = totalLength % 3;
            minimumPrecision = minimumPrecision === 0 ? 3 : minimumPrecision;

            if (intPrecision && abs !== 0) {
                pow = 3 * ~~((Math.min(intPrecision, totalLength) - minimumPrecision) / 3);
                abs = abs / Math.pow(10, pow);
            }

            if (totalLength !== intPrecision) {
                if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
                    // trillion
                    abbr = abbr + cultures[currentCulture].abbreviations.trillion;
                    value = value / Math.pow(10, 12);
                } else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
                    // billion
                    abbr = abbr + cultures[currentCulture].abbreviations.billion;
                    value = value / Math.pow(10, 9);
                } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
                    // million
                    abbr = abbr + cultures[currentCulture].abbreviations.million;
                    value = value / Math.pow(10, 6);
                } else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
                    // thousand
                    abbr = abbr + cultures[currentCulture].abbreviations.thousand;
                    value = value / Math.pow(10, 3);
                }
            }

            length = numberLength(value);
            if (intPrecision && length < intPrecision && format.indexOf('.') === -1) {
                format += '[.]';
                format += zeroes(intPrecision - length);
            }
        }

        // see if we are formatting
        //   binary-decimal bytes (1024 MB), binary bytes (1024 MiB), or decimal bytes (1000 MB)
        for (i = 0; i < byteFormatOrder.length; ++i) {
            byteFormat = byteFormatOrder[i];

            if (format.indexOf(byteFormat.marker) > -1) {
                // check for space before
                if (format.indexOf(' ' + byteFormat.marker) >-1) {
                    bytes = ' ';
                }

                // remove the marker (with the space if it had one)
                format = format.replace(bytes + byteFormat.marker, '');

                units = formatByteUnits(value, byteFormat.suffixes, byteFormat.scale);

                value = units.value;
                bytes = bytes + units.suffix;

                break;
            }
        }

        // see if ordinal is wanted
        if (format.indexOf('o') > -1) {
            // check for space before
            if (format.indexOf(' o') > -1) {
                ord = ' ';
                format = format.replace(' o', '');
            } else {
                format = format.replace('o', '');
            }

            if (cultures[currentCulture].ordinal) {
                ord = ord + cultures[currentCulture].ordinal(value);
            }
        }

        if (format.indexOf('[.]') > -1) {
            optDec = true;
            format = format.replace('[.]', '.');
        }

        precision = format.split('.')[1];
        thousands = format.indexOf(',');

        if (precision) {
            var dSplit = [];

            if (precision.indexOf('*') !== -1) {
                d = value.toString();
                dSplit = d.split('.');
                if (dSplit.length > 1) {
                    d = toFixed(value, dSplit[1].length, roundingFunction);
                }
            } else {
                if (precision.indexOf('[') > -1) {
                    precision = precision.replace(']', '');
                    precision = precision.split('[');
                    d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction,
                        precision[1].length);
                } else {
                    d = toFixed(value, precision.length, roundingFunction);
                }
            }

            dSplit = d.split('.');
            w = dSplit[0];

            if (dSplit.length > 1 && dSplit[1].length) {
                var p = sep ? abbr + sep : cultures[currentCulture].delimiters.decimal;
                d = p + dSplit[1];
            } else {
                d = '';
            }

            if (optDec && Number(d.slice(1)) === 0) {
                d = '';
            }
        } else {
            w = toFixed(value, 0, roundingFunction);
        }

        // format number
        if (w.indexOf('-') > -1) {
            w = w.slice(1);
            neg = true;
        }

        if (w.length < minlen) {
            w = zeroes(minlen - w.length) + w;
        }

        if (thousands > -1) {
            w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' +
                cultures[currentCulture].delimiters.thousands);
        }

        if (format.indexOf('.') === 0) {
            w = '';
        }

        indexOpenP = format.indexOf('(');
        indexMinus = format.indexOf('-');

        if (indexOpenP < indexMinus) {
            paren = ((negP && neg) ? '(' : '') + (((forcedNeg && neg) || (!negP && neg)) ? '-' : '');
        } else {
            paren = (((forcedNeg && neg) || (!negP && neg)) ? '-' : '') + ((negP && neg) ? '(' : '');
        }

        return prefix +
            paren + ((!neg && signed && value !== 0) ? '+' : '') +
            w + d +
            ((ord) ? ord : '') +
            ((abbr && !sep) ? abbr : '') +
            ((bytes) ? bytes : '') +
            ((negP && neg) ? ')' : '') +
            postfix;
    }

    /************************************
        Top Level Functions
    ************************************/

    numbro = function(input) {
        if (numbro.isNumbro(input)) {
            input = input.value();
        } else if (typeof input === 'string' || typeof input === 'number') {
            input = numbro.fn.unformat(input);
        } else {
            input = NaN;
        }

        return new Numbro(Number(input));
    };

    // version number
    numbro.version = VERSION;

    // compare numbro object
    numbro.isNumbro = function(obj) {
        return obj instanceof Numbro;
    };

    /**
     * This function allow the user to set a new language with a fallback if
     * the language does not exist. If no fallback language is provided,
     * it fallbacks to english.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `setCulture` should be used instead.
     */
    numbro.setLanguage = function(newLanguage, fallbackLanguage) {
        console.warn('`setLanguage` is deprecated since version 1.6.0. Use `setCulture` instead');
        var key = newLanguage,
            prefix = newLanguage.split('-')[0],
            matchingLanguage = null;
        if (!languages[key]) {
            Object.keys(languages).forEach(function(language) {
                if (!matchingLanguage && language.split('-')[0] === prefix) {
                    matchingLanguage = language;
                }
            });
            key = matchingLanguage || fallbackLanguage || 'en-US';
        }
        chooseCulture(key);
    };

    /**
     * This function allow the user to set a new culture with a fallback if
     * the culture does not exist. If no fallback culture is provided,
     * it falls back to "en-US".
     */
    numbro.setCulture = function(newCulture, fallbackCulture) {
        var key = newCulture,
            suffix = newCulture.split('-')[1],
            matchingCulture = null;
        if (!cultures[key]) {
            if (suffix) {
                Object.keys(cultures).forEach(function(language) {
                    if (!matchingCulture && language.split('-')[1] === suffix) {
                        matchingCulture = language;
                    }
                });
            }

            key = matchingCulture || fallbackCulture || 'en-US';
        }
        chooseCulture(key);
    };

    /**
     * This function will load languages and then set the global language.  If
     * no arguments are passed in, it will simply return the current global
     * language key.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.language = function(key, values) {
        console.warn('`language` is deprecated since version 1.6.0. Use `culture` instead');

        if (!key) {
            return currentCulture;
        }

        if (key && !values) {
            if (!languages[key]) {
                throw new Error('Unknown language : ' + key);
            }
            chooseCulture(key);
        }

        if (values || !languages[key]) {
            setCulture(key, values);
        }

        return numbro;
    };

    /**
     * This function will load cultures and then set the global culture.  If
     * no arguments are passed in, it will simply return the current global
     * culture code.
     */
    numbro.culture = function(code, values) {
        if (!code) {
            return currentCulture;
        }

        if (code && !values) {
            if (!cultures[code]) {
                throw new Error('Unknown culture : ' + code);
            }
            chooseCulture(code);
        }

        if (values || !cultures[code]) {
            setCulture(code, values);
        }

        return numbro;
    };

    /**
     * This function provides access to the loaded language data.  If
     * no arguments are passed in, it will simply return the current
     * global language object.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.languageData = function(key) {
        console.warn('`languageData` is deprecated since version 1.6.0. Use `cultureData` instead');

        if (!key) {
            return languages[currentCulture];
        }

        if (!languages[key]) {
            throw new Error('Unknown language : ' + key);
        }

        return languages[key];
    };

    /**
     * This function provides access to the loaded culture data.  If
     * no arguments are passed in, it will simply return the current
     * global culture object.
     */
    numbro.cultureData = function(code) {
        if (!code) {
            return cultures[currentCulture];
        }

        if (!cultures[code]) {
            throw new Error('Unknown culture : ' + code);
        }

        return cultures[code];
    };

    numbro.culture('en-US', enUS);

    /**
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `cultures` should be used instead.
     */
    numbro.languages = function() {
        console.warn('`languages` is deprecated since version 1.6.0. Use `cultures` instead');

        return languages;
    };

    numbro.cultures = function() {
        return cultures;
    };

    numbro.zeroFormat = function(format) {
        zeroFormat = typeof(format) === 'string' ? format : null;
    };

    numbro.defaultFormat = function(format) {
        defaultFormat = typeof(format) === 'string' ? format : '0.0';
    };

    numbro.defaultCurrencyFormat = function (format) {
        defaultCurrencyFormat = typeof(format) === 'string' ? format : '0$';
    };

    numbro.validate = function(val, culture) {

        var _decimalSep,
            _thousandSep,
            _currSymbol,
            _valArray,
            _abbrObj,
            _thousandRegEx,
            cultureData,
            temp;

        //coerce val to string
        if (typeof val !== 'string') {
            val += '';
            if (console.warn) {
                console.warn('Numbro.js: Value is not string. It has been co-erced to: ', val);
            }
        }

        //trim whitespaces from either sides
        val = val.trim();

        //replace the initial '+' or '-' sign if present
        val = val.replace(/^[+-]?/, '');

        //if val is just digits return true
        if ( !! val.match(/^\d+$/)) {
            return true;
        }

        //if val is empty return false
        if (val === '') {
            return false;
        }

        //get the decimal and thousands separator from numbro.cultureData
        try {
            //check if the culture is understood by numbro. if not, default it to current culture
            cultureData = numbro.cultureData(culture);
        } catch (e) {
            cultureData = numbro.cultureData(numbro.culture());
        }

        //setup the delimiters and currency symbol based on culture
        _currSymbol = cultureData.currency.symbol;
        _abbrObj = cultureData.abbreviations;
        _decimalSep = cultureData.delimiters.decimal;
        if (cultureData.delimiters.thousands === '.') {
            _thousandSep = '\\.';
        } else {
            _thousandSep = cultureData.delimiters.thousands;
        }

        // validating currency symbol
        temp = val.match(/^[^\d\.\,]+/);
        if (temp !== null) {
            val = val.substr(1);
            if (temp[0] !== _currSymbol) {
                return false;
            }
        }

        //validating abbreviation symbol
        temp = val.match(/[^\d]+$/);
        if (temp !== null) {
            val = val.slice(0, -1);
            if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million &&
                    temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
                return false;
            }
        }

        _thousandRegEx = new RegExp(_thousandSep + '{2}');

        if (!val.match(/[^\d.,]/g)) {
            _valArray = val.split(_decimalSep);
            if (_valArray.length > 2) {
                return false;
            } else {
                if (_valArray.length < 2) {
                    return ( !! _valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
                } else {
                    if (_valArray[0] === '') {
                        // for values without leading zero eg. .984
                        return (!_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));

                    } else if (_valArray[0].length === 1) {
                        return ( !! _valArray[0].match(/^\d+$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !! _valArray[1].match(/^\d+$/));
                    } else {
                        return ( !! _valArray[0].match(/^\d+.*\d$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !! _valArray[1].match(/^\d+$/));
                    }
                }
            }
        }

        return false;
    };

    /**
     * * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `loadCulturesInNode` should be used instead.
     */
    numbro.loadLanguagesInNode = function() {
        console.warn('`loadLanguagesInNode` is deprecated since version 1.6.0. Use `loadCulturesInNode` instead');

        numbro.loadCulturesInNode();
    };

    numbro.loadCulturesInNode = function() {
        // TODO: Rename the folder in 2.0.0
        var cultures = __webpack_require__(362);

        for(var langLocaleCode in cultures) {
            if(langLocaleCode) {
                numbro.culture(langLocaleCode, cultures[langLocaleCode]);
            }
        }
    };

    /************************************
        Helpers
    ************************************/

    function setCulture(code, values) {
        cultures[code] = values;
    }

    function chooseCulture(code) {
        currentCulture = code;
        var defaults = cultures[code].defaults;
        if (defaults && defaults.format) {
            numbro.defaultFormat(defaults.format);
        }
        if (defaults && defaults.currencyFormat) {
            numbro.defaultCurrencyFormat(defaults.currencyFormat);
        }
    }

    function inNodejsRuntime() {
        return (typeof process !== 'undefined') &&
            (process.browser === undefined) &&
            process.title &&
            (
                process.title.indexOf('node') !== -1 ||
                process.title.indexOf('meteor-tool') > 0 ||
                process.title === 'grunt' ||
                process.title === 'gulp'
            ) &&
            ("function" !== 'undefined');
    }

    /************************************
        Floating-point helpers
    ************************************/

    // The floating-point helper functions and implementation
    // borrows heavily from sinful.js: http://guipn.github.io/sinful.js/

    /**
     * Array.prototype.reduce for browsers that don't support it
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Compatibility
     */
    if ('function' !== typeof Array.prototype.reduce) {
        Array.prototype.reduce = function(callback, optInitialValue) {

            if (null === this || 'undefined' === typeof this) {
                // At the moment all modern browsers, that support strict mode, have
                // native implementation of Array.prototype.reduce. For instance, IE8
                // does not support strict mode, so this check is actually useless.
                throw new TypeError('Array.prototype.reduce called on null or undefined');
            }

            if ('function' !== typeof callback) {
                throw new TypeError(callback + ' is not a function');
            }

            var index,
                value,
                length = this.length >>> 0,
                isValueSet = false;

            if (1 < arguments.length) {
                value = optInitialValue;
                isValueSet = true;
            }

            for (index = 0; length > index; ++index) {
                if (this.hasOwnProperty(index)) {
                    if (isValueSet) {
                        value = callback(value, this[index], index, this);
                    } else {
                        value = this[index];
                        isValueSet = true;
                    }
                }
            }

            if (!isValueSet) {
                throw new TypeError('Reduce of empty array with no initial value');
            }

            return value;
        };
    }


    /**
     * Computes the multiplier necessary to make x >= 1,
     * effectively eliminating miscalculations caused by
     * finite precision.
     */
    function multiplier(x) {
        var parts = x.toString().split('.');
        if (parts.length < 2) {
            return 1;
        }
        return Math.pow(10, parts[1].length);
    }

    /**
     * Given a variable number of arguments, returns the maximum
     * multiplier that must be used to normalize an operation involving
     * all of them.
     */
    function correctionFactor() {
        var args = Array.prototype.slice.call(arguments);
        return args.reduce(function(prev, next) {
            var mp = multiplier(prev),
                mn = multiplier(next);
            return mp > mn ? mp : mn;
        }, -Infinity);
    }

    /************************************
        Numbro Prototype
    ************************************/


    numbro.fn = Numbro.prototype = {

        clone: function() {
            return numbro(this);
        },

        format: function(inputString, roundingFunction) {
            return formatNumbro(this,
                inputString ? inputString : defaultFormat,
                (roundingFunction !== undefined) ? roundingFunction : Math.round
            );
        },

        formatCurrency: function(inputString, roundingFunction) {
            return formatCurrency(this,
                cultures[currentCulture].currency.symbol,
                inputString ? inputString : defaultCurrencyFormat,
                (roundingFunction !== undefined) ? roundingFunction : Math.round
            );
        },

        formatForeignCurrency: function(currencySymbol, inputString, roundingFunction) {
            return formatForeignCurrency(this,
                currencySymbol,
                inputString ? inputString : defaultCurrencyFormat,
                (roundingFunction !== undefined) ? roundingFunction : Math.round
            );
        },

        unformat: function(inputString) {
            if (typeof inputString === 'number') {
                return inputString;
            } else if (typeof inputString === 'string') {
                var result = unformatNumbro(this, inputString);

                // Any unparseable string (represented as NaN in the result) is
                // converted into undefined.
                return isNaN(result) ? undefined : result;
            } else {
                return undefined;
            }
        },

        binaryByteUnits: function() {
            return formatByteUnits(this._value, bytes.binary.suffixes, bytes.binary.scale).suffix;
        },

        byteUnits: function() {
            return formatByteUnits(this._value, bytes.general.suffixes, bytes.general.scale).suffix;
        },

        decimalByteUnits: function() {
            return formatByteUnits(this._value, bytes.decimal.suffixes, bytes.decimal.scale).suffix;
        },

        value: function() {
            return this._value;
        },

        valueOf: function() {
            return this._value;
        },

        set: function(value) {
            this._value = Number(value);
            return this;
        },

        add: function(value) {
            var corrFactor = correctionFactor.call(null, this._value, value);

            function cback(accum, curr) {
                return accum + corrFactor * curr;
            }
            this._value = [this._value, value].reduce(cback, 0) / corrFactor;
            return this;
        },

        subtract: function(value) {
            var corrFactor = correctionFactor.call(null, this._value, value);

            function cback(accum, curr) {
                return accum - corrFactor * curr;
            }
            this._value = [value].reduce(cback, this._value * corrFactor) / corrFactor;
            return this;
        },

        multiply: function(value) {
            function cback(accum, curr) {
                var corrFactor = correctionFactor(accum, curr),
                    result = accum * corrFactor;
                result *= curr * corrFactor;
                result /= corrFactor * corrFactor;
                return result;
            }
            this._value = [this._value, value].reduce(cback, 1);
            return this;
        },

        divide: function(value) {
            function cback(accum, curr) {
                var corrFactor = correctionFactor(accum, curr);
                return (accum * corrFactor) / (curr * corrFactor);
            }
            this._value = [this._value, value].reduce(cback);
            return this;
        },

        difference: function(value) {
            return Math.abs(numbro(this._value).subtract(value).value());
        }

    };

    /************************************
        Exposing Numbro
    ************************************/

    if (inNodejsRuntime()) {
        //Todo: Rename the folder in 2.0.0
        numbro.loadCulturesInNode();
    }

    // CommonJS module is defined
    if (hasModule) {
        module.exports = numbro;
    } else {
        /*global ender:false */
        if (typeof ender === 'undefined') {
            // here, `this` means `window` in the browser, or `global` on the server
            // add `numbro` as a global object via a string identifier,
            // for Closure Compiler 'advanced' mode
            this.numbro = numbro;
        }

        /*global define:false */
        if (true) {
            !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
                return numbro;
            }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
        }
    }

}.call(typeof window === 'undefined' ? this : window));


/*** EXPORTS FROM exports-to-window-loader ***/
window['numbro'] = __webpack_require__(305);

/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.getNormalizedDate = getNormalizedDate;
/* eslint-disable import/prefer-default-export */

/**
 * Get normalized Date object for the ISO formatted date strings.
 * Natively, the date object parsed from a ISO 8601 string will be offsetted by the timezone difference, which may result in returning a wrong date.
 * See: Github issue #3338.
 *
 * @param {String} dateString String representing the date.
 * @returns {Date} The proper Date object.
 */
function getNormalizedDate(dateString) {
  var nativeDate = new Date(dateString);

  // NaN if dateString is not in ISO format
  if (!isNaN(new Date(dateString + "T00:00").getDate())) {

    // Compensate timezone offset
    return new Date(nativeDate.getTime() + nativeDate.getTimezoneOffset() * 60000);
  }

  return nativeDate;
}

/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * SheetClip - Spreadsheet Clipboard Parser
 * version 0.2
 *
 * This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice,
 * Google Docs and Microsoft Excel.
 *
 * Copyright 2012, Marcin Warpechowski
 * Licensed under the MIT license.
 * http://github.com/warpech/sheetclip/
 */
/*jslint white: true*/
(function (global) {
  "use strict";

  function countQuotes(str) {
    return str.split('"').length - 1;
  }

  var SheetClip = {
    /**
     * Decode spreadsheet string into array
     *
     * @param {String} str
     * @returns {Array}
     */
    parse: function parse(str) {
      var r,
          rLen,
          rows,
          arr = [],
          a = 0,
          c,
          cLen,
          multiline,
          last;

      rows = str.split('\n');

      if (rows.length > 1 && rows[rows.length - 1] === '') {
        rows.pop();
      }
      for (r = 0, rLen = rows.length; r < rLen; r += 1) {
        rows[r] = rows[r].split('\t');

        for (c = 0, cLen = rows[r].length; c < cLen; c += 1) {
          if (!arr[a]) {
            arr[a] = [];
          }
          if (multiline && c === 0) {
            last = arr[a].length - 1;
            arr[a][last] = arr[a][last] + '\n' + rows[r][0];

            if (multiline && countQuotes(rows[r][0]) & 1) {
              //& 1 is a bitwise way of performing mod 2
              multiline = false;
              arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"');
            }
          } else {
            if (c === cLen - 1 && rows[r][c].indexOf('"') === 0 && countQuotes(rows[r][c]) & 1) {
              arr[a].push(rows[r][c].substring(1).replace(/""/g, '"'));
              multiline = true;
            } else {
              arr[a].push(rows[r][c].replace(/""/g, '"'));
              multiline = false;
            }
          }
        }
        if (!multiline) {
          a += 1;
        }
      }

      return arr;
    },

    /**
     * Encode array into valid spreadsheet string
     *
     * @param arr
     * @returns {String}
     */
    stringify: function stringify(arr) {
      var r,
          rLen,
          c,
          cLen,
          str = '',
          val;

      for (r = 0, rLen = arr.length; r < rLen; r += 1) {
        cLen = arr[r].length;

        for (c = 0; c < cLen; c += 1) {
          if (c > 0) {
            str += '\t';
          }
          val = arr[r][c];

          if (typeof val === 'string') {
            if (val.indexOf('\n') > -1) {
              str += '"' + val.replace(/"/g, '""') + '"';
            } else {
              str += val;
            }
          } else if (val === null || val === void 0) {
            // void 0 resolves to undefined
            str += '';
          } else {
            str += val;
          }
        }

        if (r !== rLen - 1) {
          str += '\n';
        }
      }

      return str;
    }
  };

  if (true) {
    exports.parse = SheetClip.parse;
    exports.stringify = SheetClip.stringify;
  } else {
    global.SheetClip = SheetClip;
  }
})(window);

/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.RecordTranslator = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.registerIdentity = registerIdentity;
exports.getTranslator = getTranslator;

var _core = __webpack_require__(84);

var _core2 = _interopRequireDefault(_core);

var _object = __webpack_require__(1);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class RecordTranslator
 * @util
 */
var RecordTranslator = function () {
  function RecordTranslator(hot) {
    _classCallCheck(this, RecordTranslator);

    this.hot = hot;
  }

  /**
   * Translate physical row index into visual.
   *
   * @param {Number} row Physical row index.
   * @returns {Number} Returns visual row index.
   */


  _createClass(RecordTranslator, [{
    key: 'toVisualRow',
    value: function toVisualRow(row) {
      return this.hot.runHooks('unmodifyRow', row);
    }

    /**
     * Translate physical column index into visual.
     *
     * @param {Number} column Physical column index.
     * @returns {Number} Returns visual column index.
     */

  }, {
    key: 'toVisualColumn',
    value: function toVisualColumn(column) {
      return this.hot.runHooks('unmodifyCol', column);
    }

    /**
     * Translate physical coordinates into visual. Can be passed as separate 2 arguments (row, column) or as an object in first
     * argument with `row` and `column` keys.
     *
     * @param {Number|Object} row Physical coordinates or row index.
     * @param {Number} [column] Physical column index.
     * @returns {Object|Array} Returns an object with visual records or an array if coordinates passed as separate arguments.
     */

  }, {
    key: 'toVisual',
    value: function toVisual(row, column) {
      var result = void 0;

      if ((0, _object.isObject)(row)) {
        result = {
          row: this.toVisualRow(row.row),
          column: this.toVisualColumn(row.column)
        };
      } else {
        result = [this.toVisualRow(row), this.toVisualColumn(column)];
      }

      return result;
    }

    /**
     * Translate visual row index into physical.
     *
     * @param {Number} row Visual row index.
     * @returns {Number} Returns physical row index.
     */

  }, {
    key: 'toPhysicalRow',
    value: function toPhysicalRow(row) {
      return this.hot.runHooks('modifyRow', row);
    }

    /**
     * Translate visual column index into physical.
     *
     * @param {Number} column Visual column index.
     * @returns {Number} Returns physical column index.
     */

  }, {
    key: 'toPhysicalColumn',
    value: function toPhysicalColumn(column) {
      return this.hot.runHooks('modifyCol', column);
    }

    /**
     * Translate visual coordinates into physical. Can be passed as separate 2 arguments (row, column) or as an object in first
     * argument with `row` and `column` keys.
     *
     * @param {Number|Object} row Visual coordinates or row index.
     * @param {Number} [column] Visual column index.
     * @returns {Object|Array} Returns an object with physical records or an array if coordinates passed as separate arguments.
     */

  }, {
    key: 'toPhysical',
    value: function toPhysical(row, column) {
      var result = void 0;

      if ((0, _object.isObject)(row)) {
        result = {
          row: this.toPhysicalRow(row.row),
          column: this.toPhysicalColumn(row.column)
        };
      } else {
        result = [this.toPhysicalRow(row), this.toPhysicalColumn(column)];
      }

      return result;
    }
  }]);

  return RecordTranslator;
}();

exports.RecordTranslator = RecordTranslator;


var identities = new WeakMap();
var translatorSingletons = new WeakMap();

function registerIdentity(identity, hot) {
  identities.set(identity, hot);
}

function getTranslator(identity) {
  var singleton = void 0;

  if (!(identity instanceof _core2.default)) {
    if (!identities.has(identity)) {
      throw Error('Record translator was not registered for this object identity');
    }
    identity = identities.get(identity);
  }
  if (translatorSingletons.has(identity)) {
    singleton = translatorSingletons.get(identity);
  } else {
    singleton = new RecordTranslator(identity);
    translatorSingletons.set(identity, singleton);
  }

  return singleton;
}

/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.registerAsRootInstance = registerAsRootInstance;
exports.hasValidParameter = hasValidParameter;
exports.isRootInstance = isRootInstance;
var holder = exports.holder = new WeakMap();

var rootInstanceSymbol = exports.rootInstanceSymbol = Symbol('rootInstance');

/**
 * Register an object as a root instance.
 *
 * @param  {Object} object An object to associate with root instance flag.
 */
function registerAsRootInstance(object) {
  holder.set(object, true);
}

/**
 * Check if the source of the root indication call is valid.
 *
 * @param  {Symbol} rootSymbol A symbol as a source of truth.
 * @return {Boolean}
 */
function hasValidParameter(rootSymbol) {
  return rootSymbol === rootInstanceSymbol;
}

/**
 * Check if passed an object was flagged as a root instance.
 *
 * @param  {Object} object An object to check.
 * @return {Boolean}
 */
function isRootInstance(object) {
  return holder.has(object);
}

/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _mixed = __webpack_require__(17);

var _object = __webpack_require__(1);

/**
 * @alias Options
 * @constructor
 * @description

 * ## Constructor options
 *
 * Constructor options are applied using an object literal passed as a second argument to the Handsontable constructor.
 *
 * ```js
 * var hot = new Handsontable(document.getElementById('example1'), {
 *   data: myArray,
 *   width: 400,
 *   height: 300
 * });
 * ```
 *
 * ---
 * ## Cascading configuration
 *
 * Handsontable 0.9 and newer is using *Cascading Configuration*, which is a fast way to provide configuration options
 * for the entire table, including its columns and particular cells.
 *
 * Consider the following example:
 * ```js
 * var hot = new Handsontable(document.getElementById('example'), {
 *   readOnly: true,
 *   columns: [
 *     {readOnly: false},
 *     {},
 *     {}
 *   ],
 *   cells: function (row, col, prop) {
 *     var cellProperties = {};
 *
 *     if (row === 0 && col === 0) {
 *       cellProperties.readOnly = true;
 *     }
 *
 *     return cellProperties;
 *   }
 * });
 * ```
 *
 * The above notation will result in all TDs being *read only*, except for first column TDs which will be *editable*, except for the TD in top left corner which will still be *read only*.
 *
 * ### The Cascading Configuration model
 *
 * ##### 1. Constructor
 *
 * Configuration options that are provided using first-level `handsontable(container, {option: "value"})` and `updateSettings` method.
 *
 * ##### 2. Columns
 *
 * Configuration options that are provided using second-level object `handsontable(container, {columns: {option: "value"}]})`
 *
 * ##### 3. Cells
 *
 * Configuration options that are provided using third-level function `handsontable(container, {cells: function: (row, col, prop){ }})`
 *
 * ---
 * ## Architecture performance
 *
 * The Cascading Configuration model is based on prototypical inheritance. It is much faster and memory efficient compared
 * to the previous model that used jQuery extend. See: [http://jsperf.com/extending-settings](http://jsperf.com/extending-settings).
 *
 * ---
 * __Important notice:__ In order for the data separation to work properly, make sure that each instance of Handsontable has a unique `id`.
 */
function DefaultSettings() {};

DefaultSettings.prototype = {
  /**
   * License key for commercial version of Handsontable.
   *
   * @pro
   * @type {String}
   * @default 'trial'
   */
  licenseKey: 'trial',

  /**
   * @description
   * Initial data source that will be bound to the data grid __by reference__ (editing data grid alters the data source).
   * Can be declared as an Array of Arrays, Array of Objects or a Function.
   *
   * See [Understanding binding as reference](http://docs.handsontable.com/tutorial-data-binding.html#page-reference).
   *
   * @type {Array|Function}
   * @default undefined
   */
  data: void 0,

  /**
   * @description
   * Defines the structure of a new row when data source is an array of objects.
   *
   * See [data-schema](http://docs.handsontable.com/tutorial-data-sources.html#page-data-schema) for examples.
   *
   * @type {Object}
   * @default undefined
   */
  dataSchema: void 0,

  /**
   * Width of the grid. Can be a value or a function that returns a value.
   *
   * @type {Number|Function}
   * @default undefined
   */
  width: void 0,

  /**
   * Height of the grid. Can be a number or a function that returns a number.
   *
   * @type {Number|Function}
   * @default undefined
   */
  height: void 0,

  /**
   * @description
   * Initial number of rows.
   *
   * __Notice:__ This option only has effect in Handsontable constructor and only if `data` option is not provided
   *
   * @type {Number}
   * @default 5
   */
  startRows: 5,

  /**
   * @description
   * Initial number of columns.
   *
   * __Notice:__ This option only has effect in Handsontable constructor and only if `data` option is not provided
   *
   * @type {Number}
   * @default 5
   */
  startCols: 5,

  /**
   * Setting `true` or `false` will enable or disable the default row headers (1, 2, 3).
   * You can also define an array `['One', 'Two', 'Three', ...]` or a function to define the headers.
   * If a function is set the index of the row is passed as a parameter.
   *
   * @type {Boolean|Array|Function}
   * @default null
   * @example
   * ```js
   * ...
   * // as boolean
   * rowHeaders: true,
   * ...
   *
   * ...
   * // as array
   * rowHeaders: [1, 2, 3],
   * ...
   *
   * ...
   * // as function
   * rowHeaders: function(index) {
   *   return index + ': AB';
   * },
   * ...
   * ```
   */
  rowHeaders: void 0,

  /**
   * Setting `true` or `false` will enable or disable the default column headers (A, B, C).
   * You can also define an array `['One', 'Two', 'Three', ...]` or a function to define the headers.
   * If a function is set, then the index of the column is passed as a parameter.
   *
   * @type {Boolean|Array|Function}
   * @default null
   * @example
   * ```js
   * ...
   * // as boolean
   * colHeaders: true,
   * ...
   *
   * ...
   * // as array
   * colHeaders: ['A', 'B', 'C'],
   * ...
   *
   * ...
   * // as function
   * colHeaders: function(index) {
   *   return index + ': AB';
   * },
   * ...
   * ```
   */
  colHeaders: null,

  /**
   * Defines column widths in pixels. Accepts number, string (that will be converted to a number),
   * array of numbers (if you want to define column width separately for each column) or a
   * function (if you want to set column width dynamically on each render).
   *
   * @type {Array|Function|Number|String}
   * @default undefined
   * @example
   * ```js
   * ...
   * // as numeric, for each column.
   * colWidths: 100,
   * ...
   *
   * * ...
   * // as string, for each column.
   * colWidths: '100px',
   * ...
   *
   * ...
   * // as array, based on visual indexes. The rest of the columns have a default width.
   * colWidths: [100, 120, 90],
   * ...
   *
   * ...
   * // as function, based on visual indexes.
   * colWidths: function(index) {
   *   return index * 10;
   * },
   * ...
   * ```
   */
  colWidths: void 0,

  /**
   * Defines row heights in pixels. Accepts numbers, strings (that will be converted into a number),
   * array of numbers (if you want to define row height separately for each row) or a
   * function (if you want to set row height dynamically on each render).
   * If the ManualRowResize or AutoRowSize plugins are enabled, this is also the minimum height that can be set
   * via either of those two plugins.
   * Height should be equal or greater than 23px. Table is rendered incorrectly if height is less than 23px.
   *
   * @type {Array|Function|Number|String}
   * @default undefined
   * @example
   * ```js
   * ...
   * // as numeric, for each row.
   * rowHeights: 100,
   * ...
   *
   * * ...
   * // as string, for each row.
   * rowHeights: '100px',
   * ...
   *
   * ...
   * // as array, based on visual indexes. The rest of the rows have a default height.
   * rowHeights: [100, 120, 90],
   * ...
   *
   * ...
   * // as function, based on visual indexes.
   * rowHeights: function(index) {
   *   return index * 10;
   * },
   * ...
   * ```
   */
  rowHeights: void 0,

  /**
   * @description
   * Defines the cell properties and data binding for certain columns.
   *
   * __Notice:__ Using this option sets a fixed number of columns (options `startCols`, `minCols`, `maxCols` will be ignored).
   *
   * See [documentation -> datasources.html](http://docs.handsontable.com/tutorial-data-sources.html#page-nested) for examples.
   *
   * @type {Array|Function}
   * @default undefined
   * @example
   * ```js
   * ...
   * // as an array of objects. Order of the objects in array is representation of physical indexes.
   * columns: [
   *   {
   *     // column options for the first column
   *     type: 'numeric',
   *     numericFormat: {
   *       pattern: '0,0.00 $'
   *     }
   *   },
   *   {
   *     // column options for the second column
   *     type: 'text',
   *     readOnly: true
   *   }
   * ],
   * ...
   *
   * // or as function, based on physical indexes
   * ...
   * columns: function(index) {
  *    return {
  *      type: index > 0 ? 'numeric' : 'text',
  *      readOnly: index < 1
  *    }
   * }
   * ...
   * ```
   */
  columns: void 0,

  /**
   * @description
   * Defines the cell properties for given `row`, `col`, `prop` coordinates.
   * Any constructor or column option may be overwritten for a particular cell (row/column combination)
   * using the `cells` property in the Handsontable constructor.
   *
   * __Note:__ Parameters `row` and `col` always represent __physical indexes__. Example below show how to execute
   * operations based on the __visual__ representation of Handsontable.
   *
   * Possible values of `prop`:
   * - property name for column's data source object, when dataset is an [array of objects](/tutorial-data-sources.html#page-object)
   * - the same number as `col`, when dataset is an [array of arrays](/tutorial-data-sources.html#page-array)
   *
   * @type {Function}
   * @default undefined
   * @example
   * ```js
   * ...
   * cells: function (row, col, prop) {
   *   var cellProperties = {};
   *   var visualRowIndex = this.instance.toVisualRow(row);
   *   var visualColIndex = this.instance.toVisualColumn(col);
   *
   *   if (visualRowIndex === 0 && visualColIndex === 0) {
   *     cellProperties.readOnly = true;
   *   }
   *
   *   return cellProperties;
   * },
   * ...
   * ```
   */
  cells: void 0,

  /**
   * Any constructor or column option may be overwritten for a particular cell (row/column combination), using `cell`
   * array passed to the Handsontable constructor.
   *
   * @type {Array}
   * @default []
   * @example
   * ```js
   * ...
   * cell: [
   *   {row: 0, col: 0, readOnly: true}
   * ],
   * ...
   * ```
   */
  cell: [],

  /**
   * @description
   * If `true`, enables the {@link Comments} plugin, which enables an option to apply cell comments through the context menu
   * (configurable with context menu keys `commentsAddEdit`, `commentsRemove`).
   *
   * To initialize Handsontable with predefined comments, provide cell coordinates and comment text values in a form of an array.
   *
   * See [Comments](http://docs.handsontable.com/demo-comments_.html) demo for examples.
   *
   * @since 0.11.0
   * @type {Boolean|Array}
   * @default false
   * @example
   * ```js
   * ...
   * comments: [{row: 1, col: 1, comment: {value: "Test comment"}}],
   * ...
   * ```
   */
  comments: false,

  /**
   * @description
   * If `true`, enables the Custom Borders plugin, which enables an option to apply custom borders through the context menu (configurable with context menu key `borders`).
   *
   * To initialize Handsontable with predefined custom borders, provide cell coordinates and border styles in a form of an array.
   *
   * See [Custom Borders](http://docs.handsontable.com/demo-custom-borders.html) demo for examples.
   *
   * @since 0.11.0
   * @type {Boolean|Array}
   * @default false
   * @example
   * ```js
   * ...
   * customBorders: [
   *   {range: {
   *     from: {row: 1, col: 1},
   *     to: {row: 3, col: 4}},
   *     left: {},
   *     right: {},
   *     top: {},
   *     bottom: {}
   *   }
   * ],
   * ...
   *
   * // or
   * ...
   * customBorders: [
   *   {row: 2, col: 2, left: {width: 2, color: 'red'},
   *     right: {width: 1, color: 'green'}, top: '', bottom: ''}
   * ],
   * ...
   * ```
   */
  customBorders: false,

  /**
   * Minimum number of rows. At least that number of rows will be created during initialization.
   *
   * @type {Number}
   * @default 0
   */
  minRows: 0,

  /**
   * Minimum number of columns. At least that number of columns will be created during initialization.
   *
   * @type {Number}
   * @default 0
   */
  minCols: 0,

  /**
   * Maximum number of rows. If set to a value lower than the initial row count, the data will be trimmed to the provided value as the number of rows.
   *
   * @type {Number}
   * @default Infinity
   */
  maxRows: Infinity,

  /**
   * Maximum number of cols. If set to a value lower than the initial col count, the data will be trimmed to the provided value as the number of cols.
   *
   * @type {Number}
   * @default Infinity
   */
  maxCols: Infinity,

  /**
   * When set to 1 (or more), Handsontable will add a new row at the end of grid if there are no more empty rows.
   * (unless the number of rows exceeds the one set in the `maxRows` property)
   *
   * @type {Number}
   * @default 0
   */
  minSpareRows: 0,

  /**
   * When set to 1 (or more), Handsontable will add a new column at the end of grid if there are no more empty columns.
   * (unless the number of rows exceeds the one set in the `maxCols` property)
   *
   * @type {Number}
   * @default 0
   */
  minSpareCols: 0,

  /**
   * If set to `false`, there won't be an option to insert new rows in the Context Menu.
   *
   * @type {Boolean}
   * @default true
   */
  allowInsertRow: true,

  /**
   * If set to `false`, there won't be an option to insert new columns in the Context Menu.
   *
   * @type {Boolean}
   * @default true
   */
  allowInsertColumn: true,

  /**
   * If set to `false`, there won't be an option to remove rows in the Context Menu.
   *
   * @type {Boolean}
   * @default true
   */
  allowRemoveRow: true,

  /**
   * If set to `false`, there won't be an option to remove columns in the Context Menu.
   *
   * @type {Boolean}
   * @default true
   */
  allowRemoveColumn: true,

  /**
   * If true, selection of multiple cells using keyboard or mouse is allowed.
   *
   * @type {Boolean}
   * @default true
   */
  multiSelect: true,

  /**
   * Enables the fill handle (drag-down and copy-down) functionality, which shows a small rectangle in bottom
   * right corner of the selected area, that let's you expand values to the adjacent cells.
   *
   * Possible values: `true` (to enable in all directions), `'vertical'` or `'horizontal'` (to enable in one direction),
   * `false` (to disable completely). Setting to `true` enables the fillHandle plugin.
   *
   * Since 0.23.0 you can pass object to plugin which allows you to add more options for this functionality. If `autoInsertRow`
   * option is `true`, fill-handler will create new rows till it reaches the last row. It is enabled by default.
   *
   * @example
   * ```js
   * ...
   * fillHandle: true // enable plugin in all directions and with autoInsertRow as true
   * ...
   * // or
   * ...
   * fillHandle: 'vertical' // enable plugin in vertical direction and with autoInsertRow as true
   * ...
   * // or
   * ...
   * fillHandle: { // enable plugin in both directions and with autoInsertRow as false
   *   autoInsertRow: false,
   * }
   * // or
   * ...
   * fillHandle: { // enable plugin in vertical direction and with autoInsertRow as false
   *   autoInsertRow: false,
   *   direction: 'vertical' // 'vertical' or 'horizontal'
   * }
   * ```
   *
   * @type {Boolean|String|Object}
   * @default true
   */
  fillHandle: true,

  /**
   * Allows to specify the number of fixed (or *frozen*) rows at the top of the table.
   *
   * @type {Number}
   * @default 0
   * @example
   * ```js
   * fixedRowsTop: 3 // This would freeze the top 3 rows of the table.
   * ```
   */
  fixedRowsTop: 0,

  /**
   * Allows to specify the number of fixed (or *frozen*) rows at the bottom of the table.
   *
   * @pro
   * @type {Number}
   * @default 0
   * @example
   * ```js
   * fixedRowsBottom: 3 // This would freeze the top 3 rows of the table.
   * ```
   */
  fixedRowsBottom: 0,

  /**
   * Allows to specify the number of fixed (or *frozen*) columns on the left of the table.
   *
   * @type {Number}
   * @default 0
   * @example
   * ```js
   * fixedColumnsLeft: 3 // This would freeze the top 3 rows of the table.
   * ```
   */
  fixedColumnsLeft: 0,

  /**
   * If `true`, mouse click outside the grid will deselect the current selection.
   * Can be a function that takes the click event target and returns a boolean.
   *
   * @type {Boolean|Function}
   * @default true
   */
  outsideClickDeselects: true,

  /**
   * If `true`, <kbd>ENTER</kbd> begins editing mode (like in Google Docs). If `false`, <kbd>ENTER</kbd> moves to next
   * row (like Excel) and adds a new row if necessary. <kbd>TAB</kbd> adds new column if necessary.
   *
   * @type {Boolean}
   * @default true
   */
  enterBeginsEditing: true,

  /**
   * Defines the cursor movement after <kbd>ENTER</kbd> was pressed (<kbd>SHIFT</kbd> + <kbd>ENTER</kbd> uses a negative vector).
   * Can be an object or a function that returns an object. The event argument passed to the function
   * is a DOM Event object received after the <kbd>ENTER</kbd> key has been pressed. This event object can be used to check
   * whether user pressed <kbd>ENTER</kbd> or <kbd>SHIFT</kbd> + <kbd>ENTER</kbd>.
   *
   * @type {Object|Function}
   * @default {row: 1, col: 0}
   */
  enterMoves: { row: 1, col: 0 },

  /**
   * Defines the cursor movement after <kbd>TAB</kbd> is pressed (<kbd>SHIFT</kbd> + <kbd>TAB</kbd> uses a negative vector).
   * Can be an object or a function that returns an object. The event argument passed to the function
   * is a DOM Event object received after the <kbd>TAB</kbd> key has been pressed. This event object can be used to check
   * whether user pressed <kbd>TAB</kbd> or <kbd>SHIFT</kbd> + <kbd>TAB</kbd>.
   *
   * @type {Object}
   * @default {row: 0, col: 1}
   */
  tabMoves: { row: 0, col: 1 },

  /**
   * If `true`, pressing <kbd>TAB</kbd> or right arrow in the last column will move to first column in next row.
   *
   * @type {Boolean}
   * @default false
   */
  autoWrapRow: false,

  /**
   * If `true`, pressing <kbd>ENTER</kbd> or down arrow in the last row will move to the first row in the next column.
   *
   * @type {Boolean}
   * @default false
   */
  autoWrapCol: false,

  /**
   * @description
   * Turns on saving the state of column sorting, column positions and column sizes in local storage.
   *
   * You can save any sort of data in local storage to preserve table state between page reloads.
   * In order to enable data storage mechanism, `persistentState` option must be set to `true` (you can set it
   * either during Handsontable initialization or using the `updateSettings` method). When `persistentState` is enabled it exposes 3 hooks:
   *
   * __persistentStateSave__ (key: String, value: Mixed)
   *
   *   * Saves value under given key in browser local storage.
   *
   * __persistentStateLoad__ (key: String, valuePlaceholder: Object)
   *
   *   * Loads `value`, saved under given key, form browser local storage. The loaded `value` will be saved in `valuePlaceholder.value`
   *     (this is due to specific behaviour of `Hooks.run()` method). If no value have been saved under key `valuePlaceholder.value`
   *     will be `undefined`.
   *
   * __persistentStateReset__ (key: String)
   *
   *   * Clears the value saved under `key`. If no `key` is given, all values associated with table will be cleared.
   *
   * __Note:__ The main reason behind using `persistentState` hooks rather than regular LocalStorage API is that it
   * ensures separation of data stored by multiple Handsontable instances. In other words, if you have two (or more)
   * instances of Handsontable on one page, data saved by one instance won't be accessible by the second instance.
   * Those two instances can store data under the same key and no data would be overwritten.
   *
   * __Important:__ In order for the data separation to work properly, make sure that each instance of Handsontable has a unique `id`.
   *
   * @type {Boolean}
   * @default false
   */
  persistentState: void 0,

  /**
   * Class name for all visible rows in the current selection.
   *
   * @type {String}
   * @default undefined
   * @example
   * ```js
   * currentRowClassName: 'currentRow' // This will add a 'currentRow' class name to appropriate table cells.
   * ```
   */
  currentRowClassName: void 0,

  /**
   * Class name for all visible columns in the current selection.
   *
   * @type {String}
   * @default undefined
   * @example
   * ```js
   * currentColClassName: 'currentColumn' // This will add a 'currentColumn' class name to appropriate table cells.
   * ```
   */
  currentColClassName: void 0,

  /**
   * Class name for all visible headers in current selection.
   *
   * @type {String}
   * @since 0.27.0
   * @default 'ht__highlight'
   * @example
   * ```js
   * currentHeaderClassName: 'ht__highlight' // This will add a 'ht__highlight' class name to appropriate table headers.
   * ```
   */
  currentHeaderClassName: 'ht__highlight',
  /**
   * Class name for the Handsontable container element.
   *
   * @type {String|Array}
   * @default undefined
   */
  className: void 0,

  /**
   * Class name for all tables inside container element.
   *
   * @since 0.17.0
   * @type {String|Array}
   * @default undefined
   */
  tableClassName: void 0,

  /**
   * @description
   * Defines how the columns react, when the declared table width is different than the calculated sum of all column widths.
   * [See more](http://docs.handsontable.com/demo-stretching.html) mode. Possible values:
   *  * `'none'` Disable stretching
   *  * `'last'` Stretch only the last column
   *  * `'all'` Stretch all the columns evenly
   *
   * @type {String}
   * @default 'none'
   */
  stretchH: 'none',

  /**
   * Lets you overwrite the default `isEmptyRow` method, which checks if row at the provided index is empty.
   *
   * @type {Function}
   * @param {Number} row Visual row index.
   * @returns {Boolean}
   */
  isEmptyRow: function isEmptyRow(row) {
    var col, colLen, value, meta;

    for (col = 0, colLen = this.countCols(); col < colLen; col++) {
      value = this.getDataAtCell(row, col);

      if (value !== '' && value !== null && (0, _mixed.isDefined)(value)) {
        if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
          meta = this.getCellMeta(row, col);

          return (0, _object.isObjectEquals)(this.getSchema()[meta.prop], value);
        }
        return false;
      }
    }

    return true;
  },


  /**
   * Lets you overwrite the default `isEmptyCol` method, which checks if column at the provided index is empty.
   *
   * @type {Function}
   * @param {Number} col Visual column index
   * @returns {Boolean}
   */
  isEmptyCol: function isEmptyCol(col) {
    var row, rowLen, value;

    for (row = 0, rowLen = this.countRows(); row < rowLen; row++) {
      value = this.getDataAtCell(row, col);

      if (value !== '' && value !== null && (0, _mixed.isDefined)(value)) {
        return false;
      }
    }

    return true;
  },


  /**
   * When set to `true`, the table is re-rendered when it is detected that it was made visible in DOM.
   *
   * @type {Boolean}
   * @default true
   */
  observeDOMVisibility: true,

  /**
   * If set to `true`, Handsontable will accept values that were marked as invalid by the cell `validator`.
   * It will result with *invalid* cells being treated as *valid* (will save the *invalid* value into the Handsontable data source).
   * If set to `false`, Handsontable will *not* accept the invalid values and won't allow the user to close the editor.
   * This option will be particularly useful when used with the Autocomplete's `strict` mode.
   *
   * @type {Boolean}
   * @default true
   * @since 0.9.5
   */
  allowInvalid: true,

  /**
   * If set to `true`, Handsontable will accept values that are empty (`null`, `undefined` or `''`).
   * If set to `false`, Handsontable will *not* accept the empty values and mark cell as invalid.
   *
   * @example
   * ```js
   * ...
   * allowEmpty: true // allow empty values for all cells (whole table)
   * ...
   * // or
   * ...
   * columns: [
   *   // allow empty values only for 'date' column
   *   {data: 'date', dateFormat: 'DD/MM/YYYY', allowEmpty: true}
   * ]
   * ...
   * ```
   *
   * @type {Boolean}
   * @default true
   * @since 0.23.0
   */
  allowEmpty: true,

  /**
   * CSS class name for cells that did not pass validation.
   *
   * @type {String}
   * @default 'htInvalid'
   */
  invalidCellClassName: 'htInvalid',

  /**
   * When set to an non-empty string, displayed as the cell content for empty cells. If a value of a different type is provided,
   * it will be stringified and applied as a string.
   *
   * @type {Mixed}
   * @default false
   */
  placeholder: false,

  /**
   * CSS class name for cells that have a placeholder in use.
   *
   * @type {String}
   * @default 'htPlaceholder'
   */
  placeholderCellClassName: 'htPlaceholder',

  /**
   * CSS class name for read-only cells.
   *
   * @type {String}
   * @default 'htDimmed'
   */
  readOnlyCellClassName: 'htDimmed',

  /**
   * @description
   * If a string is provided, it may be one of the following predefined values:
   * * `autocomplete`,
   * * `checkbox`,
   * * `html`,
   * * `numeric`,
   * * `password`.
   * * `text`.
   *
   * Or you can [register](http://docs.handsontable.com/demo-custom-renderers.html) the custom renderer under specified name and use
   * its name as an alias in your configuration.
   *
   * If a function is provided, it will receive the following arguments:
   * ```js
   * function(instance, TD, row, col, prop, value, cellProperties) {}
   * ```
   *
   * You can read more about custom renderes [in the documentation](http://docs.handsontable.com/demo-custom-renderers.html).
   *
   * @example
   * ```js
   * ...
   * Handsontable.renderers.registerRenderer('my.renderer', function(instance, TD, row, col, prop, value, cellProperties) {
   *   TD.innerHTML = value;
   * });
   * ...
   * columns: [
   *   {
   *     editor: 'select',
   *     renderer: 'autocomplete' // as string
   *   },
   *   {
   *     renderer: 'my.renderer' // custom renderer as an alias
   *   },
   *   {
   *     // renderer as custom function
   *     renderer: function(hotInstance, TD, row, col, prop, value, cellProperties) {
   *       TD.style.color = 'blue';
   *       TD.innerHTML = value;
   *     }
   *   }
   * ]
   * ...
   * ```
   *
   * @type {String|Function}
   * @default undefined
   */
  renderer: void 0,

  /**
   * CSS class name added to the commented cells.
   *
   * @type {String}
   * @default 'htCommentCell'
   */
  commentedCellClassName: 'htCommentCell',

  /**
   * If set to `true`, it enables the browser's native selection of a fragment of the text within a single cell, between adjacent cells or in a whole table.
   * If set to `'cell'`, it enables the possibility of selecting a fragment of the text within a single cell's body.
   *
   * @type {Boolean|String}
   * @default false
   */
  fragmentSelection: false,

  /**
   * @description
   * Make cell [read only](http://docs.handsontable.com/demo-read-only.html).
   *
   * @type {Boolean}
   * @default false
   */
  readOnly: false,

  /**
   * @description
   * When added to a `column` property, it skips the column on paste and pastes the data on the next column to the right.
   *
   * @type {Boolean}
   * @default false
   */
  skipColumnOnPaste: false,

  /**
   * @description
   * Setting to true enables the search plugin (see [demo](http://docs.handsontable.com/demo-search-for-values.html)).
   *
   * @type {Boolean}
   * @default false
   */
  search: false,

  /**
   * @description
   * Shortcut to define the combination of the cell renderer, editor and validator for the column, cell or whole table.
   *
   * Possible values:
   *  * [autocomplete](http://docs.handsontable.com/demo-autocomplete.html)
   *  * [checkbox](http://docs.handsontable.com/demo-checkbox.html)
   *  * [date](http://docs.handsontable.com/demo-date.html)
   *  * [dropdown](http://docs.handsontable.com/demo-dropdown.html)
   *  * [handsontable](http://docs.handsontable.com/demo-handsontable.html)
   *  * [numeric](http://docs.handsontable.com/demo-numeric.html)
   *  * [password](http://docs.handsontable.com/demo-password.html)
   *  * text
   *  * [time](http://docs.handsontable.com/demo-time.html)
   *
   * Or you can register the custom cell type under specified name and use
   * its name as an alias in your configuration.
   *
   * @example
   * ```js
   * ...
   * Handsontable.cellTypes.registerCellType('my.type', {
   *   editor: MyEditorClass,
   *   renderer: function(hot, td, row, col, prop, value, cellProperties) {
   *     td.innerHTML = value;
   *   },
   *   validator: function(value, callback) {
   *     callback(value === 'foo' ? true : false);
   *   }
   * });
   * ...
   * columns: [
   *   {
   *     type: 'text'
   *   },
   *   {
   *     type: 'my.type' // an alias to custom type
   *   },
   *   {
   *     type: 'checkbox'
   *   }
   * ]
   * ...
   * ```
   *
   * @type {String}
   * @default 'text'
   */
  type: 'text',

  /**
   * @description
   * Make cell copyable (pressing <kbd>CTRL</kbd> + <kbd>C</kbd> on your keyboard moves its value to system clipboard).
   *
   * __Note:__ this setting is `false` by default for cells with type `password`.
   *
   * @type {Boolean}
   * @default true
   * @since 0.10.2
   */
  copyable: true,

  /**
   * Defines the editor for the table/column/cell.
   *
   * If a string is provided, it may be one of the following predefined values:
   *  * [autocomplete](http://docs.handsontable.com/demo-autocomplete.html)
   *  * [checkbox](http://docs.handsontable.com/demo-checkbox.html)
   *  * [date](http://docs.handsontable.com/demo-date.html)
   *  * [dropdown](http://docs.handsontable.com/demo-dropdown.html)
   *  * [handsontable](http://docs.handsontable.com/demo-handsontable.html)
   *  * [mobile](http://docs.handsontable.com/demo-mobiles-and-tablets.html)
   *  * [password](http://docs.handsontable.com/demo-password.html)
   *  * [select](http://docs.handsontable.com/demo-select.html)
   *  * text
   *
   * Or you can [register](http://docs.handsontable.com/tutorial-cell-editor.html#registering-an-editor) the custom editor under specified name and use
   * its name as an alias in your configuration.
   *
   * To disable cell editing completely set `editor` property to `false`.
   *
   * @example
   * ```js
   * ...
   * columns: [
   *   {
   *     editor: 'select'
   *   },
   *   {
   *     editor: false
   *   }
   * ]
   * ...
   * ```
   *
   * @type {String|Function|Boolean}
   * @default 'text'
   */
  editor: void 0,

  /**
   * @description
   * Autocomplete definitions. See [autocomplete demo](http://docs.handsontable.com/demo-autocomplete.html) for examples and definitions.
   *
   * @type {Array}
   * @default undefined
   */
  autoComplete: void 0,

  /**
   * Control number of choices for the autocomplete (or dropdown) typed cells. After exceeding it, a scrollbar for the dropdown list of choices will appear.
   *
   * @since 0.18.0
   * @type {Number}
   * @default 10
   */
  visibleRows: 10,

  /**
   * Makes autocomplete or dropdown width the same as the edited cell width. If `false` then editor will be scaled
   * according to its content.
   *
   * @since 0.17.0
   * @type {Boolean}
   * @default true
   */
  trimDropdown: true,

  /**
   * Setting to true enables the debug mode, currently used to test the correctness of the row and column
   * header fixed positioning on a layer above the master table.
   *
   * @type {Boolean}
   * @default false
   */
  debug: false,

  /**
   * When set to `true`, the text of the cell content is wrapped if it does not fit in the fixed column width.
   *
   * @type {Boolean}
   * @default true
   * @since 0.11.0
   */
  wordWrap: true,

  /**
   * CSS class name added to cells with cell meta `wordWrap: false`.
   *
   * @type {String}
   * @default 'htNoWrap'
   * @since 0.11.0
   */
  noWordWrapClassName: 'htNoWrap',

  /**
   * @description
   * Defines if the right-click context menu should be enabled. Context menu allows to create new row or
   * column at any place in the grid among [other features](http://docs.handsontable.com/demo-context-menu.html).
   * Possible values:
   * * `true` (to enable default options),
   * * `false` (to disable completely)
   * * an array of [predefined options](https://docs.handsontable.com/demo-context-menu.html#page-specific),
   * * an object [with defined structure](http://docs.handsontable.com/demo-context-menu.html#page-custom)
   *
   * See [the context menu demo](http://docs.handsontable.com/demo-context-menu.html) for examples.
   *
   * @example
   * ```js
   * ...
   * // as a boolean
   * contextMenu: true
   * ...
   * // as an array
   * contextMenu: ['row_above', 'row_below', '--------', 'undo', 'redo']
   * ...
   * ```
   * ...
   * // as an object (`name` attribute is required in the custom keys)
   * contextMenu: {
   *   items: {
   *     "option1": {
   *       name: "option1"
   *     },
   *     "option2": {
   *       name: "option2",
   *       submenu: {
   *         items: [
   *           {
   *             key: "option2:suboption1",
   *             name: "option2:suboption1",
   *             callback: function(key, options) {
   *               ...
   *             }
   *           },
   *           ...
   *         ]
   *       }
   *     }
   *   }
   * }
   * ...
   * ```
   * @type {Boolean|Array|Object}
   * @default undefined
   */
  contextMenu: void 0,

  /**
   * @description
   * Disable or enable the copy/paste functionality.
   *
   * @example
   * ```js
   * ...
   * copyPaste: false,
   * ...
   * ```
   *
   * @type {Boolean}
   * @default true
   */
  copyPaste: true,

  /**
   * If `true`, undo/redo functionality is enabled.
   *
   * @type {Boolean}
   * @default undefined
   */
  undo: void 0,

  /**
   * @description
   * Turns on [Column sorting](http://docs.handsontable.com/demo-sorting-data.html).
   * Can be either a boolean (true/false) or an object with a declared sorting options. See the below example:
   *
   * @example
   * ```js
   * ...
   * // as boolean
   * columnSorting: true
   * ...
   * // as a object with initial order (sort ascending column at index 2)
   * columnSorting: {
   *   column: 2,
   *   sortOrder: true, // true = ascending, false = descending, undefined = original order
   *   sortEmptyCells: true // true = the table sorts empty cells, false = the table moves all empty cells to the end of the table
   * }
   * ...
   * ```
   *
   * @type {Boolean|Object}
   * @default undefined
   */
  columnSorting: void 0,

  /**
   * @description
   * Turns on [Manual column move](http://docs.handsontable.com/demo-moving-rows-and-columns.html), if set to a boolean or define initial
   * column order, if set to an array of column indexes.
   *
   * @example
   * ```js
   * ...
   * // as boolean
   * manualColumnMove: true
   * ...
   * // as a array with initial order (move column index at 0 to 1 and move column index at 1 to 4)
   * manualColumnMove: [1, 4]
   * ...
   * ```
   *
   * @type {Boolean|Array}
   * @default undefined
   */
  manualColumnMove: void 0,

  /**
   * @description
   * Turns on [Manual column resize](http://docs.handsontable.com/demo-resizing.html), if set to a boolean or define initial
   * column resized widths, if set to an array of numbers.
   *
   * @example
   * ```js
   * ...
   * // as boolean
   * manualColumnResize: true
   * ...
   * // as a array with initial widths (column at 0 index has 40px and column at 1 index has 50px)
   * manualColumnResize: [40, 50]
   * ...
   * ```
   *
   * @type {Boolean|Array}
   * @default undefined
   */
  manualColumnResize: void 0,

  /**
   * @description
   * Turns on [Manual row move](http://docs.handsontable.com/demo-moving-rows-and-columns.html), if set to a boolean or define initial
   * row order, if set to an array of row indexes.
   *
   * @example
   * ```js
   * ...
   * // as boolean
   * manualRowMove: true
   * ...
   * // as a array with initial order (move row index at 0 to 1 and move row index at 1 to 4)
   * manualRowMove: [1, 4]
   * ...
   * ```
   *
   * @type {Boolean|Array}
   * @default undefined
   * @since 0.11.0
   */
  manualRowMove: void 0,

  /**
   * @description
   * Turns on [Manual row resize](http://docs.handsontable.com/demo-resizing.html), if set to a boolean or define initial
   * row resized heights, if set to an array of numbers.
   *
   * @example
   * ```js
   * ...
   * // as boolean
   * manualRowResize: true
   * ...
   * // as a array with initial heights (row at 0 index has 40px and row at 1 index has 50px)
   * manualRowResize: [40, 50]
   * ...
   * ```
   *
   * @type {Boolean|Array}
   * @default undefined
   * @since 0.11.0
   */
  manualRowResize: void 0,

  /**
   * @description
   * If set to `true`, it enables a possibility to merge cells. If set to an array of objects, it merges the cells provided in the objects (see the example below).
   * [More information on the demo page.](http://docs.handsontable.com/demo-merge-cells.html)
   *
   * @example
   * ```js
   * // enables the mergeCells plugin:
   * margeCells: true
   * ...
   * // declares a list of merged sections:
   * mergeCells: [
   *   {row: 1, col: 1, rowspan: 3, colspan: 3}, // rowspan and colspan properties declare the width and height of a merged section in cells
   *   {row: 3, col: 4, rowspan: 2, colspan: 2},
   *   {row: 5, col: 6, rowspan: 3, colspan: 3}
   * ]
   * ```
   * @type {Boolean|Array}
   * @default false
   */
  mergeCells: false,

  /**
   * Number of rows to be rendered outside of the visible part of the table.
   * By default, it's set to `'auto'`, which makes Handsontable to attempt to calculate the best offset performance-wise.
   *
   * You may test out different values to find the best one that works for your specific implementation.
   *
   * @type {Number|String}
   * @default 'auto'
   */
  viewportRowRenderingOffset: 'auto',

  /**
   * Number of columns to be rendered outside of the visible part of the table.
   * By default, it's set to `'auto'`, which makes Handsontable try calculating the best offset performance-wise.
   *
   * You may experiment with the value to find the one that works best for your specific implementation.
   *
   * @type {Number|String}
   * @default 'auto'
   */
  viewportColumnRenderingOffset: 'auto',

  /**
   * A function, regular expression or a string, which will be used in the process of cell validation.
   * If a function is used, be sure to execute the callback argument with either `true` (`callback(true)`) if the validation passed
   * or with `false` (`callback(false)`), if the validation failed.
   * Note, that `this` in the function points to the `cellProperties` object.
   *
   * If a string is provided, it may be one of the following predefined values:
   * * `autocomplete`,
   * * `date`,
   * * `numeric`,
   * * `time`.
   *
   * Or you can [register](http://docs.handsontable.com/demo-data-validation.html) the validator function under specified name and use
   * its name as an alias in your configuration.
   *
   * See more [in the demo](http://docs.handsontable.com/demo-data-validation.html).
   *
   * @example
   * ```js
   * // as a function
   * columns: [
   *    {
   *      validator: function(value, callback) { // validation rules }
   *    }
   * ]
   * ...
   * // as a regexp
   * columns: [
   *    {
   *      validator: /^[0-9]$/ // regular expression
   *    }
   * ]
   * // as a string
   * columns: [
   *    {
   *      validator: 'numeric'
   *    }
   * ]
   * ```
   * @type {Function|RegExp|String}
   * @default undefined
   * @since 0.9.5
   */
  validator: void 0,

  /**
   * @description
   * Disable visual cells selection.
   *
   * Possible values:
   *  * `true` - Disables any type of visual selection (current and area selection),
   *  * `false` - Enables any type of visual selection. This is default value.
   *  * `current` - Disables the selection of a currently selected cell, the area selection is still present.
   *  * `area` - Disables the area selection, the currently selected cell selection is still present.
   *
   * @type {Boolean|String|Array}
   * @default false
   * @since 0.13.2
   * @example
   * ```js
   * ...
   * // as boolean
   * disableVisualSelection: true,
   * ...
   *
   * ...
   * // as string ('current' or 'area')
   * disableVisualSelection: 'current',
   * ...
   *
   * ...
   * // as array
   * disableVisualSelection: ['current', 'area'],
   * ...
   * ```
   */
  disableVisualSelection: false,

  /**
   * @description
   * Set whether to display the current sorting order indicator (a triangle icon in the column header, specifying the sorting order).
   *
   * @type {Boolean}
   * @default false
   * @since 0.15.0-beta3
   */
  sortIndicator: void 0,

  /**
   * Disable or enable ManualColumnFreeze plugin.
   *
   * @type {Boolean}
   * @default false
   */
  manualColumnFreeze: void 0,

  /**
   * @description
   * Defines whether Handsontable should trim the whitespace at the beginning and the end of the cell contents.
   *
   * @type {Boolean}
   * @default true
   */
  trimWhitespace: true,

  settings: void 0,

  /**
   * @description
   * Defines data source for Autocomplete or Dropdown cell types.
   *
   * @example
   * ```js
   * ...
   * // source as a array
   * columns: [{
   *   type: 'autocomplete',
   *   source: ['A', 'B', 'C', 'D']
   * }]
   * ...
   * // source as a function
   * columns: [{
   *   type: 'autocomplete',
   *   source: function(query, callback) {
   *     fetch('http://example.com/query?q=' + query, function(response) {
   *       callback(response.items);
   *     })
   *   }
   * }]
   * ...
   * ```
   *
   * @type {Array|Function}
   * @default undefined
   */
  source: void 0,

  /**
   * @description
   * Defines the column header name.
   *
   * @example
   * ```js
   * ...
   * columns: [{
   *     title: 'First name',
   *     type: 'text',
   *   },
   *   {
   *     title: 'Last name',
   *     type: 'text',
   *   }]
   * ...
   * ```
   *
   * @type {String}
   * @default undefined
   */
  title: void 0,

  /**
   * Data template for `'checkbox'` type when checkbox is checked.
   *
   * @example
   * ```js
   * checkedTemplate: 'good'
   *
   * // if a checkbox-typed cell is checked, then getDataAtCell(x,y), where x and y are the coordinates of the cell
   * // will return 'good'.
   * ```
   * @type {Boolean|String}
   * @default true
   */
  checkedTemplate: void 0,

  /**
   * Data template for `'checkbox'` type when checkbox is unchecked.
   *
   * @example
   * ```js
   * uncheckedTemplate: 'bad'
   *
   * // if a checkbox-typed cell is not checked, then getDataAtCell(x,y), where x and y are the coordinates of the cell
   * // will return 'bad'.
   * ```
   * @type {Boolean|String}
   * @default false
   */
  uncheckedTemplate: void 0,

  /**
   * @description
   * Object which describes if renderer should create checkbox element with label element as a parent. Option desired for
   * [checkbox](http://docs.handsontable.com/demo-checkbox.html)-typed cells.
   *
   * By default the [checkbox](http://docs.handsontable.com/demo-checkbox.html) renderer renders the checkbox without a label.
   *
   * Possible object properties:
   *  * `property` - Defines the property name of the data object, which will to be used as a label.
   *  (eg. `label: {property: 'name.last'}`). This option works only if data was passed as an array of objects.
   *  * `position` - String which describes where to place the label text (before or after checkbox element).
   * Valid values are `'before'` and '`after`' (defaults to `'after'`).
   *  * `value` - String or a Function which will be used as label text.
   *
   * @example
   * ```js
   * ...
   * columns: [{
   *   type: 'checkbox',
   *   label: {position: 'after', value: 'My label: '}
   * }]
   * ...
   * ```
   *
   * @since 0.19.0
   * @type {Object}
   * @default undefined
   */
  label: void 0,

  /**
   * Display format. This option is desired for [numeric-typed](http://docs.handsontable.com/demo-numeric.html) cells. Format is described by two properties:
   *
   * - pattern, which is handled by `numbro` for purpose of formatting numbers to desired pattern. List of supported patterns can be found [here](http://numbrojs.com/format.html#numbers).
   * - culture, which is handled by `numbro` for purpose of formatting currencies. Examples showing how it works can be found [here](http://numbrojs.com/format.html#currency). List of supported cultures can be found [here](http://numbrojs.com/languages.html#supported-languages).
   *
   * __Note:__ Please keep in mind that this option is used only to format the displayed output! It has no effect on the input data provided for the cell. The numeric data can be entered to the table only as floats (separated by a dot or a comma) or integers, and are stored in the source dataset as JavaScript numbers.
   *
   * Since 0.26.0 Handsontable uses [numbro](http://numbrojs.com/) as a main library for numbers formatting.
   *
   * @example
   * ```js
   * ...
   * columns: [{
   *   type: 'numeric',
   *   numericFormat: {
   *     pattern: '0,00',
   *     culture: 'en-US'
   *   }
   * }]
   * ...
   * ```
   *
   * @since 0.35.0
   * @type {Object}
   */
  numericFormat: void 0,

  /**
   * Language for Handsontable translation. Possible language codes are: `en-US`, `pl-PL`.
   *
   * @type {String}
   * @default 'en-US'
   */
  language: void 0,

  /**
   * @description
   * Data source for [select](http://docs.handsontable.com/demo-select.html)-typed cells.
   *
   * @example
   * ```js
   * ...
   * columns: [{
   *   editor: 'select',
   *   selectOptions: ['A', 'B', 'C'],
   * }]
   * ...
   * ```
   *
   * @type {Array}
   */
  selectOptions: void 0,

  /**
   * Enables or disables the autoColumnSize plugin. Default value is `undefined`, which has the same effect as `true`.
   * Disabling this plugin can increase performance, as no size-related calculations would be done.
   *
   * Column width calculations are divided into sync and async part. Each of this parts has their own advantages and
   * disadvantages. Synchronous calculations are faster but they block the browser UI, while the slower asynchronous operations don't
   * block the browser UI.
   *
   * To configure the sync/async distribution, you can pass an absolute value (number of columns) or a percentage value.
   * `syncLimit` option is available since 0.16.0.
   *
   * You can also use the `useHeaders` option to take the column headers with into calculation.
   *
   * @example
   * ```js
   * ...
   * // as a number (300 columns in sync, rest async)
   * autoColumnSize: {syncLimit: 300},
   * ...
   *
   * ...
   * // as a string (percent)
   * autoColumnSize: {syncLimit: '40%'},
   * ...
   *
   * ...
   * // use headers width while calculation the column width
   * autoColumnSize: {useHeaders: true},
   * ...
   *
   * ```
   *
   * @type {Object|Boolean}
   * @default {syncLimit: 50}
   */
  autoColumnSize: void 0,

  /**
   * Enables or disables autoRowSize plugin. Default value is `undefined`, which has the same effect as `false` (disabled).
   * Enabling this plugin can decrease performance, as size-related calculations would be performed.
   *
   * Row height calculations are divided into sync and async stages. Each of these stages has their own advantages and
   * disadvantages. Synchronous calculations are faster but they block the browser UI, while the slower asynchronous operations don't
   * block the browser UI.
   *
   * To configure the sync/async distribution, you can pass an absolute value (number of columns) or a percentage value.
   * `syncLimit` options is available since 0.16.0.
   *
   * @example
   * ```js
   * ...
   * // as number (300 columns in sync, rest async)
   * autoRowSize: {syncLimit: 300},
   * ...
   *
   * ...
   * // as string (percent)
   * autoRowSize: {syncLimit: '40%'},
   * ...
   * ```
   * @type {Object|Boolean}
   * @default {syncLimit: 1000}
   */
  autoRowSize: void 0,

  /**
   * Date validation format.
   *
   * Option desired for `'date'` - typed cells.
   *
   * @example
   * ```js
   * ...
   * columns: [{
   *   type: 'date',
   *   dateFormat: 'MM/DD/YYYY'
   * }]
   * ...
   * ```
   *
   * @type {String}
   * @default 'DD/MM/YYYY'
   */
  dateFormat: void 0,

  /**
   * If `true` then dates will be automatically formatted to match the desired format.
   *
   * Option desired for `'date'`-typed typed cells.
   *
   * @example
   * ```js
   * ...
   * columns: [{
   *   type: 'date',
   *   dateFormat: 'YYYY-MM-DD',
   *   correctFormat: true
   * }]
   * ...
   * ```
   *
   * @type {Boolean}
   * @default false
   */
  correctFormat: false,

  /**
   * Definition of default value which will fill the empty cells.
   *
   * Option desired for `'date'`-typed cells.
   *
   * @example
   * ```js
   * ...
   * columns: [{
   *   type: 'date',
   *   defaultData: '2015-02-02'
   * }]
   * ...
   * ```
   *
   * @type {String}
   */
  defaultDate: void 0,

  /**
   * If set to `true`, the value entered into the cell must match (case-sensitive) the autocomplete source. Otherwise, cell won't pass the validation.
   * When filtering the autocomplete source list, the editor will be working in case-insensitive mode.
   *
   * Option desired for `autocomplete`-typed cells.
   *
   * @example
   * ```js
   * ...
   * columns: [{
   *   type: 'autocomplete',
   *   source: ['A', 'B', 'C'],
   *   strict: true
   * }]
   * ...
   * ```
   *
   * @type {Boolean}
   */
  strict: void 0,

  /**
   * @description
   * If typed `true`, data defined in `source` of the autocomplete or dropdown cell will be treated as HTML.
   *
   * __Warning:__ Enabling this option can cause serious XSS vulnerabilities.
   *
   * Option desired for `'autocomplete'`-typed cells.
   * @example
   * ```js
   * ...
   * columns: [{
   *   type: 'autocomplete',
   *   allowHtml: true,
   *   source: ['<b>foo</b>', '<b>bar</b>']
   * }]
   * ...
   * ```
   * @type {Boolean}
   * @default false
   */
  allowHtml: false,

  /**
   * If typed `true` then virtual rendering mechanism for handsontable will be disabled.
   *
   * @type {Boolean}
   */
  renderAllRows: void 0,

  /**
   * Prevents table to overlap outside the parent element. If `'horizontal'` option is chosen then table will appear horizontal
   * scrollbar in case where parent's width is narrower then table's width.
   *
   * Possible values:
   *  * `false` - Disables functionality (Default option).
   *  * `horizontal` - Prevents horizontal overflow table.
   *  * `vertical` - Prevents vertical overflow table (Not implemented yet).
   *
   * @since 0.20.3
   * @example
   * ```js
   * ...
   * preventOverflow: 'horizontal'
   * ...
   * ```
   *
   * @type {String|Boolean}
   */
  preventOverflow: false,

  /**
   * @description
   * Plugin allowing binding the table rows with their headers.
   * If the plugin is enabled, the table row headers will "stick" to the rows, when they are hidden/moved. Basically, if at the initialization
   * row 0 has a header titled "A", it will have it no matter what you do with the table.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Boolean|String}
   * @example
   *
   * ```js
   * ...
   * var hot = new Handsontable(document.getElementById('example'), {
   *   date: getData(),
   *   bindRowsWithHeaders: true
   * });
   * ...
   * ```
   *
   */
  bindRowsWithHeaders: void 0,

  /**
   * @description
   * The CollapsibleColumns plugin allows collapsing of columns, covered by a header with the `colspan` property defined.
   *
   * Clicking the "collapse/expand" button collapses (or expands) all "child" headers except the first one.
   *
   * Setting the `collapsibleColumns` property to `true` will display a "collapse/expand" button in every header with a defined
   * `colspan` property.
   *
   * To limit this functionality to a smaller group of headers, define the `collapsibleColumns` property as an array of objects, as in
   * the example below.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Boolean|Array}
   * @example
   * ```js
   * ...
   *  collapsibleColumns: [
   *    {row: -4, col: 1, collapsible: true},
   *    {row: -3, col: 5, collapsible: true}
   *  ]
   * ...
   * // or
   * ...
   *  collapsibleColumns: true
   * ...
   * ```
   */
  collapsibleColumns: void 0,

  /**
   * @description
   * Allows making pre-defined calculations on the cell values and display the results within Handsontable.
   * See the demo for more information.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Object}
   */
  columnSummary: void 0,

  /**
   * This plugin allows adding a configurable dropdown menu to the table's column headers.
   * The dropdown menu acts like the Context Menu, but is triggered by clicking the button in the header.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Boolean|Object|Array}
   */
  dropdownMenu: void 0,

  /**
   * The filters plugin.
   * It allows filtering the table data either by the built-in component or with the API.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Boolean}
   */
  filters: void 0,

  /**
   * It allows Handsontable to process formula expressions defined in the provided data.
   *
   * @pro
   * @since 1.7.0
   * @type {Boolean}
   */
  formulas: void 0,

  /**
   * @description
   * GanttChart plugin enables a possibility to create a Gantt chart using a Handsontable instance.
   * In this case, the whole table becomes read-only.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Object}
   */
  ganttChart: void 0,

  /**
   * @description
   * Allows adding a tooltip to the table headers.
   *
   * Available options:
   * * the `rows` property defines if tooltips should be added to row headers,
   * * the `columns` property defines if tooltips should be added to column headers,
   * * the `onlyTrimmed` property defines if tooltips should be added only to headers, which content is trimmed by the header itself (the content being wider then the header).
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Boolean|Object}
   */
  headerTooltips: void 0,

  /**
   * Plugin allowing hiding of certain columns.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Boolean|Object}
   */
  hiddenColumns: void 0,

  /**
   * @description
   * Plugin allowing hiding of certain rows.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Boolean|Object}
   */
  hiddenRows: void 0,

  /**
   * @description
   * Allows creating a nested header structure, using the HTML's colspan attribute.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Array}
   */
  nestedHeaders: void 0,

  /**
   * @description
   * Plugin allowing hiding of certain rows.
   *
   * @pro
   * @since 1.0.0-beta1
   * @type {Boolean|Array}
   */
  trimRows: void 0,

  /**
   * @description
   * Allows setting a custom width of the row headers. You can provide a number or an array of widths, if many row header levels are defined.
   *
   * @since 0.22.0
   * @type {Number|Array}
   */
  rowHeaderWidth: void 0,

  /**
   * @description
   * Allows setting a custom height of the column headers. You can provide a number or an array of heights, if many column header levels are defined.
   *
   * @since 0.22.0
   * @type {Number|Array}
   */
  columnHeaderHeight: void 0,

  /**
   * @description
   * Enabling this plugin switches table into one-way data binding where changes are applied into data source (from outside table)
   * will be automatically reflected in the table.
   *
   * For every data change [afterChangesObserved](Hooks.html#event:afterChangesObserved) hook will be fired.
   *
   * @type {Boolean}
   * @default false
   */
  observeChanges: void 0,

  /**
   * @description
   * When passed to the `column` property, allows specifying a custom sorting function for the desired column.
   *
   * @since 0.24.0
   * @type {Function}
   * @example
   * ```js
   * columns: [
   *   {
   *     sortFunction: function(sortOrder) {
   *        return function(a, b) {
   *          // sorting function body.
   *          //
   *          // Function parameters:
   *          // sortOrder: If true, the order is ascending, if false - descending. undefined = original order
   *          // a, b: Two compared elements. These are 2-element arrays, with the first element being the row index, the second - cell value.
   *        }
   *     }
   *   }
   * ]
   * ```
   */
  sortFunction: void 0,

  /**
   * If defined as 'true', the Autocomplete's suggestion list would be sorted by relevance (the closer to the left the match is, the higher the suggestion).
   *
   * Option desired for cells of the `'autocomplete'` type.
   *
   * @type {Boolean}
   * @default true
   */
  sortByRelevance: true,

  /**
   * If defined as 'true', when the user types into the input area the Autocomplete's suggestion list is updated to only
   * include those choices starting with what has been typed; if defined as 'false' all suggestions remain shown, with
   * those matching what has been typed marked in bold.
   *
   * @type {Boolean}
   * @default true
   */
  filter: true,

  /**
   * If defined as 'true', filtering in the Autocomplete Editor will be case-sensitive.
   *
   * @type {Boolean}
   * @default: false
   */
  filteringCaseSensitive: false,

  /**
   * @description
   * Disable or enable the drag to scroll functionality.
   *
   * @example
   * ```js
   * ...
   * dragToScroll: false,
   * ...
   * ```
   *
   * @type {Boolean}
   * @default true
   */
  dragToScroll: true
};

exports.default = DefaultSettings;

/***/ }),
/* 311 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.getTranslatedPhrase = getTranslatedPhrase;

var _array = __webpack_require__(2);

var _dictionariesManager = __webpack_require__(67);

var _phraseFormatters = __webpack_require__(385);

var _mixed = __webpack_require__(17);

/**
 * Get phrase for specified dictionary key.
 *
 * @param {String} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'.
 * @param {String} dictionaryKey Constant which is dictionary key.
 * @param {*} argumentsForFormatters Arguments which will be handled by formatters.
 *
 * @returns {String}
 */
// eslint-disable-next-line import/prefer-default-export
function getTranslatedPhrase(languageCode, dictionaryKey, argumentsForFormatters) {
  var languageDictionary = (0, _dictionariesManager.getLanguageDictionary)(languageCode);

  if (languageDictionary === null) {
    return null;
  }

  var phrasePropositions = languageDictionary[dictionaryKey];

  if ((0, _mixed.isUndefined)(phrasePropositions)) {
    return null;
  }

  var formattedPhrase = getFormattedPhrase(phrasePropositions, argumentsForFormatters);

  if (Array.isArray(formattedPhrase)) {
    return formattedPhrase[0];
  }

  return formattedPhrase;
}

/**
 * Get formatted phrase from phrases propositions for specified dictionary key.
 *
 * @private
 * @param {Array|string} phrasePropositions List of phrase propositions.
 * @param {*} argumentsForFormatters Arguments which will be handled by formatters.
 *
 * @returns {Array|string}
 */
function getFormattedPhrase(phrasePropositions, argumentsForFormatters) {
  var formattedPhrasePropositions = phrasePropositions;

  (0, _array.arrayEach)((0, _phraseFormatters.getPhraseFormatters)(), function (formatter) {
    formattedPhrasePropositions = formatter(phrasePropositions, argumentsForFormatters);
  });

  return formattedPhrasePropositions;
}

/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _templateObject = _taggedTemplateLiteral(['Language with code "', '" was not found. You should register particular language \n    before using it. Read more about this issue at: https://docs.handsontable.com/i18n/missing-language-code.'], ['Language with code "', '" was not found. You should register particular language \n    before using it. Read more about this issue at: https://docs.handsontable.com/i18n/missing-language-code.']);

exports.extendNotExistingKeys = extendNotExistingKeys;
exports.createCellHeadersRange = createCellHeadersRange;
exports.normalizeLanguageCode = normalizeLanguageCode;
exports.applyLanguageSetting = applyLanguageSetting;
exports.warnUserAboutLanguageRegistration = warnUserAboutLanguageRegistration;

var _mixed = __webpack_require__(17);

var _object = __webpack_require__(1);

var _templateLiteralTag = __webpack_require__(294);

var _dictionariesManager = __webpack_require__(67);

function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }

/**
 * Perform shallow extend of a target object with only this extension's properties which doesn't exist in the target.
 *
 * @param {Object} target An object that will receive the new properties.
 * @param {Object} extension An object containing additional properties to merge into the target.
 */
// TODO: Maybe it should be moved to global helpers? It's changed `extend` function.
function extendNotExistingKeys(target, extension) {
  (0, _object.objectEach)(extension, function (value, key) {
    if ((0, _mixed.isUndefined)(target[key])) {
      target[key] = value;
    }
  });

  return target;
}

/**
 * Create range of values basing on cell indexes. For example, it will create below ranges for specified function arguments:
 *
 * createCellHeadersRange(2, 7) => `2-7`
 * createCellHeadersRange(7, 2) => `2-7`
 * createCellHeadersRange(0, 4, 'A', 'D') => `A-D`
 * createCellHeadersRange(4, 0, 'D', 'A') => `A-D`
 *
 * @param {number} firstRowIndex Index of "first" cell
 * @param {number} nextRowIndex Index of "next" cell
 * @param {*} fromValue Value which will represent "first" cell
 * @param {*} toValue Value which will represent "next" cell
 * @returns {String} Value representing range i.e. A-Z, 11-15.
 */
function createCellHeadersRange(firstRowIndex, nextRowIndex) {
  var fromValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : firstRowIndex;
  var toValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : nextRowIndex;

  // Will swap `fromValue` with `toValue` if it's necessary.
  if (firstRowIndex > nextRowIndex) {
    var _ref = [toValue, fromValue];
    fromValue = _ref[0];
    toValue = _ref[1];
  }

  return fromValue + '-' + toValue;
}

/**
 * Normalize language code. It takes handled languageCode proposition and change it to proper languageCode.
 * For example, when it takes `eN-us` as parameter it return `en-US`
 *
 * @param {String} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'.
 * @returns {String}
 */
function normalizeLanguageCode(languageCode) {
  var languageCodePattern = /^([a-zA-Z]{2})-([a-zA-Z]{2})$/;
  var partsOfLanguageCode = languageCodePattern.exec(languageCode);

  if (partsOfLanguageCode) {
    return partsOfLanguageCode[1].toLowerCase() + '-' + partsOfLanguageCode[2].toUpperCase();
  }

  return languageCode;
}

/**
 * Set proper start language code. User may set language code which is not proper.
 *
 * @param {Object} settings Settings object.
 * @param {String} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'.
 * @returns {String}
 */
function applyLanguageSetting(settings, languageCode) {
  var normalizedLanguageCode = normalizeLanguageCode(languageCode);

  if ((0, _dictionariesManager.hasLanguageDictionary)(normalizedLanguageCode)) {
    settings.language = normalizedLanguageCode;
  } else {
    settings.language = _dictionariesManager.DEFAULT_LANGUAGE_CODE;

    warnUserAboutLanguageRegistration(languageCode);
  }
}

/**
 *
 * Warn user if there is no registered language.
 *
 * @param {String} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'.
 */
function warnUserAboutLanguageRegistration(languageCode) {
  if ((0, _mixed.isDefined)(languageCode)) {
    console.error((0, _templateLiteralTag.toSingleLine)(_templateObject, languageCode));
  }
}

/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _object = __webpack_require__(1);

var _number = __webpack_require__(6);

var _mixed = __webpack_require__(17);

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class SamplesGenerator
 * @util
 */
var SamplesGenerator = function () {
  _createClass(SamplesGenerator, null, [{
    key: 'SAMPLE_COUNT',

    /**
     * Number of samples to take of each value length.
     *
     * @type {Number}
     */
    get: function get() {
      return 3;
    }
  }]);

  function SamplesGenerator(dataFactory) {
    _classCallCheck(this, SamplesGenerator);

    /**
     * Samples prepared for calculations.
     *
     * @type {Map}
     * @default {null}
     */
    this.samples = null;
    /**
     * Function which give the data to collect samples.
     *
     * @type {Function}
     */
    this.dataFactory = dataFactory;
    /**
     * Custom number of samples to take of each value length.
     *
     * @type {Number}
     * @default {null}
     */
    this.customSampleCount = null;
    /**
     * `true` if duplicate samples collection should be allowed, `false` otherwise.
     *
     * @type {Boolean}
     * @default {false}
     */
    this.allowDuplicates = false;
  }

  /**
   * Get the sample count for this instance.
   *
   * @returns {Number}
   */


  _createClass(SamplesGenerator, [{
    key: 'getSampleCount',
    value: function getSampleCount() {
      if (this.customSampleCount) {
        return this.customSampleCount;
      }
      return SamplesGenerator.SAMPLE_COUNT;
    }
  }, {
    key: 'setSampleCount',


    /**
     * Set the sample count.
     *
     * @param {Number} sampleCount Number of samples to be collected.
     */
    value: function setSampleCount(sampleCount) {
      this.customSampleCount = sampleCount;
    }

    /**
     * Set if the generator should accept duplicate values.
     *
     * @param {Boolean} allowDuplicates `true` to allow duplicate values.
     */

  }, {
    key: 'setAllowDuplicates',
    value: function setAllowDuplicates(allowDuplicates) {
      this.allowDuplicates = allowDuplicates;
    }

    /**
     * Generate samples for row. You can control which area should be sampled by passing `rowRange` object and `colRange` object.
     *
     * @param {Object|Number} rowRange
     * @param {Object} colRange
     * @returns {Object}
     */

  }, {
    key: 'generateRowSamples',
    value: function generateRowSamples(rowRange, colRange) {
      return this.generateSamples('row', colRange, rowRange);
    }

    /**
     * Generate samples for column. You can control which area should be sampled by passing `colRange` object and `rowRange` object.
     *
     * @param {Object} colRange Column index.
     * @param {Object} rowRange Column index.
     * @returns {Object}
     */

  }, {
    key: 'generateColumnSamples',
    value: function generateColumnSamples(colRange, rowRange) {
      return this.generateSamples('col', rowRange, colRange);
    }

    /**
     * Generate collection of samples.
     *
     * @param {String} type Type to generate. Can be `col` or `row`.
     * @param {Object} range
     * @param {Object|Number} specifierRange
     * @returns {Map}
     */

  }, {
    key: 'generateSamples',
    value: function generateSamples(type, range, specifierRange) {
      var _this = this;

      var samples = new Map();

      if (typeof specifierRange === 'number') {
        specifierRange = { from: specifierRange, to: specifierRange };
      }
      (0, _number.rangeEach)(specifierRange.from, specifierRange.to, function (index) {
        var sample = _this.generateSample(type, range, index);

        samples.set(index, sample);
      });

      return samples;
    }

    /**
     * Generate sample for specified type (`row` or `col`).
     *
     * @param {String} type Samples type `row` or `col`.
     * @param {Object} range
     * @param {Number} specifierValue
     * @returns {Map}
     */

  }, {
    key: 'generateSample',
    value: function generateSample(type, range, specifierValue) {
      var _this2 = this;

      var samples = new Map();
      var sampledValues = [];
      var length = void 0;

      (0, _number.rangeEach)(range.from, range.to, function (index) {
        var value = void 0;

        if (type === 'row') {
          value = _this2.dataFactory(specifierValue, index);
        } else if (type === 'col') {
          value = _this2.dataFactory(index, specifierValue);
        } else {
          throw new Error('Unsupported sample type');
        }

        if ((0, _object.isObject)(value)) {
          length = Object.keys(value).length;
        } else if (Array.isArray(value)) {
          length = value.length;
        } else {
          length = (0, _mixed.stringify)(value).length;
        }

        if (!samples.has(length)) {
          samples.set(length, {
            needed: _this2.getSampleCount(),
            strings: []
          });
        }
        var sample = samples.get(length);

        if (sample.needed) {
          var duplicate = sampledValues.indexOf(value) > -1;

          if (!duplicate || _this2.allowDuplicates) {
            var computedKey = type === 'row' ? 'col' : 'row';

            sample.strings.push(_defineProperty({ value: value }, computedKey, index));
            sampledValues.push(value);
            sample.needed--;
          }
        }
      });

      return samples;
    }
  }]);

  return SamplesGenerator;
}();

exports.default = SamplesGenerator;

/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _array = __webpack_require__(2);

var _object = __webpack_require__(1);

var _number = __webpack_require__(6);

var MIXIN_NAME = 'arrayMapper';

/**
 * @type {Object}
 */
var arrayMapper = {
  _arrayMap: [],

  /**
   * Get value by map index.
   *
   * @param {Number} index Array index.
   * @return {*} Returns value mapped to passed index.
   */
  getValueByIndex: function getValueByIndex(index) {
    var value = void 0;

    // eslint-disable-next-line no-cond-assign, no-return-assign
    return (value = this._arrayMap[index]) === void 0 ? null : value;
  },


  /**
   * Get map index by its value.
   *
   * @param {*} value Value to search.
   * @returns {Number} Returns array index.
   */
  getIndexByValue: function getIndexByValue(value) {
    var index = void 0;

    // eslint-disable-next-line no-cond-assign, no-return-assign
    return (index = this._arrayMap.indexOf(value)) === -1 ? null : index;
  },


  /**
   * Insert new items to array mapper starting at passed index. New entries will be a continuation of last value in the array.
   *
   * @param {Number} index Array index.
   * @param {Number} [amount=1] Defines how many items will be created to an array.
   * @returns {Array} Returns added items.
   */
  insertItems: function insertItems(index) {
    var _this = this;

    var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;

    var newIndex = (0, _array.arrayMax)(this._arrayMap) + 1;
    var addedItems = [];

    (0, _number.rangeEach)(amount - 1, function (count) {
      addedItems.push(_this._arrayMap.splice(index + count, 0, newIndex + count));
    });

    return addedItems;
  },


  /**
   * Remove items from array mapper.
   *
   * @param {Number} index Array index.
   * @param {Number} [amount=1] Defines how many items will be created to an array.
   * @returns {Array} Returns removed items.
   */
  removeItems: function removeItems(index) {
    var _this2 = this;

    var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;

    var removedItems = [];

    if (Array.isArray(index)) {
      var mapCopy = [].concat(this._arrayMap);

      // Sort descending
      index.sort(function (a, b) {
        return b - a;
      });

      removedItems = (0, _array.arrayReduce)(index, function (acc, item) {
        _this2._arrayMap.splice(item, 1);

        return acc.concat(mapCopy.slice(item, item + 1));
      }, []);
    } else {
      removedItems = this._arrayMap.splice(index, amount);
    }

    return removedItems;
  },


  /**
   * Unshift items (remove and shift chunk of array to the left).
   *
   * @param {Number|Array} index Array index or Array of indexes to unshift.
   * @param {Number} [amount=1] Defines how many items will be removed from an array (when index is passed as number).
   */
  unshiftItems: function unshiftItems(index) {
    var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;

    var removedItems = this.removeItems(index, amount);

    function countRowShift(logicalRow) {
      // Todo: compare perf between reduce vs sort->each->brake
      return (0, _array.arrayReduce)(removedItems, function (count, removedLogicalRow) {
        if (logicalRow > removedLogicalRow) {
          count++;
        }

        return count;
      }, 0);
    }

    this._arrayMap = (0, _array.arrayMap)(this._arrayMap, function (logicalRow, physicalRow) {
      var rowShift = countRowShift(logicalRow);

      if (rowShift) {
        logicalRow -= rowShift;
      }

      return logicalRow;
    });
  },


  /**
   * Shift (right shifting) items starting at passed index.
   *
   * @param {Number} index Array index.
   * @param {Number} [amount=1] Defines how many items will be created to an array.
   */
  shiftItems: function shiftItems(index) {
    var _this3 = this;

    var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;

    this._arrayMap = (0, _array.arrayMap)(this._arrayMap, function (row) {
      if (row >= index) {
        row += amount;
      }

      return row;
    });

    (0, _number.rangeEach)(amount - 1, function (count) {
      _this3._arrayMap.splice(index + count, 0, index + count);
    });
  },


  /**
   * Clear all stored index<->value information from an array.
   */
  clearMap: function clearMap() {
    this._arrayMap.length = 0;
  }
};

(0, _object.defineGetter)(arrayMapper, 'MIXIN_NAME', MIXIN_NAME, {
  writable: false,
  enumerable: false
});

exports.default = arrayMapper;

/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _number = __webpack_require__(6);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var STATE_INITIALIZED = 0;
var STATE_BUILT = 1;
var STATE_APPENDED = 2;
var UNIT = 'px';

/**
 * @class
 * @private
 */

var BaseUI = function () {
  function BaseUI(hotInstance) {
    _classCallCheck(this, BaseUI);

    /**
     * Instance of Handsontable.
     *
     * @type {Core}
     */
    this.hot = hotInstance;
    /**
     * DOM element representing the ui element.
     *
     * @type {HTMLElement}
     * @private
     */
    this._element = null;
    /**
     * Flag which determines build state of element.
     *
     * @type {Boolean}
     */
    this.state = STATE_INITIALIZED;
  }

  /**
   * Add created UI elements to table.
   *
   * @param {HTMLElement} wrapper Element which are parent for our UI element.
   */


  _createClass(BaseUI, [{
    key: 'appendTo',
    value: function appendTo(wrapper) {
      wrapper.appendChild(this._element);

      this.state = STATE_APPENDED;
    }

    /**
     * Method for create UI element. Only create, without append to table.
     */

  }, {
    key: 'build',
    value: function build() {
      this._element = document.createElement('div');
      this.state = STATE_BUILT;
    }

    /**
     * Method for remove UI element.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      if (this.isAppended()) {
        this._element.parentElement.removeChild(this._element);
      }

      this._element = null;
      this.state = STATE_INITIALIZED;
    }

    /**
     * Check if UI element are appended.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isAppended',
    value: function isAppended() {
      return this.state === STATE_APPENDED;
    }

    /**
     * Check if UI element are built.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isBuilt',
    value: function isBuilt() {
      return this.state >= STATE_BUILT;
    }

    /**
     * Setter for position.
     *
     * @param {Number} top New top position of the element.
     * @param {Number} left New left position of the element.
     */

  }, {
    key: 'setPosition',
    value: function setPosition(top, left) {
      if ((0, _number.isNumeric)(top)) {
        this._element.style.top = top + UNIT;
      }
      if ((0, _number.isNumeric)(left)) {
        this._element.style.left = left + UNIT;
      }
    }

    /**
     * Getter for the element position.
     *
     * @returns {Object} Object contains left and top position of the element.
     */

  }, {
    key: 'getPosition',
    value: function getPosition() {
      return {
        top: this._element.style.top ? parseInt(this._element.style.top, 10) : 0,
        left: this._element.style.left ? parseInt(this._element.style.left, 10) : 0
      };
    }

    /**
     * Setter for the element size.
     *
     * @param {Number} width New width of the element.
     * @param {Number} height New height of the element.
     */

  }, {
    key: 'setSize',
    value: function setSize(width, height) {
      if ((0, _number.isNumeric)(width)) {
        this._element.style.width = width + UNIT;
      }
      if ((0, _number.isNumeric)(height)) {
        this._element.style.height = height + UNIT;
      }
    }

    /**
     * Getter for the element position.
     *
     * @returns {Object} Object contains height and width of the element.
     */

  }, {
    key: 'getSize',
    value: function getSize() {
      return {
        width: this._element.style.width ? parseInt(this._element.style.width, 10) : 0,
        height: this._element.style.height ? parseInt(this._element.style.height, 10) : 0
      };
    }

    /**
     * Setter for the element offset. Offset means marginTop and marginLeft of the element.
     *
     * @param {Number} top New margin top of the element.
     * @param {Number} left New margin left of the element.
     */

  }, {
    key: 'setOffset',
    value: function setOffset(top, left) {
      if ((0, _number.isNumeric)(top)) {
        this._element.style.marginTop = top + UNIT;
      }
      if ((0, _number.isNumeric)(left)) {
        this._element.style.marginLeft = left + UNIT;
      }
    }

    /**
     * Getter for the element offset.
     *
     * @returns {Object} Object contains top and left offset of the element.
     */

  }, {
    key: 'getOffset',
    value: function getOffset() {
      return {
        top: this._element.style.marginTop ? parseInt(this._element.style.marginTop, 10) : 0,
        left: this._element.style.marginLeft ? parseInt(this._element.style.marginLeft, 10) : 0
      };
    }
  }]);

  return BaseUI;
}();

exports.default = BaseUI;

/***/ }),
/* 316 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var STATE_INITIALIZED = 0;
var STATE_BUILT = 1;
var STATE_APPENDED = 2;
var UNIT = 'px';

/**
 * @class
 * @private
 */

var BaseUI = function () {
  function BaseUI(hotInstance) {
    _classCallCheck(this, BaseUI);

    /**
     * Instance of Handsontable.
     *
     * @type {Core}
     */
    this.hot = hotInstance;
    /**
     * DOM element representing the ui element.
     *
     * @type {HTMLElement}
     * @private
     */
    this._element = null;
    /**
     * Flag which determines build state of element.
     *
     * @type {Boolean}
     */
    this.state = STATE_INITIALIZED;
  }

  /**
   * Add created UI elements to table.
   *
   * @param {HTMLElement} wrapper Element which are parent for our UI element.
   */


  _createClass(BaseUI, [{
    key: 'appendTo',
    value: function appendTo(wrapper) {
      wrapper.appendChild(this._element);

      this.state = STATE_APPENDED;
    }

    /**
     * Method for create UI element. Only create, without append to table.
     */

  }, {
    key: 'build',
    value: function build() {
      this._element = document.createElement('div');
      this.state = STATE_BUILT;
    }

    /**
     * Method for remove UI element.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      if (this.isAppended()) {
        this._element.parentElement.removeChild(this._element);
      }

      this._element = null;
      this.state = STATE_INITIALIZED;
    }

    /**
     * Check if UI element are appended.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isAppended',
    value: function isAppended() {
      return this.state === STATE_APPENDED;
    }

    /**
     * Check if UI element are built.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isBuilt',
    value: function isBuilt() {
      return this.state >= STATE_BUILT;
    }

    /**
     * Setter for position.
     *
     * @param {Number} top New top position of the element.
     * @param {Number} left New left position of the element.
     */

  }, {
    key: 'setPosition',
    value: function setPosition(top, left) {
      if (top !== void 0) {
        this._element.style.top = top + UNIT;
      }
      if (left !== void 0) {
        this._element.style.left = left + UNIT;
      }
    }

    /**
     * Getter for the element position.
     *
     * @returns {Object} Object contains left and top position of the element.
     */

  }, {
    key: 'getPosition',
    value: function getPosition() {
      return {
        top: this._element.style.top ? parseInt(this._element.style.top, 10) : 0,
        left: this._element.style.left ? parseInt(this._element.style.left, 10) : 0
      };
    }

    /**
     * Setter for the element size.
     *
     * @param {Number} width New width of the element.
     * @param {Number} height New height of the element.
     */

  }, {
    key: 'setSize',
    value: function setSize(width, height) {
      if (width) {
        this._element.style.width = width + UNIT;
      }
      if (height) {
        this._element.style.height = height + UNIT;
      }
    }

    /**
     * Getter for the element position.
     *
     * @returns {Object} Object contains height and width of the element.
     */

  }, {
    key: 'getSize',
    value: function getSize() {
      return {
        width: this._element.style.width ? parseInt(this._element.style.width, 10) : 0,
        height: this._element.style.height ? parseInt(this._element.style.height, 10) : 0
      };
    }

    /**
     * Setter for the element offset. Offset means marginTop and marginLeft of the element.
     *
     * @param {Number} top New margin top of the element.
     * @param {Number} left New margin left of the element.
     */

  }, {
    key: 'setOffset',
    value: function setOffset(top, left) {
      if (top) {
        this._element.style.marginTop = top + UNIT;
      }
      if (left) {
        this._element.style.marginLeft = left + UNIT;
      }
    }

    /**
     * Getter for the element offset.
     *
     * @returns {Object} Object contains top and left offset of the element.
     */

  }, {
    key: 'getOffset',
    value: function getOffset() {
      return {
        top: this._element.style.marginTop ? parseInt(this._element.style.marginTop, 10) : 0,
        left: this._element.style.marginLeft ? parseInt(this._element.style.marginLeft, 10) : 0
      };
    }
  }]);

  return BaseUI;
}();

exports.default = BaseUI;

/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/*!
 * https://github.com/Starcounter-Jack/JSON-Patch
 * json-patch-duplex.js version: 0.5.7
 * (c) 2013 Joachim Wester
 * MIT license
 */
var __extends = undefined && undefined.__extends || function (d, b) {
    for (var p in b) {
        if (b.hasOwnProperty(p)) d[p] = b[p];
    }function __() {
        this.constructor = d;
    }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var OriginalError = Error;
var jsonpatch;
(function (jsonpatch) {
    var _objectKeys = function _objectKeys(obj) {
        if (_isArray(obj)) {
            var keys = new Array(obj.length);
            for (var k = 0; k < keys.length; k++) {
                keys[k] = "" + k;
            }
            return keys;
        }
        if (Object.keys) {
            return Object.keys(obj);
        }
        var keys = [];
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                keys.push(i);
            }
        }
        return keys;
    };
    function _equals(a, b) {
        switch (typeof a === 'undefined' ? 'undefined' : _typeof(a)) {
            case 'undefined': //backward compatibility, but really I think we should return false
            case 'boolean':
            case 'string':
            case 'number':
                return a === b;
            case 'object':
                if (a === null) return b === null;
                if (_isArray(a)) {
                    if (!_isArray(b) || a.length !== b.length) return false;
                    for (var i = 0, l = a.length; i < l; i++) {
                        if (!_equals(a[i], b[i])) return false;
                    }return true;
                }
                var bKeys = _objectKeys(b);
                var bLength = bKeys.length;
                if (_objectKeys(a).length !== bLength) return false;
                for (var i = 0; i < bLength; i++) {
                    if (!_equals(a[i], b[i])) return false;
                }return true;
            default:
                return false;
        }
    }
    /* We use a Javascript hash to store each
     function. Each hash entry (property) uses
     the operation identifiers specified in rfc6902.
     In this way, we can map each patch operation
     to its dedicated function in efficient way.
     */
    /* The operations applicable to an object */
    var objOps = {
        add: function add(obj, key) {
            obj[key] = this.value;
            return true;
        },
        remove: function remove(obj, key) {
            delete obj[key];
            return true;
        },
        replace: function replace(obj, key) {
            obj[key] = this.value;
            return true;
        },
        move: function move(obj, key, tree) {
            var temp = { op: "_get", path: this.from };
            apply(tree, [temp]);
            apply(tree, [{ op: "remove", path: this.from }]);
            apply(tree, [{ op: "add", path: this.path, value: temp.value }]);
            return true;
        },
        copy: function copy(obj, key, tree) {
            var temp = { op: "_get", path: this.from };
            apply(tree, [temp]);
            apply(tree, [{ op: "add", path: this.path, value: temp.value }]);
            return true;
        },
        test: function test(obj, key) {
            return _equals(obj[key], this.value);
        },
        _get: function _get(obj, key) {
            this.value = obj[key];
        }
    };
    /* The operations applicable to an array. Many are the same as for the object */
    var arrOps = {
        add: function add(arr, i) {
            arr.splice(i, 0, this.value);
            return true;
        },
        remove: function remove(arr, i) {
            arr.splice(i, 1);
            return true;
        },
        replace: function replace(arr, i) {
            arr[i] = this.value;
            return true;
        },
        move: objOps.move,
        copy: objOps.copy,
        test: objOps.test,
        _get: objOps._get
    };
    /* The operations applicable to object root. Many are the same as for the object */
    var rootOps = {
        add: function add(obj) {
            rootOps.remove.call(this, obj);
            for (var key in this.value) {
                if (this.value.hasOwnProperty(key)) {
                    obj[key] = this.value[key];
                }
            }
            return true;
        },
        remove: function remove(obj) {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    objOps.remove.call(this, obj, key);
                }
            }
            return true;
        },
        replace: function replace(obj) {
            apply(obj, [{ op: "remove", path: this.path }]);
            apply(obj, [{ op: "add", path: this.path, value: this.value }]);
            return true;
        },
        move: objOps.move,
        copy: objOps.copy,
        test: function test(obj) {
            return JSON.stringify(obj) === JSON.stringify(this.value);
        },
        _get: function _get(obj) {
            this.value = obj;
        }
    };
    var observeOps = {
        add: function add(patches, path) {
            var patch = {
                op: "add",
                path: path + escapePathComponent(this.name),
                value: this.object[this.name] };
            patches.push(patch);
        },
        'delete': function _delete(patches, path) {
            var patch = {
                op: "remove",
                path: path + escapePathComponent(this.name)
            };
            patches.push(patch);
        },
        update: function update(patches, path) {
            var patch = {
                op: "replace",
                path: path + escapePathComponent(this.name),
                value: this.object[this.name]
            };
            patches.push(patch);
        }
    };
    function escapePathComponent(str) {
        if (str.indexOf('/') === -1 && str.indexOf('~') === -1) return str;
        return str.replace(/~/g, '~0').replace(/\//g, '~1');
    }
    function _getPathRecursive(root, obj) {
        var found;
        for (var key in root) {
            if (root.hasOwnProperty(key)) {
                if (root[key] === obj) {
                    return escapePathComponent(key) + '/';
                } else if (_typeof(root[key]) === 'object') {
                    found = _getPathRecursive(root[key], obj);
                    if (found != '') {
                        return escapePathComponent(key) + '/' + found;
                    }
                }
            }
        }
        return '';
    }
    function getPath(root, obj) {
        if (root === obj) {
            return '/';
        }
        var path = _getPathRecursive(root, obj);
        if (path === '') {
            throw new OriginalError("Object not found in root");
        }
        return '/' + path;
    }
    var beforeDict = [];
    var Mirror = function () {
        function Mirror(obj) {
            this.observers = [];
            this.obj = obj;
        }
        return Mirror;
    }();
    var ObserverInfo = function () {
        function ObserverInfo(callback, observer) {
            this.callback = callback;
            this.observer = observer;
        }
        return ObserverInfo;
    }();
    function getMirror(obj) {
        for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
            if (beforeDict[i].obj === obj) {
                return beforeDict[i];
            }
        }
    }
    function getObserverFromMirror(mirror, callback) {
        for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
            if (mirror.observers[j].callback === callback) {
                return mirror.observers[j].observer;
            }
        }
    }
    function removeObserverFromMirror(mirror, observer) {
        for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
            if (mirror.observers[j].observer === observer) {
                mirror.observers.splice(j, 1);
                return;
            }
        }
    }
    function unobserve(root, observer) {
        observer.unobserve();
    }
    jsonpatch.unobserve = unobserve;
    function deepClone(obj) {
        if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === "object") {
            return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
        } else {
            return obj; //no need to clone primitives
        }
    }
    function observe(obj, callback) {
        var patches = [];
        var root = obj;
        var observer;
        var mirror = getMirror(obj);
        if (!mirror) {
            mirror = new Mirror(obj);
            beforeDict.push(mirror);
        } else {
            observer = getObserverFromMirror(mirror, callback);
        }
        if (observer) {
            return observer;
        }
        observer = {};
        mirror.value = deepClone(obj);
        if (callback) {
            observer.callback = callback;
            observer.next = null;
            var intervals = this.intervals || [100, 1000, 10000, 60000];
            if (intervals.push === void 0) {
                throw new OriginalError("jsonpatch.intervals must be an array");
            }
            var currentInterval = 0;
            var dirtyCheck = function dirtyCheck() {
                generate(observer);
            };
            var fastCheck = function fastCheck() {
                clearTimeout(observer.next);
                observer.next = setTimeout(function () {
                    dirtyCheck();
                    currentInterval = 0;
                    observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
                }, 0);
            };
            var slowCheck = function slowCheck() {
                dirtyCheck();
                if (currentInterval == intervals.length) currentInterval = intervals.length - 1;
                observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
            };
            if (typeof window !== 'undefined') {
                if (window.addEventListener) {
                    window.addEventListener('mousedown', fastCheck);
                    window.addEventListener('mouseup', fastCheck);
                    window.addEventListener('keydown', fastCheck);
                } else {
                    document.documentElement.attachEvent('onmousedown', fastCheck);
                    document.documentElement.attachEvent('onmouseup', fastCheck);
                    document.documentElement.attachEvent('onkeydown', fastCheck);
                }
            }
            observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
        }
        observer.patches = patches;
        observer.object = obj;
        observer.unobserve = function () {
            generate(observer);
            clearTimeout(observer.next);
            removeObserverFromMirror(mirror, observer);
            if (typeof window !== 'undefined') {
                if (window.removeEventListener) {
                    window.removeEventListener('mousedown', fastCheck);
                    window.removeEventListener('mouseup', fastCheck);
                    window.removeEventListener('keydown', fastCheck);
                } else {
                    document.documentElement.detachEvent('onmousedown', fastCheck);
                    document.documentElement.detachEvent('onmouseup', fastCheck);
                    document.documentElement.detachEvent('onkeydown', fastCheck);
                }
            }
        };
        mirror.observers.push(new ObserverInfo(callback, observer));
        return observer;
    }
    jsonpatch.observe = observe;
    function generate(observer) {
        var mirror;
        for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
            if (beforeDict[i].obj === observer.object) {
                mirror = beforeDict[i];
                break;
            }
        }
        _generate(mirror.value, observer.object, observer.patches, "");
        if (observer.patches.length) {
            apply(mirror.value, observer.patches);
        }
        var temp = observer.patches;
        if (temp.length > 0) {
            observer.patches = [];
            if (observer.callback) {
                observer.callback(temp);
            }
        }
        return temp;
    }
    jsonpatch.generate = generate;
    // Dirty check if obj is different from mirror, generate patches and update mirror
    function _generate(mirror, obj, patches, path) {
        var newKeys = _objectKeys(obj);
        var oldKeys = _objectKeys(mirror);
        var changed = false;
        var deleted = false;
        //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)"
        for (var t = oldKeys.length - 1; t >= 0; t--) {
            var key = oldKeys[t];
            var oldVal = mirror[key];
            if (obj.hasOwnProperty(key)) {
                var newVal = obj[key];
                if ((typeof oldVal === 'undefined' ? 'undefined' : _typeof(oldVal)) == "object" && oldVal != null && (typeof newVal === 'undefined' ? 'undefined' : _typeof(newVal)) == "object" && newVal != null) {
                    _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key));
                } else {
                    if (oldVal != newVal) {
                        changed = true;
                        patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: deepClone(newVal) });
                    }
                }
            } else {
                patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) });
                deleted = true; // property has been deleted
            }
        }
        if (!deleted && newKeys.length == oldKeys.length) {
            return;
        }
        for (var t = 0; t < newKeys.length; t++) {
            var key = newKeys[t];
            if (!mirror.hasOwnProperty(key)) {
                patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: deepClone(obj[key]) });
            }
        }
    }
    var _isArray;
    if (Array.isArray) {
        _isArray = Array.isArray;
    } else {
        _isArray = function _isArray(obj) {
            return obj.push && typeof obj.length === 'number';
        };
    }
    //3x faster than cached /^\d+$/.test(str)
    function isInteger(str) {
        var i = 0;
        var len = str.length;
        var charCode;
        while (i < len) {
            charCode = str.charCodeAt(i);
            if (charCode >= 48 && charCode <= 57) {
                i++;
                continue;
            }
            return false;
        }
        return true;
    }
    /// Apply a json-patch operation on an object tree
    function apply(tree, patches, validate) {
        var result = false,
            p = 0,
            plen = patches.length,
            patch,
            key;
        while (p < plen) {
            patch = patches[p];
            p++;
            // Find the object
            var path = patch.path || "";
            var keys = path.split('/');
            var obj = tree;
            var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift
            var len = keys.length;
            var existingPathFragment = undefined;
            while (true) {
                key = keys[t];
                if (validate) {
                    if (existingPathFragment === undefined) {
                        if (obj[key] === undefined) {
                            existingPathFragment = keys.slice(0, t).join('/');
                        } else if (t == len - 1) {
                            existingPathFragment = patch.path;
                        }
                        if (existingPathFragment !== undefined) {
                            this.validator(patch, p - 1, tree, existingPathFragment);
                        }
                    }
                }
                t++;
                if (key === undefined) {
                    if (t >= len) {
                        result = rootOps[patch.op].call(patch, obj, key, tree); // Apply patch
                        break;
                    }
                }
                if (_isArray(obj)) {
                    if (key === '-') {
                        key = obj.length;
                    } else {
                        if (validate && !isInteger(key)) {
                            throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", p - 1, patch.path, patch);
                        }
                        key = parseInt(key, 10);
                    }
                    if (t >= len) {
                        if (validate && patch.op === "add" && key > obj.length) {
                            throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", p - 1, patch.path, patch);
                        }
                        result = arrOps[patch.op].call(patch, obj, key, tree); // Apply patch
                        break;
                    }
                } else {
                    if (key && key.indexOf('~') != -1) key = key.replace(/~1/g, '/').replace(/~0/g, '~'); // escape chars
                    if (t >= len) {
                        result = objOps[patch.op].call(patch, obj, key, tree); // Apply patch
                        break;
                    }
                }
                obj = obj[key];
            }
        }
        return result;
    }
    jsonpatch.apply = apply;
    function compare(tree1, tree2) {
        var patches = [];
        _generate(tree1, tree2, patches, '');
        return patches;
    }
    jsonpatch.compare = compare;
    var JsonPatchError = function (_super) {
        __extends(JsonPatchError, _super);
        function JsonPatchError(message, name, index, operation, tree) {
            _super.call(this, message);
            this.message = message;
            this.name = name;
            this.index = index;
            this.operation = operation;
            this.tree = tree;
        }
        return JsonPatchError;
    }(OriginalError);
    jsonpatch.JsonPatchError = JsonPatchError;
    jsonpatch.Error = JsonPatchError;
    /**
     * Recursively checks whether an object has any undefined values inside.
     */
    function hasUndefined(obj) {
        if (obj === undefined) {
            return true;
        }
        if (typeof obj == "array" || (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) == "object") {
            for (var i in obj) {
                if (hasUndefined(obj[i])) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.
     * @param {object} operation - operation object (patch)
     * @param {number} index - index of operation in the sequence
     * @param {object} [tree] - object where the operation is supposed to be applied
     * @param {string} [existingPathFragment] - comes along with `tree`
     */
    function validator(operation, index, tree, existingPathFragment) {
        if ((typeof operation === 'undefined' ? 'undefined' : _typeof(operation)) !== 'object' || operation === null || _isArray(operation)) {
            throw new JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, tree);
        } else if (!objOps[operation.op]) {
            throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, tree);
        } else if (typeof operation.path !== 'string') {
            throw new JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, tree);
        } else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') {
            throw new JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, tree);
        } else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) {
            throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, tree);
        } else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && hasUndefined(operation.value)) {
            throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, tree);
        } else if (tree) {
            if (operation.op == "add") {
                var pathLen = operation.path.split("/").length;
                var existingPathLen = existingPathFragment.split("/").length;
                if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {
                    throw new JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, tree);
                }
            } else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') {
                if (operation.path !== existingPathFragment) {
                    throw new JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, tree);
                }
            } else if (operation.op === 'move' || operation.op === 'copy') {
                var existingValue = { op: "_get", path: operation.from, value: undefined };
                var error = jsonpatch.validate([existingValue], tree);
                if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') {
                    throw new JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, tree);
                }
            }
        }
    }
    jsonpatch.validator = validator;
    /**
     * Validates a sequence of operations. If `tree` parameter is provided, the sequence is additionally validated against the object tree.
     * If error is encountered, returns a JsonPatchError object
     * @param sequence
     * @param tree
     * @returns {JsonPatchError|undefined}
     */
    function validate(sequence, tree) {
        try {
            if (!_isArray(sequence)) {
                throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
            }
            if (tree) {
                tree = JSON.parse(JSON.stringify(tree)); //clone tree so that we can safely try applying operations
                apply.call(this, tree, sequence, true);
            } else {
                for (var i = 0; i < sequence.length; i++) {
                    this.validator(sequence[i], i);
                }
            }
        } catch (e) {
            if (e instanceof JsonPatchError) {
                return e;
            } else {
                throw e;
            }
        }
    }
    jsonpatch.validate = validate;
})(jsonpatch || (jsonpatch = {}));
if (true) {
    exports.apply = jsonpatch.apply;
    exports.observe = jsonpatch.observe;
    exports.unobserve = jsonpatch.unobserve;
    exports.generate = jsonpatch.generate;
    exports.compare = jsonpatch.compare;
    exports.validate = jsonpatch.validate;
    exports.validator = jsonpatch.validator;
    exports.JsonPatchError = jsonpatch.JsonPatchError;
    exports.Error = jsonpatch.Error;
}

/***/ }),
/* 318 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

__webpack_require__(91);

__webpack_require__(106);

__webpack_require__(107);

__webpack_require__(111);

__webpack_require__(112);

__webpack_require__(114);

__webpack_require__(117);

__webpack_require__(118);

__webpack_require__(119);

__webpack_require__(120);

__webpack_require__(121);

__webpack_require__(122);

__webpack_require__(123);

__webpack_require__(124);

__webpack_require__(125);

__webpack_require__(126);

__webpack_require__(127);

__webpack_require__(128);

__webpack_require__(129);

__webpack_require__(130);

__webpack_require__(131);

__webpack_require__(132);

__webpack_require__(133);

__webpack_require__(134);

__webpack_require__(136);

__webpack_require__(138);

__webpack_require__(139);

__webpack_require__(140);

__webpack_require__(141);

__webpack_require__(142);

__webpack_require__(143);

__webpack_require__(144);

__webpack_require__(145);

__webpack_require__(146);

__webpack_require__(147);

__webpack_require__(148);

__webpack_require__(149);

__webpack_require__(150);

__webpack_require__(81);

__webpack_require__(151);

__webpack_require__(152);

__webpack_require__(154);

__webpack_require__(155);

__webpack_require__(156);

__webpack_require__(157);

__webpack_require__(158);

__webpack_require__(159);

__webpack_require__(160);

__webpack_require__(162);

__webpack_require__(163);

__webpack_require__(164);

__webpack_require__(167);

__webpack_require__(168);

__webpack_require__(169);

__webpack_require__(337);

__webpack_require__(338);

__webpack_require__(339);

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var _cellTypes = __webpack_require__(83);

var _core = __webpack_require__(84);

var _core2 = _interopRequireDefault(_core);

var _jquery = __webpack_require__(387);

var _jquery2 = _interopRequireDefault(_jquery);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _ghostTable = __webpack_require__(87);

var _ghostTable2 = _interopRequireDefault(_ghostTable);

var _array = __webpack_require__(2);

var arrayHelpers = _interopRequireWildcard(_array);

var _browser = __webpack_require__(28);

var browserHelpers = _interopRequireWildcard(_browser);

var _data = __webpack_require__(86);

var dataHelpers = _interopRequireWildcard(_data);

var _date = __webpack_require__(306);

var dateHelpers = _interopRequireWildcard(_date);

var _feature = __webpack_require__(39);

var featureHelpers = _interopRequireWildcard(_feature);

var _function = __webpack_require__(41);

var functionHelpers = _interopRequireWildcard(_function);

var _mixed = __webpack_require__(17);

var mixedHelpers = _interopRequireWildcard(_mixed);

var _number = __webpack_require__(6);

var numberHelpers = _interopRequireWildcard(_number);

var _object = __webpack_require__(1);

var objectHelpers = _interopRequireWildcard(_object);

var _setting = __webpack_require__(85);

var settingHelpers = _interopRequireWildcard(_setting);

var _string = __webpack_require__(36);

var stringHelpers = _interopRequireWildcard(_string);

var _unicode = __webpack_require__(20);

var unicodeHelpers = _interopRequireWildcard(_unicode);

var _element = __webpack_require__(0);

var domHelpers = _interopRequireWildcard(_element);

var _event = __webpack_require__(12);

var domEventHelpers = _interopRequireWildcard(_event);

var _index = __webpack_require__(388);

var plugins = _interopRequireWildcard(_index);

var _plugins = __webpack_require__(7);

var _defaultSettings = __webpack_require__(310);

var _defaultSettings2 = _interopRequireDefault(_defaultSettings);

var _rootInstance = __webpack_require__(309);

var _i18n = __webpack_require__(311);

var _constants = __webpack_require__(8);

var constants = _interopRequireWildcard(_constants);

var _dictionariesManager = __webpack_require__(67);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function Handsontable(rootElement, userSettings) {
  var instance = new _core2.default(rootElement, userSettings || {}, _rootInstance.rootInstanceSymbol);

  instance.init();

  return instance;
}

(0, _jquery2.default)(Handsontable);

Handsontable.Core = _core2.default;
Handsontable.DefaultSettings = _defaultSettings2.default;
Handsontable.EventManager = _eventManager2.default;
Handsontable._getListenersCounter = _eventManager.getListenersCounter; // For MemoryLeak tests

Handsontable.buildDate = '25/01/2018 10:06:15';
Handsontable.packageName = 'handsontable';
Handsontable.version = '0.35.1';

var baseVersion = '';

if (baseVersion) {
  Handsontable.baseVersion = baseVersion;
}

// Export Hooks singleton
Handsontable.hooks = _pluginHooks2.default.getSingleton();

// TODO: Remove this exports after rewrite tests about this module
Handsontable.__GhostTable = _ghostTable2.default;
//

// Export all helpers to the Handsontable object
var HELPERS = [arrayHelpers, browserHelpers, dataHelpers, dateHelpers, featureHelpers, functionHelpers, mixedHelpers, numberHelpers, objectHelpers, settingHelpers, stringHelpers, unicodeHelpers];
var DOM = [domHelpers, domEventHelpers];

Handsontable.helper = {};
Handsontable.dom = {};

// Fill general helpers.
arrayHelpers.arrayEach(HELPERS, function (helper) {
  arrayHelpers.arrayEach(Object.getOwnPropertyNames(helper), function (key) {
    if (key.charAt(0) !== '_') {
      Handsontable.helper[key] = helper[key];
    }
  });
});

// Fill DOM helpers.
arrayHelpers.arrayEach(DOM, function (helper) {
  arrayHelpers.arrayEach(Object.getOwnPropertyNames(helper), function (key) {
    if (key.charAt(0) !== '_') {
      Handsontable.dom[key] = helper[key];
    }
  });
});

// Export cell types.
Handsontable.cellTypes = {};

arrayHelpers.arrayEach((0, _cellTypes.getRegisteredCellTypeNames)(), function (cellTypeName) {
  Handsontable.cellTypes[cellTypeName] = (0, _cellTypes.getCellType)(cellTypeName);
});

Handsontable.cellTypes.registerCellType = _cellTypes.registerCellType;
Handsontable.cellTypes.getCellType = _cellTypes.getCellType;

// Export all registered editors from the Handsontable.
Handsontable.editors = {};

arrayHelpers.arrayEach((0, _editors.getRegisteredEditorNames)(), function (editorName) {
  Handsontable.editors[stringHelpers.toUpperCaseFirst(editorName) + 'Editor'] = (0, _editors.getEditor)(editorName);
});

Handsontable.editors.registerEditor = _editors.registerEditor;
Handsontable.editors.getEditor = _editors.getEditor;

// Export all registered renderers from the Handsontable.
Handsontable.renderers = {};

arrayHelpers.arrayEach((0, _renderers.getRegisteredRendererNames)(), function (rendererName) {
  var renderer = (0, _renderers.getRenderer)(rendererName);

  if (rendererName === 'base') {
    Handsontable.renderers.cellDecorator = renderer;
  }
  Handsontable.renderers[stringHelpers.toUpperCaseFirst(rendererName) + 'Renderer'] = renderer;
});

Handsontable.renderers.registerRenderer = _renderers.registerRenderer;
Handsontable.renderers.getRenderer = _renderers.getRenderer;

// Export all registered validators from the Handsontable.
Handsontable.validators = {};

arrayHelpers.arrayEach((0, _validators.getRegisteredValidatorNames)(), function (validatorName) {
  Handsontable.validators[stringHelpers.toUpperCaseFirst(validatorName) + 'Validator'] = (0, _validators.getValidator)(validatorName);
});

Handsontable.validators.registerValidator = _validators.registerValidator;
Handsontable.validators.getValidator = _validators.getValidator;

// Export all registered plugins from the Handsontable.
Handsontable.plugins = {};

arrayHelpers.arrayEach(Object.getOwnPropertyNames(plugins), function (pluginName) {
  var plugin = plugins[pluginName];

  if (pluginName === 'Base') {
    Handsontable.plugins[pluginName + 'Plugin'] = plugin;
  } else {
    Handsontable.plugins[pluginName] = plugin;
  }
});

Handsontable.plugins.registerPlugin = _plugins.registerPlugin;

Handsontable.languages = {};
Handsontable.languages.dictionaryKeys = constants;
Handsontable.languages.getLanguageDictionary = _dictionariesManager.getLanguageDictionary;
Handsontable.languages.getLanguagesDictionaries = _dictionariesManager.getLanguagesDictionaries;
Handsontable.languages.registerLanguageDictionary = _dictionariesManager.registerLanguageDictionary;

// Alias to `getTranslatedPhrase` function, for more information check it API.
Handsontable.languages.getTranslatedPhrase = function () {
  return _i18n.getTranslatedPhrase.apply(undefined, arguments);
};

exports.default = Handsontable;

/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {

var dP = __webpack_require__(19);
var anObject = __webpack_require__(18);
var getKeys = __webpack_require__(37);

module.exports = __webpack_require__(22) ? Object.defineProperties : function defineProperties(O, Properties) {
  anObject(O);
  var keys = getKeys(Properties);
  var length = keys.length;
  var i = 0;
  var P;
  while (length > i) dP.f(O, P = keys[i++], Properties[P]);
  return O;
};


/***/ }),
/* 320 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var create = __webpack_require__(70);
var descriptor = __webpack_require__(49);
var setToStringTag = __webpack_require__(51);
var IteratorPrototype = {};

// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(31)(IteratorPrototype, __webpack_require__(10)('iterator'), function () { return this; });

module.exports = function (Constructor, NAME, next) {
  Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
  setToStringTag(Constructor, NAME + ' Iterator');
};


/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(5);
var setPrototypeOf = __webpack_require__(105).set;
module.exports = function (that, target, C) {
  var S = target.constructor;
  var P;
  if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) {
    setPrototypeOf(that, P);
  } return that;
};


/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {

// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__(323);

module.exports = function (original, length) {
  return new (speciesConstructor(original))(length);
};


/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(5);
var isArray = __webpack_require__(108);
var SPECIES = __webpack_require__(10)('species');

module.exports = function (original) {
  var C;
  if (isArray(original)) {
    C = original.constructor;
    // cross-realm fallback
    if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
    if (isObject(C)) {
      C = C[SPECIES];
      if (C === null) C = undefined;
    }
  } return C === undefined ? Array : C;
};


/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {

// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(18);
var aFunction = __webpack_require__(58);
var SPECIES = __webpack_require__(10)('species');
module.exports = function (O, D) {
  var C = anObject(O).constructor;
  var S;
  return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};


/***/ }),
/* 325 */
/***/ (function(module, exports) {

// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function (fn, args, that) {
  var un = that === undefined;
  switch (args.length) {
    case 0: return un ? fn()
                      : fn.call(that);
    case 1: return un ? fn(args[0])
                      : fn.call(that, args[0]);
    case 2: return un ? fn(args[0], args[1])
                      : fn.call(that, args[0], args[1]);
    case 3: return un ? fn(args[0], args[1], args[2])
                      : fn.call(that, args[0], args[1], args[2]);
    case 4: return un ? fn(args[0], args[1], args[2], args[3])
                      : fn.call(that, args[0], args[1], args[2], args[3]);
  } return fn.apply(that, args);
};


/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(13);
var macrotask = __webpack_require__(76).set;
var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var isNode = __webpack_require__(42)(process) == 'process';

module.exports = function () {
  var head, last, notify;

  var flush = function () {
    var parent, fn;
    if (isNode && (parent = process.domain)) parent.exit();
    while (head) {
      fn = head.fn;
      head = head.next;
      try {
        fn();
      } catch (e) {
        if (head) notify();
        else last = undefined;
        throw e;
      }
    } last = undefined;
    if (parent) parent.enter();
  };

  // Node.js
  if (isNode) {
    notify = function () {
      process.nextTick(flush);
    };
  // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
  } else if (Observer && !(global.navigator && global.navigator.standalone)) {
    var toggle = true;
    var node = document.createTextNode('');
    new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
    notify = function () {
      node.data = toggle = !toggle;
    };
  // environments with maybe non-completely correct, but existent Promise
  } else if (Promise && Promise.resolve) {
    var promise = Promise.resolve();
    notify = function () {
      promise.then(flush);
    };
  // for other environments - macrotask based on:
  // - setImmediate
  // - MessageChannel
  // - window.postMessag
  // - onreadystatechange
  // - setTimeout
  } else {
    notify = function () {
      // strange IE + webpack dev server bug - use .call(global)
      macrotask.call(global, flush);
    };
  }

  return function (fn) {
    var task = { fn: fn, next: undefined };
    if (last) last.next = task;
    if (!head) {
      head = task;
      notify();
    } last = task;
  };
};


/***/ }),
/* 327 */
/***/ (function(module, exports) {

module.exports = function (exec) {
  try {
    return { e: false, v: exec() };
  } catch (e) {
    return { e: true, v: e };
  }
};


/***/ }),
/* 328 */
/***/ (function(module, exports, __webpack_require__) {

var anObject = __webpack_require__(18);
var isObject = __webpack_require__(5);
var newPromiseCapability = __webpack_require__(113);

module.exports = function (C, x) {
  anObject(C);
  if (isObject(x) && x.constructor === C) return x;
  var promiseCapability = newPromiseCapability.f(C);
  var resolve = promiseCapability.resolve;
  resolve(x);
  return promiseCapability.promise;
};


/***/ }),
/* 329 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(13);
var core = __webpack_require__(43);
var LIBRARY = __webpack_require__(61);
var wksExt = __webpack_require__(115);
var defineProperty = __webpack_require__(19).f;
module.exports = function (name) {
  var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
  if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};


/***/ }),
/* 330 */
/***/ (function(module, exports, __webpack_require__) {

// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(37);
var gOPS = __webpack_require__(65);
var pIE = __webpack_require__(52);
module.exports = function (it) {
  var result = getKeys(it);
  var getSymbols = gOPS.f;
  if (getSymbols) {
    var symbols = getSymbols(it);
    var isEnum = pIE.f;
    var i = 0;
    var key;
    while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
  } return result;
};


/***/ }),
/* 331 */
/***/ (function(module, exports) {

// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y) {
  // eslint-disable-next-line no-self-compare
  return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};


/***/ }),
/* 332 */
/***/ (function(module, exports, __webpack_require__) {

var toInteger = __webpack_require__(55);
var defined = __webpack_require__(38);
// true  -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
  return function (that, pos) {
    var s = String(defined(that));
    var i = toInteger(pos);
    var l = s.length;
    var a, b;
    if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
    a = s.charCodeAt(i);
    return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
      ? TO_STRING ? s.charAt(i) : a
      : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
  };
};


/***/ }),
/* 333 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__(18);
module.exports = function () {
  var that = anObject(this);
  var result = '';
  if (that.global) result += 'g';
  if (that.ignoreCase) result += 'i';
  if (that.multiline) result += 'm';
  if (that.unicode) result += 'u';
  if (that.sticky) result += 'y';
  return result;
};


/***/ }),
/* 334 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)

var toObject = __webpack_require__(33);
var toAbsoluteIndex = __webpack_require__(56);
var toLength = __webpack_require__(25);

module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
  var O = toObject(this);
  var len = toLength(O.length);
  var to = toAbsoluteIndex(target, len);
  var from = toAbsoluteIndex(start, len);
  var end = arguments.length > 2 ? arguments[2] : undefined;
  var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
  var inc = 1;
  if (from < to && to < from + count) {
    inc = -1;
    from += count - 1;
    to += count - 1;
  }
  while (count-- > 0) {
    if (from in O) O[to] = O[from];
    else delete O[to];
    to += inc;
    from += inc;
  } return O;
};


/***/ }),
/* 335 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)

var toObject = __webpack_require__(33);
var toAbsoluteIndex = __webpack_require__(56);
var toLength = __webpack_require__(25);
module.exports = function fill(value /* , start = 0, end = @length */) {
  var O = toObject(this);
  var length = toLength(O.length);
  var aLen = arguments.length;
  var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length);
  var end = aLen > 2 ? arguments[2] : undefined;
  var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
  while (endPos > index) O[index++] = value;
  return O;
};


/***/ }),
/* 336 */
/***/ (function(module, exports, __webpack_require__) {

// all object keys, includes non-enumerable and symbols
var gOPN = __webpack_require__(77);
var gOPS = __webpack_require__(65);
var anObject = __webpack_require__(18);
var Reflect = __webpack_require__(13).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) {
  var keys = gOPN.f(anObject(it));
  var getSymbols = gOPS.f;
  return getSymbols ? keys.concat(getSymbols(it)) : keys;
};


/***/ }),
/* 337 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 338 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 339 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 340 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

var _base = __webpack_require__(35);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays.
 * Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly
 *
 * @class DebugOverlay
 */
var DebugOverlay = function (_Overlay) {
  _inherits(DebugOverlay, _Overlay);

  /**
   * @param {Walkontable} wotInstance
   */
  function DebugOverlay(wotInstance) {
    _classCallCheck(this, DebugOverlay);

    var _this = _possibleConstructorReturn(this, (DebugOverlay.__proto__ || Object.getPrototypeOf(DebugOverlay)).call(this, wotInstance));

    _this.clone = _this.makeClone(_base2.default.CLONE_DEBUG);
    _this.clone.wtTable.holder.style.opacity = 0.4;
    _this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000';

    (0, _element.addClass)(_this.clone.wtTable.holder.parentNode, 'wtDebugVisible');
    return _this;
  }

  return DebugOverlay;
}(_base2.default);

_base2.default.registerOverlay(_base2.default.CLONE_DEBUG, DebugOverlay);

exports.default = DebugOverlay;

/***/ }),
/* 341 */
/***/ (function(module, exports) {

module.exports = function(module) {
	if(!module.webpackPolyfill) {
		module.deprecate = function() {};
		module.paths = [];
		// module.parent = undefined by default
		if(!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function() {
				return module.i;
			}
		});
		module.webpackPolyfill = 1;
	}
	return module;
};


/***/ }),
/* 342 */
/***/ (function(module, exports, __webpack_require__) {

var map = {
	"./af": 175,
	"./af.js": 175,
	"./ar": 176,
	"./ar-dz": 177,
	"./ar-dz.js": 177,
	"./ar-kw": 178,
	"./ar-kw.js": 178,
	"./ar-ly": 179,
	"./ar-ly.js": 179,
	"./ar-ma": 180,
	"./ar-ma.js": 180,
	"./ar-sa": 181,
	"./ar-sa.js": 181,
	"./ar-tn": 182,
	"./ar-tn.js": 182,
	"./ar.js": 176,
	"./az": 183,
	"./az.js": 183,
	"./be": 184,
	"./be.js": 184,
	"./bg": 185,
	"./bg.js": 185,
	"./bm": 186,
	"./bm.js": 186,
	"./bn": 187,
	"./bn.js": 187,
	"./bo": 188,
	"./bo.js": 188,
	"./br": 189,
	"./br.js": 189,
	"./bs": 190,
	"./bs.js": 190,
	"./ca": 191,
	"./ca.js": 191,
	"./cs": 192,
	"./cs.js": 192,
	"./cv": 193,
	"./cv.js": 193,
	"./cy": 194,
	"./cy.js": 194,
	"./da": 195,
	"./da.js": 195,
	"./de": 196,
	"./de-at": 197,
	"./de-at.js": 197,
	"./de-ch": 198,
	"./de-ch.js": 198,
	"./de.js": 196,
	"./dv": 199,
	"./dv.js": 199,
	"./el": 200,
	"./el.js": 200,
	"./en-au": 201,
	"./en-au.js": 201,
	"./en-ca": 202,
	"./en-ca.js": 202,
	"./en-gb": 203,
	"./en-gb.js": 203,
	"./en-ie": 204,
	"./en-ie.js": 204,
	"./en-nz": 205,
	"./en-nz.js": 205,
	"./eo": 206,
	"./eo.js": 206,
	"./es": 207,
	"./es-do": 208,
	"./es-do.js": 208,
	"./es-us": 209,
	"./es-us.js": 209,
	"./es.js": 207,
	"./et": 210,
	"./et.js": 210,
	"./eu": 211,
	"./eu.js": 211,
	"./fa": 212,
	"./fa.js": 212,
	"./fi": 213,
	"./fi.js": 213,
	"./fo": 214,
	"./fo.js": 214,
	"./fr": 215,
	"./fr-ca": 216,
	"./fr-ca.js": 216,
	"./fr-ch": 217,
	"./fr-ch.js": 217,
	"./fr.js": 215,
	"./fy": 218,
	"./fy.js": 218,
	"./gd": 219,
	"./gd.js": 219,
	"./gl": 220,
	"./gl.js": 220,
	"./gom-latn": 221,
	"./gom-latn.js": 221,
	"./gu": 222,
	"./gu.js": 222,
	"./he": 223,
	"./he.js": 223,
	"./hi": 224,
	"./hi.js": 224,
	"./hr": 225,
	"./hr.js": 225,
	"./hu": 226,
	"./hu.js": 226,
	"./hy-am": 227,
	"./hy-am.js": 227,
	"./id": 228,
	"./id.js": 228,
	"./is": 229,
	"./is.js": 229,
	"./it": 230,
	"./it.js": 230,
	"./ja": 231,
	"./ja.js": 231,
	"./jv": 232,
	"./jv.js": 232,
	"./ka": 233,
	"./ka.js": 233,
	"./kk": 234,
	"./kk.js": 234,
	"./km": 235,
	"./km.js": 235,
	"./kn": 236,
	"./kn.js": 236,
	"./ko": 237,
	"./ko.js": 237,
	"./ky": 238,
	"./ky.js": 238,
	"./lb": 239,
	"./lb.js": 239,
	"./lo": 240,
	"./lo.js": 240,
	"./lt": 241,
	"./lt.js": 241,
	"./lv": 242,
	"./lv.js": 242,
	"./me": 243,
	"./me.js": 243,
	"./mi": 244,
	"./mi.js": 244,
	"./mk": 245,
	"./mk.js": 245,
	"./ml": 246,
	"./ml.js": 246,
	"./mr": 247,
	"./mr.js": 247,
	"./ms": 248,
	"./ms-my": 249,
	"./ms-my.js": 249,
	"./ms.js": 248,
	"./mt": 250,
	"./mt.js": 250,
	"./my": 251,
	"./my.js": 251,
	"./nb": 252,
	"./nb.js": 252,
	"./ne": 253,
	"./ne.js": 253,
	"./nl": 254,
	"./nl-be": 255,
	"./nl-be.js": 255,
	"./nl.js": 254,
	"./nn": 256,
	"./nn.js": 256,
	"./pa-in": 257,
	"./pa-in.js": 257,
	"./pl": 258,
	"./pl.js": 258,
	"./pt": 259,
	"./pt-br": 260,
	"./pt-br.js": 260,
	"./pt.js": 259,
	"./ro": 261,
	"./ro.js": 261,
	"./ru": 262,
	"./ru.js": 262,
	"./sd": 263,
	"./sd.js": 263,
	"./se": 264,
	"./se.js": 264,
	"./si": 265,
	"./si.js": 265,
	"./sk": 266,
	"./sk.js": 266,
	"./sl": 267,
	"./sl.js": 267,
	"./sq": 268,
	"./sq.js": 268,
	"./sr": 269,
	"./sr-cyrl": 270,
	"./sr-cyrl.js": 270,
	"./sr.js": 269,
	"./ss": 271,
	"./ss.js": 271,
	"./sv": 272,
	"./sv.js": 272,
	"./sw": 273,
	"./sw.js": 273,
	"./ta": 274,
	"./ta.js": 274,
	"./te": 275,
	"./te.js": 275,
	"./tet": 276,
	"./tet.js": 276,
	"./th": 277,
	"./th.js": 277,
	"./tl-ph": 278,
	"./tl-ph.js": 278,
	"./tlh": 279,
	"./tlh.js": 279,
	"./tr": 280,
	"./tr.js": 280,
	"./tzl": 281,
	"./tzl.js": 281,
	"./tzm": 282,
	"./tzm-latn": 283,
	"./tzm-latn.js": 283,
	"./tzm.js": 282,
	"./uk": 284,
	"./uk.js": 284,
	"./ur": 285,
	"./ur.js": 285,
	"./uz": 286,
	"./uz-latn": 287,
	"./uz-latn.js": 287,
	"./uz.js": 286,
	"./vi": 288,
	"./vi.js": 288,
	"./x-pseudo": 289,
	"./x-pseudo.js": 289,
	"./yo": 290,
	"./yo.js": 290,
	"./zh-cn": 291,
	"./zh-cn.js": 291,
	"./zh-hk": 292,
	"./zh-hk.js": 292,
	"./zh-tw": 293,
	"./zh-tw.js": 293
};
function webpackContext(req) {
	return __webpack_require__(webpackContextResolve(req));
};
function webpackContextResolve(req) {
	var id = map[req];
	if(!(id + 1)) // check for number or string
		throw new Error("Cannot find module '" + req + "'.");
	return id;
};
webpackContext.keys = function webpackContextKeys() {
	return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = 342;

/***/ }),
/* 343 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _base = __webpack_require__(35);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @class LeftOverlay
 */
var LeftOverlay = function (_Overlay) {
  _inherits(LeftOverlay, _Overlay);

  /**
   * @param {Walkontable} wotInstance
   */
  function LeftOverlay(wotInstance) {
    _classCallCheck(this, LeftOverlay);

    var _this = _possibleConstructorReturn(this, (LeftOverlay.__proto__ || Object.getPrototypeOf(LeftOverlay)).call(this, wotInstance));

    _this.clone = _this.makeClone(_base2.default.CLONE_LEFT);
    return _this;
  }

  /**
   * Checks if overlay should be fully rendered
   *
   * @returns {Boolean}
   */


  _createClass(LeftOverlay, [{
    key: 'shouldBeRendered',
    value: function shouldBeRendered() {
      return !!(this.wot.getSetting('fixedColumnsLeft') || this.wot.getSetting('rowHeaders').length);
    }

    /**
     * Updates the left overlay position
     */

  }, {
    key: 'resetFixedPosition',
    value: function resetFixedPosition() {
      if (!this.needFullRender || !this.wot.wtTable.holder.parentNode) {
        // removed from DOM
        return;
      }
      var overlayRoot = this.clone.wtTable.holder.parentNode;
      var headerPosition = 0;
      var preventOverflow = this.wot.getSetting('preventOverflow');

      if (this.trimmingContainer === window && (!preventOverflow || preventOverflow !== 'horizontal')) {
        var box = this.wot.wtTable.hider.getBoundingClientRect();
        var left = Math.ceil(box.left);
        var right = Math.ceil(box.right);
        var finalLeft = void 0;
        var finalTop = void 0;

        finalTop = this.wot.wtTable.hider.style.top;
        finalTop = finalTop === '' ? 0 : finalTop;

        if (left < 0 && right - overlayRoot.offsetWidth > 0) {
          finalLeft = -left;
        } else {
          finalLeft = 0;
        }
        headerPosition = finalLeft;
        finalLeft += 'px';

        (0, _element.setOverlayPosition)(overlayRoot, finalLeft, finalTop);
      } else {
        headerPosition = this.getScrollPosition();
        (0, _element.resetCssTransform)(overlayRoot);
      }
      this.adjustHeaderBordersPosition(headerPosition);

      this.adjustElementsSize();
    }

    /**
     * Sets the main overlay's horizontal scroll position
     *
     * @param {Number} pos
     */

  }, {
    key: 'setScrollPosition',
    value: function setScrollPosition(pos) {
      if (this.mainTableScrollableElement === window) {
        window.scrollTo(pos, (0, _element.getWindowScrollTop)());
      } else {
        this.mainTableScrollableElement.scrollLeft = pos;
      }
    }

    /**
     * Triggers onScroll hook callback
     */

  }, {
    key: 'onScroll',
    value: function onScroll() {
      this.wot.getSetting('onScrollVertically');
    }

    /**
     * Calculates total sum cells width
     *
     * @param {Number} from Column index which calculates started from
     * @param {Number} to Column index where calculation is finished
     * @returns {Number} Width sum
     */

  }, {
    key: 'sumCellSizes',
    value: function sumCellSizes(from, to) {
      var sum = 0;
      var defaultColumnWidth = this.wot.wtSettings.defaultColumnWidth;

      while (from < to) {
        sum += this.wot.wtTable.getStretchedColumnWidth(from) || defaultColumnWidth;
        from++;
      }

      return sum;
    }

    /**
     * Adjust overlay root element, childs and master table element sizes (width, height).
     *
     * @param {Boolean} [force=false]
     */

  }, {
    key: 'adjustElementsSize',
    value: function adjustElementsSize() {
      var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      this.updateTrimmingContainer();

      if (this.needFullRender || force) {
        this.adjustRootElementSize();
        this.adjustRootChildrenSize();

        if (!force) {
          this.areElementSizesAdjusted = true;
        }
      }
    }

    /**
     * Adjust overlay root element size (width and height).
     */

  }, {
    key: 'adjustRootElementSize',
    value: function adjustRootElementSize() {
      var masterHolder = this.wot.wtTable.holder;
      var scrollbarHeight = masterHolder.clientHeight === masterHolder.offsetHeight ? 0 : (0, _element.getScrollbarWidth)();
      var overlayRoot = this.clone.wtTable.holder.parentNode;
      var overlayRootStyle = overlayRoot.style;
      var preventOverflow = this.wot.getSetting('preventOverflow');
      var tableWidth = void 0;

      if (this.trimmingContainer !== window || preventOverflow === 'vertical') {
        var height = this.wot.wtViewport.getWorkspaceHeight() - scrollbarHeight;

        height = Math.min(height, (0, _element.innerHeight)(this.wot.wtTable.wtRootElement));

        overlayRootStyle.height = height + 'px';
      } else {
        overlayRootStyle.height = '';
      }

      this.clone.wtTable.holder.style.height = overlayRootStyle.height;

      tableWidth = (0, _element.outerWidth)(this.clone.wtTable.TABLE);
      overlayRootStyle.width = (tableWidth === 0 ? tableWidth : tableWidth + 4) + 'px';
    }

    /**
     * Adjust overlay root childs size
     */

  }, {
    key: 'adjustRootChildrenSize',
    value: function adjustRootChildrenSize() {
      var scrollbarWidth = (0, _element.getScrollbarWidth)();

      this.clone.wtTable.hider.style.height = this.hider.style.height;
      this.clone.wtTable.holder.style.height = this.clone.wtTable.holder.parentNode.style.height;

      if (scrollbarWidth === 0) {
        scrollbarWidth = 30;
      }
      this.clone.wtTable.holder.style.width = parseInt(this.clone.wtTable.holder.parentNode.style.width, 10) + scrollbarWidth + 'px';
    }

    /**
     * Adjust the overlay dimensions and position
     */

  }, {
    key: 'applyToDOM',
    value: function applyToDOM() {
      var total = this.wot.getSetting('totalColumns');

      if (!this.areElementSizesAdjusted) {
        this.adjustElementsSize();
      }
      if (typeof this.wot.wtViewport.columnsRenderCalculator.startPosition === 'number') {
        this.spreader.style.left = this.wot.wtViewport.columnsRenderCalculator.startPosition + 'px';
      } else if (total === 0) {
        this.spreader.style.left = '0';
      } else {
        throw new Error('Incorrect value of the columnsRenderCalculator');
      }
      this.spreader.style.right = '';

      if (this.needFullRender) {
        this.syncOverlayOffset();
      }
    }

    /**
     * Synchronize calculated top position to an element
     */

  }, {
    key: 'syncOverlayOffset',
    value: function syncOverlayOffset() {
      if (typeof this.wot.wtViewport.rowsRenderCalculator.startPosition === 'number') {
        this.clone.wtTable.spreader.style.top = this.wot.wtViewport.rowsRenderCalculator.startPosition + 'px';
      } else {
        this.clone.wtTable.spreader.style.top = '';
      }
    }

    /**
     * Scrolls horizontally to a column at the left edge of the viewport
     *
     * @param sourceCol {Number} Column index which you want to scroll to
     * @param [beyondRendered=false] {Boolean} if `true`, scrolls according to the bottom edge (top edge is by default)
     */

  }, {
    key: 'scrollTo',
    value: function scrollTo(sourceCol, beyondRendered) {
      var newX = this.getTableParentOffset();
      var sourceInstance = this.wot.cloneSource ? this.wot.cloneSource : this.wot;
      var mainHolder = sourceInstance.wtTable.holder;
      var scrollbarCompensation = 0;

      if (beyondRendered && mainHolder.offsetWidth !== mainHolder.clientWidth) {
        scrollbarCompensation = (0, _element.getScrollbarWidth)();
      }
      if (beyondRendered) {
        newX += this.sumCellSizes(0, sourceCol + 1);
        newX -= this.wot.wtViewport.getViewportWidth();
      } else {
        newX += this.sumCellSizes(this.wot.getSetting('fixedColumnsLeft'), sourceCol);
      }
      newX += scrollbarCompensation;

      this.setScrollPosition(newX);
    }

    /**
     * Gets table parent left position
     *
     * @returns {Number}
     */

  }, {
    key: 'getTableParentOffset',
    value: function getTableParentOffset() {
      var preventOverflow = this.wot.getSetting('preventOverflow');
      var offset = 0;

      if (!preventOverflow && this.trimmingContainer === window) {
        offset = this.wot.wtTable.holderOffset.left;
      }

      return offset;
    }

    /**
     * Gets the main overlay's horizontal scroll position
     *
     * @returns {Number} Main table's vertical scroll position
     */

  }, {
    key: 'getScrollPosition',
    value: function getScrollPosition() {
      return (0, _element.getScrollLeft)(this.mainTableScrollableElement);
    }

    /**
     * Adds css classes to hide the header border's header (cell-selection border hiding issue)
     *
     * @param {Number} position Header X position if trimming container is window or scroll top if not
     */

  }, {
    key: 'adjustHeaderBordersPosition',
    value: function adjustHeaderBordersPosition(position) {
      var masterParent = this.wot.wtTable.holder.parentNode;
      var rowHeaders = this.wot.getSetting('rowHeaders');
      var fixedColumnsLeft = this.wot.getSetting('fixedColumnsLeft');
      var totalRows = this.wot.getSetting('totalRows');

      if (totalRows) {
        (0, _element.removeClass)(masterParent, 'emptyRows');
      } else {
        (0, _element.addClass)(masterParent, 'emptyRows');
      }

      if (fixedColumnsLeft && !rowHeaders.length) {
        (0, _element.addClass)(masterParent, 'innerBorderLeft');
      } else if (!fixedColumnsLeft && rowHeaders.length) {
        var previousState = (0, _element.hasClass)(masterParent, 'innerBorderLeft');

        if (position) {
          (0, _element.addClass)(masterParent, 'innerBorderLeft');
        } else {
          (0, _element.removeClass)(masterParent, 'innerBorderLeft');
        }
        if (!previousState && position || previousState && !position) {
          this.wot.wtOverlays.adjustElementsSize();
        }
      }
    }
  }]);

  return LeftOverlay;
}(_base2.default);

_base2.default.registerOverlay(_base2.default.CLONE_LEFT, LeftOverlay);

exports.default = LeftOverlay;

/***/ }),
/* 344 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _base = __webpack_require__(35);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @class TopOverlay
 */
var TopOverlay = function (_Overlay) {
  _inherits(TopOverlay, _Overlay);

  /**
   * @param {Walkontable} wotInstance
   */
  function TopOverlay(wotInstance) {
    _classCallCheck(this, TopOverlay);

    var _this = _possibleConstructorReturn(this, (TopOverlay.__proto__ || Object.getPrototypeOf(TopOverlay)).call(this, wotInstance));

    _this.clone = _this.makeClone(_base2.default.CLONE_TOP);
    return _this;
  }

  /**
   * Checks if overlay should be fully rendered
   *
   * @returns {Boolean}
   */


  _createClass(TopOverlay, [{
    key: 'shouldBeRendered',
    value: function shouldBeRendered() {
      return !!(this.wot.getSetting('fixedRowsTop') || this.wot.getSetting('columnHeaders').length);
    }

    /**
     * Updates the top overlay position
     */

  }, {
    key: 'resetFixedPosition',
    value: function resetFixedPosition() {
      if (!this.needFullRender || !this.wot.wtTable.holder.parentNode) {
        // removed from DOM
        return;
      }
      var overlayRoot = this.clone.wtTable.holder.parentNode;
      var headerPosition = 0;
      var preventOverflow = this.wot.getSetting('preventOverflow');

      if (this.trimmingContainer === window && (!preventOverflow || preventOverflow !== 'vertical')) {
        var box = this.wot.wtTable.hider.getBoundingClientRect();
        var top = Math.ceil(box.top);
        var bottom = Math.ceil(box.bottom);
        var finalLeft = void 0;
        var finalTop = void 0;

        finalLeft = this.wot.wtTable.hider.style.left;
        finalLeft = finalLeft === '' ? 0 : finalLeft;

        if (top < 0 && bottom - overlayRoot.offsetHeight > 0) {
          finalTop = -top;
        } else {
          finalTop = 0;
        }
        headerPosition = finalTop;
        finalTop += 'px';

        (0, _element.setOverlayPosition)(overlayRoot, finalLeft, finalTop);
      } else {
        headerPosition = this.getScrollPosition();
        (0, _element.resetCssTransform)(overlayRoot);
      }

      this.adjustHeaderBordersPosition(headerPosition);

      this.adjustElementsSize();
    }

    /**
     * Sets the main overlay's vertical scroll position
     *
     * @param {Number} pos
     */

  }, {
    key: 'setScrollPosition',
    value: function setScrollPosition(pos) {
      if (this.mainTableScrollableElement === window) {
        window.scrollTo((0, _element.getWindowScrollLeft)(), pos);
      } else {
        this.mainTableScrollableElement.scrollTop = pos;
      }
    }

    /**
     * Triggers onScroll hook callback
     */

  }, {
    key: 'onScroll',
    value: function onScroll() {
      this.wot.getSetting('onScrollHorizontally');
    }

    /**
     * Calculates total sum cells height
     *
     * @param {Number} from Row index which calculates started from
     * @param {Number} to Row index where calculation is finished
     * @returns {Number} Height sum
     */

  }, {
    key: 'sumCellSizes',
    value: function sumCellSizes(from, to) {
      var sum = 0;
      var defaultRowHeight = this.wot.wtSettings.settings.defaultRowHeight;

      while (from < to) {
        var height = this.wot.wtTable.getRowHeight(from);

        sum += height === void 0 ? defaultRowHeight : height;
        from++;
      }

      return sum;
    }

    /**
     * Adjust overlay root element, childs and master table element sizes (width, height).
     *
     * @param {Boolean} [force=false]
     */

  }, {
    key: 'adjustElementsSize',
    value: function adjustElementsSize() {
      var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      this.updateTrimmingContainer();

      if (this.needFullRender || force) {
        this.adjustRootElementSize();
        this.adjustRootChildrenSize();

        if (!force) {
          this.areElementSizesAdjusted = true;
        }
      }
    }

    /**
     * Adjust overlay root element size (width and height).
     */

  }, {
    key: 'adjustRootElementSize',
    value: function adjustRootElementSize() {
      var masterHolder = this.wot.wtTable.holder;
      var scrollbarWidth = masterHolder.clientWidth === masterHolder.offsetWidth ? 0 : (0, _element.getScrollbarWidth)();
      var overlayRoot = this.clone.wtTable.holder.parentNode;
      var overlayRootStyle = overlayRoot.style;
      var preventOverflow = this.wot.getSetting('preventOverflow');
      var tableHeight = void 0;

      if (this.trimmingContainer !== window || preventOverflow === 'horizontal') {
        var width = this.wot.wtViewport.getWorkspaceWidth() - scrollbarWidth;

        width = Math.min(width, (0, _element.innerWidth)(this.wot.wtTable.wtRootElement));

        overlayRootStyle.width = width + 'px';
      } else {
        overlayRootStyle.width = '';
      }

      this.clone.wtTable.holder.style.width = overlayRootStyle.width;

      tableHeight = (0, _element.outerHeight)(this.clone.wtTable.TABLE);
      overlayRootStyle.height = (tableHeight === 0 ? tableHeight : tableHeight + 4) + 'px';
    }

    /**
     * Adjust overlay root childs size
     */

  }, {
    key: 'adjustRootChildrenSize',
    value: function adjustRootChildrenSize() {
      var scrollbarWidth = (0, _element.getScrollbarWidth)();

      this.clone.wtTable.hider.style.width = this.hider.style.width;
      this.clone.wtTable.holder.style.width = this.clone.wtTable.holder.parentNode.style.width;

      if (scrollbarWidth === 0) {
        scrollbarWidth = 30;
      }
      this.clone.wtTable.holder.style.height = parseInt(this.clone.wtTable.holder.parentNode.style.height, 10) + scrollbarWidth + 'px';
    }

    /**
     * Adjust the overlay dimensions and position
     */

  }, {
    key: 'applyToDOM',
    value: function applyToDOM() {
      var total = this.wot.getSetting('totalRows');

      if (!this.areElementSizesAdjusted) {
        this.adjustElementsSize();
      }
      if (typeof this.wot.wtViewport.rowsRenderCalculator.startPosition === 'number') {
        this.spreader.style.top = this.wot.wtViewport.rowsRenderCalculator.startPosition + 'px';
      } else if (total === 0) {
        // can happen if there are 0 rows
        this.spreader.style.top = '0';
      } else {
        throw new Error('Incorrect value of the rowsRenderCalculator');
      }
      this.spreader.style.bottom = '';

      if (this.needFullRender) {
        this.syncOverlayOffset();
      }
    }

    /**
     * Synchronize calculated left position to an element
     */

  }, {
    key: 'syncOverlayOffset',
    value: function syncOverlayOffset() {
      if (typeof this.wot.wtViewport.columnsRenderCalculator.startPosition === 'number') {
        this.clone.wtTable.spreader.style.left = this.wot.wtViewport.columnsRenderCalculator.startPosition + 'px';
      } else {
        this.clone.wtTable.spreader.style.left = '';
      }
    }

    /**
     * Scrolls vertically to a row
     *
     * @param sourceRow {Number} Row index which you want to scroll to
     * @param [bottomEdge=false] {Boolean} if `true`, scrolls according to the bottom edge (top edge is by default)
     */

  }, {
    key: 'scrollTo',
    value: function scrollTo(sourceRow, bottomEdge) {
      var newY = this.getTableParentOffset();
      var sourceInstance = this.wot.cloneSource ? this.wot.cloneSource : this.wot;
      var mainHolder = sourceInstance.wtTable.holder;
      var scrollbarCompensation = 0;

      if (bottomEdge && mainHolder.offsetHeight !== mainHolder.clientHeight) {
        scrollbarCompensation = (0, _element.getScrollbarWidth)();
      }

      if (bottomEdge) {
        var fixedRowsBottom = this.wot.getSetting('fixedRowsBottom');
        var fixedRowsTop = this.wot.getSetting('fixedRowsTop');
        var totalRows = this.wot.getSetting('totalRows');

        newY += this.sumCellSizes(0, sourceRow + 1);
        newY -= this.wot.wtViewport.getViewportHeight() - this.sumCellSizes(totalRows - fixedRowsBottom, totalRows);
        // Fix 1 pixel offset when cell is selected
        newY += 1;
      } else {
        newY += this.sumCellSizes(this.wot.getSetting('fixedRowsTop'), sourceRow);
      }
      newY += scrollbarCompensation;

      this.setScrollPosition(newY);
    }

    /**
     * Gets table parent top position
     *
     * @returns {Number}
     */

  }, {
    key: 'getTableParentOffset',
    value: function getTableParentOffset() {
      if (this.mainTableScrollableElement === window) {
        return this.wot.wtTable.holderOffset.top;
      }
      return 0;
    }

    /**
     * Gets the main overlay's vertical scroll position
     *
     * @returns {Number} Main table's vertical scroll position
     */

  }, {
    key: 'getScrollPosition',
    value: function getScrollPosition() {
      return (0, _element.getScrollTop)(this.mainTableScrollableElement);
    }

    /**
     * Redraw borders of selection
     *
     * @param {WalkontableSelection} selection Selection for redraw
     */

  }, {
    key: 'redrawSelectionBorders',
    value: function redrawSelectionBorders(selection) {
      if (selection && selection.cellRange) {
        var border = selection.getBorder(this.wot);

        if (border) {
          var corners = selection.getCorners();
          border.disappear();
          border.appear(corners);
        }
      }
    }

    /**
     * Redrawing borders of all selections
     */

  }, {
    key: 'redrawAllSelectionsBorders',
    value: function redrawAllSelectionsBorders() {
      var selections = this.wot.selections;

      this.redrawSelectionBorders(selections.current);
      this.redrawSelectionBorders(selections.area);
      this.redrawSelectionBorders(selections.fill);
      this.wot.wtTable.wot.wtOverlays.leftOverlay.refresh();
    }

    /**
     * Adds css classes to hide the header border's header (cell-selection border hiding issue)
     *
     * @param {Number} position Header Y position if trimming container is window or scroll top if not
     */

  }, {
    key: 'adjustHeaderBordersPosition',
    value: function adjustHeaderBordersPosition(position) {
      var masterParent = this.wot.wtTable.holder.parentNode;
      var totalColumns = this.wot.getSetting('totalColumns');

      if (totalColumns) {
        (0, _element.removeClass)(masterParent, 'emptyColumns');
      } else {
        (0, _element.addClass)(masterParent, 'emptyColumns');
      }

      if (this.wot.getSetting('fixedRowsTop') === 0 && this.wot.getSetting('columnHeaders').length > 0) {
        var previousState = (0, _element.hasClass)(masterParent, 'innerBorderTop');

        if (position || this.wot.getSetting('totalRows') === 0) {
          (0, _element.addClass)(masterParent, 'innerBorderTop');
        } else {
          (0, _element.removeClass)(masterParent, 'innerBorderTop');
        }

        if (!previousState && position || previousState && !position) {
          this.wot.wtOverlays.adjustElementsSize();

          // cell borders should be positioned once again,
          // because we added / removed 1px border from table header
          this.redrawAllSelectionsBorders();
        }
      }

      // nasty workaround for double border in the header, TODO: find a pure-css solution
      if (this.wot.getSetting('rowHeaders').length === 0) {
        var secondHeaderCell = this.clone.wtTable.THEAD.querySelectorAll('th:nth-of-type(2)');

        if (secondHeaderCell) {
          for (var i = 0; i < secondHeaderCell.length; i++) {
            secondHeaderCell[i].style['border-left-width'] = 0;
          }
        }
      }
    }
  }]);

  return TopOverlay;
}(_base2.default);

_base2.default.registerOverlay(_base2.default.CLONE_TOP, TopOverlay);

exports.default = TopOverlay;

/***/ }),
/* 345 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _base = __webpack_require__(35);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @class TopLeftCornerOverlay
 */
var TopLeftCornerOverlay = function (_Overlay) {
  _inherits(TopLeftCornerOverlay, _Overlay);

  /**
   * @param {Walkontable} wotInstance
   */
  function TopLeftCornerOverlay(wotInstance) {
    _classCallCheck(this, TopLeftCornerOverlay);

    var _this = _possibleConstructorReturn(this, (TopLeftCornerOverlay.__proto__ || Object.getPrototypeOf(TopLeftCornerOverlay)).call(this, wotInstance));

    _this.clone = _this.makeClone(_base2.default.CLONE_TOP_LEFT_CORNER);
    return _this;
  }

  /**
   * Checks if overlay should be fully rendered
   *
   * @returns {Boolean}
   */


  _createClass(TopLeftCornerOverlay, [{
    key: 'shouldBeRendered',
    value: function shouldBeRendered() {
      return !!((this.wot.getSetting('fixedRowsTop') || this.wot.getSetting('columnHeaders').length) && (this.wot.getSetting('fixedColumnsLeft') || this.wot.getSetting('rowHeaders').length));
    }

    /**
     * Updates the corner overlay position
     */

  }, {
    key: 'resetFixedPosition',
    value: function resetFixedPosition() {
      this.updateTrimmingContainer();

      if (!this.wot.wtTable.holder.parentNode) {
        // removed from DOM
        return;
      }
      var overlayRoot = this.clone.wtTable.holder.parentNode;
      var tableHeight = (0, _element.outerHeight)(this.clone.wtTable.TABLE);
      var tableWidth = (0, _element.outerWidth)(this.clone.wtTable.TABLE);
      var preventOverflow = this.wot.getSetting('preventOverflow');

      if (this.trimmingContainer === window) {
        var box = this.wot.wtTable.hider.getBoundingClientRect();
        var top = Math.ceil(box.top);
        var left = Math.ceil(box.left);
        var bottom = Math.ceil(box.bottom);
        var right = Math.ceil(box.right);
        var finalLeft = '0';
        var finalTop = '0';

        if (!preventOverflow || preventOverflow === 'vertical') {
          if (left < 0 && right - overlayRoot.offsetWidth > 0) {
            finalLeft = -left + 'px';
          }
        }

        if (!preventOverflow || preventOverflow === 'horizontal') {
          if (top < 0 && bottom - overlayRoot.offsetHeight > 0) {
            finalTop = -top + 'px';
          }
        }
        (0, _element.setOverlayPosition)(overlayRoot, finalLeft, finalTop);
      } else {
        (0, _element.resetCssTransform)(overlayRoot);
      }
      overlayRoot.style.height = (tableHeight === 0 ? tableHeight : tableHeight + 4) + 'px';
      overlayRoot.style.width = (tableWidth === 0 ? tableWidth : tableWidth + 4) + 'px';
    }
  }]);

  return TopLeftCornerOverlay;
}(_base2.default);

_base2.default.registerOverlay(_base2.default.CLONE_TOP_LEFT_CORNER, TopLeftCornerOverlay);

exports.default = TopLeftCornerOverlay;

/***/ }),
/* 346 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _border2 = __webpack_require__(302);

var _border3 = _interopRequireDefault(_border2);

var _coords = __webpack_require__(53);

var _coords2 = _interopRequireDefault(_coords);

var _range = __webpack_require__(82);

var _range2 = _interopRequireDefault(_range);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Selection
 */
var Selection = function () {
  /**
   * @param {Object} settings
   * @param {CellRange} cellRange
   */
  function Selection(settings, cellRange) {
    _classCallCheck(this, Selection);

    this.settings = settings;
    this.cellRange = cellRange || null;
    this.instanceBorders = {};
  }

  /**
   * Each Walkontable clone requires it's own border for every selection. This method creates and returns selection
   * borders per instance
   *
   * @param {Walkontable} wotInstance
   * @returns {Border}
   */


  _createClass(Selection, [{
    key: 'getBorder',
    value: function getBorder(wotInstance) {
      if (this.instanceBorders[wotInstance.guid]) {
        return this.instanceBorders[wotInstance.guid];
      }

      // where is this returned?
      this.instanceBorders[wotInstance.guid] = new _border3.default(wotInstance, this.settings);
    }

    /**
     * Checks if selection is empty
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isEmpty',
    value: function isEmpty() {
      return this.cellRange === null;
    }

    /**
     * Adds a cell coords to the selection
     *
     * @param {CellCoords} coords
     */

  }, {
    key: 'add',
    value: function add(coords) {
      if (this.isEmpty()) {
        this.cellRange = new _range2.default(coords, coords, coords);
      } else {
        this.cellRange.expand(coords);
      }
    }

    /**
     * If selection range from or to property equals oldCoords, replace it with newCoords. Return boolean
     * information about success
     *
     * @param {CellCoords} oldCoords
     * @param {CellCoords} newCoords
     * @returns {Boolean}
     */

  }, {
    key: 'replace',
    value: function replace(oldCoords, newCoords) {
      if (!this.isEmpty()) {
        if (this.cellRange.from.isEqual(oldCoords)) {
          this.cellRange.from = newCoords;

          return true;
        }
        if (this.cellRange.to.isEqual(oldCoords)) {
          this.cellRange.to = newCoords;

          return true;
        }
      }

      return false;
    }

    /**
     * Clears selection
     */

  }, {
    key: 'clear',
    value: function clear() {
      this.cellRange = null;
    }

    /**
     * Returns the top left (TL) and bottom right (BR) selection coordinates
     *
     * @returns {Array} Returns array of coordinates for example `[1, 1, 5, 5]`
     */

  }, {
    key: 'getCorners',
    value: function getCorners() {
      var topLeft = this.cellRange.getTopLeftCorner();
      var bottomRight = this.cellRange.getBottomRightCorner();

      return [topLeft.row, topLeft.col, bottomRight.row, bottomRight.col];
    }

    /**
     * Adds class name to cell element at given coords
     *
     * @param {Walkontable} wotInstance Walkontable instance
     * @param {Number} sourceRow Cell row coord
     * @param {Number} sourceColumn Cell column coord
     * @param {String} className Class name
     */

  }, {
    key: 'addClassAtCoords',
    value: function addClassAtCoords(wotInstance, sourceRow, sourceColumn, className) {
      var TD = wotInstance.wtTable.getCell(new _coords2.default(sourceRow, sourceColumn));

      if ((typeof TD === 'undefined' ? 'undefined' : _typeof(TD)) === 'object') {
        (0, _element.addClass)(TD, className);
      }
    }

    /**
     * @param wotInstance
     */

  }, {
    key: 'draw',
    value: function draw(wotInstance) {
      if (this.isEmpty()) {
        if (this.settings.border) {
          var border = this.getBorder(wotInstance);

          if (border) {
            border.disappear();
          }
        }

        return;
      }
      var renderedRows = wotInstance.wtTable.getRenderedRowsCount();
      var renderedColumns = wotInstance.wtTable.getRenderedColumnsCount();
      var corners = this.getCorners();
      var sourceRow = void 0,
          sourceCol = void 0,
          TH = void 0;

      for (var column = 0; column < renderedColumns; column++) {
        sourceCol = wotInstance.wtTable.columnFilter.renderedToSource(column);

        if (sourceCol >= corners[1] && sourceCol <= corners[3]) {
          TH = wotInstance.wtTable.getColumnHeader(sourceCol);

          if (TH) {
            var newClasses = [];

            if (this.settings.highlightHeaderClassName) {
              newClasses.push(this.settings.highlightHeaderClassName);
            }

            if (this.settings.highlightColumnClassName) {
              newClasses.push(this.settings.highlightColumnClassName);
            }

            (0, _element.addClass)(TH, newClasses);
          }
        }
      }

      for (var row = 0; row < renderedRows; row++) {
        sourceRow = wotInstance.wtTable.rowFilter.renderedToSource(row);

        if (sourceRow >= corners[0] && sourceRow <= corners[2]) {
          TH = wotInstance.wtTable.getRowHeader(sourceRow);

          if (TH) {
            var _newClasses = [];

            if (this.settings.highlightHeaderClassName) {
              _newClasses.push(this.settings.highlightHeaderClassName);
            }

            if (this.settings.highlightRowClassName) {
              _newClasses.push(this.settings.highlightRowClassName);
            }

            (0, _element.addClass)(TH, _newClasses);
          }
        }

        for (var _column = 0; _column < renderedColumns; _column++) {
          sourceCol = wotInstance.wtTable.columnFilter.renderedToSource(_column);

          if (sourceRow >= corners[0] && sourceRow <= corners[2] && sourceCol >= corners[1] && sourceCol <= corners[3]) {
            // selected cell
            if (this.settings.className) {
              this.addClassAtCoords(wotInstance, sourceRow, sourceCol, this.settings.className);
            }
          } else if (sourceRow >= corners[0] && sourceRow <= corners[2]) {
            // selection is in this row
            if (this.settings.highlightRowClassName) {
              this.addClassAtCoords(wotInstance, sourceRow, sourceCol, this.settings.highlightRowClassName);
            }
          } else if (sourceCol >= corners[1] && sourceCol <= corners[3]) {
            // selection is in this column
            if (this.settings.highlightColumnClassName) {
              this.addClassAtCoords(wotInstance, sourceRow, sourceCol, this.settings.highlightColumnClassName);
            }
          }
        }
      }
      wotInstance.getSetting('onBeforeDrawBorders', corners, this.settings.className);

      if (this.settings.border) {
        var _border = this.getBorder(wotInstance);

        if (_border) {
          // warning! border.appear modifies corners!
          _border.appear(corners);
        }
      }
    }
  }]);

  return Selection;
}();

exports.default = Selection;

/***/ }),
/* 347 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * autoResize - resizes a DOM element to the width and height of another DOM element
 *
 * Copyright 2014, Marcin Warpechowski
 * Licensed under the MIT license
 */

function autoResize() {
  var defaults = {
    minHeight: 200,
    maxHeight: 300,
    minWidth: 100,
    maxWidth: 300
  },
      el,
      body = document.body,
      text = document.createTextNode(''),
      span = document.createElement('SPAN'),
      observe = function observe(element, event, handler) {
    if (element.attachEvent) {
      element.attachEvent('on' + event, handler);
    } else {
      element.addEventListener(event, handler, false);
    }
  },
      _unObserve = function _unObserve(element, event, handler) {
    if (element.removeEventListener) {
      element.removeEventListener(event, handler, false);
    } else {
      element.detachEvent('on' + event, handler);
    }
  },
      resize = function resize(newChar) {
    var width, scrollHeight;

    if (!newChar) {
      newChar = "";
    } else if (!/^[a-zA-Z \.,\\\/\|0-9]$/.test(newChar)) {
      newChar = ".";
    }

    if (text.textContent !== void 0) {
      text.textContent = el.value + newChar;
    } else {
      text.data = el.value + newChar; //IE8
    }
    span.style.fontSize = getComputedStyle(el).fontSize;
    span.style.fontFamily = getComputedStyle(el).fontFamily;
    span.style.whiteSpace = "pre";

    body.appendChild(span);
    width = span.clientWidth + 2;
    body.removeChild(span);

    el.style.height = defaults.minHeight + 'px';

    if (defaults.minWidth > width) {
      el.style.width = defaults.minWidth + 'px';
    } else if (width > defaults.maxWidth) {
      el.style.width = defaults.maxWidth + 'px';
    } else {
      el.style.width = width + 'px';
    }
    scrollHeight = el.scrollHeight ? el.scrollHeight - 1 : 0;

    if (defaults.minHeight > scrollHeight) {
      el.style.height = defaults.minHeight + 'px';
    } else if (defaults.maxHeight < scrollHeight) {
      el.style.height = defaults.maxHeight + 'px';
      el.style.overflowY = 'visible';
    } else {
      el.style.height = scrollHeight + 'px';
    }
  },
      delayedResize = function delayedResize() {
    window.setTimeout(resize, 0);
  },
      extendDefaults = function extendDefaults(config) {

    if (config && config.minHeight) {
      if (config.minHeight == 'inherit') {
        defaults.minHeight = el.clientHeight;
      } else {
        var minHeight = parseInt(config.minHeight);
        if (!isNaN(minHeight)) {
          defaults.minHeight = minHeight;
        }
      }
    }

    if (config && config.maxHeight) {
      if (config.maxHeight == 'inherit') {
        defaults.maxHeight = el.clientHeight;
      } else {
        var maxHeight = parseInt(config.maxHeight);
        if (!isNaN(maxHeight)) {
          defaults.maxHeight = maxHeight;
        }
      }
    }

    if (config && config.minWidth) {
      if (config.minWidth == 'inherit') {
        defaults.minWidth = el.clientWidth;
      } else {
        var minWidth = parseInt(config.minWidth);
        if (!isNaN(minWidth)) {
          defaults.minWidth = minWidth;
        }
      }
    }

    if (config && config.maxWidth) {
      if (config.maxWidth == 'inherit') {
        defaults.maxWidth = el.clientWidth;
      } else {
        var maxWidth = parseInt(config.maxWidth);
        if (!isNaN(maxWidth)) {
          defaults.maxWidth = maxWidth;
        }
      }
    }

    if (!span.firstChild) {
      span.className = "autoResize";
      span.style.display = 'inline-block';
      span.appendChild(text);
    }
  },
      _init = function _init(el_, config, doObserve) {
    el = el_;
    extendDefaults(config);

    if (el.nodeName == 'TEXTAREA') {

      el.style.resize = 'none';
      el.style.overflowY = '';
      el.style.height = defaults.minHeight + 'px';
      el.style.minWidth = defaults.minWidth + 'px';
      el.style.maxWidth = defaults.maxWidth + 'px';
      el.style.overflowY = 'hidden';
    }

    if (doObserve) {
      observe(el, 'change', resize);
      observe(el, 'cut', delayedResize);
      observe(el, 'paste', delayedResize);
      observe(el, 'drop', delayedResize);
      observe(el, 'keydown', delayedResize);
      observe(el, 'focus', resize);
    }

    resize();
  };

  function getComputedStyle(element) {
    return element.currentStyle || document.defaultView.getComputedStyle(element);
  }

  return {
    init: function init(el_, config, doObserve) {
      _init(el_, config, doObserve);
    },
    unObserve: function unObserve() {
      _unObserve(el, 'change', resize);
      _unObserve(el, 'cut', delayedResize);
      _unObserve(el, 'paste', delayedResize);
      _unObserve(el, 'drop', delayedResize);
      _unObserve(el, 'keydown', delayedResize);
      _unObserve(el, 'focus', resize);
    },
    resize: resize
  };
}

if (true) {
  module.exports = autoResize;
}

/***/ }),
/* 348 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _baseEditor = __webpack_require__(47);

var _baseEditor2 = _interopRequireDefault(_baseEditor);

var _element = __webpack_require__(0);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @private
 * @editor CheckboxEditor
 * @class CheckboxEditor
 */
var CheckboxEditor = function (_BaseEditor) {
  _inherits(CheckboxEditor, _BaseEditor);

  function CheckboxEditor() {
    _classCallCheck(this, CheckboxEditor);

    return _possibleConstructorReturn(this, (CheckboxEditor.__proto__ || Object.getPrototypeOf(CheckboxEditor)).apply(this, arguments));
  }

  _createClass(CheckboxEditor, [{
    key: 'beginEditing',
    value: function beginEditing(initialValue, event) {
      // Just some events connected with checkbox editor are delegated here. Some `keydown` events like `enter` and `space` key press
      // are handled inside `checkboxRenderer`. Some events come here from `editorManager`. Below `if` statement was created by author
      // for purpose of handling only `doubleclick` event which may be done on a cell with checkbox.

      if (event.type === 'mouseup') {
        var checkbox = this.TD.querySelector('input[type="checkbox"]');

        if (!(0, _element.hasClass)(checkbox, 'htBadValue')) {
          checkbox.click();
        }
      }
    }
  }, {
    key: 'finishEditing',
    value: function finishEditing() {}
  }, {
    key: 'init',
    value: function init() {}
  }, {
    key: 'open',
    value: function open() {}
  }, {
    key: 'close',
    value: function close() {}
  }, {
    key: 'getValue',
    value: function getValue() {}
  }, {
    key: 'setValue',
    value: function setValue() {}
  }, {
    key: 'focus',
    value: function focus() {}
  }]);

  return CheckboxEditor;
}(_baseEditor2.default);

exports.default = CheckboxEditor;

/***/ }),
/* 349 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _moment = __webpack_require__(40);

var _moment2 = _interopRequireDefault(_moment);

var _pikaday = __webpack_require__(350);

var _pikaday2 = _interopRequireDefault(_pikaday);

__webpack_require__(351);

var _element = __webpack_require__(0);

var _object = __webpack_require__(1);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _unicode = __webpack_require__(20);

var _event = __webpack_require__(12);

var _textEditor = __webpack_require__(54);

var _textEditor2 = _interopRequireDefault(_textEditor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @private
 * @editor DateEditor
 * @class DateEditor
 * @dependencies TextEditor moment pikaday
 */
var DateEditor = function (_TextEditor) {
  _inherits(DateEditor, _TextEditor);

  /**
   * @param {Core} hotInstance Handsontable instance
   * @private
   */
  function DateEditor(hotInstance) {
    _classCallCheck(this, DateEditor);

    // TODO: Move this option to general settings
    var _this = _possibleConstructorReturn(this, (DateEditor.__proto__ || Object.getPrototypeOf(DateEditor)).call(this, hotInstance));

    _this.defaultDateFormat = 'DD/MM/YYYY';
    _this.isCellEdited = false;
    _this.parentDestroyed = false;
    return _this;
  }

  _createClass(DateEditor, [{
    key: 'init',
    value: function init() {
      var _this2 = this;

      if (typeof _moment2.default !== 'function') {
        throw new Error('You need to include moment.js to your project.');
      }

      if (typeof _pikaday2.default !== 'function') {
        throw new Error('You need to include Pikaday to your project.');
      }
      _get(DateEditor.prototype.__proto__ || Object.getPrototypeOf(DateEditor.prototype), 'init', this).call(this);
      this.instance.addHook('afterDestroy', function () {
        _this2.parentDestroyed = true;
        _this2.destroyElements();
      });
    }

    /**
     * Create data picker instance
     */

  }, {
    key: 'createElements',
    value: function createElements() {
      _get(DateEditor.prototype.__proto__ || Object.getPrototypeOf(DateEditor.prototype), 'createElements', this).call(this);

      this.datePicker = document.createElement('DIV');
      this.datePickerStyle = this.datePicker.style;
      this.datePickerStyle.position = 'absolute';
      this.datePickerStyle.top = 0;
      this.datePickerStyle.left = 0;
      this.datePickerStyle.zIndex = 9999;

      (0, _element.addClass)(this.datePicker, 'htDatepickerHolder');
      document.body.appendChild(this.datePicker);

      this.$datePicker = new _pikaday2.default(this.getDatePickerConfig());
      var eventManager = new _eventManager2.default(this);

      /**
       * Prevent recognizing clicking on datepicker as clicking outside of table
       */
      eventManager.addEventListener(this.datePicker, 'mousedown', function (event) {
        return (0, _event.stopPropagation)(event);
      });
      this.hideDatepicker();
    }

    /**
     * Destroy data picker instance
     */

  }, {
    key: 'destroyElements',
    value: function destroyElements() {
      this.$datePicker.destroy();
    }

    /**
     * Prepare editor to appear
     *
     * @param {Number} row Row index
     * @param {Number} col Column index
     * @param {String} prop Property name (passed when datasource is an array of objects)
     * @param {HTMLTableCellElement} td Table cell element
     * @param {*} originalValue Original value
     * @param {Object} cellProperties Object with cell properties ({@see Core#getCellMeta})
     */

  }, {
    key: 'prepare',
    value: function prepare(row, col, prop, td, originalValue, cellProperties) {
      this._opened = false;
      _get(DateEditor.prototype.__proto__ || Object.getPrototypeOf(DateEditor.prototype), 'prepare', this).call(this, row, col, prop, td, originalValue, cellProperties);
    }

    /**
     * Open editor
     *
     * @param {Event} [event=null]
     */

  }, {
    key: 'open',
    value: function open() {
      var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

      _get(DateEditor.prototype.__proto__ || Object.getPrototypeOf(DateEditor.prototype), 'open', this).call(this);
      this.showDatepicker(event);
    }

    /**
     * Close editor
     */

  }, {
    key: 'close',
    value: function close() {
      var _this3 = this;

      this._opened = false;
      this.instance._registerTimeout(setTimeout(function () {
        _this3.instance.selection.refreshBorders();
      }, 0));

      _get(DateEditor.prototype.__proto__ || Object.getPrototypeOf(DateEditor.prototype), 'close', this).call(this);
    }

    /**
     * @param {Boolean} [isCancelled=false]
     * @param {Boolean} [ctrlDown=false]
     */

  }, {
    key: 'finishEditing',
    value: function finishEditing() {
      var isCancelled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var ctrlDown = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      if (isCancelled) {
        // pressed ESC, restore original value
        // var value = this.instance.getDataAtCell(this.row, this.col);
        var value = this.originalValue;

        if (value !== void 0) {
          this.setValue(value);
        }
      }
      this.hideDatepicker();
      _get(DateEditor.prototype.__proto__ || Object.getPrototypeOf(DateEditor.prototype), 'finishEditing', this).call(this, isCancelled, ctrlDown);
    }

    /**
     * Show data picker
     *
     * @param {Event} event
     */

  }, {
    key: 'showDatepicker',
    value: function showDatepicker(event) {
      this.$datePicker.config(this.getDatePickerConfig());

      var offset = this.TD.getBoundingClientRect();
      var dateFormat = this.cellProperties.dateFormat || this.defaultDateFormat;
      var datePickerConfig = this.$datePicker.config();
      var dateStr = void 0;
      var isMouseDown = this.instance.view.isMouseDown();
      var isMeta = event ? (0, _unicode.isMetaKey)(event.keyCode) : false;

      this.datePickerStyle.top = window.pageYOffset + offset.top + (0, _element.outerHeight)(this.TD) + 'px';
      this.datePickerStyle.left = window.pageXOffset + offset.left + 'px';

      this.$datePicker._onInputFocus = function () {};
      datePickerConfig.format = dateFormat;

      if (this.originalValue) {
        dateStr = this.originalValue;

        if ((0, _moment2.default)(dateStr, dateFormat, true).isValid()) {
          this.$datePicker.setMoment((0, _moment2.default)(dateStr, dateFormat), true);
        }

        // workaround for date/time cells - pikaday resets the cell value to 12:00 AM by default, this will overwrite the value.
        if (this.getValue() !== this.originalValue) {
          this.setValue(this.originalValue);
        }

        if (!isMeta && !isMouseDown) {
          this.setValue('');
        }
      } else if (this.cellProperties.defaultDate) {
        dateStr = this.cellProperties.defaultDate;

        datePickerConfig.defaultDate = dateStr;

        if ((0, _moment2.default)(dateStr, dateFormat, true).isValid()) {
          this.$datePicker.setMoment((0, _moment2.default)(dateStr, dateFormat), true);
        }

        if (!isMeta && !isMouseDown) {
          this.setValue('');
        }
      } else {
        // if a default date is not defined, set a soft-default-date: display the current day and month in the
        // datepicker, but don't fill the editor input
        this.$datePicker.gotoToday();
      }

      this.datePickerStyle.display = 'block';
      this.$datePicker.show();
    }

    /**
     * Hide data picker
     */

  }, {
    key: 'hideDatepicker',
    value: function hideDatepicker() {
      this.datePickerStyle.display = 'none';
      this.$datePicker.hide();
    }

    /**
     * Get date picker options.
     *
     * @returns {Object}
     */

  }, {
    key: 'getDatePickerConfig',
    value: function getDatePickerConfig() {
      var _this4 = this;

      var htInput = this.TEXTAREA;
      var options = {};

      if (this.cellProperties && this.cellProperties.datePickerConfig) {
        (0, _object.deepExtend)(options, this.cellProperties.datePickerConfig);
      }
      var origOnSelect = options.onSelect;
      var origOnClose = options.onClose;

      options.field = htInput;
      options.trigger = htInput;
      options.container = this.datePicker;
      options.bound = false;
      options.format = options.format || this.defaultDateFormat;
      options.reposition = options.reposition || false;
      options.onSelect = function (dateStr) {
        if (!isNaN(dateStr.getTime())) {
          dateStr = (0, _moment2.default)(dateStr).format(_this4.cellProperties.dateFormat || _this4.defaultDateFormat);
        }
        _this4.setValue(dateStr);
        _this4.hideDatepicker();

        if (origOnSelect) {
          origOnSelect();
        }
      };
      options.onClose = function () {
        if (!_this4.parentDestroyed) {
          _this4.finishEditing(false);
        }
        if (origOnClose) {
          origOnClose();
        }
      };

      return options;
    }
  }]);

  return DateEditor;
}(_textEditor2.default);

exports.default = DateEditor;

/***/ }),
/* 350 */
/***/ (function(module, exports, __webpack_require__) {

/*!
 * Pikaday
 *
 * Copyright © 2014 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday
 */

(function (root, factory)
{
    'use strict';

    var moment;
    if (true) {
        // CommonJS module
        // Load moment.js as an optional dependency
        try { moment = __webpack_require__(40); } catch (e) {}
        module.exports = factory(moment);
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(function (req)
        {
            // Load moment.js as an optional dependency
            var id = 'moment';
            try { moment = req(id); } catch (e) {}
            return factory(moment);
        });
    } else {
        root.Pikaday = factory(root.moment);
    }
}(this, function (moment)
{
    'use strict';

    /**
     * feature detection and helper functions
     */
    var hasMoment = typeof moment === 'function',

    hasEventListeners = !!window.addEventListener,

    document = window.document,

    sto = window.setTimeout,

    addEvent = function(el, e, callback, capture)
    {
        if (hasEventListeners) {
            el.addEventListener(e, callback, !!capture);
        } else {
            el.attachEvent('on' + e, callback);
        }
    },

    removeEvent = function(el, e, callback, capture)
    {
        if (hasEventListeners) {
            el.removeEventListener(e, callback, !!capture);
        } else {
            el.detachEvent('on' + e, callback);
        }
    },

    fireEvent = function(el, eventName, data)
    {
        var ev;

        if (document.createEvent) {
            ev = document.createEvent('HTMLEvents');
            ev.initEvent(eventName, true, false);
            ev = extend(ev, data);
            el.dispatchEvent(ev);
        } else if (document.createEventObject) {
            ev = document.createEventObject();
            ev = extend(ev, data);
            el.fireEvent('on' + eventName, ev);
        }
    },

    trim = function(str)
    {
        return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g,'');
    },

    hasClass = function(el, cn)
    {
        return (' ' + el.className + ' ').indexOf(' ' + cn + ' ') !== -1;
    },

    addClass = function(el, cn)
    {
        if (!hasClass(el, cn)) {
            el.className = (el.className === '') ? cn : el.className + ' ' + cn;
        }
    },

    removeClass = function(el, cn)
    {
        el.className = trim((' ' + el.className + ' ').replace(' ' + cn + ' ', ' '));
    },

    isArray = function(obj)
    {
        return (/Array/).test(Object.prototype.toString.call(obj));
    },

    isDate = function(obj)
    {
        return (/Date/).test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());
    },

    isWeekend = function(date)
    {
        var day = date.getDay();
        return day === 0 || day === 6;
    },

    isLeapYear = function(year)
    {
        // solution by Matti Virkkunen: http://stackoverflow.com/a/4881951
        return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
    },

    getDaysInMonth = function(year, month)
    {
        return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
    },

    setToStartOfDay = function(date)
    {
        if (isDate(date)) date.setHours(0,0,0,0);
    },

    compareDates = function(a,b)
    {
        // weak date comparison (use setToStartOfDay(date) to ensure correct result)
        return a.getTime() === b.getTime();
    },

    extend = function(to, from, overwrite)
    {
        var prop, hasProp;
        for (prop in from) {
            hasProp = to[prop] !== undefined;
            if (hasProp && typeof from[prop] === 'object' && from[prop] !== null && from[prop].nodeName === undefined) {
                if (isDate(from[prop])) {
                    if (overwrite) {
                        to[prop] = new Date(from[prop].getTime());
                    }
                }
                else if (isArray(from[prop])) {
                    if (overwrite) {
                        to[prop] = from[prop].slice(0);
                    }
                } else {
                    to[prop] = extend({}, from[prop], overwrite);
                }
            } else if (overwrite || !hasProp) {
                to[prop] = from[prop];
            }
        }
        return to;
    },

    adjustCalendar = function(calendar) {
        if (calendar.month < 0) {
            calendar.year -= Math.ceil(Math.abs(calendar.month)/12);
            calendar.month += 12;
        }
        if (calendar.month > 11) {
            calendar.year += Math.floor(Math.abs(calendar.month)/12);
            calendar.month -= 12;
        }
        return calendar;
    },

    /**
     * defaults and localisation
     */
    defaults = {

        // bind the picker to a form field
        field: null,

        // automatically show/hide the picker on `field` focus (default `true` if `field` is set)
        bound: undefined,

        // position of the datepicker, relative to the field (default to bottom & left)
        // ('bottom' & 'left' keywords are not used, 'top' & 'right' are modifier on the bottom/left position)
        position: 'bottom left',

        // automatically fit in the viewport even if it means repositioning from the position option
        reposition: true,

        // the default output format for `.toString()` and `field` value
        format: 'YYYY-MM-DD',

        // the initial date to view when first opened
        defaultDate: null,

        // make the `defaultDate` the initial selected value
        setDefaultDate: false,

        // first day of week (0: Sunday, 1: Monday etc)
        firstDay: 0,

        // the default flag for moment's strict date parsing
        formatStrict: false,

        // the minimum/earliest date that can be selected
        minDate: null,
        // the maximum/latest date that can be selected
        maxDate: null,

        // number of years either side, or array of upper/lower range
        yearRange: 10,

        // show week numbers at head of row
        showWeekNumber: false,

        // used internally (don't config outside)
        minYear: 0,
        maxYear: 9999,
        minMonth: undefined,
        maxMonth: undefined,

        startRange: null,
        endRange: null,

        isRTL: false,

        // Additional text to append to the year in the calendar title
        yearSuffix: '',

        // Render the month after year in the calendar title
        showMonthAfterYear: false,

        // Render days of the calendar grid that fall in the next or previous month
        showDaysInNextAndPreviousMonths: false,

        // how many months are visible
        numberOfMonths: 1,

        // when numberOfMonths is used, this will help you to choose where the main calendar will be (default `left`, can be set to `right`)
        // only used for the first display or when a selected date is not visible
        mainCalendar: 'left',

        // Specify a DOM element to render the calendar in
        container: undefined,

        // internationalization
        i18n: {
            previousMonth : 'Previous Month',
            nextMonth     : 'Next Month',
            months        : ['January','February','March','April','May','June','July','August','September','October','November','December'],
            weekdays      : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
            weekdaysShort : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
        },

        // Theme Classname
        theme: null,

        // callback function
        onSelect: null,
        onOpen: null,
        onClose: null,
        onDraw: null
    },


    /**
     * templating functions to abstract HTML rendering
     */
    renderDayName = function(opts, day, abbr)
    {
        day += opts.firstDay;
        while (day >= 7) {
            day -= 7;
        }
        return abbr ? opts.i18n.weekdaysShort[day] : opts.i18n.weekdays[day];
    },

    renderDay = function(opts)
    {
        var arr = [];
        var ariaSelected = 'false';
        if (opts.isEmpty) {
            if (opts.showDaysInNextAndPreviousMonths) {
                arr.push('is-outside-current-month');
            } else {
                return '<td class="is-empty"></td>';
            }
        }
        if (opts.isDisabled) {
            arr.push('is-disabled');
        }
        if (opts.isToday) {
            arr.push('is-today');
        }
        if (opts.isSelected) {
            arr.push('is-selected');
            ariaSelected = 'true';
        }
        if (opts.isInRange) {
            arr.push('is-inrange');
        }
        if (opts.isStartRange) {
            arr.push('is-startrange');
        }
        if (opts.isEndRange) {
            arr.push('is-endrange');
        }
        return '<td data-day="' + opts.day + '" class="' + arr.join(' ') + '" aria-selected="' + ariaSelected + '">' +
                 '<button class="pika-button pika-day" type="button" ' +
                    'data-pika-year="' + opts.year + '" data-pika-month="' + opts.month + '" data-pika-day="' + opts.day + '">' +
                        opts.day +
                 '</button>' +
               '</td>';
    },

    renderWeek = function (d, m, y) {
        // Lifted from http://javascript.about.com/library/blweekyear.htm, lightly modified.
        var onejan = new Date(y, 0, 1),
            weekNum = Math.ceil((((new Date(y, m, d) - onejan) / 86400000) + onejan.getDay()+1)/7);
        return '<td class="pika-week">' + weekNum + '</td>';
    },

    renderRow = function(days, isRTL)
    {
        return '<tr>' + (isRTL ? days.reverse() : days).join('') + '</tr>';
    },

    renderBody = function(rows)
    {
        return '<tbody>' + rows.join('') + '</tbody>';
    },

    renderHead = function(opts)
    {
        var i, arr = [];
        if (opts.showWeekNumber) {
            arr.push('<th></th>');
        }
        for (i = 0; i < 7; i++) {
            arr.push('<th scope="col"><abbr title="' + renderDayName(opts, i) + '">' + renderDayName(opts, i, true) + '</abbr></th>');
        }
        return '<thead><tr>' + (opts.isRTL ? arr.reverse() : arr).join('') + '</tr></thead>';
    },

    renderTitle = function(instance, c, year, month, refYear, randId)
    {
        var i, j, arr,
            opts = instance._o,
            isMinYear = year === opts.minYear,
            isMaxYear = year === opts.maxYear,
            html = '<div id="' + randId + '" class="pika-title" role="heading" aria-live="assertive">',
            monthHtml,
            yearHtml,
            prev = true,
            next = true;

        for (arr = [], i = 0; i < 12; i++) {
            arr.push('<option value="' + (year === refYear ? i - c : 12 + i - c) + '"' +
                (i === month ? ' selected="selected"': '') +
                ((isMinYear && i < opts.minMonth) || (isMaxYear && i > opts.maxMonth) ? 'disabled="disabled"' : '') + '>' +
                opts.i18n.months[i] + '</option>');
        }

        monthHtml = '<div class="pika-label">' + opts.i18n.months[month] + '<select class="pika-select pika-select-month" tabindex="-1">' + arr.join('') + '</select></div>';

        if (isArray(opts.yearRange)) {
            i = opts.yearRange[0];
            j = opts.yearRange[1] + 1;
        } else {
            i = year - opts.yearRange;
            j = 1 + year + opts.yearRange;
        }

        for (arr = []; i < j && i <= opts.maxYear; i++) {
            if (i >= opts.minYear) {
                arr.push('<option value="' + i + '"' + (i === year ? ' selected="selected"': '') + '>' + (i) + '</option>');
            }
        }
        yearHtml = '<div class="pika-label">' + year + opts.yearSuffix + '<select class="pika-select pika-select-year" tabindex="-1">' + arr.join('') + '</select></div>';

        if (opts.showMonthAfterYear) {
            html += yearHtml + monthHtml;
        } else {
            html += monthHtml + yearHtml;
        }

        if (isMinYear && (month === 0 || opts.minMonth >= month)) {
            prev = false;
        }

        if (isMaxYear && (month === 11 || opts.maxMonth <= month)) {
            next = false;
        }

        if (c === 0) {
            html += '<button class="pika-prev' + (prev ? '' : ' is-disabled') + '" type="button">' + opts.i18n.previousMonth + '</button>';
        }
        if (c === (instance._o.numberOfMonths - 1) ) {
            html += '<button class="pika-next' + (next ? '' : ' is-disabled') + '" type="button">' + opts.i18n.nextMonth + '</button>';
        }

        return html += '</div>';
    },

    renderTable = function(opts, data, randId)
    {
        return '<table cellpadding="0" cellspacing="0" class="pika-table" role="grid" aria-labelledby="' + randId + '">' + renderHead(opts) + renderBody(data) + '</table>';
    },


    /**
     * Pikaday constructor
     */
    Pikaday = function(options)
    {
        var self = this,
            opts = self.config(options);

        self._onMouseDown = function(e)
        {
            if (!self._v) {
                return;
            }
            e = e || window.event;
            var target = e.target || e.srcElement;
            if (!target) {
                return;
            }

            if (!hasClass(target, 'is-disabled')) {
                if (hasClass(target, 'pika-button') && !hasClass(target, 'is-empty') && !hasClass(target.parentNode, 'is-disabled')) {
                    self.setDate(new Date(target.getAttribute('data-pika-year'), target.getAttribute('data-pika-month'), target.getAttribute('data-pika-day')));
                    if (opts.bound) {
                        sto(function() {
                            self.hide();
                            if (opts.field) {
                                opts.field.blur();
                            }
                        }, 100);
                    }
                }
                else if (hasClass(target, 'pika-prev')) {
                    self.prevMonth();
                }
                else if (hasClass(target, 'pika-next')) {
                    self.nextMonth();
                }
            }
            if (!hasClass(target, 'pika-select')) {
                // if this is touch event prevent mouse events emulation
                if (e.preventDefault) {
                    e.preventDefault();
                } else {
                    e.returnValue = false;
                    return false;
                }
            } else {
                self._c = true;
            }
        };

        self._onChange = function(e)
        {
            e = e || window.event;
            var target = e.target || e.srcElement;
            if (!target) {
                return;
            }
            if (hasClass(target, 'pika-select-month')) {
                self.gotoMonth(target.value);
            }
            else if (hasClass(target, 'pika-select-year')) {
                self.gotoYear(target.value);
            }
        };

        self._onKeyChange = function(e)
        {
            e = e || window.event;

            if (self.isVisible()) {

                switch(e.keyCode){
                    case 13:
                    case 27:
                        opts.field.blur();
                        break;
                    case 37:
                        e.preventDefault();
                        self.adjustDate('subtract', 1);
                        break;
                    case 38:
                        self.adjustDate('subtract', 7);
                        break;
                    case 39:
                        self.adjustDate('add', 1);
                        break;
                    case 40:
                        self.adjustDate('add', 7);
                        break;
                }
            }
        };

        self._onInputChange = function(e)
        {
            var date;

            if (e.firedBy === self) {
                return;
            }
            if (hasMoment) {
                date = moment(opts.field.value, opts.format, opts.formatStrict);
                date = (date && date.isValid()) ? date.toDate() : null;
            }
            else {
                date = new Date(Date.parse(opts.field.value));
            }
            if (isDate(date)) {
              self.setDate(date);
            }
            if (!self._v) {
                self.show();
            }
        };

        self._onInputFocus = function()
        {
            self.show();
        };

        self._onInputClick = function()
        {
            self.show();
        };

        self._onInputBlur = function()
        {
            // IE allows pika div to gain focus; catch blur the input field
            var pEl = document.activeElement;
            do {
                if (hasClass(pEl, 'pika-single')) {
                    return;
                }
            }
            while ((pEl = pEl.parentNode));

            if (!self._c) {
                self._b = sto(function() {
                    self.hide();
                }, 50);
            }
            self._c = false;
        };

        self._onClick = function(e)
        {
            e = e || window.event;
            var target = e.target || e.srcElement,
                pEl = target;
            if (!target) {
                return;
            }
            if (!hasEventListeners && hasClass(target, 'pika-select')) {
                if (!target.onchange) {
                    target.setAttribute('onchange', 'return;');
                    addEvent(target, 'change', self._onChange);
                }
            }
            do {
                if (hasClass(pEl, 'pika-single') || pEl === opts.trigger) {
                    return;
                }
            }
            while ((pEl = pEl.parentNode));
            if (self._v && target !== opts.trigger && pEl !== opts.trigger) {
                self.hide();
            }
        };

        self.el = document.createElement('div');
        self.el.className = 'pika-single' + (opts.isRTL ? ' is-rtl' : '') + (opts.theme ? ' ' + opts.theme : '');

        addEvent(self.el, 'mousedown', self._onMouseDown, true);
        addEvent(self.el, 'touchend', self._onMouseDown, true);
        addEvent(self.el, 'change', self._onChange);
        addEvent(document, 'keydown', self._onKeyChange);

        if (opts.field) {
            if (opts.container) {
                opts.container.appendChild(self.el);
            } else if (opts.bound) {
                document.body.appendChild(self.el);
            } else {
                opts.field.parentNode.insertBefore(self.el, opts.field.nextSibling);
            }
            addEvent(opts.field, 'change', self._onInputChange);

            if (!opts.defaultDate) {
                if (hasMoment && opts.field.value) {
                    opts.defaultDate = moment(opts.field.value, opts.format).toDate();
                } else {
                    opts.defaultDate = new Date(Date.parse(opts.field.value));
                }
                opts.setDefaultDate = true;
            }
        }

        var defDate = opts.defaultDate;

        if (isDate(defDate)) {
            if (opts.setDefaultDate) {
                self.setDate(defDate, true);
            } else {
                self.gotoDate(defDate);
            }
        } else {
            self.gotoDate(new Date());
        }

        if (opts.bound) {
            this.hide();
            self.el.className += ' is-bound';
            addEvent(opts.trigger, 'click', self._onInputClick);
            addEvent(opts.trigger, 'focus', self._onInputFocus);
            addEvent(opts.trigger, 'blur', self._onInputBlur);
        } else {
            this.show();
        }
    };


    /**
     * public Pikaday API
     */
    Pikaday.prototype = {


        /**
         * configure functionality
         */
        config: function(options)
        {
            if (!this._o) {
                this._o = extend({}, defaults, true);
            }

            var opts = extend(this._o, options, true);

            opts.isRTL = !!opts.isRTL;

            opts.field = (opts.field && opts.field.nodeName) ? opts.field : null;

            opts.theme = (typeof opts.theme) === 'string' && opts.theme ? opts.theme : null;

            opts.bound = !!(opts.bound !== undefined ? opts.field && opts.bound : opts.field);

            opts.trigger = (opts.trigger && opts.trigger.nodeName) ? opts.trigger : opts.field;

            opts.disableWeekends = !!opts.disableWeekends;

            opts.disableDayFn = (typeof opts.disableDayFn) === 'function' ? opts.disableDayFn : null;

            var nom = parseInt(opts.numberOfMonths, 10) || 1;
            opts.numberOfMonths = nom > 4 ? 4 : nom;

            if (!isDate(opts.minDate)) {
                opts.minDate = false;
            }
            if (!isDate(opts.maxDate)) {
                opts.maxDate = false;
            }
            if ((opts.minDate && opts.maxDate) && opts.maxDate < opts.minDate) {
                opts.maxDate = opts.minDate = false;
            }
            if (opts.minDate) {
                this.setMinDate(opts.minDate);
            }
            if (opts.maxDate) {
                this.setMaxDate(opts.maxDate);
            }

            if (isArray(opts.yearRange)) {
                var fallback = new Date().getFullYear() - 10;
                opts.yearRange[0] = parseInt(opts.yearRange[0], 10) || fallback;
                opts.yearRange[1] = parseInt(opts.yearRange[1], 10) || fallback;
            } else {
                opts.yearRange = Math.abs(parseInt(opts.yearRange, 10)) || defaults.yearRange;
                if (opts.yearRange > 100) {
                    opts.yearRange = 100;
                }
            }

            return opts;
        },

        /**
         * return a formatted string of the current selection (using Moment.js if available)
         */
        toString: function(format)
        {
            return !isDate(this._d) ? '' : hasMoment ? moment(this._d).format(format || this._o.format) : this._d.toDateString();
        },

        /**
         * return a Moment.js object of the current selection (if available)
         */
        getMoment: function()
        {
            return hasMoment ? moment(this._d) : null;
        },

        /**
         * set the current selection from a Moment.js object (if available)
         */
        setMoment: function(date, preventOnSelect)
        {
            if (hasMoment && moment.isMoment(date)) {
                this.setDate(date.toDate(), preventOnSelect);
            }
        },

        /**
         * return a Date object of the current selection with fallback for the current date
         */
        getDate: function()
        {
            return isDate(this._d) ? new Date(this._d.getTime()) : new Date();
        },

        /**
         * set the current selection
         */
        setDate: function(date, preventOnSelect)
        {
            if (!date) {
                this._d = null;

                if (this._o.field) {
                    this._o.field.value = '';
                    fireEvent(this._o.field, 'change', { firedBy: this });
                }

                return this.draw();
            }
            if (typeof date === 'string') {
                date = new Date(Date.parse(date));
            }
            if (!isDate(date)) {
                return;
            }

            var min = this._o.minDate,
                max = this._o.maxDate;

            if (isDate(min) && date < min) {
                date = min;
            } else if (isDate(max) && date > max) {
                date = max;
            }

            this._d = new Date(date.getTime());
            setToStartOfDay(this._d);
            this.gotoDate(this._d);

            if (this._o.field) {
                this._o.field.value = this.toString();
                fireEvent(this._o.field, 'change', { firedBy: this });
            }
            if (!preventOnSelect && typeof this._o.onSelect === 'function') {
                this._o.onSelect.call(this, this.getDate());
            }
        },

        /**
         * change view to a specific date
         */
        gotoDate: function(date)
        {
            var newCalendar = true;

            if (!isDate(date)) {
                return;
            }

            if (this.calendars) {
                var firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1),
                    lastVisibleDate = new Date(this.calendars[this.calendars.length-1].year, this.calendars[this.calendars.length-1].month, 1),
                    visibleDate = date.getTime();
                // get the end of the month
                lastVisibleDate.setMonth(lastVisibleDate.getMonth()+1);
                lastVisibleDate.setDate(lastVisibleDate.getDate()-1);
                newCalendar = (visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate);
            }

            if (newCalendar) {
                this.calendars = [{
                    month: date.getMonth(),
                    year: date.getFullYear()
                }];
                if (this._o.mainCalendar === 'right') {
                    this.calendars[0].month += 1 - this._o.numberOfMonths;
                }
            }

            this.adjustCalendars();
        },

        adjustDate: function(sign, days) {

            var day = this.getDate();
            var difference = parseInt(days)*24*60*60*1000;

            var newDay;

            if (sign === 'add') {
                newDay = new Date(day.valueOf() + difference);
            } else if (sign === 'subtract') {
                newDay = new Date(day.valueOf() - difference);
            }

            if (hasMoment) {
                if (sign === 'add') {
                    newDay = moment(day).add(days, "days").toDate();
                } else if (sign === 'subtract') {
                    newDay = moment(day).subtract(days, "days").toDate();
                }
            }

            this.setDate(newDay);
        },

        adjustCalendars: function() {
            this.calendars[0] = adjustCalendar(this.calendars[0]);
            for (var c = 1; c < this._o.numberOfMonths; c++) {
                this.calendars[c] = adjustCalendar({
                    month: this.calendars[0].month + c,
                    year: this.calendars[0].year
                });
            }
            this.draw();
        },

        gotoToday: function()
        {
            this.gotoDate(new Date());
        },

        /**
         * change view to a specific month (zero-index, e.g. 0: January)
         */
        gotoMonth: function(month)
        {
            if (!isNaN(month)) {
                this.calendars[0].month = parseInt(month, 10);
                this.adjustCalendars();
            }
        },

        nextMonth: function()
        {
            this.calendars[0].month++;
            this.adjustCalendars();
        },

        prevMonth: function()
        {
            this.calendars[0].month--;
            this.adjustCalendars();
        },

        /**
         * change view to a specific full year (e.g. "2012")
         */
        gotoYear: function(year)
        {
            if (!isNaN(year)) {
                this.calendars[0].year = parseInt(year, 10);
                this.adjustCalendars();
            }
        },

        /**
         * change the minDate
         */
        setMinDate: function(value)
        {
            if(value instanceof Date) {
                setToStartOfDay(value);
                this._o.minDate = value;
                this._o.minYear  = value.getFullYear();
                this._o.minMonth = value.getMonth();
            } else {
                this._o.minDate = defaults.minDate;
                this._o.minYear  = defaults.minYear;
                this._o.minMonth = defaults.minMonth;
                this._o.startRange = defaults.startRange;
            }

            this.draw();
        },

        /**
         * change the maxDate
         */
        setMaxDate: function(value)
        {
            if(value instanceof Date) {
                setToStartOfDay(value);
                this._o.maxDate = value;
                this._o.maxYear = value.getFullYear();
                this._o.maxMonth = value.getMonth();
            } else {
                this._o.maxDate = defaults.maxDate;
                this._o.maxYear = defaults.maxYear;
                this._o.maxMonth = defaults.maxMonth;
                this._o.endRange = defaults.endRange;
            }

            this.draw();
        },

        setStartRange: function(value)
        {
            this._o.startRange = value;
        },

        setEndRange: function(value)
        {
            this._o.endRange = value;
        },

        /**
         * refresh the HTML
         */
        draw: function(force)
        {
            if (!this._v && !force) {
                return;
            }
            var opts = this._o,
                minYear = opts.minYear,
                maxYear = opts.maxYear,
                minMonth = opts.minMonth,
                maxMonth = opts.maxMonth,
                html = '',
                randId;

            if (this._y <= minYear) {
                this._y = minYear;
                if (!isNaN(minMonth) && this._m < minMonth) {
                    this._m = minMonth;
                }
            }
            if (this._y >= maxYear) {
                this._y = maxYear;
                if (!isNaN(maxMonth) && this._m > maxMonth) {
                    this._m = maxMonth;
                }
            }

            randId = 'pika-title-' + Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 2);

            for (var c = 0; c < opts.numberOfMonths; c++) {
                html += '<div class="pika-lendar">' + renderTitle(this, c, this.calendars[c].year, this.calendars[c].month, this.calendars[0].year, randId) + this.render(this.calendars[c].year, this.calendars[c].month, randId) + '</div>';
            }

            this.el.innerHTML = html;

            if (opts.bound) {
                if(opts.field.type !== 'hidden') {
                    sto(function() {
                        opts.trigger.focus();
                    }, 1);
                }
            }

            if (typeof this._o.onDraw === 'function') {
                this._o.onDraw(this);
            }
            
            if (opts.bound) {
                // let the screen reader user know to use arrow keys
                opts.field.setAttribute('aria-label', 'Use the arrow keys to pick a date');
            }
        },

        adjustPosition: function()
        {
            var field, pEl, width, height, viewportWidth, viewportHeight, scrollTop, left, top, clientRect;

            if (this._o.container) return;

            this.el.style.position = 'absolute';

            field = this._o.trigger;
            pEl = field;
            width = this.el.offsetWidth;
            height = this.el.offsetHeight;
            viewportWidth = window.innerWidth || document.documentElement.clientWidth;
            viewportHeight = window.innerHeight || document.documentElement.clientHeight;
            scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;

            if (typeof field.getBoundingClientRect === 'function') {
                clientRect = field.getBoundingClientRect();
                left = clientRect.left + window.pageXOffset;
                top = clientRect.bottom + window.pageYOffset;
            } else {
                left = pEl.offsetLeft;
                top  = pEl.offsetTop + pEl.offsetHeight;
                while((pEl = pEl.offsetParent)) {
                    left += pEl.offsetLeft;
                    top  += pEl.offsetTop;
                }
            }

            // default position is bottom & left
            if ((this._o.reposition && left + width > viewportWidth) ||
                (
                    this._o.position.indexOf('right') > -1 &&
                    left - width + field.offsetWidth > 0
                )
            ) {
                left = left - width + field.offsetWidth;
            }
            if ((this._o.reposition && top + height > viewportHeight + scrollTop) ||
                (
                    this._o.position.indexOf('top') > -1 &&
                    top - height - field.offsetHeight > 0
                )
            ) {
                top = top - height - field.offsetHeight;
            }

            this.el.style.left = left + 'px';
            this.el.style.top = top + 'px';
        },

        /**
         * render HTML for a particular month
         */
        render: function(year, month, randId)
        {
            var opts   = this._o,
                now    = new Date(),
                days   = getDaysInMonth(year, month),
                before = new Date(year, month, 1).getDay(),
                data   = [],
                row    = [];
            setToStartOfDay(now);
            if (opts.firstDay > 0) {
                before -= opts.firstDay;
                if (before < 0) {
                    before += 7;
                }
            }
            var previousMonth = month === 0 ? 11 : month - 1,
                nextMonth = month === 11 ? 0 : month + 1,
                yearOfPreviousMonth = month === 0 ? year - 1 : year,
                yearOfNextMonth = month === 11 ? year + 1 : year,
                daysInPreviousMonth = getDaysInMonth(yearOfPreviousMonth, previousMonth);
            var cells = days + before,
                after = cells;
            while(after > 7) {
                after -= 7;
            }
            cells += 7 - after;
            for (var i = 0, r = 0; i < cells; i++)
            {
                var day = new Date(year, month, 1 + (i - before)),
                    isSelected = isDate(this._d) ? compareDates(day, this._d) : false,
                    isToday = compareDates(day, now),
                    isEmpty = i < before || i >= (days + before),
                    dayNumber = 1 + (i - before),
                    monthNumber = month,
                    yearNumber = year,
                    isStartRange = opts.startRange && compareDates(opts.startRange, day),
                    isEndRange = opts.endRange && compareDates(opts.endRange, day),
                    isInRange = opts.startRange && opts.endRange && opts.startRange < day && day < opts.endRange,
                    isDisabled = (opts.minDate && day < opts.minDate) ||
                                 (opts.maxDate && day > opts.maxDate) ||
                                 (opts.disableWeekends && isWeekend(day)) ||
                                 (opts.disableDayFn && opts.disableDayFn(day));

                if (isEmpty) {
                    if (i < before) {
                        dayNumber = daysInPreviousMonth + dayNumber;
                        monthNumber = previousMonth;
                        yearNumber = yearOfPreviousMonth;
                    } else {
                        dayNumber = dayNumber - days;
                        monthNumber = nextMonth;
                        yearNumber = yearOfNextMonth;
                    }
                }

                var dayConfig = {
                        day: dayNumber,
                        month: monthNumber,
                        year: yearNumber,
                        isSelected: isSelected,
                        isToday: isToday,
                        isDisabled: isDisabled,
                        isEmpty: isEmpty,
                        isStartRange: isStartRange,
                        isEndRange: isEndRange,
                        isInRange: isInRange,
                        showDaysInNextAndPreviousMonths: opts.showDaysInNextAndPreviousMonths
                    };

                row.push(renderDay(dayConfig));

                if (++r === 7) {
                    if (opts.showWeekNumber) {
                        row.unshift(renderWeek(i - before, month, year));
                    }
                    data.push(renderRow(row, opts.isRTL));
                    row = [];
                    r = 0;
                }
            }
            return renderTable(opts, data, randId);
        },

        isVisible: function()
        {
            return this._v;
        },

        show: function()
        {
            if (!this.isVisible()) {
                removeClass(this.el, 'is-hidden');
                this._v = true;
                this.draw();
                if (this._o.bound) {
                    addEvent(document, 'click', this._onClick);
                    this.adjustPosition();
                }
                if (typeof this._o.onOpen === 'function') {
                    this._o.onOpen.call(this);
                }
            }
        },

        hide: function()
        {
            var v = this._v;
            if (v !== false) {
                if (this._o.bound) {
                    removeEvent(document, 'click', this._onClick);
                }
                this.el.style.position = 'static'; // reset
                this.el.style.left = 'auto';
                this.el.style.top = 'auto';
                addClass(this.el, 'is-hidden');
                this._v = false;
                if (v !== undefined && typeof this._o.onClose === 'function') {
                    this._o.onClose.call(this);
                }
            }
        },

        /**
         * GAME OVER
         */
        destroy: function()
        {
            this.hide();
            removeEvent(this.el, 'mousedown', this._onMouseDown, true);
            removeEvent(this.el, 'touchend', this._onMouseDown, true);
            removeEvent(this.el, 'change', this._onChange);
            if (this._o.field) {
                removeEvent(this._o.field, 'change', this._onInputChange);
                if (this._o.bound) {
                    removeEvent(this._o.trigger, 'click', this._onInputClick);
                    removeEvent(this._o.trigger, 'focus', this._onInputFocus);
                    removeEvent(this._o.trigger, 'blur', this._onInputBlur);
                }
            }
            if (this.el.parentNode) {
                this.el.parentNode.removeChild(this.el);
            }
        }

    };

    return Pikaday;

}));


/***/ }),
/* 351 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 352 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _autocompleteEditor = __webpack_require__(303);

var _autocompleteEditor2 = _interopRequireDefault(_autocompleteEditor);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @private
 * @editor DropdownEditor
 * @class DropdownEditor
 * @dependencies AutocompleteEditor
 */
var DropdownEditor = function (_AutocompleteEditor) {
  _inherits(DropdownEditor, _AutocompleteEditor);

  function DropdownEditor() {
    _classCallCheck(this, DropdownEditor);

    return _possibleConstructorReturn(this, (DropdownEditor.__proto__ || Object.getPrototypeOf(DropdownEditor)).apply(this, arguments));
  }

  _createClass(DropdownEditor, [{
    key: 'prepare',
    value: function prepare(row, col, prop, td, originalValue, cellProperties) {
      _get(DropdownEditor.prototype.__proto__ || Object.getPrototypeOf(DropdownEditor.prototype), 'prepare', this).call(this, row, col, prop, td, originalValue, cellProperties);
      this.cellProperties.filter = false;
      this.cellProperties.strict = true;
    }
  }]);

  return DropdownEditor;
}(_autocompleteEditor2.default);

_pluginHooks2.default.getSingleton().add('beforeValidate', function (value, row, col, source) {
  var cellMeta = this.getCellMeta(row, this.propToCol(col));

  if (cellMeta.editor === DropdownEditor) {
    if (cellMeta.strict === void 0) {
      cellMeta.filter = false;
      cellMeta.strict = true;
    }
  }
});

exports.default = DropdownEditor;

/***/ }),
/* 353 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _unicode = __webpack_require__(20);

var _event = __webpack_require__(12);

var _element = __webpack_require__(0);

var _baseEditor = __webpack_require__(47);

var _baseEditor2 = _interopRequireDefault(_baseEditor);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var MobileTextEditor = _baseEditor2.default.prototype.extend();
var domDimensionsCache = {};

/**
 * @private
 * @editor MobileTextEditor
 * @class MobileTextEditor
 */
var createControls = function createControls() {
  this.controls = {};

  this.controls.leftButton = document.createElement('DIV');
  this.controls.leftButton.className = 'leftButton';
  this.controls.rightButton = document.createElement('DIV');
  this.controls.rightButton.className = 'rightButton';
  this.controls.upButton = document.createElement('DIV');
  this.controls.upButton.className = 'upButton';
  this.controls.downButton = document.createElement('DIV');
  this.controls.downButton.className = 'downButton';

  for (var button in this.controls) {
    if (Object.prototype.hasOwnProperty.call(this.controls, button)) {
      this.positionControls.appendChild(this.controls[button]);
    }
  }
};

MobileTextEditor.prototype.valueChanged = function () {
  return this.initValue != this.getValue();
};

MobileTextEditor.prototype.init = function () {
  var that = this;
  this.eventManager = new _eventManager2.default(this.instance);

  this.createElements();
  this.bindEvents();

  this.instance.addHook('afterDestroy', function () {
    that.destroy();
  });
};

MobileTextEditor.prototype.getValue = function () {
  return this.TEXTAREA.value;
};

MobileTextEditor.prototype.setValue = function (newValue) {
  this.initValue = newValue;

  this.TEXTAREA.value = newValue;
};

MobileTextEditor.prototype.createElements = function () {
  this.editorContainer = document.createElement('DIV');
  this.editorContainer.className = 'htMobileEditorContainer';

  this.cellPointer = document.createElement('DIV');
  this.cellPointer.className = 'cellPointer';

  this.moveHandle = document.createElement('DIV');
  this.moveHandle.className = 'moveHandle';

  this.inputPane = document.createElement('DIV');
  this.inputPane.className = 'inputs';

  this.positionControls = document.createElement('DIV');
  this.positionControls.className = 'positionControls';

  this.TEXTAREA = document.createElement('TEXTAREA');
  (0, _element.addClass)(this.TEXTAREA, 'handsontableInput');

  this.inputPane.appendChild(this.TEXTAREA);

  this.editorContainer.appendChild(this.cellPointer);
  this.editorContainer.appendChild(this.moveHandle);
  this.editorContainer.appendChild(this.inputPane);
  this.editorContainer.appendChild(this.positionControls);

  createControls.call(this);

  document.body.appendChild(this.editorContainer);
};

MobileTextEditor.prototype.onBeforeKeyDown = function (event) {
  var instance = this;
  var that = instance.getActiveEditor();

  if (event.target !== that.TEXTAREA || (0, _event.isImmediatePropagationStopped)(event)) {
    return;
  }

  switch (event.keyCode) {
    case _unicode.KEY_CODES.ENTER:
      that.close();
      event.preventDefault(); // don't add newline to field
      break;
    case _unicode.KEY_CODES.BACKSPACE:
      (0, _event.stopImmediatePropagation)(event); // backspace, delete, home, end should only work locally when cell is edited (not in table context)
      break;
    default:
      break;
  }
};

MobileTextEditor.prototype.open = function () {
  this.instance.addHook('beforeKeyDown', this.onBeforeKeyDown);

  (0, _element.addClass)(this.editorContainer, 'active');
  (0, _element.removeClass)(this.cellPointer, 'hidden');

  this.updateEditorPosition();
};

MobileTextEditor.prototype.focus = function () {
  this.TEXTAREA.focus();
  (0, _element.setCaretPosition)(this.TEXTAREA, this.TEXTAREA.value.length);
};

MobileTextEditor.prototype.close = function () {
  this.TEXTAREA.blur();
  this.instance.removeHook('beforeKeyDown', this.onBeforeKeyDown);

  (0, _element.removeClass)(this.editorContainer, 'active');
};

MobileTextEditor.prototype.scrollToView = function () {
  var coords = this.instance.getSelectedRange().highlight;
  this.instance.view.scrollViewport(coords);
};

MobileTextEditor.prototype.hideCellPointer = function () {
  if (!(0, _element.hasClass)(this.cellPointer, 'hidden')) {
    (0, _element.addClass)(this.cellPointer, 'hidden');
  }
};

MobileTextEditor.prototype.updateEditorPosition = function (x, y) {
  if (x && y) {
    x = parseInt(x, 10);
    y = parseInt(y, 10);

    this.editorContainer.style.top = y + 'px';
    this.editorContainer.style.left = x + 'px';
  } else {
    var selection = this.instance.getSelected(),
        selectedCell = this.instance.getCell(selection[0], selection[1]);

    // cache sizes
    if (!domDimensionsCache.cellPointer) {
      domDimensionsCache.cellPointer = {
        height: (0, _element.outerHeight)(this.cellPointer),
        width: (0, _element.outerWidth)(this.cellPointer)
      };
    }
    if (!domDimensionsCache.editorContainer) {
      domDimensionsCache.editorContainer = {
        width: (0, _element.outerWidth)(this.editorContainer)
      };
    }

    if (selectedCell !== undefined) {
      var scrollLeft = this.instance.view.wt.wtOverlays.leftOverlay.trimmingContainer == window ? 0 : (0, _element.getScrollLeft)(this.instance.view.wt.wtOverlays.leftOverlay.holder);
      var scrollTop = this.instance.view.wt.wtOverlays.topOverlay.trimmingContainer == window ? 0 : (0, _element.getScrollTop)(this.instance.view.wt.wtOverlays.topOverlay.holder);

      var selectedCellOffset = (0, _element.offset)(selectedCell),
          selectedCellWidth = (0, _element.outerWidth)(selectedCell),
          currentScrollPosition = {
        x: scrollLeft,
        y: scrollTop
      };

      this.editorContainer.style.top = parseInt(selectedCellOffset.top + (0, _element.outerHeight)(selectedCell) - currentScrollPosition.y + domDimensionsCache.cellPointer.height, 10) + 'px';
      this.editorContainer.style.left = parseInt(window.innerWidth / 2 - domDimensionsCache.editorContainer.width / 2, 10) + 'px';

      if (selectedCellOffset.left + selectedCellWidth / 2 > parseInt(this.editorContainer.style.left, 10) + domDimensionsCache.editorContainer.width) {
        this.editorContainer.style.left = window.innerWidth - domDimensionsCache.editorContainer.width + 'px';
      } else if (selectedCellOffset.left + selectedCellWidth / 2 < parseInt(this.editorContainer.style.left, 10) + 20) {
        this.editorContainer.style.left = 0 + 'px';
      }

      this.cellPointer.style.left = parseInt(selectedCellOffset.left - domDimensionsCache.cellPointer.width / 2 - (0, _element.offset)(this.editorContainer).left + selectedCellWidth / 2 - currentScrollPosition.x, 10) + 'px';
    }
  }
};

MobileTextEditor.prototype.updateEditorData = function () {
  var selected = this.instance.getSelected(),
      selectedValue = this.instance.getDataAtCell(selected[0], selected[1]);

  this.row = selected[0];
  this.col = selected[1];
  this.setValue(selectedValue);
  this.updateEditorPosition();
};

MobileTextEditor.prototype.prepareAndSave = function () {
  var val;

  if (!this.valueChanged()) {
    return;
  }

  if (this.instance.getSettings().trimWhitespace) {
    val = [[String.prototype.trim.call(this.getValue())]];
  } else {
    val = [[this.getValue()]];
  }

  this.saveValue(val);
};

MobileTextEditor.prototype.bindEvents = function () {
  var that = this;

  this.eventManager.addEventListener(this.controls.leftButton, 'touchend', function (event) {
    that.prepareAndSave();
    that.instance.selection.transformStart(0, -1, null, true);
    that.updateEditorData();
    event.preventDefault();
  });
  this.eventManager.addEventListener(this.controls.rightButton, 'touchend', function (event) {
    that.prepareAndSave();
    that.instance.selection.transformStart(0, 1, null, true);
    that.updateEditorData();
    event.preventDefault();
  });
  this.eventManager.addEventListener(this.controls.upButton, 'touchend', function (event) {
    that.prepareAndSave();
    that.instance.selection.transformStart(-1, 0, null, true);
    that.updateEditorData();
    event.preventDefault();
  });
  this.eventManager.addEventListener(this.controls.downButton, 'touchend', function (event) {
    that.prepareAndSave();
    that.instance.selection.transformStart(1, 0, null, true);
    that.updateEditorData();
    event.preventDefault();
  });

  this.eventManager.addEventListener(this.moveHandle, 'touchstart', function (event) {
    if (event.touches.length == 1) {
      var touch = event.touches[0];
      var onTouchPosition = {
        x: that.editorContainer.offsetLeft,
        y: that.editorContainer.offsetTop
      };
      var onTouchOffset = {
        x: touch.pageX - onTouchPosition.x,
        y: touch.pageY - onTouchPosition.y
      };

      that.eventManager.addEventListener(this, 'touchmove', function (event) {
        var touch = event.touches[0];
        that.updateEditorPosition(touch.pageX - onTouchOffset.x, touch.pageY - onTouchOffset.y);
        that.hideCellPointer();
        event.preventDefault();
      });
    }
  });

  this.eventManager.addEventListener(document.body, 'touchend', function (event) {
    if (!(0, _element.isChildOf)(event.target, that.editorContainer) && !(0, _element.isChildOf)(event.target, that.instance.rootElement)) {
      that.close();
    }
  });

  this.eventManager.addEventListener(this.instance.view.wt.wtOverlays.leftOverlay.holder, 'scroll', function (event) {
    if (that.instance.view.wt.wtOverlays.leftOverlay.trimmingContainer != window) {
      that.hideCellPointer();
    }
  });

  this.eventManager.addEventListener(this.instance.view.wt.wtOverlays.topOverlay.holder, 'scroll', function (event) {
    if (that.instance.view.wt.wtOverlays.topOverlay.trimmingContainer != window) {
      that.hideCellPointer();
    }
  });
};

MobileTextEditor.prototype.destroy = function () {
  this.eventManager.clear();

  this.editorContainer.parentNode.removeChild(this.editorContainer);
};

exports.default = MobileTextEditor;

/***/ }),
/* 354 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _textEditor = __webpack_require__(54);

var _textEditor2 = _interopRequireDefault(_textEditor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @private
 * @editor NumericEditor
 * @class NumericEditor
 */
var NumericEditor = function (_TextEditor) {
  _inherits(NumericEditor, _TextEditor);

  function NumericEditor() {
    _classCallCheck(this, NumericEditor);

    return _possibleConstructorReturn(this, (NumericEditor.__proto__ || Object.getPrototypeOf(NumericEditor)).apply(this, arguments));
  }

  return NumericEditor;
}(_textEditor2.default);

exports.default = NumericEditor;

/***/ }),
/* 355 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _element = __webpack_require__(0);

var _textEditor = __webpack_require__(54);

var _textEditor2 = _interopRequireDefault(_textEditor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @private
 * @editor PasswordEditor
 * @class PasswordEditor
 * @dependencies TextEditor
 */
var PasswordEditor = function (_TextEditor) {
  _inherits(PasswordEditor, _TextEditor);

  function PasswordEditor() {
    _classCallCheck(this, PasswordEditor);

    return _possibleConstructorReturn(this, (PasswordEditor.__proto__ || Object.getPrototypeOf(PasswordEditor)).apply(this, arguments));
  }

  _createClass(PasswordEditor, [{
    key: 'createElements',
    value: function createElements() {
      _get(PasswordEditor.prototype.__proto__ || Object.getPrototypeOf(PasswordEditor.prototype), 'createElements', this).call(this);

      this.TEXTAREA = document.createElement('input');
      this.TEXTAREA.setAttribute('type', 'password');
      this.TEXTAREA.className = 'handsontableInput';
      this.textareaStyle = this.TEXTAREA.style;
      this.textareaStyle.width = 0;
      this.textareaStyle.height = 0;

      (0, _element.empty)(this.TEXTAREA_PARENT);
      this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
    }
  }]);

  return PasswordEditor;
}(_textEditor2.default);

exports.default = PasswordEditor;

/***/ }),
/* 356 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _element = __webpack_require__(0);

var _event = __webpack_require__(12);

var _unicode = __webpack_require__(20);

var _baseEditor = __webpack_require__(47);

var _baseEditor2 = _interopRequireDefault(_baseEditor);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SelectEditor = _baseEditor2.default.prototype.extend();

/**
 * @private
 * @editor SelectEditor
 * @class SelectEditor
 */
SelectEditor.prototype.init = function () {
  this.select = document.createElement('SELECT');
  (0, _element.addClass)(this.select, 'htSelectEditor');
  this.select.style.display = 'none';
  this.instance.rootElement.appendChild(this.select);
  this.registerHooks();
};

SelectEditor.prototype.registerHooks = function () {
  var _this = this;

  this.instance.addHook('afterScrollHorizontally', function () {
    return _this.refreshDimensions();
  });
  this.instance.addHook('afterScrollVertically', function () {
    return _this.refreshDimensions();
  });
  this.instance.addHook('afterColumnResize', function () {
    return _this.refreshDimensions();
  });
  this.instance.addHook('afterRowResize', function () {
    return _this.refreshDimensions();
  });
};

SelectEditor.prototype.prepare = function () {
  _baseEditor2.default.prototype.prepare.apply(this, arguments);

  var selectOptions = this.cellProperties.selectOptions;
  var options;

  if (typeof selectOptions == 'function') {
    options = this.prepareOptions(selectOptions(this.row, this.col, this.prop));
  } else {
    options = this.prepareOptions(selectOptions);
  }

  (0, _element.empty)(this.select);

  for (var option in options) {
    if (Object.prototype.hasOwnProperty.call(options, option)) {
      var optionElement = document.createElement('OPTION');
      optionElement.value = option;
      (0, _element.fastInnerHTML)(optionElement, options[option]);
      this.select.appendChild(optionElement);
    }
  }
};

SelectEditor.prototype.prepareOptions = function (optionsToPrepare) {
  var preparedOptions = {};

  if (Array.isArray(optionsToPrepare)) {
    for (var i = 0, len = optionsToPrepare.length; i < len; i++) {
      preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i];
    }
  } else if ((typeof optionsToPrepare === 'undefined' ? 'undefined' : _typeof(optionsToPrepare)) == 'object') {
    preparedOptions = optionsToPrepare;
  }

  return preparedOptions;
};

SelectEditor.prototype.getValue = function () {
  return this.select.value;
};

SelectEditor.prototype.setValue = function (value) {
  this.select.value = value;
};

var onBeforeKeyDown = function onBeforeKeyDown(event) {
  var instance = this;
  var editor = instance.getActiveEditor();

  switch (event.keyCode) {
    case _unicode.KEY_CODES.ARROW_UP:
      var previousOptionIndex = editor.select.selectedIndex - 1;
      if (previousOptionIndex >= 0) {
        editor.select[previousOptionIndex].selected = true;
      }

      (0, _event.stopImmediatePropagation)(event);
      event.preventDefault();
      break;

    case _unicode.KEY_CODES.ARROW_DOWN:
      var nextOptionIndex = editor.select.selectedIndex + 1;
      if (nextOptionIndex <= editor.select.length - 1) {
        editor.select[nextOptionIndex].selected = true;
      }

      (0, _event.stopImmediatePropagation)(event);
      event.preventDefault();
      break;
    default:
      break;
  }
};

SelectEditor.prototype.open = function () {
  this._opened = true;
  this.refreshDimensions();
  this.select.style.display = '';
  this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};

SelectEditor.prototype.close = function () {
  this._opened = false;
  this.select.style.display = 'none';
  this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};

SelectEditor.prototype.focus = function () {
  this.select.focus();
};

SelectEditor.prototype.refreshValue = function () {
  var sourceData = this.instance.getSourceDataAtCell(this.row, this.prop);
  this.originalValue = sourceData;

  this.setValue(sourceData);
  this.refreshDimensions();
};

SelectEditor.prototype.refreshDimensions = function () {
  if (this.state !== _baseEditor.EditorState.EDITING) {
    return;
  }
  this.TD = this.getEditedCell();

  // TD is outside of the viewport.
  if (!this.TD) {
    this.close();

    return;
  }
  var width = (0, _element.outerWidth)(this.TD) + 1,
      height = (0, _element.outerHeight)(this.TD) + 1,
      currentOffset = (0, _element.offset)(this.TD),
      containerOffset = (0, _element.offset)(this.instance.rootElement),
      scrollableContainer = (0, _element.getScrollableElement)(this.TD),
      editTop = currentOffset.top - containerOffset.top - 1 - (scrollableContainer.scrollTop || 0),
      editLeft = currentOffset.left - containerOffset.left - 1 - (scrollableContainer.scrollLeft || 0),
      editorSection = this.checkEditorSection(),
      cssTransformOffset;

  var settings = this.instance.getSettings();
  var rowHeadersCount = settings.rowHeaders ? 1 : 0;
  var colHeadersCount = settings.colHeaders ? 1 : 0;

  switch (editorSection) {
    case 'top':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'left':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'top-left-corner':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'bottom-left-corner':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'bottom':
      cssTransformOffset = (0, _element.getCssTransform)(this.instance.view.wt.wtOverlays.bottomOverlay.clone.wtTable.holder.parentNode);
      break;
    default:
      break;
  }
  if (this.instance.getSelected()[0] === 0) {
    editTop += 1;
  }

  if (this.instance.getSelected()[1] === 0) {
    editLeft += 1;
  }

  var selectStyle = this.select.style;

  if (cssTransformOffset && cssTransformOffset != -1) {
    selectStyle[cssTransformOffset[0]] = cssTransformOffset[1];
  } else {
    (0, _element.resetCssTransform)(this.select);
  }
  var cellComputedStyle = (0, _element.getComputedStyle)(this.TD);

  if (parseInt(cellComputedStyle.borderTopWidth, 10) > 0) {
    height -= 1;
  }
  if (parseInt(cellComputedStyle.borderLeftWidth, 10) > 0) {
    width -= 1;
  }

  selectStyle.height = height + 'px';
  selectStyle.minWidth = width + 'px';
  selectStyle.top = editTop + 'px';
  selectStyle.left = editLeft + 'px';
  selectStyle.margin = '0px';
};

SelectEditor.prototype.getEditedCell = function () {
  var editorSection = this.checkEditorSection(),
      editedCell;

  switch (editorSection) {
    case 'top':
      editedCell = this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.select.style.zIndex = 101;
      break;
    case 'corner':
      editedCell = this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.select.style.zIndex = 103;
      break;
    case 'left':
      editedCell = this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.select.style.zIndex = 102;
      break;
    default:
      editedCell = this.instance.getCell(this.row, this.col);
      this.select.style.zIndex = '';
      break;
  }

  return editedCell != -1 && editedCell != -2 ? editedCell : void 0;
};

exports.default = SelectEditor;

/***/ }),
/* 357 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

function cellDecorator(instance, TD, row, col, prop, value, cellProperties) {
  if (cellProperties.className) {
    if (TD.className) {
      TD.className = TD.className + ' ' + cellProperties.className;
    } else {
      TD.className = cellProperties.className;
    }
  }

  if (cellProperties.readOnly) {
    (0, _element.addClass)(TD, cellProperties.readOnlyCellClassName);
  }

  if (cellProperties.valid === false && cellProperties.invalidCellClassName) {
    (0, _element.addClass)(TD, cellProperties.invalidCellClassName);
  } else {
    (0, _element.removeClass)(TD, cellProperties.invalidCellClassName);
  }

  if (cellProperties.wordWrap === false && cellProperties.noWordWrapClassName) {
    (0, _element.addClass)(TD, cellProperties.noWordWrapClassName);
  }

  if (!value && cellProperties.placeholder) {
    (0, _element.addClass)(TD, cellProperties.placeholderCellClassName);
  }
} /**
   * Adds appropriate CSS class to table cell, based on cellProperties
   */
exports.default = cellDecorator;

/***/ }),
/* 358 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _src = __webpack_require__(15);

var _index = __webpack_require__(9);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var clonableWRAPPER = document.createElement('DIV');
clonableWRAPPER.className = 'htAutocompleteWrapper';

var clonableARROW = document.createElement('DIV');
clonableARROW.className = 'htAutocompleteArrow';
// workaround for https://github.com/handsontable/handsontable/issues/1946
// this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
clonableARROW.appendChild(document.createTextNode(String.fromCharCode(9660)));

var wrapTdContentWithWrapper = function wrapTdContentWithWrapper(TD, WRAPPER) {
  WRAPPER.innerHTML = TD.innerHTML;
  (0, _element.empty)(TD);
  TD.appendChild(WRAPPER);
};

/**
 * Autocomplete renderer
 *
 * @private
 * @renderer AutocompleteRenderer
 * @param {Object} instance Handsontable instance
 * @param {Element} TD Table cell where to render
 * @param {Number} row
 * @param {Number} col
 * @param {String|Number} prop Row object property name
 * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
 * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
 */
function autocompleteRenderer(instance, TD, row, col, prop, value, cellProperties) {
  var WRAPPER = clonableWRAPPER.cloneNode(true); // this is faster than createElement
  var ARROW = clonableARROW.cloneNode(true); // this is faster than createElement

  if (cellProperties.allowHtml) {
    (0, _index.getRenderer)('html').apply(this, arguments);
  } else {
    (0, _index.getRenderer)('text').apply(this, arguments);
  }

  TD.appendChild(ARROW);
  (0, _element.addClass)(TD, 'htAutocomplete');

  if (!TD.firstChild) {
    // http://jsperf.com/empty-node-if-needed
    // otherwise empty fields appear borderless in demo/renderers.html (IE)
    TD.appendChild(document.createTextNode(String.fromCharCode(160))); // workaround for https://github.com/handsontable/handsontable/issues/1946
    // this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
  }

  if (!instance.acArrowListener) {
    var eventManager = new _eventManager2.default(instance);

    // not very elegant but easy and fast
    instance.acArrowListener = function (event) {
      if ((0, _element.hasClass)(event.target, 'htAutocompleteArrow')) {
        instance.view.wt.getSetting('onCellDblClick', null, new _src.CellCoords(row, col), TD);
      }
    };

    eventManager.addEventListener(instance.rootElement, 'mousedown', instance.acArrowListener);

    // We need to unbind the listener after the table has been destroyed
    instance.addHookOnce('afterDestroy', function () {
      eventManager.destroy();
    });
  }
}

exports.default = autocompleteRenderer;

/***/ }),
/* 359 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

var _string = __webpack_require__(36);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _unicode = __webpack_require__(20);

var _function = __webpack_require__(41);

var _event = __webpack_require__(12);

var _index = __webpack_require__(9);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var isListeningKeyDownEvent = new WeakMap();
var isCheckboxListenerAdded = new WeakMap();
var BAD_VALUE_CLASS = 'htBadValue';

/**
 * Checkbox renderer
 *
 * @private
 * @param {Object} instance Handsontable instance
 * @param {Element} TD Table cell where to render
 * @param {Number} row
 * @param {Number} col
 * @param {String|Number} prop Row object property name
 * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
 * @param {Object} cellProperties Cell properties (shared by cell renderer and editor)
 */
function checkboxRenderer(instance, TD, row, col, prop, value, cellProperties) {
  (0, _index.getRenderer)('base').apply(this, arguments);

  var eventManager = registerEvents(instance);
  var input = createInput();
  var labelOptions = cellProperties.label;
  var badValue = false;

  if (typeof cellProperties.checkedTemplate === 'undefined') {
    cellProperties.checkedTemplate = true;
  }
  if (typeof cellProperties.uncheckedTemplate === 'undefined') {
    cellProperties.uncheckedTemplate = false;
  }

  (0, _element.empty)(TD); // TODO identify under what circumstances this line can be removed

  if (value === cellProperties.checkedTemplate || (0, _string.equalsIgnoreCase)(value, cellProperties.checkedTemplate)) {
    input.checked = true;
  } else if (value === cellProperties.uncheckedTemplate || (0, _string.equalsIgnoreCase)(value, cellProperties.uncheckedTemplate)) {
    input.checked = false;
  } else if (value === null) {
    // default value
    (0, _element.addClass)(input, 'noValue');
  } else {
    input.style.display = 'none';
    (0, _element.addClass)(input, BAD_VALUE_CLASS);
    badValue = true;
  }

  input.setAttribute('data-row', row);
  input.setAttribute('data-col', col);

  if (!badValue && labelOptions) {
    var labelText = '';

    if (labelOptions.value) {
      labelText = typeof labelOptions.value === 'function' ? labelOptions.value.call(this, row, col, prop, value) : labelOptions.value;
    } else if (labelOptions.property) {
      labelText = instance.getDataAtRowProp(row, labelOptions.property);
    }
    var label = createLabel(labelText);

    if (labelOptions.position === 'before') {
      label.appendChild(input);
    } else {
      label.insertBefore(input, label.firstChild);
    }
    input = label;
  }

  TD.appendChild(input);

  if (badValue) {
    TD.appendChild(document.createTextNode('#bad-value#'));
  }

  if (!isListeningKeyDownEvent.has(instance)) {
    isListeningKeyDownEvent.set(instance, true);
    instance.addHook('beforeKeyDown', onBeforeKeyDown);
  }

  /**
   * On before key down DOM listener.
   *
   * @private
   * @param {Event} event
   */
  function onBeforeKeyDown(event) {
    var toggleKeys = 'SPACE|ENTER';
    var switchOffKeys = 'DELETE|BACKSPACE';
    var isKeyCode = (0, _function.partial)(_unicode.isKey, event.keyCode);

    if (isKeyCode(toggleKeys + '|' + switchOffKeys) && !(0, _event.isImmediatePropagationStopped)(event)) {
      eachSelectedCheckboxCell(function () {
        (0, _event.stopImmediatePropagation)(event);
        event.preventDefault();
      });
    }
    if (isKeyCode(toggleKeys)) {
      changeSelectedCheckboxesState();
    }
    if (isKeyCode(switchOffKeys)) {
      changeSelectedCheckboxesState(true);
    }
  }

  /**
   * Change checkbox checked property
   *
   * @private
   * @param {Boolean} [uncheckCheckbox=false]
   */
  function changeSelectedCheckboxesState() {
    var uncheckCheckbox = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

    var selRange = instance.getSelectedRange();

    if (!selRange) {
      return;
    }

    var _selRange$getTopLeftC = selRange.getTopLeftCorner(),
        startRow = _selRange$getTopLeftC.row,
        startColumn = _selRange$getTopLeftC.col;

    var _selRange$getBottomRi = selRange.getBottomRightCorner(),
        endRow = _selRange$getBottomRi.row,
        endColumn = _selRange$getBottomRi.col;

    var changes = [];

    for (var _row = startRow; _row <= endRow; _row += 1) {
      for (var _col = startColumn; _col <= endColumn; _col += 1) {
        var _cellProperties = instance.getCellMeta(_row, _col);

        if (_cellProperties.type !== 'checkbox') {
          return;
        }

        /* eslint-disable no-continue */
        if (_cellProperties.readOnly === true) {
          continue;
        }

        if (typeof _cellProperties.checkedTemplate === 'undefined') {
          _cellProperties.checkedTemplate = true;
        }
        if (typeof _cellProperties.uncheckedTemplate === 'undefined') {
          _cellProperties.uncheckedTemplate = false;
        }

        var dataAtCell = instance.getDataAtCell(_row, _col);

        if (uncheckCheckbox === false) {
          if ([_cellProperties.checkedTemplate, _cellProperties.checkedTemplate.toString()].includes(dataAtCell)) {
            changes.push([_row, _col, _cellProperties.uncheckedTemplate]);
          } else if ([_cellProperties.uncheckedTemplate, _cellProperties.uncheckedTemplate.toString(), null, void 0].includes(dataAtCell)) {
            changes.push([_row, _col, _cellProperties.checkedTemplate]);
          }
        } else {
          changes.push([_row, _col, _cellProperties.uncheckedTemplate]);
        }
      }
    }

    if (changes.length > 0) {
      instance.setDataAtCell(changes);
    }
  }

  /**
   * Call callback for each found selected cell with checkbox type.
   *
   * @private
   * @param {Function} callback
   */
  function eachSelectedCheckboxCell(callback) {
    var selRange = instance.getSelectedRange();

    if (!selRange) {
      return;
    }
    var topLeft = selRange.getTopLeftCorner();
    var bottomRight = selRange.getBottomRightCorner();

    for (var _row2 = topLeft.row; _row2 <= bottomRight.row; _row2++) {
      for (var _col2 = topLeft.col; _col2 <= bottomRight.col; _col2++) {
        var _cellProperties2 = instance.getCellMeta(_row2, _col2);

        if (_cellProperties2.type !== 'checkbox') {
          return;
        }

        var cell = instance.getCell(_row2, _col2);

        if (cell == null) {

          callback(_row2, _col2, _cellProperties2);
        } else {
          var checkboxes = cell.querySelectorAll('input[type=checkbox]');

          if (checkboxes.length > 0 && !_cellProperties2.readOnly) {
            callback(checkboxes);
          }
        }
      }
    }
  }
}

/**
 * Register checkbox listeners.
 *
 * @param {Handsontable} instance Handsontable instance.
 * @returns {EventManager}
 */
function registerEvents(instance) {
  var eventManager = isCheckboxListenerAdded.get(instance);

  if (!eventManager) {
    eventManager = new _eventManager2.default(instance);
    eventManager.addEventListener(instance.rootElement, 'click', function (event) {
      return onClick(event, instance);
    });
    eventManager.addEventListener(instance.rootElement, 'mouseup', function (event) {
      return onMouseUp(event, instance);
    });
    eventManager.addEventListener(instance.rootElement, 'change', function (event) {
      return onChange(event, instance);
    });

    isCheckboxListenerAdded.set(instance, eventManager);
  }

  return eventManager;
}

/**
 * Create input element.
 *
 * @returns {Node}
 */
function createInput() {
  var input = document.createElement('input');

  input.className = 'htCheckboxRendererInput';
  input.type = 'checkbox';
  input.setAttribute('autocomplete', 'off');
  input.setAttribute('tabindex', '-1');

  return input.cloneNode(false);
}

/**
 * Create label element.
 *
 * @returns {Node}
 */
function createLabel(text) {
  var label = document.createElement('label');

  label.className = 'htCheckboxRendererLabel';
  label.appendChild(document.createTextNode(text));

  return label.cloneNode(true);
}

/**
 * `mouseup` callback.
 *
 * @private
 * @param {Event} event `mouseup` event.
 * @param {Object} instance Handsontable instance.
 */
function onMouseUp(event, instance) {
  if (!isCheckboxInput(event.target)) {
    return;
  }
  setTimeout(instance.listen, 10);
}

/**
 * `click` callback.
 *
 * @private
 * @param {Event} event `click` event.
 * @param {Object} instance Handsontable instance.
 */
function onClick(event, instance) {
  if (!isCheckboxInput(event.target)) {
    return false;
  }

  var row = parseInt(event.target.getAttribute('data-row'), 10);
  var col = parseInt(event.target.getAttribute('data-col'), 10);
  var cellProperties = instance.getCellMeta(row, col);

  if (cellProperties.readOnly) {
    event.preventDefault();
  }
}

/**
 * `change` callback.
 *
 * @param {Event} event `change` event.
 * @param {Object} instance Handsontable instance.
 * @param {Object} cellProperties Reference to cell properties.
 * @returns {Boolean}
 */
function onChange(event, instance) {
  if (!isCheckboxInput(event.target)) {
    return false;
  }

  var row = parseInt(event.target.getAttribute('data-row'), 10);
  var col = parseInt(event.target.getAttribute('data-col'), 10);
  var cellProperties = instance.getCellMeta(row, col);

  if (!cellProperties.readOnly) {
    var newCheckboxValue = null;

    if (event.target.checked) {
      newCheckboxValue = cellProperties.uncheckedTemplate === void 0 ? true : cellProperties.checkedTemplate;
    } else {
      newCheckboxValue = cellProperties.uncheckedTemplate === void 0 ? false : cellProperties.uncheckedTemplate;
    }

    instance.setDataAtCell(row, col, newCheckboxValue);
  }
}

/**
 * Check if the provided element is the checkbox input.
 *
 * @private
 * @param {HTMLElement} element The element in question.
 * @returns {Boolean}
 */
function isCheckboxInput(element) {
  return element.tagName === 'INPUT' && element.getAttribute('type') === 'checkbox';
}

exports.default = checkboxRenderer;

/***/ }),
/* 360 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

var _index = __webpack_require__(9);

/**
 * @private
 * @renderer HtmlRenderer
 * @param instance
 * @param TD
 * @param row
 * @param col
 * @param prop
 * @param value
 * @param cellProperties
 */
function htmlRenderer(instance, TD, row, col, prop, value, cellProperties) {
  (0, _index.getRenderer)('base').apply(this, arguments);

  if (value === null || value === void 0) {
    value = '';
  }

  (0, _element.fastInnerHTML)(TD, value);
}

exports.default = htmlRenderer;

/***/ }),
/* 361 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _numbro = __webpack_require__(305);

var _numbro2 = _interopRequireDefault(_numbro);

var _index = __webpack_require__(9);

var _number = __webpack_require__(6);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Numeric cell renderer
 *
 * @private
 * @renderer NumericRenderer
 * @dependencies numbro
 * @param {Object} instance Handsontable instance
 * @param {Element} TD Table cell where to render
 * @param {Number} row
 * @param {Number} col
 * @param {String|Number} prop Row object property name
 * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
 * @param {Object} cellProperties Cell properties (shared by cell renderer and editor)
 */
function numericRenderer(instance, TD, row, col, prop, value, cellProperties) {
  if ((0, _number.isNumeric)(value)) {
    var numericFormat = cellProperties.numericFormat;
    var cellCulture = numericFormat && numericFormat.culture;
    var cellFormatPattern = numericFormat && numericFormat.pattern;
    var className = cellProperties.className || '';
    var classArr = className.length ? className.split(' ') : [];

    if (typeof cellCulture !== 'undefined') {
      _numbro2.default.culture(cellCulture);
    }

    value = (0, _numbro2.default)(value).format(cellFormatPattern || '0');

    if (classArr.indexOf('htLeft') < 0 && classArr.indexOf('htCenter') < 0 && classArr.indexOf('htRight') < 0 && classArr.indexOf('htJustify') < 0) {
      classArr.push('htRight');
    }

    if (classArr.indexOf('htNumeric') < 0) {
      classArr.push('htNumeric');
    }

    cellProperties.className = classArr.join(' ');
  }

  (0, _index.getRenderer)('text')(instance, TD, row, col, prop, value, cellProperties);
}

exports.default = numericRenderer;

/***/ }),
/* 362 */
/***/ (function(module, exports) {



/***/ }),
/* 363 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

var _index = __webpack_require__(9);

var _number = __webpack_require__(6);

/**
 * @private
 * @renderer PasswordRenderer
 * @param instance
 * @param TD
 * @param row
 * @param col
 * @param prop
 * @param value
 * @param cellProperties
 */
function passwordRenderer(instance, TD, row, col, prop, value, cellProperties) {
  (0, _index.getRenderer)('text').apply(this, arguments);

  value = TD.innerHTML;

  var hashLength = cellProperties.hashLength || value.length;
  var hashSymbol = cellProperties.hashSymbol || '*';

  var hash = '';

  (0, _number.rangeEach)(hashLength - 1, function () {
    hash += hashSymbol;
  });
  (0, _element.fastInnerHTML)(TD, hash);
}

exports.default = passwordRenderer;

/***/ }),
/* 364 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _element = __webpack_require__(0);

var _mixed = __webpack_require__(17);

var _index = __webpack_require__(9);

/**
 * Default text renderer
 *
 * @private
 * @renderer TextRenderer
 * @param {Object} instance Handsontable instance
 * @param {Element} TD Table cell where to render
 * @param {Number} row
 * @param {Number} col
 * @param {String|Number} prop Row object property name
 * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
 * @param {Object} cellProperties Cell properties (shared by cell renderer and editor)
 */
function textRenderer(instance, TD, row, col, prop, value, cellProperties) {
  (0, _index.getRenderer)('base').apply(this, arguments);

  if (!value && cellProperties.placeholder) {
    value = cellProperties.placeholder;
  }

  var escaped = (0, _mixed.stringify)(value);

  if (!instance.getSettings().trimWhitespace) {
    escaped = escaped.replace(/ /g, String.fromCharCode(160));
  }

  if (cellProperties.rendererTemplate) {
    (0, _element.empty)(TD);
    var TEMPLATE = document.createElement('TEMPLATE');
    TEMPLATE.setAttribute('bind', '{{}}');
    TEMPLATE.innerHTML = cellProperties.rendererTemplate;
    HTMLTemplateElement.decorate(TEMPLATE);
    TEMPLATE.model = instance.getSourceDataAtRow(row);
    TD.appendChild(TEMPLATE);
  } else {
    // this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips
    (0, _element.fastInnerText)(TD, escaped);
  }
}

exports.default = textRenderer;

/***/ }),
/* 365 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = autocompleteValidator;
/**
 * Autocomplete cell validator.
 *
 * @private
 * @validator AutocompleteValidator
 * @param {*} value - Value of edited cell
 * @param {Function} callback - Callback called with validation result
 */
function autocompleteValidator(value, callback) {
  if (value == null) {
    value = '';
  }

  if (this.allowEmpty && value === '') {
    callback(true);

    return;
  }

  if (this.strict && this.source) {
    if (typeof this.source === 'function') {
      this.source(value, process(value, callback));
    } else {
      process(value, callback)(this.source);
    }
  } else {
    callback(true);
  }
};

/**
 * Function responsible for validation of autocomplete value.
 *
 * @param {*} value - Value of edited cell
 * @param {Function} callback - Callback called with validation result
 */
function process(value, callback) {
  var originalVal = value;

  return function (source) {
    var found = false;

    for (var s = 0, slen = source.length; s < slen; s++) {
      if (originalVal === source[s]) {
        found = true; // perfect match
        break;
      }
    }

    callback(found);
  };
}

/***/ }),
/* 366 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = dateValidator;
exports.correctFormat = correctFormat;

var _moment = __webpack_require__(40);

var _moment2 = _interopRequireDefault(_moment);

var _date = __webpack_require__(306);

var _editors = __webpack_require__(16);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Date cell validator
 *
 * @private
 * @validator DateValidator
 * @dependencies moment
 * @param {*} value - Value of edited cell
 * @param {Function} callback - Callback called with validation result
 */
function dateValidator(value, callback) {
  var valid = true;
  var dateEditor = (0, _editors.getEditorInstance)('date', this.instance);

  if (value == null) {
    value = '';
  }
  var isValidDate = (0, _moment2.default)(new Date(value)).isValid() || (0, _moment2.default)(value, dateEditor.defaultDateFormat).isValid();
  // is it in the specified format
  var isValidFormat = (0, _moment2.default)(value, this.dateFormat || dateEditor.defaultDateFormat, true).isValid();

  if (this.allowEmpty && value === '') {
    isValidDate = true;
    isValidFormat = true;
  }
  if (!isValidDate) {
    valid = false;
  }
  if (!isValidDate && isValidFormat) {
    valid = true;
  }

  if (isValidDate && !isValidFormat) {
    if (this.correctFormat === true) {
      // if format correction is enabled
      var correctedValue = correctFormat(value, this.dateFormat);
      var row = this.instance.runHooks('unmodifyRow', this.row);
      var column = this.instance.runHooks('unmodifyCol', this.col);

      this.instance.setDataAtCell(row, column, correctedValue, 'dateValidator');
      valid = true;
    } else {
      valid = false;
    }
  }

  callback(valid);
};

/**
 * Format the given string using moment.js' format feature
 *
 * @param {String} value
 * @param {String} dateFormat
 * @returns {String}
 */
function correctFormat(value, dateFormat) {
  var dateFromDate = (0, _moment2.default)((0, _date.getNormalizedDate)(value));
  var dateFromMoment = (0, _moment2.default)(value, dateFormat);
  var isAlphanumeric = value.search(/[A-z]/g) > -1;
  var date = void 0;

  if (dateFromDate.isValid() && dateFromDate.format('x') === dateFromMoment.format('x') || !dateFromMoment.isValid() || isAlphanumeric) {
    date = dateFromDate;
  } else {
    date = dateFromMoment;
  }

  return date.format(dateFormat);
};

/***/ }),
/* 367 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = numericValidator;
/**
 * Numeric cell validator
 *
 * @private
 * @validator NumericValidator
 * @param {*} value - Value of edited cell
 * @param {*} callback - Callback called with validation result
 */
function numericValidator(value, callback) {
  if (value == null) {
    value = '';
  }
  if (this.allowEmpty && value === '') {
    callback(true);
  } else if (value === '') {
    callback(false);
  } else {
    callback(/^-?\d*(\.|,)?\d*$/.test(value));
  }
};

/***/ }),
/* 368 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = timeValidator;

var _moment = __webpack_require__(40);

var _moment2 = _interopRequireDefault(_moment);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// Formats which are correctly parsed to time (supported by momentjs)
var STRICT_FORMATS = ['YYYY-MM-DDTHH:mm:ss.SSSZ', 'X', // Unix timestamp
'x' // Unix ms timestamp
];

/**
 * Time cell validator
 *
 * @private
 * @validator TimeValidator
 * @dependencies moment
 * @param {*} value - Value of edited cell
 * @param {Function} callback - Callback called with validation result
 */
function timeValidator(value, callback) {
  var valid = true;
  var timeFormat = this.timeFormat || 'h:mm:ss a';

  if (value === null) {
    value = '';
  }

  value = /^\d{3,}$/.test(value) ? parseInt(value, 10) : value;

  var twoDigitValue = /^\d{1,2}$/.test(value);

  if (twoDigitValue) {
    value += ':00';
  }

  var date = (0, _moment2.default)(value, STRICT_FORMATS, true).isValid() ? (0, _moment2.default)(value) : (0, _moment2.default)(value, timeFormat);
  var isValidTime = date.isValid();

  // is it in the specified format
  var isValidFormat = (0, _moment2.default)(value, timeFormat, true).isValid() && !twoDigitValue;

  if (this.allowEmpty && value === '') {
    isValidTime = true;
    isValidFormat = true;
  }
  if (!isValidTime) {
    valid = false;
  }
  if (!isValidTime && isValidFormat) {
    valid = true;
  }
  if (isValidTime && !isValidFormat) {
    if (this.correctFormat === true) {
      // if format correction is enabled
      var correctedValue = date.format(timeFormat);
      var row = this.instance.runHooks('unmodifyRow', this.row);
      var column = this.instance.runHooks('unmodifyCol', this.col);

      this.instance.setDataAtCell(row, column, correctedValue, 'timeValidator');
      valid = true;
    } else {
      valid = false;
    }
  }

  callback(valid);
};

/***/ }),
/* 369 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var CELL_TYPE = 'autocomplete';

exports.default = {
  editor: (0, _editors.getEditor)(CELL_TYPE),
  renderer: (0, _renderers.getRenderer)(CELL_TYPE),
  validator: (0, _validators.getValidator)(CELL_TYPE)
};

/***/ }),
/* 370 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var CELL_TYPE = 'checkbox';

exports.default = {
  editor: (0, _editors.getEditor)(CELL_TYPE),
  renderer: (0, _renderers.getRenderer)(CELL_TYPE)
};

/***/ }),
/* 371 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var CELL_TYPE = 'date';

exports.default = {
  editor: (0, _editors.getEditor)(CELL_TYPE),
  // displays small gray arrow on right side of the cell
  renderer: (0, _renderers.getRenderer)('autocomplete'),
  validator: (0, _validators.getValidator)(CELL_TYPE)
};

/***/ }),
/* 372 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var CELL_TYPE = 'dropdown';

exports.default = {
  editor: (0, _editors.getEditor)(CELL_TYPE),
  // displays small gray arrow on right side of the cell
  renderer: (0, _renderers.getRenderer)('autocomplete'),
  validator: (0, _validators.getValidator)('autocomplete')
};

/***/ }),
/* 373 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var CELL_TYPE = 'handsontable';

exports.default = {
  editor: (0, _editors.getEditor)(CELL_TYPE),
  // displays small gray arrow on right side of the cell
  renderer: (0, _renderers.getRenderer)('autocomplete')
};

/***/ }),
/* 374 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var CELL_TYPE = 'numeric';

exports.default = {
  editor: (0, _editors.getEditor)(CELL_TYPE),
  renderer: (0, _renderers.getRenderer)(CELL_TYPE),
  validator: (0, _validators.getValidator)(CELL_TYPE),
  dataType: 'number'
};

/***/ }),
/* 375 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var CELL_TYPE = 'password';

exports.default = {
  editor: (0, _editors.getEditor)(CELL_TYPE),
  renderer: (0, _renderers.getRenderer)(CELL_TYPE),
  copyable: false
};

/***/ }),
/* 376 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _browser = __webpack_require__(28);

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var CELL_TYPE = 'text';

exports.default = {
  editor: (0, _browser.isMobileBrowser)() ? (0, _editors.getEditor)('mobile') : (0, _editors.getEditor)(CELL_TYPE),
  renderer: (0, _renderers.getRenderer)(CELL_TYPE)
};

/***/ }),
/* 377 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _editors = __webpack_require__(16);

var _renderers = __webpack_require__(9);

var _validators = __webpack_require__(29);

var CELL_TYPE = 'time';

exports.default = {
  editor: (0, _editors.getEditor)('text'),
  // displays small gray arrow on right side of the cell
  renderer: (0, _renderers.getRenderer)('text'),
  validator: (0, _validators.getValidator)(CELL_TYPE)
};

/***/ }),
/* 378 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _SheetClip = __webpack_require__(307);

var _SheetClip2 = _interopRequireDefault(_SheetClip);

var _data = __webpack_require__(86);

var _setting = __webpack_require__(85);

var _object = __webpack_require__(1);

var _array = __webpack_require__(2);

var _interval = __webpack_require__(379);

var _interval2 = _interopRequireDefault(_interval);

var _number = __webpack_require__(6);

var _multiMap = __webpack_require__(380);

var _multiMap2 = _interopRequireDefault(_multiMap);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Utility class that gets and saves data from/to the data source using mapping of columns numbers to object property names
 * @todo refactor arguments of methods getRange, getText to be numbers (not objects)
 * @todo remove priv, GridSettings from object constructor
 *
 * @param {Object} instance Instance of Handsontable
 * @param {*} priv
 * @param {*} GridSettings Grid settings
 * @util
 * @class DataMap
 */
function DataMap(instance, priv, GridSettings) {
  var _this = this;

  this.instance = instance;
  this.priv = priv;
  this.GridSettings = GridSettings;
  this.dataSource = this.instance.getSettings().data;
  this.cachedLength = null;
  this.skipCache = false;
  this.latestSourceRowsCount = 0;

  if (this.dataSource && this.dataSource[0]) {
    this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]);
  } else {
    this.duckSchema = {};
  }
  this.createMap();
  this.interval = _interval2.default.create(function () {
    return _this.clearLengthCache();
  }, '15fps');

  this.instance.addHook('skipLengthCache', function (delay) {
    return _this.onSkipLengthCache(delay);
  });
  this.onSkipLengthCache(500);
}

DataMap.prototype.DESTINATION_RENDERER = 1;
DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2;

/**
 * @param {Object|Array} object
 * @returns {Object|Array}
 */
DataMap.prototype.recursiveDuckSchema = function (object) {
  return (0, _object.duckSchema)(object);
};

/**
 * @param {Object} schema
 * @param {Number} lastCol
 * @param {Number} parent
 * @returns {Number}
 */
DataMap.prototype.recursiveDuckColumns = function (schema, lastCol, parent) {
  var prop, i;
  if (typeof lastCol === 'undefined') {
    lastCol = 0;
    parent = '';
  }
  if ((typeof schema === 'undefined' ? 'undefined' : _typeof(schema)) === 'object' && !Array.isArray(schema)) {
    for (i in schema) {
      if ((0, _object.hasOwnProperty)(schema, i)) {
        if (schema[i] === null) {
          prop = parent + i;
          this.colToPropCache.push(prop);
          this.propToColCache.set(prop, lastCol);

          lastCol++;
        } else {
          lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.');
        }
      }
    }
  }

  return lastCol;
};

DataMap.prototype.createMap = function () {
  var i = void 0;
  var schema = this.getSchema();

  if (typeof schema === 'undefined') {
    throw new Error('trying to create `columns` definition but you didn\'t provide `schema` nor `data`');
  }

  this.colToPropCache = [];
  this.propToColCache = new _multiMap2.default();

  var columns = this.instance.getSettings().columns;

  if (columns) {
    var maxCols = this.instance.getSettings().maxCols;
    var columnsLen = Math.min(maxCols, columns.length);
    var filteredIndex = 0;
    var columnsAsFunc = false;
    var schemaLen = (0, _object.deepObjectSize)(schema);

    if (typeof columns === 'function') {
      columnsLen = schemaLen > 0 ? schemaLen : this.instance.countSourceCols();
      columnsAsFunc = true;
    }

    for (i = 0; i < columnsLen; i++) {
      var column = columnsAsFunc ? columns(i) : columns[i];

      if ((0, _object.isObject)(column)) {
        if (typeof column.data !== 'undefined') {
          var index = columnsAsFunc ? filteredIndex : i;
          this.colToPropCache[index] = column.data;
          this.propToColCache.set(column.data, index);
        }

        filteredIndex++;
      }
    }
  } else {
    this.recursiveDuckColumns(schema);
  }
};

/**
 * Returns property name that corresponds with the given column index.
 *
 * @param {Number} col Visual column index.
 * @returns {Number} Physical column index.
 */
DataMap.prototype.colToProp = function (col) {
  col = this.instance.runHooks('modifyCol', col);

  if (!isNaN(col) && this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') {
    return this.colToPropCache[col];
  }

  return col;
};

/**
 * @param {Object} prop
 * @fires Hooks#modifyCol
 * @returns {*}
 */
DataMap.prototype.propToCol = function (prop) {
  var col;

  if (typeof this.propToColCache.get(prop) === 'undefined') {
    col = prop;
  } else {
    col = this.propToColCache.get(prop);
  }
  col = this.instance.runHooks('unmodifyCol', col);

  return col;
};

/**
 * @returns {Object}
 */
DataMap.prototype.getSchema = function () {
  var schema = this.instance.getSettings().dataSchema;

  if (schema) {
    if (typeof schema === 'function') {
      return schema();
    }
    return schema;
  }

  return this.duckSchema;
};

/**
 * Creates row at the bottom of the data array.
 *
 * @param {Number} [index] Physical index of the row before which the new row will be inserted.
 * @param {Number} [amount] An amount of rows to add.
 * @param {String} [source] Source of method call.
 * @fires Hooks#afterCreateRow
 * @returns {Number} Returns number of created rows.
 */
DataMap.prototype.createRow = function (index, amount, source) {
  var row,
      colCount = this.instance.countCols(),
      numberOfCreatedRows = 0,
      currentIndex;

  if (!amount) {
    amount = 1;
  }

  if (typeof index !== 'number' || index >= this.instance.countSourceRows()) {
    index = this.instance.countSourceRows();
  }
  this.instance.runHooks('beforeCreateRow', index, amount, source);

  currentIndex = index;
  var maxRows = this.instance.getSettings().maxRows;

  while (numberOfCreatedRows < amount && this.instance.countSourceRows() < maxRows) {
    if (this.instance.dataType === 'array') {
      if (this.instance.getSettings().dataSchema) {
        // Clone template array
        row = (0, _object.deepClone)(this.getSchema());
      } else {
        row = [];
        /* eslint-disable no-loop-func */
        (0, _number.rangeEach)(colCount - 1, function () {
          return row.push(null);
        });
      }
    } else if (this.instance.dataType === 'function') {
      row = this.instance.getSettings().dataSchema(index);
    } else {
      row = {};
      (0, _object.deepExtend)(row, this.getSchema());
    }

    if (index === this.instance.countSourceRows()) {
      this.dataSource.push(row);
    } else {
      this.spliceData(index, 0, row);
    }

    numberOfCreatedRows++;
    currentIndex++;
  }

  this.instance.runHooks('afterCreateRow', index, numberOfCreatedRows, source);
  this.instance.forceFullRender = true; // used when data was changed

  return numberOfCreatedRows;
};

/**
 * Creates col at the right of the data array.
 *
 * @param {Number} [index] Visual index of the column before which the new column will be inserted
 * @param {Number} [amount] An amount of columns to add.
 * @param {String} [source] Source of method call.
 * @fires Hooks#afterCreateCol
 * @returns {Number} Returns number of created columns
 */
DataMap.prototype.createCol = function (index, amount, source) {
  if (!this.instance.isColumnModificationAllowed()) {
    throw new Error('Cannot create new column. When data source in an object, ' + 'you can only have as much columns as defined in first data row, data schema or in the \'columns\' setting.' + 'If you want to be able to add new columns, you have to use array datasource.');
  }
  var rlen = this.instance.countSourceRows(),
      data = this.dataSource,
      constructor,
      numberOfCreatedCols = 0,
      currentIndex;

  if (!amount) {
    amount = 1;
  }

  if (typeof index !== 'number' || index >= this.instance.countCols()) {
    index = this.instance.countCols();
  }
  this.instance.runHooks('beforeCreateCol', index, amount, source);

  currentIndex = index;

  var maxCols = this.instance.getSettings().maxCols;
  while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) {
    constructor = (0, _setting.columnFactory)(this.GridSettings, this.priv.columnsSettingConflicts);

    if (typeof index !== 'number' || index >= this.instance.countCols()) {
      if (rlen > 0) {
        for (var r = 0; r < rlen; r++) {
          if (typeof data[r] === 'undefined') {
            data[r] = [];
          }
          data[r].push(null);
        }
      } else {
        data.push([null]);
      }
      // Add new column constructor
      this.priv.columnSettings.push(constructor);
    } else {
      for (var _r = 0; _r < rlen; _r++) {
        data[_r].splice(currentIndex, 0, null);
      }
      // Add new column constructor at given index
      this.priv.columnSettings.splice(currentIndex, 0, constructor);
    }

    numberOfCreatedCols++;
    currentIndex++;
  }

  this.instance.runHooks('afterCreateCol', index, numberOfCreatedCols, source);
  this.instance.forceFullRender = true; // used when data was changed

  return numberOfCreatedCols;
};

/**
 * Removes row from the data array.
 *
 * @param {Number} [index] Visual index of the row to be removed. If not provided, the last row will be removed
 * @param {Number} [amount] Amount of the rows to be removed. If not provided, one row will be removed
 * @param {String} [source] Source of method call.
 * @fires Hooks#beforeRemoveRow
 * @fires Hooks#afterRemoveRow
 */
DataMap.prototype.removeRow = function (index, amount, source) {
  if (!amount) {
    amount = 1;
  }
  if (typeof index !== 'number') {
    index = -amount;
  }

  amount = this.instance.runHooks('modifyRemovedAmount', amount, index);

  index = (this.instance.countSourceRows() + index) % this.instance.countSourceRows();

  var logicRows = this.visualRowsToPhysical(index, amount);
  var actionWasNotCancelled = this.instance.runHooks('beforeRemoveRow', index, amount, logicRows, source);

  if (actionWasNotCancelled === false) {
    return;
  }

  var data = this.dataSource;
  var newData = void 0;

  newData = this.filterData(index, amount);

  if (newData) {
    data.length = 0;
    Array.prototype.push.apply(data, newData);
  }

  this.instance.runHooks('afterRemoveRow', index, amount, logicRows, source);

  this.instance.forceFullRender = true; // used when data was changed
};

/**
 * Removes column from the data array.
 *
 * @param {Number} [index] Visual index of the column to be removed. If not provided, the last column will be removed
 * @param {Number} [amount] Amount of the columns to be removed. If not provided, one column will be removed
 * @param {String} [source] Source of method call.
 * @fires Hooks#beforeRemoveCol
 * @fires Hooks#afterRemoveCol
 */
DataMap.prototype.removeCol = function (index, amount, source) {
  if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
    throw new Error('cannot remove column with object data source or columns option specified');
  }
  if (!amount) {
    amount = 1;
  }
  if (typeof index !== 'number') {
    index = -amount;
  }

  index = (this.instance.countCols() + index) % this.instance.countCols();

  var logicColumns = this.visualColumnsToPhysical(index, amount);
  var descendingLogicColumns = logicColumns.slice(0).sort(function (a, b) {
    return b - a;
  });
  var actionWasNotCancelled = this.instance.runHooks('beforeRemoveCol', index, amount, logicColumns, source);

  if (actionWasNotCancelled === false) {
    return;
  }

  var isTableUniform = true;
  var removedColumnsCount = descendingLogicColumns.length;
  var data = this.dataSource;

  for (var c = 0; c < removedColumnsCount; c++) {
    if (isTableUniform && logicColumns[0] !== logicColumns[c] - c) {
      isTableUniform = false;
    }
  }

  if (isTableUniform) {
    for (var r = 0, rlen = this.instance.countSourceRows(); r < rlen; r++) {
      data[r].splice(logicColumns[0], amount);
    }
  } else {
    for (var _r2 = 0, _rlen = this.instance.countSourceRows(); _r2 < _rlen; _r2++) {
      for (var _c = 0; _c < removedColumnsCount; _c++) {
        data[_r2].splice(descendingLogicColumns[_c], 1);
      }
    }

    for (var _c2 = 0; _c2 < removedColumnsCount; _c2++) {
      this.priv.columnSettings.splice(logicColumns[_c2], 1);
    }
  }

  this.instance.runHooks('afterRemoveCol', index, amount, logicColumns, source);

  this.instance.forceFullRender = true; // used when data was changed
};

/**
 * Add/Removes data from the column.
 *
 * @param {Number} col Physical index of column in which do you want to do splice
 * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
 * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
 * @returns {Array} Returns removed portion of columns
 */
DataMap.prototype.spliceCol = function (col, index, amount /* , elements... */) {
  var elements = arguments.length >= 4 ? [].slice.call(arguments, 3) : [];

  var colData = this.instance.getDataAtCol(col);
  var removed = colData.slice(index, index + amount);
  var after = colData.slice(index + amount);

  (0, _array.extendArray)(elements, after);
  var i = 0;
  while (i < amount) {
    elements.push(null); // add null in place of removed elements
    i++;
  }
  (0, _array.to2dArray)(elements);
  this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol');

  return removed;
};

/**
 * Add/Removes data from the row.
 *
 * @param {Number} row Physical index of row in which do you want to do splice
 * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
 * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed.
 * @returns {Array} Returns removed portion of rows
 */
DataMap.prototype.spliceRow = function (row, index, amount /* , elements... */) {
  var elements = arguments.length >= 4 ? [].slice.call(arguments, 3) : [];

  var rowData = this.instance.getSourceDataAtRow(row);
  var removed = rowData.slice(index, index + amount);
  var after = rowData.slice(index + amount);

  (0, _array.extendArray)(elements, after);
  var i = 0;
  while (i < amount) {
    elements.push(null); // add null in place of removed elements
    i++;
  }
  this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow');

  return removed;
};

/**
 * Add/remove row(s) to/from the data source.
 *
 * @param {Number} index Physical index of the element to remove.
 * @param {Number} amount Number of rows to add/remove.
 * @param {Object} element Row to add.
 */
DataMap.prototype.spliceData = function (index, amount, element) {
  var continueSplicing = this.instance.runHooks('beforeDataSplice', index, amount, element);

  if (continueSplicing !== false) {
    this.dataSource.splice(index, amount, element);
  }
};

/**
 * Filter unwanted data elements from the data source.
 *
 * @param {Number} index Visual index of the element to remove.
 * @param {Number} amount Number of rows to add/remove.
 * @returns {Array}
 */
DataMap.prototype.filterData = function (index, amount) {
  var physicalRows = this.visualRowsToPhysical(index, amount);
  var continueSplicing = this.instance.runHooks('beforeDataFilter', index, amount, physicalRows);

  if (continueSplicing !== false) {
    var newData = this.dataSource.filter(function (row, index) {
      return physicalRows.indexOf(index) == -1;
    });

    return newData;
  }
};

/**
 * Returns single value from the data array.
 *
 * @param {Number} row Visual row index.
 * @param {Number} prop
 */
DataMap.prototype.get = function (row, prop) {
  row = this.instance.runHooks('modifyRow', row);

  var dataRow = this.dataSource[row];
  // TODO: To remove, use 'modifyData' hook instead (see below)
  var modifiedRowData = this.instance.runHooks('modifyRowData', row);

  dataRow = isNaN(modifiedRowData) ? modifiedRowData : dataRow;
  //

  var value = null;

  // try to get value under property `prop` (includes dot)
  if (dataRow && dataRow.hasOwnProperty && (0, _object.hasOwnProperty)(dataRow, prop)) {
    value = dataRow[prop];
  } else if (typeof prop === 'string' && prop.indexOf('.') > -1) {
    var sliced = prop.split('.');
    var out = dataRow;

    if (!out) {
      return null;
    }
    for (var i = 0, ilen = sliced.length; i < ilen; i++) {
      out = out[sliced[i]];

      if (typeof out === 'undefined') {
        return null;
      }
    }
    value = out;
  } else if (typeof prop === 'function') {
    /**
     *  allows for interacting with complex structures, for example
     *  d3/jQuery getter/setter properties:
     *
     *    {columns: [{
     *      data: function(row, value){
     *        if(arguments.length === 1){
     *          return row.property();
     *        }
     *        row.property(value);
     *      }
     *    }]}
     */
    value = prop(this.dataSource.slice(row, row + 1)[0]);
  }

  if (this.instance.hasHook('modifyData')) {
    var valueHolder = (0, _object.createObjectPropListener)(value);

    this.instance.runHooks('modifyData', row, this.propToCol(prop), valueHolder, 'get');

    if (valueHolder.isTouched()) {
      value = valueHolder.value;
    }
  }

  return value;
};

var copyableLookup = (0, _data.cellMethodLookupFactory)('copyable', false);

/**
 * Returns single value from the data array (intended for clipboard copy to an external application).
 *
 * @param {Number} row Physical row index.
 * @param {Number} prop
 * @returns {String}
 */
DataMap.prototype.getCopyable = function (row, prop) {
  if (copyableLookup.call(this.instance, row, this.propToCol(prop))) {
    return this.get(row, prop);
  }
  return '';
};

/**
 * Saves single value to the data array.
 *
 * @param {Number} row Visual row index.
 * @param {Number} prop
 * @param {String} value
 * @param {String} [source] Source of hook runner.
 */
DataMap.prototype.set = function (row, prop, value, source) {
  row = this.instance.runHooks('modifyRow', row, source || 'datamapGet');

  var dataRow = this.dataSource[row];
  // TODO: To remove, use 'modifyData' hook instead (see below)
  var modifiedRowData = this.instance.runHooks('modifyRowData', row);

  dataRow = isNaN(modifiedRowData) ? modifiedRowData : dataRow;
  //

  if (this.instance.hasHook('modifyData')) {
    var valueHolder = (0, _object.createObjectPropListener)(value);

    this.instance.runHooks('modifyData', row, this.propToCol(prop), valueHolder, 'set');

    if (valueHolder.isTouched()) {
      value = valueHolder.value;
    }
  }

  // try to set value under property `prop` (includes dot)
  if (dataRow && dataRow.hasOwnProperty && (0, _object.hasOwnProperty)(dataRow, prop)) {
    dataRow[prop] = value;
  } else if (typeof prop === 'string' && prop.indexOf('.') > -1) {
    var sliced = prop.split('.');
    var out = dataRow;
    var i = 0;
    var ilen = void 0;

    for (i = 0, ilen = sliced.length - 1; i < ilen; i++) {
      if (typeof out[sliced[i]] === 'undefined') {
        out[sliced[i]] = {};
      }
      out = out[sliced[i]];
    }
    out[sliced[i]] = value;
  } else if (typeof prop === 'function') {
    /* see the `function` handler in `get` */
    prop(this.dataSource.slice(row, row + 1)[0], value);
  } else {
    dataRow[prop] = value;
  }
};

/**
 * This ridiculous piece of code maps rows Id that are present in table data to those displayed for user.
 * The trick is, the physical row id (stored in settings.data) is not necessary the same
 * as the visual (displayed) row id (e.g. when sorting is applied).
 *
 * @param {Number} index Visual row index.
 * @param {Number} amount
 * @fires Hooks#modifyRow
 * @returns {Number}
 */
DataMap.prototype.visualRowsToPhysical = function (index, amount) {
  var totalRows = this.instance.countSourceRows();
  var physicRow = (totalRows + index) % totalRows;
  var logicRows = [];
  var rowsToRemove = amount;
  var row;

  while (physicRow < totalRows && rowsToRemove) {
    row = this.instance.runHooks('modifyRow', physicRow);
    logicRows.push(row);

    rowsToRemove--;
    physicRow++;
  }

  return logicRows;
};

/**
 *
 * @param index Visual column index.
 * @param amount
 * @returns {Array}
 */
DataMap.prototype.visualColumnsToPhysical = function (index, amount) {
  var totalCols = this.instance.countCols();
  var physicalCol = (totalCols + index) % totalCols;
  var visualCols = [];
  var colsToRemove = amount;

  while (physicalCol < totalCols && colsToRemove) {
    var col = this.instance.runHooks('modifyCol', physicalCol);

    visualCols.push(col);

    colsToRemove--;
    physicalCol++;
  }

  return visualCols;
};

/**
 * Clears the data array.
 */
DataMap.prototype.clear = function () {
  for (var r = 0; r < this.instance.countSourceRows(); r++) {
    for (var c = 0; c < this.instance.countCols(); c++) {
      this.set(r, this.colToProp(c), '');
    }
  }
};

/**
 * Clear cached data length.
 */
DataMap.prototype.clearLengthCache = function () {
  this.cachedLength = null;
};

/**
 * Get data length.
 *
 * @returns {Number}
 */
DataMap.prototype.getLength = function () {
  var _this2 = this;

  var maxRows = void 0,
      maxRowsFromSettings = this.instance.getSettings().maxRows;

  if (maxRowsFromSettings < 0 || maxRowsFromSettings === 0) {
    maxRows = 0;
  } else {
    maxRows = maxRowsFromSettings || Infinity;
  }

  var length = this.instance.countSourceRows();

  if (this.instance.hasHook('modifyRow')) {
    var reValidate = this.skipCache;

    this.interval.start();
    if (length !== this.latestSourceRowsCount) {
      reValidate = true;
    }

    this.latestSourceRowsCount = length;
    if (this.cachedLength === null || reValidate) {
      (0, _number.rangeEach)(length - 1, function (row) {
        row = _this2.instance.runHooks('modifyRow', row);

        if (row === null) {
          --length;
        }
      });
      this.cachedLength = length;
    } else {
      length = this.cachedLength;
    }
  } else {
    this.interval.stop();
  }

  return Math.min(length, maxRows);
};

/**
 * Returns the data array.
 *
 * @returns {Array}
 */
DataMap.prototype.getAll = function () {
  var start = {
    row: 0,
    col: 0
  };

  var end = {
    row: Math.max(this.instance.countSourceRows() - 1, 0),
    col: Math.max(this.instance.countCols() - 1, 0)
  };

  if (start.row - end.row === 0 && !this.instance.countSourceRows()) {
    return [];
  }

  return this.getRange(start, end, DataMap.prototype.DESTINATION_RENDERER);
};

/**
 * Returns data range as array.
 *
 * @param {Object} [start] Start selection position. Visual indexes.
 * @param {Object} [end] End selection position. Visual indexes.
 * @param {Number} destination Destination of datamap.get
 * @returns {Array}
 */
DataMap.prototype.getRange = function (start, end, destination) {
  var r,
      rlen,
      c,
      clen,
      output = [],
      row;

  var maxRows = this.instance.getSettings().maxRows;
  var maxCols = this.instance.getSettings().maxCols;

  if (maxRows === 0 || maxCols === 0) {
    return [];
  }

  var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get;

  rlen = Math.min(Math.max(maxRows - 1, 0), Math.max(start.row, end.row));
  clen = Math.min(Math.max(maxCols - 1, 0), Math.max(start.col, end.col));

  for (r = Math.min(start.row, end.row); r <= rlen; r++) {
    row = [];
    var physicalRow = this.instance.runHooks('modifyRow', r);

    for (c = Math.min(start.col, end.col); c <= clen; c++) {

      if (physicalRow === null) {
        break;
      }
      row.push(getFn.call(this, r, this.colToProp(c)));
    }
    if (physicalRow !== null) {
      output.push(row);
    }
  }

  return output;
};

/**
 * Return data as text (tab separated columns).
 *
 * @param {Object} [start] Start selection position. Visual indexes.
 * @param {Object} [end] End selection position. Visual indexes.
 * @returns {String}
 */
DataMap.prototype.getText = function (start, end) {
  return _SheetClip2.default.stringify(this.getRange(start, end, this.DESTINATION_RENDERER));
};

/**
 * Return data as copyable text (tab separated columns intended for clipboard copy to an external application).
 *
 * @param {Object} [start] Start selection position. Visual indexes.
 * @param {Object} [end] End selection position. Visual indexes.
 * @returns {String}
 */
DataMap.prototype.getCopyableText = function (start, end) {
  return _SheetClip2.default.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR));
};

/**
 * `skipLengthCache` callback.
 * @private
 * @param {Number} delay Time of the delay in milliseconds.
 */
DataMap.prototype.onSkipLengthCache = function (delay) {
  var _this3 = this;

  this.skipCache = true;
  setTimeout(function () {
    _this3.skipCache = false;
  }, delay);
};

/**
 * Destroy instance.
 */
DataMap.prototype.destroy = function () {
  this.interval.stop();

  this.interval = null;
  this.instance = null;
  this.priv = null;
  this.GridSettings = null;
  this.dataSource = null;
  this.cachedLength = null;
  this.duckSchema = null;
};

exports.default = DataMap;

/***/ }),
/* 379 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.parseDelay = parseDelay;

var _feature = __webpack_require__(39);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Interval
 * @util
 */
var Interval = function () {
  _createClass(Interval, null, [{
    key: 'create',
    value: function create(func, delay) {
      return new Interval(func, delay);
    }
  }]);

  function Interval(func, delay) {
    var _this = this;

    _classCallCheck(this, Interval);

    /**
     * Animation frame request id.
     *
     * @type {Number}
     */
    this.timer = null;
    /**
     * Function to invoke repeatedly.
     *
     * @type {Function}
     */
    this.func = func;
    /**
     * Number of milliseconds that function should wait before next call.
     */
    this.delay = parseDelay(delay);
    /**
     * Flag which indicates if interval object was stopped.
     *
     * @type {Boolean}
     * @default true
     */
    this.stopped = true;
    /**
     * Interval time (in milliseconds) of the last callback call.
     *
     * @private
     * @type {Number}
     */
    this._then = null;
    /**
     * Bounded function `func`.
     *
     * @private
     * @type {Function}
     */
    this._callback = function () {
      return _this.__callback();
    };
  }

  /**
   * Start loop.
   *
   * @returns {Interval}
   */


  _createClass(Interval, [{
    key: 'start',
    value: function start() {
      if (this.stopped) {
        this._then = Date.now();
        this.stopped = false;
        this.timer = (0, _feature.requestAnimationFrame)(this._callback);
      }

      return this;
    }

    /**
     * Stop looping.
     *
     * @returns {Interval}
     */

  }, {
    key: 'stop',
    value: function stop() {
      if (!this.stopped) {
        this.stopped = true;
        (0, _feature.cancelAnimationFrame)(this.timer);
        this.timer = null;
      }

      return this;
    }

    /**
     * Loop callback, fired on every animation frame.
     *
     * @private
     */

  }, {
    key: '__callback',
    value: function __callback() {
      this.timer = (0, _feature.requestAnimationFrame)(this._callback);

      if (this.delay) {
        var now = Date.now();
        var elapsed = now - this._then;

        if (elapsed > this.delay) {
          this._then = now - elapsed % this.delay;
          this.func();
        }
      } else {
        this.func();
      }
    }
  }]);

  return Interval;
}();

exports.default = Interval;
function parseDelay(delay) {
  if (typeof delay === 'string' && /fps$/.test(delay)) {
    delay = 1000 / parseInt(delay.replace('fps', '') || 0, 10);
  }

  return delay;
}

/***/ }),
/* 380 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

function MultiMap() {
  var map = {
    arrayMap: [],
    weakMap: new WeakMap()
  };

  return {
    get: function get(key) {
      if (canBeAnArrayMapKey(key)) {
        return map.arrayMap[key];
      } else if (canBeAWeakMapKey(key)) {
        return map.weakMap.get(key);
      }
    },
    set: function set(key, value) {
      if (canBeAnArrayMapKey(key)) {
        map.arrayMap[key] = value;
      } else if (canBeAWeakMapKey(key)) {
        map.weakMap.set(key, value);
      } else {
        throw new Error('Invalid key type');
      }
    },
    delete: function _delete(key) {
      if (canBeAnArrayMapKey(key)) {
        delete map.arrayMap[key];
      } else if (canBeAWeakMapKey(key)) {
        map.weakMap.delete(key);
      }
    }
  };

  function canBeAnArrayMapKey(obj) {
    return obj !== null && !isNaNSymbol(obj) && (typeof obj == 'string' || typeof obj == 'number');
  }

  function canBeAWeakMapKey(obj) {
    return obj !== null && ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) == 'object' || typeof obj == 'function');
  }

  function isNaNSymbol(obj) {
    /* eslint-disable no-self-compare */
    return obj !== obj; // NaN === NaN is always false
  }
}

exports.default = MultiMap;

/***/ }),
/* 381 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _src = __webpack_require__(15);

var _unicode = __webpack_require__(20);

var _event = __webpack_require__(12);

var _editors = __webpack_require__(16);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _baseEditor = __webpack_require__(47);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function EditorManager(instance, priv, selection) {
  var _this = this,
      destroyed = false,
      eventManager,
      activeEditor;

  eventManager = new _eventManager2.default(instance);

  function moveSelectionAfterEnter(shiftKey) {
    selection.setSelectedHeaders(false, false, false);
    var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves;

    if (shiftKey) {
      // move selection up
      selection.transformStart(-enterMoves.row, -enterMoves.col);
    } else {
      // move selection down (add a new row if needed)
      selection.transformStart(enterMoves.row, enterMoves.col, true);
    }
  }

  function moveSelectionUp(shiftKey) {
    if (shiftKey) {
      if (selection.selectedHeader.cols) {
        selection.setSelectedHeaders(selection.selectedHeader.rows, false, false);
      }
      selection.transformEnd(-1, 0);
    } else {
      selection.setSelectedHeaders(false, false, false);
      selection.transformStart(-1, 0);
    }
  }

  function moveSelectionDown(shiftKey) {
    if (shiftKey) {
      // expanding selection down with shift
      selection.transformEnd(1, 0);
    } else {
      selection.setSelectedHeaders(false, false, false);
      selection.transformStart(1, 0);
    }
  }

  function moveSelectionRight(shiftKey) {
    if (shiftKey) {
      selection.transformEnd(0, 1);
    } else {
      selection.setSelectedHeaders(false, false, false);
      selection.transformStart(0, 1);
    }
  }

  function moveSelectionLeft(shiftKey) {
    if (shiftKey) {
      if (selection.selectedHeader.rows) {
        selection.setSelectedHeaders(false, selection.selectedHeader.cols, false);
      }
      selection.transformEnd(0, -1);
    } else {
      selection.setSelectedHeaders(false, false, false);
      selection.transformStart(0, -1);
    }
  }

  function onKeyDown(event) {
    var ctrlDown, rangeModifier;

    if (!instance.isListening()) {
      return;
    }
    instance.runHooks('beforeKeyDown', event);

    if (destroyed) {
      return;
    }
    if ((0, _event.isImmediatePropagationStopped)(event)) {
      return;
    }
    priv.lastKeyCode = event.keyCode;

    if (!selection.isSelected()) {
      return;
    }
    // catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
    ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;

    if (activeEditor && !activeEditor.isWaiting()) {
      if (!(0, _unicode.isMetaKey)(event.keyCode) && !(0, _unicode.isCtrlKey)(event.keyCode) && !ctrlDown && !_this.isEditorOpened()) {
        _this.openEditor('', event);

        return;
      }
    }
    rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart;

    switch (event.keyCode) {
      case _unicode.KEY_CODES.A:
        if (!_this.isEditorOpened() && ctrlDown) {
          selection.selectAll();

          event.preventDefault();
          (0, _event.stopPropagation)(event);
        }
        break;

      case _unicode.KEY_CODES.ARROW_UP:
        if (_this.isEditorOpened() && !activeEditor.isWaiting()) {
          _this.closeEditorAndSaveChanges(ctrlDown);
        }
        moveSelectionUp(event.shiftKey);

        event.preventDefault();
        (0, _event.stopPropagation)(event);
        break;

      case _unicode.KEY_CODES.ARROW_DOWN:
        if (_this.isEditorOpened() && !activeEditor.isWaiting()) {
          _this.closeEditorAndSaveChanges(ctrlDown);
        }

        moveSelectionDown(event.shiftKey);

        event.preventDefault();
        (0, _event.stopPropagation)(event);
        break;

      case _unicode.KEY_CODES.ARROW_RIGHT:
        if (_this.isEditorOpened() && !activeEditor.isWaiting()) {
          _this.closeEditorAndSaveChanges(ctrlDown);
        }

        moveSelectionRight(event.shiftKey);

        event.preventDefault();
        (0, _event.stopPropagation)(event);
        break;

      case _unicode.KEY_CODES.ARROW_LEFT:
        if (_this.isEditorOpened() && !activeEditor.isWaiting()) {
          _this.closeEditorAndSaveChanges(ctrlDown);
        }

        moveSelectionLeft(event.shiftKey);

        event.preventDefault();
        (0, _event.stopPropagation)(event);
        break;

      case _unicode.KEY_CODES.TAB:
        selection.setSelectedHeaders(false, false, false);
        var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves;

        if (event.shiftKey) {
          // move selection left
          selection.transformStart(-tabMoves.row, -tabMoves.col);
        } else {
          // move selection right (add a new column if needed)
          selection.transformStart(tabMoves.row, tabMoves.col, true);
        }
        event.preventDefault();
        (0, _event.stopPropagation)(event);
        break;

      case _unicode.KEY_CODES.BACKSPACE:
      case _unicode.KEY_CODES.DELETE:
        selection.empty(event);
        _this.prepareEditor();
        event.preventDefault();
        break;

      case _unicode.KEY_CODES.F2:
        /* F2 */
        _this.openEditor(null, event);

        if (activeEditor) {
          activeEditor.enableFullEditMode();
        }
        event.preventDefault(); // prevent Opera from opening 'Go to Page dialog'
        break;

      case _unicode.KEY_CODES.ENTER:
        /* return/enter */
        if (_this.isEditorOpened()) {

          if (activeEditor && activeEditor.state !== _baseEditor.EditorState.WAITING) {
            _this.closeEditorAndSaveChanges(ctrlDown);
          }
          moveSelectionAfterEnter(event.shiftKey);
        } else if (instance.getSettings().enterBeginsEditing) {
          _this.openEditor(null, event);

          if (activeEditor) {
            activeEditor.enableFullEditMode();
          }
        } else {
          moveSelectionAfterEnter(event.shiftKey);
        }
        event.preventDefault(); // don't add newline to field
        (0, _event.stopImmediatePropagation)(event); // required by HandsontableEditor
        break;

      case _unicode.KEY_CODES.ESCAPE:
        if (_this.isEditorOpened()) {
          _this.closeEditorAndRestoreOriginalValue(ctrlDown);
        }
        event.preventDefault();
        break;

      case _unicode.KEY_CODES.HOME:
        selection.setSelectedHeaders(false, false, false);
        if (event.ctrlKey || event.metaKey) {
          rangeModifier(new _src.CellCoords(0, priv.selRange.from.col));
        } else {
          rangeModifier(new _src.CellCoords(priv.selRange.from.row, 0));
        }
        event.preventDefault(); // don't scroll the window
        (0, _event.stopPropagation)(event);
        break;

      case _unicode.KEY_CODES.END:
        selection.setSelectedHeaders(false, false, false);
        if (event.ctrlKey || event.metaKey) {
          rangeModifier(new _src.CellCoords(instance.countRows() - 1, priv.selRange.from.col));
        } else {
          rangeModifier(new _src.CellCoords(priv.selRange.from.row, instance.countCols() - 1));
        }
        event.preventDefault(); // don't scroll the window
        (0, _event.stopPropagation)(event);
        break;

      case _unicode.KEY_CODES.PAGE_UP:
        selection.setSelectedHeaders(false, false, false);
        selection.transformStart(-instance.countVisibleRows(), 0);
        event.preventDefault(); // don't page up the window
        (0, _event.stopPropagation)(event);
        break;

      case _unicode.KEY_CODES.PAGE_DOWN:
        selection.setSelectedHeaders(false, false, false);
        selection.transformStart(instance.countVisibleRows(), 0);
        event.preventDefault(); // don't page down the window
        (0, _event.stopPropagation)(event);
        break;
      default:
        break;
    }
  }

  function init() {
    instance.addHook('afterDocumentKeyDown', onKeyDown);

    eventManager.addEventListener(document.documentElement, 'keydown', function (event) {
      if (!destroyed) {
        instance.runHooks('afterDocumentKeyDown', event);
      }
    });

    function onDblClick(event, coords, elem) {
      // may be TD or TH
      if (elem.nodeName === 'TD') {
        _this.openEditor(null, event);

        if (activeEditor) {
          activeEditor.enableFullEditMode();
        }
      }
    }
    instance.view.wt.update('onCellDblClick', onDblClick);

    instance.addHook('afterDestroy', function () {
      destroyed = true;
    });
  }

  /**
   * Destroy current editor, if exists.
   *
   * @function destroyEditor
   * @memberof! Handsontable.EditorManager#
   * @param {Boolean} revertOriginal
   */
  this.destroyEditor = function (revertOriginal) {
    this.closeEditor(revertOriginal);
  };

  /**
   * Get active editor.
   *
   * @function getActiveEditor
   * @memberof! Handsontable.EditorManager#
   * @returns {*}
   */
  this.getActiveEditor = function () {
    return activeEditor;
  };

  /**
   * Prepare text input to be displayed at given grid cell.
   *
   * @function prepareEditor
   * @memberof! Handsontable.EditorManager#
   */
  this.prepareEditor = function () {
    var row, col, prop, td, originalValue, cellProperties, editorClass;

    if (activeEditor && activeEditor.isWaiting()) {
      this.closeEditor(false, false, function (dataSaved) {
        if (dataSaved) {
          _this.prepareEditor();
        }
      });

      return;
    }
    row = priv.selRange.highlight.row;
    col = priv.selRange.highlight.col;
    prop = instance.colToProp(col);
    td = instance.getCell(row, col);

    originalValue = instance.getSourceDataAtCell(instance.runHooks('modifyRow', row), col);
    cellProperties = instance.getCellMeta(row, col);
    editorClass = instance.getCellEditor(cellProperties);

    if (editorClass) {
      activeEditor = (0, _editors.getEditorInstance)(editorClass, instance);
      activeEditor.prepare(row, col, prop, td, originalValue, cellProperties);
    } else {
      activeEditor = void 0;
    }
  };

  /**
   * Check is editor is opened/showed.
   *
   * @function isEditorOpened
   * @memberof! Handsontable.EditorManager#
   * @returns {Boolean}
   */
  this.isEditorOpened = function () {
    return activeEditor && activeEditor.isOpened();
  };

  /**
   * Open editor with initial value.
   *
   * @function openEditor
   * @memberof! Handsontable.EditorManager#
   * @param {null|String} newInitialValue new value from which editor will start if handled property it's not the `null`.
   * @param {DOMEvent} event
   */
  this.openEditor = function (newInitialValue, event) {
    if (activeEditor && !activeEditor.cellProperties.readOnly) {
      activeEditor.beginEditing(newInitialValue, event);
    } else if (activeEditor && activeEditor.cellProperties.readOnly) {

      // move the selection after opening the editor with ENTER key
      if (event && event.keyCode === _unicode.KEY_CODES.ENTER) {
        moveSelectionAfterEnter();
      }
    }
  };

  /**
   * Close editor, finish editing cell.
   *
   * @function closeEditor
   * @memberof! Handsontable.EditorManager#
   * @param {Boolean} restoreOriginalValue
   * @param {Boolean} [ctrlDown]
   * @param {Function} [callback]
   */
  this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) {
    if (activeEditor) {
      activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback);
    } else if (callback) {
      callback(false);
    }
  };

  /**
   * Close editor and save changes.
   *
   * @function closeEditorAndSaveChanges
   * @memberof! Handsontable.EditorManager#
   * @param {Boolean} ctrlDown
   */
  this.closeEditorAndSaveChanges = function (ctrlDown) {
    return this.closeEditor(false, ctrlDown);
  };

  /**
   * Close editor and restore original value.
   *
   * @function closeEditorAndRestoreOriginalValue
   * @memberof! Handsontable.EditorManager#
   * @param {Boolean} ctrlDown
   */
  this.closeEditorAndRestoreOriginalValue = function (ctrlDown) {
    return this.closeEditor(true, ctrlDown);
  };

  init();
}

exports.default = EditorManager;

/***/ }),
/* 382 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _element = __webpack_require__(0);

var _browser = __webpack_require__(28);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _event = __webpack_require__(12);

var _src = __webpack_require__(15);

var _src2 = _interopRequireDefault(_src);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Handsontable TableView constructor
 * @param {Object} instance
 */
function TableView(instance) {
  var _this = this;

  var that = this;

  this.eventManager = new _eventManager2.default(instance);
  this.instance = instance;
  this.settings = instance.getSettings();
  this.selectionMouseDown = false;

  var originalStyle = instance.rootElement.getAttribute('style');

  if (originalStyle) {
    instance.rootElement.setAttribute('data-originalstyle', originalStyle); // needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions
  }

  (0, _element.addClass)(instance.rootElement, 'handsontable');

  var table = document.createElement('TABLE');
  (0, _element.addClass)(table, 'htCore');

  if (instance.getSettings().tableClassName) {
    (0, _element.addClass)(table, instance.getSettings().tableClassName);
  }
  this.THEAD = document.createElement('THEAD');
  table.appendChild(this.THEAD);
  this.TBODY = document.createElement('TBODY');
  table.appendChild(this.TBODY);

  instance.table = table;

  instance.container.insertBefore(table, instance.container.firstChild);

  this.eventManager.addEventListener(instance.rootElement, 'mousedown', function (event) {
    this.selectionMouseDown = true;

    if (!that.isTextSelectionAllowed(event.target)) {
      clearTextSelection();
      event.preventDefault();
      window.focus(); // make sure that window that contains HOT is active. Important when HOT is in iframe.
    }
  });
  this.eventManager.addEventListener(instance.rootElement, 'mouseup', function (event) {
    this.selectionMouseDown = false;
  });
  this.eventManager.addEventListener(instance.rootElement, 'mousemove', function (event) {
    if (this.selectionMouseDown && !that.isTextSelectionAllowed(event.target)) {
      clearTextSelection();
      event.preventDefault();
    }
  });

  this.eventManager.addEventListener(document.documentElement, 'keyup', function (event) {
    if (instance.selection.isInProgress() && !event.shiftKey) {
      instance.selection.finish();
    }
  });

  var isMouseDown;
  this.isMouseDown = function () {
    return isMouseDown;
  };

  this.eventManager.addEventListener(document.documentElement, 'mouseup', function (event) {
    if (instance.selection.isInProgress() && (0, _event.isLeftClick)(event)) {
      // is left mouse button
      instance.selection.finish();
    }

    isMouseDown = false;

    if ((0, _element.isOutsideInput)(document.activeElement) || !instance.selection.isSelected() && !(0, _event.isRightClick)(event)) {
      instance.unlisten();
    }
  });

  this.eventManager.addEventListener(document.documentElement, 'mousedown', function (event) {
    var originalTarget = event.target;
    var next = event.target;
    var eventX = event.x || event.clientX;
    var eventY = event.y || event.clientY;

    if (isMouseDown || !instance.rootElement) {
      return; // it must have been started in a cell
    }

    // immediate click on "holder" means click on the right side of vertical scrollbar
    if (next === instance.view.wt.wtTable.holder) {
      var scrollbarWidth = (0, _element.getScrollbarWidth)();

      if (document.elementFromPoint(eventX + scrollbarWidth, eventY) !== instance.view.wt.wtTable.holder || document.elementFromPoint(eventX, eventY + scrollbarWidth) !== instance.view.wt.wtTable.holder) {
        return;
      }
    } else {
      while (next !== document.documentElement) {
        if (next === null) {
          if (event.isTargetWebComponent) {
            break;
          }
          // click on something that was a row but now is detached (possibly because your click triggered a rerender)
          return;
        }
        if (next === instance.rootElement) {
          // click inside container
          return;
        }
        next = next.parentNode;
      }
    }

    // function did not return until here, we have an outside click!

    var outsideClickDeselects = typeof that.settings.outsideClickDeselects === 'function' ? that.settings.outsideClickDeselects(originalTarget) : that.settings.outsideClickDeselects;

    if (outsideClickDeselects) {
      instance.deselectCell();
    } else {
      instance.destroyEditor();
    }
  });

  this.eventManager.addEventListener(table, 'selectstart', function (event) {
    if (that.settings.fragmentSelection || (0, _element.isInput)(event.target)) {
      return;
    }
    // https://github.com/handsontable/handsontable/issues/160
    // Prevent text from being selected when performing drag down.
    event.preventDefault();
  });

  var clearTextSelection = function clearTextSelection() {
    // http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
    if (window.getSelection) {
      if (window.getSelection().empty) {
        // Chrome
        window.getSelection().empty();
      } else if (window.getSelection().removeAllRanges) {
        // Firefox
        window.getSelection().removeAllRanges();
      }
    } else if (document.selection) {
      // IE?
      document.selection.empty();
    }
  };

  var selections = [new _src.Selection({
    className: 'current',
    border: {
      width: 2,
      color: '#5292F7',
      // style: 'solid', // not used
      cornerVisible: function cornerVisible() {
        return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple();
      },
      multipleSelectionHandlesVisible: function multipleSelectionHandlesVisible() {
        return !that.isCellEdited() && !instance.selection.isMultiple();
      }
    }
  }), new _src.Selection({
    className: 'area',
    border: {
      width: 1,
      color: '#89AFF9',
      // style: 'solid', // not used
      cornerVisible: function cornerVisible() {
        return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple();
      },
      multipleSelectionHandlesVisible: function multipleSelectionHandlesVisible() {
        return !that.isCellEdited() && instance.selection.isMultiple();
      }
    }
  }), new _src.Selection({
    className: 'highlight',
    highlightHeaderClassName: that.settings.currentHeaderClassName,
    highlightRowClassName: that.settings.currentRowClassName,
    highlightColumnClassName: that.settings.currentColClassName
  }), new _src.Selection({
    className: 'fill',
    border: {
      width: 1,
      color: 'red'
      // style: 'solid' // not used
    }
  })];
  selections.current = selections[0];
  selections.area = selections[1];
  selections.highlight = selections[2];
  selections.fill = selections[3];

  var walkontableConfig = {
    debug: function debug() {
      return that.settings.debug;
    },
    externalRowCalculator: this.instance.getPlugin('autoRowSize') && this.instance.getPlugin('autoRowSize').isEnabled(),
    table: table,
    preventOverflow: function preventOverflow() {
      return _this.settings.preventOverflow;
    },
    stretchH: function stretchH() {
      return that.settings.stretchH;
    },
    data: instance.getDataAtCell,
    totalRows: function totalRows() {
      return instance.countRows();
    },
    totalColumns: function totalColumns() {
      return instance.countCols();
    },
    fixedColumnsLeft: function fixedColumnsLeft() {
      return that.settings.fixedColumnsLeft;
    },
    fixedRowsTop: function fixedRowsTop() {
      return that.settings.fixedRowsTop;
    },
    fixedRowsBottom: function fixedRowsBottom() {
      return that.settings.fixedRowsBottom;
    },
    minSpareRows: function minSpareRows() {
      return that.settings.minSpareRows;
    },
    renderAllRows: that.settings.renderAllRows,
    rowHeaders: function rowHeaders() {
      var headerRenderers = [];

      if (instance.hasRowHeaders()) {
        headerRenderers.push(function (row, TH) {
          that.appendRowHeader(row, TH);
        });
      }
      instance.runHooks('afterGetRowHeaderRenderers', headerRenderers);

      return headerRenderers;
    },
    columnHeaders: function columnHeaders() {
      var headerRenderers = [];

      if (instance.hasColHeaders()) {
        headerRenderers.push(function (column, TH) {
          that.appendColHeader(column, TH);
        });
      }
      instance.runHooks('afterGetColumnHeaderRenderers', headerRenderers);

      return headerRenderers;
    },
    columnWidth: instance.getColWidth,
    rowHeight: instance.getRowHeight,
    cellRenderer: function cellRenderer(row, col, TD) {
      var cellProperties = that.instance.getCellMeta(row, col);
      var prop = that.instance.colToProp(col);
      var value = that.instance.getDataAtRowProp(row, prop);

      if (that.instance.hasHook('beforeValueRender')) {
        value = that.instance.runHooks('beforeValueRender', value);
      }

      that.instance.runHooks('beforeRenderer', TD, row, col, prop, value, cellProperties);
      that.instance.getCellRenderer(cellProperties)(that.instance, TD, row, col, prop, value, cellProperties);
      that.instance.runHooks('afterRenderer', TD, row, col, prop, value, cellProperties);
    },
    selections: selections,
    hideBorderOnMouseDownOver: function hideBorderOnMouseDownOver() {
      return that.settings.fragmentSelection;
    },
    onCellMouseDown: function onCellMouseDown(event, coords, TD, wt) {
      var blockCalculations = {
        row: false,
        column: false,
        cells: false
      };

      instance.listen();

      that.activeWt = wt;
      isMouseDown = true;

      instance.runHooks('beforeOnCellMouseDown', event, coords, TD, blockCalculations);

      if ((0, _event.isImmediatePropagationStopped)(event)) {
        return;
      }

      var actualSelection = instance.getSelectedRange();
      var selection = instance.selection;
      var selectedHeader = selection.selectedHeader;

      if (event.shiftKey && actualSelection) {
        if (coords.row >= 0 && coords.col >= 0 && !blockCalculations.cells) {
          selection.setSelectedHeaders(false, false);
          selection.setRangeEnd(coords);
        } else if ((selectedHeader.cols || selectedHeader.rows) && coords.row >= 0 && coords.col >= 0 && !blockCalculations.cells) {
          selection.setSelectedHeaders(false, false);
          selection.setRangeEnd(new _src.CellCoords(coords.row, coords.col));
        } else if (selectedHeader.cols && coords.row < 0 && !blockCalculations.column) {
          selection.setRangeEnd(new _src.CellCoords(actualSelection.to.row, coords.col));
        } else if (selectedHeader.rows && coords.col < 0 && !blockCalculations.row) {
          selection.setRangeEnd(new _src.CellCoords(coords.row, actualSelection.to.col));
        } else if ((!selectedHeader.cols && !selectedHeader.rows && coords.col < 0 || selectedHeader.cols && coords.col < 0) && !blockCalculations.row) {
          selection.setSelectedHeaders(true, false);
          selection.setRangeStartOnly(new _src.CellCoords(actualSelection.from.row, 0));
          selection.setRangeEnd(new _src.CellCoords(coords.row, instance.countCols() - 1));
        } else if ((!selectedHeader.cols && !selectedHeader.rows && coords.row < 0 || selectedHeader.rows && coords.row < 0) && !blockCalculations.column) {
          selection.setSelectedHeaders(false, true);
          selection.setRangeStartOnly(new _src.CellCoords(0, actualSelection.from.col));
          selection.setRangeEnd(new _src.CellCoords(instance.countRows() - 1, coords.col));
        }
      } else {
        var doNewSelection = true;

        if (actualSelection) {
          var from = actualSelection.from,
              to = actualSelection.to;

          var coordsNotInSelection = !selection.inInSelection(coords);

          if (coords.row < 0 && selectedHeader.cols) {
            var start = Math.min(from.col, to.col);
            var end = Math.max(from.col, to.col);

            doNewSelection = coords.col < start || coords.col > end;
          } else if (coords.col < 0 && selectedHeader.rows) {
            var _start = Math.min(from.row, to.row);
            var _end = Math.max(from.row, to.row);

            doNewSelection = coords.row < _start || coords.row > _end;
          } else {
            doNewSelection = coordsNotInSelection;
          }
        }

        var rightClick = (0, _event.isRightClick)(event);
        var leftClick = (0, _event.isLeftClick)(event) || event.type === 'touchstart';

        // clicked row header and when some column was selected
        if (coords.row < 0 && coords.col >= 0 && !blockCalculations.column) {
          selection.setSelectedHeaders(false, true);

          if (leftClick || rightClick && doNewSelection) {
            selection.setRangeStartOnly(new _src.CellCoords(0, coords.col));
            selection.setRangeEnd(new _src.CellCoords(Math.max(instance.countRows() - 1, 0), coords.col), false);
          }

          // clicked column header and when some row was selected
        } else if (coords.col < 0 && coords.row >= 0 && !blockCalculations.row) {
          selection.setSelectedHeaders(true, false);

          if (leftClick || rightClick && doNewSelection) {
            selection.setRangeStartOnly(new _src.CellCoords(coords.row, 0));
            selection.setRangeEnd(new _src.CellCoords(coords.row, Math.max(instance.countCols() - 1, 0)), false);
          }
        } else if (coords.col >= 0 && coords.row >= 0 && !blockCalculations.cells) {
          if (leftClick || rightClick && doNewSelection) {
            selection.setSelectedHeaders(false, false);
            selection.setRangeStart(coords);
          }
        } else if (coords.col < 0 && coords.row < 0) {
          coords.row = 0;
          coords.col = 0;

          selection.setSelectedHeaders(false, false, true);
          selection.setRangeStart(coords);
        }
      }

      instance.runHooks('afterOnCellMouseDown', event, coords, TD);
      that.activeWt = that.wt;
    },
    onCellMouseOut: function onCellMouseOut(event, coords, TD, wt) {
      that.activeWt = wt;
      instance.runHooks('beforeOnCellMouseOut', event, coords, TD);

      if ((0, _event.isImmediatePropagationStopped)(event)) {
        return;
      }

      instance.runHooks('afterOnCellMouseOut', event, coords, TD);
      that.activeWt = that.wt;
    },
    onCellMouseOver: function onCellMouseOver(event, coords, TD, wt) {
      var blockCalculations = {
        row: false,
        column: false,
        cell: false
      };

      that.activeWt = wt;
      instance.runHooks('beforeOnCellMouseOver', event, coords, TD, blockCalculations);

      if ((0, _event.isImmediatePropagationStopped)(event)) {
        return;
      }

      if (event.button === 0 && isMouseDown) {
        if (coords.row >= 0 && coords.col >= 0) {
          // is not a header
          if (instance.selection.selectedHeader.cols && !blockCalculations.column) {
            instance.selection.setRangeEnd(new _src.CellCoords(instance.countRows() - 1, coords.col), false);
          } else if (instance.selection.selectedHeader.rows && !blockCalculations.row) {
            instance.selection.setRangeEnd(new _src.CellCoords(coords.row, instance.countCols() - 1), false);
          } else if (!blockCalculations.cell) {
            instance.selection.setRangeEnd(coords);
          }
        } else {
          /* eslint-disable no-lonely-if */
          if (instance.selection.selectedHeader.cols && !blockCalculations.column) {
            instance.selection.setRangeEnd(new _src.CellCoords(instance.countRows() - 1, coords.col), false);
          } else if (instance.selection.selectedHeader.rows && !blockCalculations.row) {
            instance.selection.setRangeEnd(new _src.CellCoords(coords.row, instance.countCols() - 1), false);
          } else if (!blockCalculations.cell) {
            instance.selection.setRangeEnd(coords);
          }
        }
      }

      instance.runHooks('afterOnCellMouseOver', event, coords, TD);
      that.activeWt = that.wt;
    },
    onCellMouseUp: function onCellMouseUp(event, coords, TD, wt) {
      that.activeWt = wt;
      instance.runHooks('beforeOnCellMouseUp', event, coords, TD);

      instance.runHooks('afterOnCellMouseUp', event, coords, TD);
      that.activeWt = that.wt;
    },
    onCellCornerMouseDown: function onCellCornerMouseDown(event) {
      event.preventDefault();
      instance.runHooks('afterOnCellCornerMouseDown', event);
    },
    onCellCornerDblClick: function onCellCornerDblClick(event) {
      event.preventDefault();
      instance.runHooks('afterOnCellCornerDblClick', event);
    },
    beforeDraw: function beforeDraw(force, skipRender) {
      that.beforeRender(force, skipRender);
    },
    onDraw: function onDraw(force) {
      that.onDraw(force);
    },
    onScrollVertically: function onScrollVertically() {
      instance.runHooks('afterScrollVertically');
    },
    onScrollHorizontally: function onScrollHorizontally() {
      instance.runHooks('afterScrollHorizontally');
    },
    onBeforeDrawBorders: function onBeforeDrawBorders(corners, borderClassName) {
      instance.runHooks('beforeDrawBorders', corners, borderClassName);
    },
    onBeforeTouchScroll: function onBeforeTouchScroll() {
      instance.runHooks('beforeTouchScroll');
    },
    onAfterMomentumScroll: function onAfterMomentumScroll() {
      instance.runHooks('afterMomentumScroll');
    },
    onBeforeStretchingColumnWidth: function onBeforeStretchingColumnWidth(stretchedWidth, column) {
      return instance.runHooks('beforeStretchingColumnWidth', stretchedWidth, column);
    },
    onModifyRowHeaderWidth: function onModifyRowHeaderWidth(rowHeaderWidth) {
      return instance.runHooks('modifyRowHeaderWidth', rowHeaderWidth);
    },
    viewportRowCalculatorOverride: function viewportRowCalculatorOverride(calc) {
      var rows = instance.countRows();
      var viewportOffset = that.settings.viewportRowRenderingOffset;

      if (viewportOffset === 'auto' && that.settings.fixedRowsTop) {
        viewportOffset = 10;
      }
      if (typeof viewportOffset === 'number') {
        calc.startRow = Math.max(calc.startRow - viewportOffset, 0);
        calc.endRow = Math.min(calc.endRow + viewportOffset, rows - 1);
      }
      if (viewportOffset === 'auto') {
        var center = calc.startRow + calc.endRow - calc.startRow;
        var offset = Math.ceil(center / rows * 12);

        calc.startRow = Math.max(calc.startRow - offset, 0);
        calc.endRow = Math.min(calc.endRow + offset, rows - 1);
      }
      instance.runHooks('afterViewportRowCalculatorOverride', calc);
    },
    viewportColumnCalculatorOverride: function viewportColumnCalculatorOverride(calc) {
      var cols = instance.countCols();
      var viewportOffset = that.settings.viewportColumnRenderingOffset;

      if (viewportOffset === 'auto' && that.settings.fixedColumnsLeft) {
        viewportOffset = 10;
      }
      if (typeof viewportOffset === 'number') {
        calc.startColumn = Math.max(calc.startColumn - viewportOffset, 0);
        calc.endColumn = Math.min(calc.endColumn + viewportOffset, cols - 1);
      }
      if (viewportOffset === 'auto') {
        var center = calc.startColumn + calc.endColumn - calc.startColumn;
        var offset = Math.ceil(center / cols * 12);

        calc.startRow = Math.max(calc.startColumn - offset, 0);
        calc.endColumn = Math.min(calc.endColumn + offset, cols - 1);
      }
      instance.runHooks('afterViewportColumnCalculatorOverride', calc);
    },
    rowHeaderWidth: function rowHeaderWidth() {
      return that.settings.rowHeaderWidth;
    },
    columnHeaderHeight: function columnHeaderHeight() {
      var columnHeaderHeight = instance.runHooks('modifyColumnHeaderHeight');
      return that.settings.columnHeaderHeight || columnHeaderHeight;
    }
  };

  instance.runHooks('beforeInitWalkontable', walkontableConfig);

  this.wt = new _src2.default(walkontableConfig);
  this.activeWt = this.wt;

  if (!(0, _browser.isChrome)() && !(0, _browser.isSafari)()) {
    this.eventManager.addEventListener(instance.rootElement, 'wheel', function (event) {
      event.preventDefault();

      var lineHeight = parseInt((0, _element.getComputedStyle)(document.body)['font-size'], 10);
      var holder = that.wt.wtOverlays.scrollableElement;

      var deltaY = event.wheelDeltaY || event.deltaY;
      var deltaX = event.wheelDeltaX || event.deltaX;

      switch (event.deltaMode) {
        case 0:
          holder.scrollLeft += deltaX;
          holder.scrollTop += deltaY;
          break;

        case 1:
          holder.scrollLeft += deltaX * lineHeight;
          holder.scrollTop += deltaY * lineHeight;
          break;

        default:
          break;
      }
    });
  }

  this.eventManager.addEventListener(that.wt.wtTable.spreader, 'mousedown', function (event) {
    // right mouse button exactly on spreader means right click on the right hand side of vertical scrollbar
    if (event.target === that.wt.wtTable.spreader && event.which === 3) {
      (0, _event.stopPropagation)(event);
    }
  });

  this.eventManager.addEventListener(that.wt.wtTable.spreader, 'contextmenu', function (event) {
    // right mouse button exactly on spreader means right click on the right hand side of vertical scrollbar
    if (event.target === that.wt.wtTable.spreader && event.which === 3) {
      (0, _event.stopPropagation)(event);
    }
  });

  this.eventManager.addEventListener(document.documentElement, 'click', function () {
    if (that.settings.observeDOMVisibility) {
      if (that.wt.drawInterrupted) {
        that.instance.forceFullRender = true;
        that.render();
      }
    }
  });
}

TableView.prototype.isTextSelectionAllowed = function (el) {
  if ((0, _element.isInput)(el)) {
    return true;
  }
  var isChildOfTableBody = (0, _element.isChildOf)(el, this.instance.view.wt.wtTable.spreader);

  if (this.settings.fragmentSelection === true && isChildOfTableBody) {
    return true;
  }
  if (this.settings.fragmentSelection === 'cell' && this.isSelectedOnlyCell() && isChildOfTableBody) {
    return true;
  }
  if (!this.settings.fragmentSelection && this.isCellEdited() && this.isSelectedOnlyCell()) {
    return true;
  }

  return false;
};

/**
 * Check if selected only one cell.
 *
 * @returns {Boolean}
 */
TableView.prototype.isSelectedOnlyCell = function () {
  var _ref = this.instance.getSelected() || [],
      _ref2 = _slicedToArray(_ref, 4),
      row = _ref2[0],
      col = _ref2[1],
      rowEnd = _ref2[2],
      colEnd = _ref2[3];

  return row !== void 0 && row === rowEnd && col === colEnd;
};

TableView.prototype.isCellEdited = function () {
  var activeEditor = this.instance.getActiveEditor();

  return activeEditor && activeEditor.isOpened();
};

TableView.prototype.beforeRender = function (force, skipRender) {
  if (force) {
    // this.instance.forceFullRender = did Handsontable request full render?
    this.instance.runHooks('beforeRender', this.instance.forceFullRender, skipRender);
  }
};

TableView.prototype.onDraw = function (force) {
  if (force) {
    // this.instance.forceFullRender = did Handsontable request full render?
    this.instance.runHooks('afterRender', this.instance.forceFullRender);
  }
};

TableView.prototype.render = function () {
  this.wt.draw(!this.instance.forceFullRender);
  this.instance.forceFullRender = false;
  this.instance.renderCall = false;
};

/**
 * Returns td object given coordinates
 *
 * @param {CellCoords} coords
 * @param {Boolean} topmost
 */
TableView.prototype.getCellAtCoords = function (coords, topmost) {
  var td = this.wt.getCell(coords, topmost);

  if (td < 0) {
    // there was an exit code (cell is out of bounds)
    return null;
  }

  return td;
};

/**
 * Scroll viewport to selection.
 *
 * @param {CellCoords} coords
 */
TableView.prototype.scrollViewport = function (coords) {
  this.wt.scrollViewport(coords);
};

/**
 * Append row header to a TH element
 * @param row
 * @param TH
 */
TableView.prototype.appendRowHeader = function (row, TH) {
  if (TH.firstChild) {
    var container = TH.firstChild;

    if (!(0, _element.hasClass)(container, 'relative')) {
      (0, _element.empty)(TH);
      this.appendRowHeader(row, TH);

      return;
    }
    this.updateCellHeader(container.querySelector('.rowHeader'), row, this.instance.getRowHeader);
  } else {
    var div = document.createElement('div');
    var span = document.createElement('span');

    div.className = 'relative';
    span.className = 'rowHeader';
    this.updateCellHeader(span, row, this.instance.getRowHeader);

    div.appendChild(span);
    TH.appendChild(div);
  }

  this.instance.runHooks('afterGetRowHeader', row, TH);
};

/**
 * Append column header to a TH element
 * @param col
 * @param TH
 */
TableView.prototype.appendColHeader = function (col, TH) {
  if (TH.firstChild) {
    var container = TH.firstChild;

    if ((0, _element.hasClass)(container, 'relative')) {
      this.updateCellHeader(container.querySelector('.colHeader'), col, this.instance.getColHeader);
    } else {
      (0, _element.empty)(TH);
      this.appendColHeader(col, TH);
    }
  } else {
    var div = document.createElement('div');
    var span = document.createElement('span');

    div.className = 'relative';
    span.className = 'colHeader';
    this.updateCellHeader(span, col, this.instance.getColHeader);

    div.appendChild(span);
    TH.appendChild(div);
  }

  this.instance.runHooks('afterGetColHeader', col, TH);
};

/**
 * Update header cell content
 *
 * @since 0.15.0-beta4
 * @param {HTMLElement} element Element to update
 * @param {Number} index Row index or column index
 * @param {Function} content Function which should be returns content for this cell
 */
TableView.prototype.updateCellHeader = function (element, index, content) {
  var renderedIndex = index;
  var parentOverlay = this.wt.wtOverlays.getParentOverlay(element) || this.wt;

  // prevent wrong calculations from SampleGenerator
  if (element.parentNode) {
    if ((0, _element.hasClass)(element, 'colHeader')) {
      renderedIndex = parentOverlay.wtTable.columnFilter.sourceToRendered(index);
    } else if ((0, _element.hasClass)(element, 'rowHeader')) {
      renderedIndex = parentOverlay.wtTable.rowFilter.sourceToRendered(index);
    }
  }

  if (renderedIndex > -1) {
    (0, _element.fastInnerHTML)(element, content(index));
  } else {
    // workaround for https://github.com/handsontable/handsontable/issues/1946
    (0, _element.fastInnerText)(element, String.fromCharCode(160));
    (0, _element.addClass)(element, 'cornerHeader');
  }
};

/**
 * Given a element's left position relative to the viewport, returns maximum element width until the right
 * edge of the viewport (before scrollbar)
 *
 * @param {Number} leftOffset
 * @return {Number}
 */
TableView.prototype.maximumVisibleElementWidth = function (leftOffset) {
  var workspaceWidth = this.wt.wtViewport.getWorkspaceWidth();
  var maxWidth = workspaceWidth - leftOffset;
  return maxWidth > 0 ? maxWidth : 0;
};

/**
 * Given a element's top position relative to the viewport, returns maximum element height until the bottom
 * edge of the viewport (before scrollbar)
 *
 * @param {Number} topOffset
 * @return {Number}
 */
TableView.prototype.maximumVisibleElementHeight = function (topOffset) {
  var workspaceHeight = this.wt.wtViewport.getWorkspaceHeight();
  var maxHeight = workspaceHeight - topOffset;
  return maxHeight > 0 ? maxHeight : 0;
};

TableView.prototype.mainViewIsActive = function () {
  return this.wt === this.activeWt;
};

TableView.prototype.destroy = function () {
  this.wt.destroy();
  this.eventManager.destroy();
};

exports.default = TableView;

/***/ }),
/* 383 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _object = __webpack_require__(1);

var _array = __webpack_require__(2);

var _number = __webpack_require__(6);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class DataSource
 * @private
 */
var DataSource = function () {
  function DataSource(hotInstance) {
    var dataSource = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

    _classCallCheck(this, DataSource);

    /**
     * Instance of Handsontable.
     *
     * @type {Handsontable}
     */
    this.hot = hotInstance;
    /**
     * Data source
     *
     * @type {Array}
     */
    this.data = dataSource;
    /**
     * Type of data source.
     *
     * @type {String}
     * @default 'array'
     */
    this.dataType = 'array';

    this.colToProp = function () {};
    this.propToCol = function () {};
  }

  /**
   * Get all data.
   *
   * @param {Boolean} [toArray=false] If `true` return source data as an array of arrays even when source data was provided
   *                                  in another format.
   * @returns {Array}
   */


  _createClass(DataSource, [{
    key: 'getData',
    value: function getData() {
      var toArray = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var result = this.data;

      if (toArray) {
        result = this.getByRange({ row: 0, col: 0 }, { row: Math.max(this.countRows() - 1, 0), col: Math.max(this.countColumns() - 1, 0) }, true);
      }

      return result;
    }

    /**
     * Set new data source.
     *
     * @param data {Array}
     */

  }, {
    key: 'setData',
    value: function setData(data) {
      this.data = data;
    }

    /**
     * Returns array of column values from the data source. `column` is the index of the row in the data source.
     *
     * @param {Number} column Visual column index.
     * @returns {Array}
     */

  }, {
    key: 'getAtColumn',
    value: function getAtColumn(column) {
      var _this = this;

      var result = [];

      (0, _array.arrayEach)(this.data, function (row) {
        var property = _this.colToProp(column);

        if (typeof property === 'string') {
          row = (0, _object.getProperty)(row, property);
        } else {
          row = row[property];
        }
        result.push(row);
      });

      return result;
    }

    /**
     * Returns a single row of the data (array or object, depending on what you have). `row` is the index of the row in the data source.
     *
     * @param {Number} row Physical row index.
     * @returns {Array|Object}
     */

  }, {
    key: 'getAtRow',
    value: function getAtRow(row) {
      return this.data[row];
    }

    /**
     * Returns a single value from the data.
     *
     * @param {Number} row Physical row index.
     * @param {Number} column Visual column index.
     * @returns {*}
     */

  }, {
    key: 'getAtCell',
    value: function getAtCell(row, column) {
      var result = null;

      var modifyRowData = this.hot.runHooks('modifyRowData', row);

      var dataRow = isNaN(modifyRowData) ? modifyRowData : this.data[row];

      if (dataRow) {
        var prop = this.colToProp(column);

        if (typeof prop === 'string') {
          result = (0, _object.getProperty)(dataRow, prop);
        } else if (typeof prop === 'function') {
          result = prop(this.data.slice(row, row + 1)[0]);
        } else {
          result = dataRow[prop];
        }
      }

      return result;
    }

    /**
     * Returns source data by passed range.
     *
     * @param {Object} start Object with physical `row` and `col` keys (or visual column index, if data type is an array of objects).
     * @param {Object} end Object with physical `row` and `col` keys (or visual column index, if data type is an array of objects).
     * @param {Boolean} [toArray=false] If `true` return source data as an array of arrays even when source data was provided
     *                                  in another format.
     * @returns {Array}
     */

  }, {
    key: 'getByRange',
    value: function getByRange(start, end) {
      var _this2 = this;

      var toArray = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

      var startRow = Math.min(start.row, end.row);
      var startCol = Math.min(start.col, end.col);
      var endRow = Math.max(start.row, end.row);
      var endCol = Math.max(start.col, end.col);
      var result = [];

      (0, _number.rangeEach)(startRow, endRow, function (currentRow) {
        var row = _this2.getAtRow(currentRow);
        var newRow = void 0;

        if (_this2.dataType === 'array') {
          newRow = row.slice(startCol, endCol + 1);
        } else if (_this2.dataType === 'object') {
          newRow = toArray ? [] : {};

          (0, _number.rangeEach)(startCol, endCol, function (column) {
            var prop = _this2.colToProp(column);

            if (toArray) {
              newRow.push(row[prop]);
            } else {
              newRow[prop] = row[prop];
            }
          });
        }

        result.push(newRow);
      });

      return result;
    }

    /**
     * Count number of rows.
     *
     * @returns {Number}
     */

  }, {
    key: 'countRows',
    value: function countRows() {
      return Array.isArray(this.data) ? this.data.length : 0;
    }

    /**
     * Count number of columns.
     *
     * @returns {Number}
     */

  }, {
    key: 'countColumns',
    value: function countColumns() {
      var result = 0;

      if (Array.isArray(this.data)) {
        if (this.dataType === 'array') {
          result = this.data[0].length;
        } else if (this.dataType === 'object') {
          result = Object.keys(this.data[0]).length;
        }
      }

      return result;
    }

    /**
     * Destroy instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.data = null;
      this.hot = null;
    }
  }]);

  return DataSource;
}();

exports.default = DataSource;

/***/ }),
/* 384 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _dictionary;

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /**
                                                                                                                                                                                                                   * @preserve
                                                                                                                                                                                                                   * Authors: Handsoncode
                                                                                                                                                                                                                   * Last updated: Nov 15, 2017
                                                                                                                                                                                                                   *
                                                                                                                                                                                                                   * Description: Definition file for English - United States language-country.
                                                                                                                                                                                                                   */


var dictionary = (_dictionary = {
  languageCode: 'en-US'
}, _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ROW_ABOVE, 'Insert row above'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ROW_BELOW, 'Insert row below'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_INSERT_LEFT, 'Insert column left'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_INSERT_RIGHT, 'Insert column right'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_REMOVE_ROW, ['Remove row', 'Remove rows']), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_REMOVE_COLUMN, ['Remove column', 'Remove columns']), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_UNDO, 'Undo'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_REDO, 'Redo'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_READ_ONLY, 'Read only'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_CLEAR_COLUMN, 'Clear column'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ALIGNMENT, 'Alignment'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ALIGNMENT_LEFT, 'Left'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ALIGNMENT_CENTER, 'Center'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT, 'Right'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY, 'Justify'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ALIGNMENT_TOP, 'Top'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE, 'Middle'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM, 'Bottom'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_FREEZE_COLUMN, 'Freeze column'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_UNFREEZE_COLUMN, 'Unfreeze column'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_BORDERS, 'Borders'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_BORDERS_TOP, 'Top'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_BORDERS_RIGHT, 'Right'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_BORDERS_BOTTOM, 'Bottom'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_BORDERS_LEFT, 'Left'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_REMOVE_BORDERS, 'Remove border(s)'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_ADD_COMMENT, 'Add comment'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_EDIT_COMMENT, 'Edit comment'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_REMOVE_COMMENT, 'Delete comment'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_READ_ONLY_COMMENT, 'Read-only comment'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_MERGE_CELLS, 'Merge cells'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_UNMERGE_CELLS, 'Unmerge cells'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_COPY, 'Copy'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_CUT, 'Cut'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD, 'Insert child row'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD, 'Detach from parent'), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_HIDE_COLUMN, ['Hide column', 'Hide columns']), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_SHOW_COLUMN, ['Show column', 'Show columns']), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_HIDE_ROW, ['Hide row', 'Hide rows']), _defineProperty(_dictionary, C.CONTEXTMENU_ITEMS_SHOW_ROW, ['Show row', 'Show rows']), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_NONE, 'None'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_EMPTY, 'Is empty'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_NOT_EMPTY, 'Is not empty'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_EQUAL, 'Is equal to'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_NOT_EQUAL, 'Is not equal to'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_BEGINS_WITH, 'Begins with'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_ENDS_WITH, 'Ends with'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_CONTAINS, 'Contains'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_NOT_CONTAIN, 'Does not contain'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_GREATER_THAN, 'Greater than'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL, 'Greater than or equal to'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_LESS_THAN, 'Less than'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL, 'Less than or equal to'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_BETWEEN, 'Is between'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_NOT_BETWEEN, 'Is not between'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_AFTER, 'After'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_BEFORE, 'Before'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_TODAY, 'Today'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_TOMORROW, 'Tomorrow'), _defineProperty(_dictionary, C.FILTERS_CONDITIONS_YESTERDAY, 'Yesterday'), _defineProperty(_dictionary, C.FILTERS_VALUES_BLANK_CELLS, 'Blank cells'), _defineProperty(_dictionary, C.FILTERS_DIVS_FILTER_BY_CONDITION, 'Filter by condition'), _defineProperty(_dictionary, C.FILTERS_DIVS_FILTER_BY_VALUE, 'Filter by value'), _defineProperty(_dictionary, C.FILTERS_LABELS_CONJUNCTION, 'And'), _defineProperty(_dictionary, C.FILTERS_LABELS_DISJUNCTION, 'Or'), _defineProperty(_dictionary, C.FILTERS_BUTTONS_SELECT_ALL, 'Select all'), _defineProperty(_dictionary, C.FILTERS_BUTTONS_CLEAR, 'Clear'), _defineProperty(_dictionary, C.FILTERS_BUTTONS_OK, 'OK'), _defineProperty(_dictionary, C.FILTERS_BUTTONS_CANCEL, 'Cancel'), _defineProperty(_dictionary, C.FILTERS_BUTTONS_PLACEHOLDER_SEARCH, 'Search'), _defineProperty(_dictionary, C.FILTERS_BUTTONS_PLACEHOLDER_VALUE, 'Value'), _defineProperty(_dictionary, C.FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE, 'Second value'), _dictionary);

exports.default = dictionary;

/***/ }),
/* 385 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.getPhraseFormatters = exports.registerPhraseFormatter = undefined;
exports.register = register;
exports.getAll = getAll;

var _staticRegister2 = __webpack_require__(46);

var _staticRegister3 = _interopRequireDefault(_staticRegister2);

var _pluralize = __webpack_require__(386);

var _pluralize2 = _interopRequireDefault(_pluralize);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _staticRegister = (0, _staticRegister3.default)('phraseFormatters'),
    registerGloballyPhraseFormatter = _staticRegister.register,
    getGlobalPhraseFormatters = _staticRegister.getValues;

/**
 * Register phrase formatter.
 *
 * @param {String} name Name of formatter.
 * @param {Function} formatterFn Function which will be applied on phrase propositions. It will transform them if it's possible.
 */


function register(name, formatterFn) {
  registerGloballyPhraseFormatter(name, formatterFn);
}

/**
 * Get all registered previously formatters.
 *
 * @returns {Array}
 */
function getAll() {
  return getGlobalPhraseFormatters();
}

exports.registerPhraseFormatter = register;
exports.getPhraseFormatters = getAll;


register('pluralize', _pluralize2.default);

/***/ }),
/* 386 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = pluralize;
/**
 * Try to choose plural form from available phrase propositions.
 *
 * @param {Array} phrasePropositions List of phrases propositions.
 * @param {number} pluralForm Number determining which phrase form should be used.
 *
 * @returns {String|Array} One particular phrase if it's possible, list of unchanged phrase propositions otherwise.
 */
function pluralize(phrasePropositions, pluralForm) {
  var isPluralizable = Array.isArray(phrasePropositions) && Number.isInteger(pluralForm);

  if (isPluralizable) {
    return phrasePropositions[pluralForm];
  }

  return phrasePropositions;
};

/***/ }),
/* 387 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = jQueryWrapper;
function jQueryWrapper(Handsontable) {
  var jQuery = typeof window === 'undefined' ? false : window.jQuery;

  if (!jQuery) {
    return;
  }

  jQuery.fn.handsontable = function (action) {
    var $this = this.first(); // Use only first element from list
    var instance = $this.data('handsontable');

    // Init case
    if (typeof action !== 'string') {
      var userSettings = action || {};

      if (instance) {
        instance.updateSettings(userSettings);
      } else {
        instance = new Handsontable.Core($this[0], userSettings);
        $this.data('handsontable', instance);
        instance.init();
      }

      return $this;
    }

    // Action case
    var args = [];
    var output = void 0;

    if (arguments.length > 1) {
      for (var i = 1, ilen = arguments.length; i < ilen; i++) {
        args.push(arguments[i]);
      }
    }

    if (instance) {
      if (typeof instance[action] !== 'undefined') {
        output = instance[action].apply(instance, args);

        if (action === 'destroy') {
          $this.removeData();
        }
      } else {
        throw new Error('Handsontable do not provide action: ' + action);
      }
    }

    return output;
  };
};

/***/ }),
/* 388 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.Base = exports.UndoRedo = exports.TouchScroll = exports.Search = exports.PersistentState = exports.ObserveChanges = exports.MultipleSelectionHandles = exports.MergeCells = exports.ManualRowResize = exports.ManualRowMove = exports.ManualColumnResize = exports.ManualColumnMove = exports.ManualColumnFreeze = exports.DragToScroll = exports.CustomBorders = exports.CopyPaste = exports.ContextMenu = exports.Comments = exports.ColumnSorting = exports.AutoRowSize = exports.AutoFill = exports.AutoColumnSize = undefined;

var _autoColumnSize = __webpack_require__(389);

var _autoColumnSize2 = _interopRequireDefault(_autoColumnSize);

var _autofill = __webpack_require__(390);

var _autofill2 = _interopRequireDefault(_autofill);

var _autoRowSize = __webpack_require__(392);

var _autoRowSize2 = _interopRequireDefault(_autoRowSize);

var _columnSorting = __webpack_require__(393);

var _columnSorting2 = _interopRequireDefault(_columnSorting);

var _comments = __webpack_require__(396);

var _comments2 = _interopRequireDefault(_comments);

var _contextMenu = __webpack_require__(400);

var _contextMenu2 = _interopRequireDefault(_contextMenu);

var _copyPaste = __webpack_require__(417);

var _copyPaste2 = _interopRequireDefault(_copyPaste);

var _customBorders = __webpack_require__(424);

var _customBorders2 = _interopRequireDefault(_customBorders);

var _dragToScroll = __webpack_require__(425);

var _dragToScroll2 = _interopRequireDefault(_dragToScroll);

var _manualColumnFreeze = __webpack_require__(426);

var _manualColumnFreeze2 = _interopRequireDefault(_manualColumnFreeze);

var _manualColumnMove = __webpack_require__(430);

var _manualColumnMove2 = _interopRequireDefault(_manualColumnMove);

var _manualColumnResize = __webpack_require__(435);

var _manualColumnResize2 = _interopRequireDefault(_manualColumnResize);

var _manualRowMove = __webpack_require__(436);

var _manualRowMove2 = _interopRequireDefault(_manualRowMove);

var _manualRowResize = __webpack_require__(441);

var _manualRowResize2 = _interopRequireDefault(_manualRowResize);

var _mergeCells = __webpack_require__(442);

var _mergeCells2 = _interopRequireDefault(_mergeCells);

var _multipleSelectionHandles = __webpack_require__(443);

var _multipleSelectionHandles2 = _interopRequireDefault(_multipleSelectionHandles);

var _observeChanges = __webpack_require__(444);

var _observeChanges2 = _interopRequireDefault(_observeChanges);

var _persistentState = __webpack_require__(447);

var _persistentState2 = _interopRequireDefault(_persistentState);

var _search = __webpack_require__(448);

var _search2 = _interopRequireDefault(_search);

var _touchScroll = __webpack_require__(449);

var _touchScroll2 = _interopRequireDefault(_touchScroll);

var _undoRedo = __webpack_require__(450);

var _undoRedo2 = _interopRequireDefault(_undoRedo);

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.AutoColumnSize = _autoColumnSize2.default;
exports.AutoFill = _autofill2.default;
exports.AutoRowSize = _autoRowSize2.default;
exports.ColumnSorting = _columnSorting2.default;
exports.Comments = _comments2.default;
exports.ContextMenu = _contextMenu2.default;
exports.CopyPaste = _copyPaste2.default;
exports.CustomBorders = _customBorders2.default;
exports.DragToScroll = _dragToScroll2.default;
exports.ManualColumnFreeze = _manualColumnFreeze2.default;
exports.ManualColumnMove = _manualColumnMove2.default;
exports.ManualColumnResize = _manualColumnResize2.default;
exports.ManualRowMove = _manualRowMove2.default;
exports.ManualRowResize = _manualRowResize2.default;
exports.MergeCells = _mergeCells2.default;
exports.MultipleSelectionHandles = _multipleSelectionHandles2.default;
exports.ObserveChanges = _observeChanges2.default;
exports.PersistentState = _persistentState2.default;
exports.Search = _search2.default;
exports.TouchScroll = _touchScroll2.default;
exports.UndoRedo = _undoRedo2.default;
exports.Base = _base2.default;

/***/ }),
/* 389 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _array = __webpack_require__(2);

var _feature = __webpack_require__(39);

var _element = __webpack_require__(0);

var _ghostTable = __webpack_require__(87);

var _ghostTable2 = _interopRequireDefault(_ghostTable);

var _object = __webpack_require__(1);

var _number = __webpack_require__(6);

var _plugins = __webpack_require__(7);

var _samplesGenerator = __webpack_require__(313);

var _samplesGenerator2 = _interopRequireDefault(_samplesGenerator);

var _string = __webpack_require__(36);

var _src = __webpack_require__(15);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var privatePool = new WeakMap();

/**
 * @plugin AutoColumnSize
 *
 * @description
 * This plugin allows to set column widths based on their widest cells.
 *
 * By default, the plugin is declared as `undefined`, which makes it enabled (same as if it was declared as `true`).
 * Enabling this plugin may decrease the overall table performance, as it needs to calculate the widths of all cells to
 * resize the columns accordingly.
 * If you experience problems with the performance, try turning this feature off and declaring the column widths manually.
 *
 * Column width calculations are divided into sync and async part. Each of this parts has their own advantages and
 * disadvantages. Synchronous calculations are faster but they block the browser UI, while the slower asynchronous operations don't
 * block the browser UI.
 *
 * To configure the sync/async distribution, you can pass an absolute value (number of columns) or a percentage value to a config object:
 * ```js
 * ...
 * // as a number (300 columns in sync, rest async)
 * autoColumnSize: {syncLimit: 300},
 * ...
 *
 * ...
 * // as a string (percent)
 * autoColumnSize: {syncLimit: '40%'},
 * ...
 * ```
 *
 * To configure this plugin see {@link Options#autoColumnSize}.
 *
 * @example
 * ```js
 * ...
 * var hot = new Handsontable(document.getElementById('example'), {
 *   date: getData(),
 *   autoColumnSize: true
 * });
 * // Access to plugin instance:
 * var plugin = hot.getPlugin('autoColumnSize');
 *
 * plugin.getColumnWidth(4);
 *
 * if (plugin.isEnabled()) {
 *   // code...
 * }
 * ...
 * ```
 */

var AutoColumnSize = function (_BasePlugin) {
  _inherits(AutoColumnSize, _BasePlugin);

  _createClass(AutoColumnSize, null, [{
    key: 'CALCULATION_STEP',
    get: function get() {
      return 50;
    }
  }, {
    key: 'SYNC_CALCULATION_LIMIT',
    get: function get() {
      return 50;
    }
  }]);

  function AutoColumnSize(hotInstance) {
    _classCallCheck(this, AutoColumnSize);

    var _this = _possibleConstructorReturn(this, (AutoColumnSize.__proto__ || Object.getPrototypeOf(AutoColumnSize)).call(this, hotInstance));

    privatePool.set(_this, {
      /**
       * Cached column header names. It is used to diff current column headers with previous state and detect which
       * columns width should be updated.
       *
       * @private
       * @type {Array}
       */
      cachedColumnHeaders: []
    });
    /**
     * Cached columns widths.
     *
     * @type {Array}
     */
    _this.widths = [];
    /**
     * Instance of {@link GhostTable} for rows and columns size calculations.
     *
     * @type {GhostTable}
     */
    _this.ghostTable = new _ghostTable2.default(_this.hot);
    /**
     * Instance of {@link SamplesGenerator} for generating samples necessary for columns width calculations.
     *
     * @type {SamplesGenerator}
     */
    _this.samplesGenerator = new _samplesGenerator2.default(function (row, col) {
      return _this.hot.getDataAtCell(row, col);
    });
    /**
     * `true` only if the first calculation was performed
     *
     * @type {Boolean}
     */
    _this.firstCalculation = true;
    /**
     * `true` if the size calculation is in progress.
     *
     * @type {Boolean}
     */
    _this.inProgress = false;

    // moved to constructor to allow auto-sizing the columns when the plugin is disabled
    _this.addHook('beforeColumnResize', function (col, size, isDblClick) {
      return _this.onBeforeColumnResize(col, size, isDblClick);
    });
    return _this;
  }

  /**
   * Check if the plugin is enabled in the handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(AutoColumnSize, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return this.hot.getSettings().autoColumnSize !== false && !this.hot.getSettings().colWidths;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      var setting = this.hot.getSettings().autoColumnSize;

      if (setting && setting.useHeaders != null) {
        this.ghostTable.setSetting('useHeaders', setting.useHeaders);
      }

      this.addHook('afterLoadData', function () {
        return _this2.onAfterLoadData();
      });
      this.addHook('beforeChange', function (changes) {
        return _this2.onBeforeChange(changes);
      });

      this.addHook('beforeRender', function (force) {
        return _this2.onBeforeRender(force);
      });
      this.addHook('modifyColWidth', function (width, col) {
        return _this2.getColumnWidth(col, width);
      });
      this.addHook('afterInit', function () {
        return _this2.onAfterInit();
      });
      _get(AutoColumnSize.prototype.__proto__ || Object.getPrototypeOf(AutoColumnSize.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Update plugin state.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      var changedColumns = this.findColumnsWhereHeaderWasChanged();

      if (changedColumns.length) {
        this.clearCache(changedColumns);
      }
      _get(AutoColumnSize.prototype.__proto__ || Object.getPrototypeOf(AutoColumnSize.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      _get(AutoColumnSize.prototype.__proto__ || Object.getPrototypeOf(AutoColumnSize.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Calculate a columns width.
     *
     * @param {Number|Object} colRange Column range object.
     * @param {Number|Object} rowRange Row range object.
     * @param {Boolean} [force=false] If `true` force calculate width even when value was cached earlier.
     */

  }, {
    key: 'calculateColumnsWidth',
    value: function calculateColumnsWidth() {
      var colRange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { from: 0, to: this.hot.countCols() - 1 };

      var _this3 = this;

      var rowRange = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { from: 0, to: this.hot.countRows() - 1 };
      var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

      if (typeof colRange === 'number') {
        colRange = { from: colRange, to: colRange };
      }
      if (typeof rowRange === 'number') {
        rowRange = { from: rowRange, to: rowRange };
      }

      (0, _number.rangeEach)(colRange.from, colRange.to, function (col) {
        if (force || _this3.widths[col] === void 0 && !_this3.hot._getColWidthFromSettings(col)) {
          var samples = _this3.samplesGenerator.generateColumnSamples(col, rowRange);

          samples.forEach(function (sample, col) {
            return _this3.ghostTable.addColumn(col, sample);
          });
        }
      });

      if (this.ghostTable.columns.length) {
        this.ghostTable.getWidths(function (col, width) {
          _this3.widths[col] = width;
        });
        this.ghostTable.clean();
      }
    }

    /**
     * Calculate all columns width.
     *
     * @param {Object|Number} rowRange Row range object.
     */

  }, {
    key: 'calculateAllColumnsWidth',
    value: function calculateAllColumnsWidth() {
      var _this4 = this;

      var rowRange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { from: 0, to: this.hot.countRows() - 1 };

      var current = 0;
      var length = this.hot.countCols() - 1;
      var timer = null;

      this.inProgress = true;

      var loop = function loop() {
        // When hot was destroyed after calculating finished cancel frame
        if (!_this4.hot) {
          (0, _feature.cancelAnimationFrame)(timer);
          _this4.inProgress = false;

          return;
        }

        _this4.calculateColumnsWidth({
          from: current,
          to: Math.min(current + AutoColumnSize.CALCULATION_STEP, length)
        }, rowRange);

        current = current + AutoColumnSize.CALCULATION_STEP + 1;

        if (current < length) {
          timer = (0, _feature.requestAnimationFrame)(loop);
        } else {
          (0, _feature.cancelAnimationFrame)(timer);
          _this4.inProgress = false;

          // @TODO Should call once per render cycle, currently fired separately in different plugins
          _this4.hot.view.wt.wtOverlays.adjustElementsSize(true);
          // tmp
          if (_this4.hot.view.wt.wtOverlays.leftOverlay.needFullRender) {
            _this4.hot.view.wt.wtOverlays.leftOverlay.clone.draw();
          }
        }
      };
      // sync
      if (this.firstCalculation && this.getSyncCalculationLimit()) {
        this.calculateColumnsWidth({ from: 0, to: this.getSyncCalculationLimit() }, rowRange);
        this.firstCalculation = false;
        current = this.getSyncCalculationLimit() + 1;
      }
      // async
      if (current < length) {
        loop();
      } else {
        this.inProgress = false;
      }
    }

    /**
     * Set the sampling options.
     *
     * @private
     */

  }, {
    key: 'setSamplingOptions',
    value: function setSamplingOptions() {
      var setting = this.hot.getSettings().autoColumnSize;
      var samplingRatio = setting && (0, _object.hasOwnProperty)(setting, 'samplingRatio') ? this.hot.getSettings().autoColumnSize.samplingRatio : void 0;
      var allowSampleDuplicates = setting && (0, _object.hasOwnProperty)(setting, 'allowSampleDuplicates') ? this.hot.getSettings().autoColumnSize.allowSampleDuplicates : void 0;

      if (samplingRatio && !isNaN(samplingRatio)) {
        this.samplesGenerator.setSampleCount(parseInt(samplingRatio, 10));
      }

      if (allowSampleDuplicates) {
        this.samplesGenerator.setAllowDuplicates(allowSampleDuplicates);
      }
    }

    /**
     * Recalculate all columns width (overwrite cache values).
     */

  }, {
    key: 'recalculateAllColumnsWidth',
    value: function recalculateAllColumnsWidth() {
      if (this.hot.view && (0, _element.isVisible)(this.hot.view.wt.wtTable.TABLE)) {
        this.clearCache();
        this.calculateAllColumnsWidth();
      }
    }

    /**
     * Get value which tells how many columns should be calculated synchronously. Rest of the columns will be calculated asynchronously.
     *
     * @returns {Number}
     */

  }, {
    key: 'getSyncCalculationLimit',
    value: function getSyncCalculationLimit() {
      /* eslint-disable no-bitwise */
      var limit = AutoColumnSize.SYNC_CALCULATION_LIMIT;
      var colsLimit = this.hot.countCols() - 1;

      if ((0, _object.isObject)(this.hot.getSettings().autoColumnSize)) {
        limit = this.hot.getSettings().autoColumnSize.syncLimit;

        if ((0, _string.isPercentValue)(limit)) {
          limit = (0, _number.valueAccordingPercent)(colsLimit, limit);
        } else {
          // Force to Number
          limit >>= 0;
        }
      }

      return Math.min(limit, colsLimit);
    }

    /**
     * Get the calculated column width.
     *
     * @param {Number} col Column index.
     * @param {Number} [defaultWidth] Default column width. It will be picked up if no calculated width found.
     * @param {Boolean} [keepMinimum=true] If `true` then returned value won't be smaller then 50 (default column width).
     * @returns {Number}
     */

  }, {
    key: 'getColumnWidth',
    value: function getColumnWidth(col) {
      var defaultWidth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : void 0;
      var keepMinimum = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

      var width = defaultWidth;

      if (width === void 0) {
        width = this.widths[col];

        if (keepMinimum && typeof width === 'number') {
          width = Math.max(width, _src.ViewportColumnsCalculator.DEFAULT_WIDTH);
        }
      }

      return width;
    }

    /**
     * Get the first visible column.
     *
     * @returns {Number} Returns column index or -1 if table is not rendered.
     */

  }, {
    key: 'getFirstVisibleColumn',
    value: function getFirstVisibleColumn() {
      var wot = this.hot.view.wt;

      if (wot.wtViewport.columnsVisibleCalculator) {
        return wot.wtTable.getFirstVisibleColumn();
      }
      if (wot.wtViewport.columnsRenderCalculator) {
        return wot.wtTable.getFirstRenderedColumn();
      }

      return -1;
    }

    /**
     * Get the last visible column.
     *
     * @returns {Number} Returns column index or -1 if table is not rendered.
     */

  }, {
    key: 'getLastVisibleColumn',
    value: function getLastVisibleColumn() {
      var wot = this.hot.view.wt;

      if (wot.wtViewport.columnsVisibleCalculator) {
        return wot.wtTable.getLastVisibleColumn();
      }
      if (wot.wtViewport.columnsRenderCalculator) {
        return wot.wtTable.getLastRenderedColumn();
      }

      return -1;
    }

    /**
     * Collects all columns which titles has been changed in comparison to the previous state.
     *
     * @returns {Array} It returns an array of physical column indexes.
     */

  }, {
    key: 'findColumnsWhereHeaderWasChanged',
    value: function findColumnsWhereHeaderWasChanged() {
      var columnHeaders = this.hot.getColHeader();

      var _privatePool$get = privatePool.get(this),
          cachedColumnHeaders = _privatePool$get.cachedColumnHeaders;

      var changedColumns = (0, _array.arrayReduce)(columnHeaders, function (acc, columnTitle, physicalColumn) {
        var cachedColumnsLength = cachedColumnHeaders.length;

        if (cachedColumnsLength - 1 < physicalColumn || cachedColumnHeaders[physicalColumn] !== columnTitle) {
          acc.push(physicalColumn);
        }
        if (cachedColumnsLength - 1 < physicalColumn) {
          cachedColumnHeaders.push(columnTitle);
        } else {
          cachedColumnHeaders[physicalColumn] = columnTitle;
        }

        return acc;
      }, []);

      return changedColumns;
    }

    /**
     * Clear cache of calculated column widths. If you want to clear only selected columns pass an array with their indexes.
     * Otherwise whole cache will be cleared.
     *
     * @param {Array} [columns=[]] List of column indexes (physical indexes) to clear.
     */

  }, {
    key: 'clearCache',
    value: function clearCache() {
      var _this5 = this;

      var columns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

      if (columns.length) {
        (0, _array.arrayEach)(columns, function (physicalIndex) {
          _this5.widths[physicalIndex] = void 0;
        });
      } else {
        this.widths.length = 0;
      }
    }

    /**
     * Check if all widths were calculated. If not then return `true` (need recalculate).
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isNeedRecalculate',
    value: function isNeedRecalculate() {
      return !!(0, _array.arrayFilter)(this.widths, function (item) {
        return item === void 0;
      }).length;
    }

    /**
     * On before render listener.
     *
     * @private
     */

  }, {
    key: 'onBeforeRender',
    value: function onBeforeRender() {
      var force = this.hot.renderCall;
      var rowsCount = this.hot.countRows();

      // Keep last column widths unchanged for situation when all rows was deleted or trimmed (pro #6)
      if (!rowsCount) {
        return;
      }

      this.calculateColumnsWidth({ from: this.getFirstVisibleColumn(), to: this.getLastVisibleColumn() }, void 0, force);

      if (this.isNeedRecalculate() && !this.inProgress) {
        this.calculateAllColumnsWidth();
      }
    }

    /**
     * On after load data listener.
     *
     * @private
     */

  }, {
    key: 'onAfterLoadData',
    value: function onAfterLoadData() {
      var _this6 = this;

      if (this.hot.view) {
        this.recalculateAllColumnsWidth();
      } else {
        // first load - initialization
        setTimeout(function () {
          if (_this6.hot) {
            _this6.recalculateAllColumnsWidth();
          }
        }, 0);
      }
    }

    /**
     * On before change listener.
     *
     * @private
     * @param {Array} changes
     */

  }, {
    key: 'onBeforeChange',
    value: function onBeforeChange(changes) {
      var _this7 = this;

      var changedColumns = (0, _array.arrayMap)(changes, function (_ref) {
        var _ref2 = _slicedToArray(_ref, 2),
            row = _ref2[0],
            column = _ref2[1];

        return _this7.hot.propToCol(column);
      });

      this.clearCache(changedColumns);
    }

    /**
     * On before column resize listener.
     *
     * @private
     * @param {Number} col
     * @param {Number} size
     * @param {Boolean} isDblClick
     * @returns {Number}
     */

  }, {
    key: 'onBeforeColumnResize',
    value: function onBeforeColumnResize(col, size, isDblClick) {
      if (isDblClick) {
        this.calculateColumnsWidth(col, void 0, true);
        size = this.getColumnWidth(col, void 0, false);
      }

      return size;
    }

    /**
     * On after Handsontable init fill plugin with all necessary values.
     *
     * @private
     */

  }, {
    key: 'onAfterInit',
    value: function onAfterInit() {
      privatePool.get(this).cachedColumnHeaders = this.hot.getColHeader();
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.ghostTable.clean();
      _get(AutoColumnSize.prototype.__proto__ || Object.getPrototypeOf(AutoColumnSize.prototype), 'destroy', this).call(this);
    }
  }]);

  return AutoColumnSize;
}(_base2.default);

(0, _plugins.registerPlugin)('autoColumnSize', AutoColumnSize);

exports.default = AutoColumnSize;

/***/ }),
/* 390 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _element = __webpack_require__(0);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _plugins = __webpack_require__(7);

var _src = __webpack_require__(15);

var _utils = __webpack_require__(391);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

_pluginHooks2.default.getSingleton().register('modifyAutofillRange');
_pluginHooks2.default.getSingleton().register('beforeAutofill');

var INSERT_ROW_ALTER_ACTION_NAME = 'insert_row';
var INTERVAL_FOR_ADDING_ROW = 200;

/**
 * This plugin provides "drag-down" and "copy-down" functionalities, both operated
 * using the small square in the right bottom of the cell selection.
 *
 * "Drag-down" expands the value of the selected cells to the neighbouring
 * cells when you drag the small square in the corner.
 *
 * "Copy-down" copies the value of the selection to all empty cells
 * below when you double click the small square.
 *
 * @class Autofill
 * @plugin Autofill
 */

var Autofill = function (_BasePlugin) {
  _inherits(Autofill, _BasePlugin);

  function Autofill(hotInstance) {
    _classCallCheck(this, Autofill);

    /**
     * Event manager
     *
     * @type {EventManager}
     */
    var _this = _possibleConstructorReturn(this, (Autofill.__proto__ || Object.getPrototypeOf(Autofill)).call(this, hotInstance));

    _this.eventManager = new _eventManager2.default(_this);
    /**
     * Specifies if adding new row started.
     *
     * @type {Boolean}
     */
    _this.addingStarted = false;
    /**
     * Specifies if there was mouse down on the cell corner.
     *
     * @type {Boolean}
     */
    _this.mouseDownOnCellCorner = false;
    /**
     * Specifies if mouse was dragged outside Handsontable.
     *
     * @type {Boolean}
     */
    _this.mouseDragOutside = false;
    /**
     * Specifies how many cell levels were dragged using the handle.
     *
     * @type {Boolean}
     */
    _this.handleDraggedCells = 0;
    /**
     * Specifies allowed directions of drag.
     *
     * @type {Array}
     */
    _this.directions = [];
    /**
     * Specifies if can insert new rows if needed.
     *
     * @type {Boolean}
     */
    _this.autoInsertRow = false;
    return _this;
  }

  /**
   * Check if the plugin is enabled in the Handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(Autofill, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return this.hot.getSettings().fillHandle;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.mapSettings();
      this.registerEvents();

      this.addHook('afterOnCellCornerMouseDown', function (event) {
        return _this2.onAfterCellCornerMouseDown(event);
      });
      this.addHook('afterOnCellCornerDblClick', function (event) {
        return _this2.onCellCornerDblClick(event);
      });
      this.addHook('beforeOnCellMouseOver', function (event, coords, TD) {
        return _this2.onBeforeCellMouseOver(coords);
      });

      _get(Autofill.prototype.__proto__ || Object.getPrototypeOf(Autofill.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Update plugin for this Handsontable instance.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();
      _get(Autofill.prototype.__proto__ || Object.getPrototypeOf(Autofill.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      this.clearMappedSettings();
      _get(Autofill.prototype.__proto__ || Object.getPrototypeOf(Autofill.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Get selection data
     *
     * @private
     * @returns {Array} Array with the data.
     */

  }, {
    key: 'getSelectionData',
    value: function getSelectionData() {
      var selRange = {
        from: this.hot.getSelectedRange().from,
        to: this.hot.getSelectedRange().to
      };

      return this.hot.getData(selRange.from.row, selRange.from.col, selRange.to.row, selRange.to.col);
    }

    /**
     * Try to apply fill values to the area in fill border, omitting the selection border.
     *
     * @private
     * @returns {Boolean} reports if fill was applied.
     */

  }, {
    key: 'fillIn',
    value: function fillIn() {
      if (this.hot.view.wt.selections.fill.isEmpty()) {
        return false;
      }

      var cornersOfSelectionAndDragAreas = this.hot.view.wt.selections.fill.getCorners();

      this.resetSelectionOfDraggedArea();

      var cornersOfSelectedCells = this.getCornersOfSelectedCells();

      var _getDragDirectionAndR = (0, _utils.getDragDirectionAndRange)(cornersOfSelectedCells, cornersOfSelectionAndDragAreas),
          directionOfDrag = _getDragDirectionAndR.directionOfDrag,
          startOfDragCoords = _getDragDirectionAndR.startOfDragCoords,
          endOfDragCoords = _getDragDirectionAndR.endOfDragCoords;

      this.hot.runHooks('modifyAutofillRange', cornersOfSelectedCells, cornersOfSelectionAndDragAreas);

      if (startOfDragCoords && startOfDragCoords.row > -1 && startOfDragCoords.col > -1) {
        var selectionData = this.getSelectionData();
        var deltas = (0, _utils.getDeltas)(startOfDragCoords, endOfDragCoords, selectionData, directionOfDrag);
        var fillData = selectionData;

        this.hot.runHooks('beforeAutofill', startOfDragCoords, endOfDragCoords, selectionData);

        if (['up', 'left'].indexOf(directionOfDrag) > -1) {
          fillData = [];

          var dragLength = null;
          var fillOffset = null;

          if (directionOfDrag === 'up') {
            dragLength = endOfDragCoords.row - startOfDragCoords.row + 1;
            fillOffset = dragLength % selectionData.length;

            for (var i = 0; i < dragLength; i++) {
              fillData.push(selectionData[(i + (selectionData.length - fillOffset)) % selectionData.length]);
            }
          } else {
            dragLength = endOfDragCoords.col - startOfDragCoords.col + 1;
            fillOffset = dragLength % selectionData[0].length;

            for (var _i = 0; _i < selectionData.length; _i++) {
              fillData.push([]);
              for (var j = 0; j < dragLength; j++) {
                fillData[_i].push(selectionData[_i][(j + (selectionData[_i].length - fillOffset)) % selectionData[_i].length]);
              }
            }
          }
        }

        this.hot.populateFromArray(startOfDragCoords.row, startOfDragCoords.col, fillData, endOfDragCoords.row, endOfDragCoords.col, this.pluginName + '.fill', null, directionOfDrag, deltas);

        this.setSelection(cornersOfSelectionAndDragAreas);
      } else {
        // reset to avoid some range bug
        this.hot.selection.refreshBorders();
      }

      return true;
    }

    /**
     * Reduce the selection area if the handle was dragged outside of the table or on headers.
     *
     * @private
     * @param {CellCoords} coords indexes of selection corners.
     * @returns {CellCoords}
     */

  }, {
    key: 'reduceSelectionAreaIfNeeded',
    value: function reduceSelectionAreaIfNeeded(coords) {
      if (coords.row < 0) {
        coords.row = 0;
      }

      if (coords.col < 0) {
        coords.col = 0;
      }
      return coords;
    }

    /**
     * Get the coordinates of the drag & drop borders.
     *
     * @private
     * @param {CellCoords} coordsOfSelection `CellCoords` coord object.
     * @returns {Array}
     */

  }, {
    key: 'getCoordsOfDragAndDropBorders',
    value: function getCoordsOfDragAndDropBorders(coordsOfSelection) {
      var topLeftCorner = this.hot.getSelectedRange().getTopLeftCorner();
      var bottomRightCorner = this.hot.getSelectedRange().getBottomRightCorner();
      var coords = void 0;

      if (this.directions.includes(_utils.DIRECTIONS.vertical) && (bottomRightCorner.row < coordsOfSelection.row || topLeftCorner.row > coordsOfSelection.row)) {
        coords = new _src.CellCoords(coordsOfSelection.row, bottomRightCorner.col);
      } else if (this.directions.includes(_utils.DIRECTIONS.horizontal)) {
        coords = new _src.CellCoords(bottomRightCorner.row, coordsOfSelection.col);
      } else {
        // wrong direction
        return;
      }

      return this.reduceSelectionAreaIfNeeded(coords);
    }

    /**
     * Show the fill border.
     *
     * @private
     * @param {CellCoords} coordsOfSelection `CellCoords` coord object.
     */

  }, {
    key: 'showBorder',
    value: function showBorder(coordsOfSelection) {
      var coordsOfDragAndDropBorders = this.getCoordsOfDragAndDropBorders(coordsOfSelection);

      if (coordsOfDragAndDropBorders) {
        this.redrawBorders(coordsOfDragAndDropBorders);
      }
    }

    /**
     * Add new row
     *
     * @private
     */

  }, {
    key: 'addRow',
    value: function addRow() {
      var _this3 = this;

      this.hot._registerTimeout(setTimeout(function () {
        _this3.hot.alter(INSERT_ROW_ALTER_ACTION_NAME, void 0, 1, _this3.pluginName + '.fill');

        _this3.addingStarted = false;
      }, INTERVAL_FOR_ADDING_ROW));
    }

    /**
     * Add new rows if they are needed to continue auto-filling values.
     *
     * @private
     */

  }, {
    key: 'addNewRowIfNeeded',
    value: function addNewRowIfNeeded() {
      if (this.hot.view.wt.selections.fill.cellRange && this.addingStarted === false && this.autoInsertRow) {
        var cornersOfSelectedCells = this.hot.getSelected();
        var cornersOfSelectedDragArea = this.hot.view.wt.selections.fill.getCorners();
        var nrOfTableRows = this.hot.countRows();

        if (cornersOfSelectedCells[2] < nrOfTableRows - 1 && cornersOfSelectedDragArea[2] === nrOfTableRows - 1) {
          this.addingStarted = true;

          this.addRow();
        }
      }
    }

    /**
     * Get corners of selected cells.
     *
     * @private
     * @returns {Array}
     */

  }, {
    key: 'getCornersOfSelectedCells',
    value: function getCornersOfSelectedCells() {
      if (this.hot.selection.isMultiple()) {
        return this.hot.view.wt.selections.area.getCorners();
      }
      return this.hot.view.wt.selections.current.getCorners();
    }

    /**
     * Get index of last adjacent filled in row
     *
     * @private
     * @param {Array} cornersOfSelectedCells indexes of selection corners.
     * @returns {Number} gives number greater than or equal to zero when selection adjacent can be applied.
     * or -1 when selection adjacent can't be applied
     */

  }, {
    key: 'getIndexOfLastAdjacentFilledInRow',
    value: function getIndexOfLastAdjacentFilledInRow(cornersOfSelectedCells) {
      var data = this.hot.getData();
      var nrOfTableRows = this.hot.countRows();
      var lastFilledInRowIndex = void 0;

      for (var rowIndex = cornersOfSelectedCells[2] + 1; rowIndex < nrOfTableRows; rowIndex++) {
        for (var columnIndex = cornersOfSelectedCells[1]; columnIndex <= cornersOfSelectedCells[3]; columnIndex++) {
          var dataInCell = data[rowIndex][columnIndex];

          if (dataInCell) {
            return -1;
          }
        }

        var dataInNextLeftCell = data[rowIndex][cornersOfSelectedCells[1] - 1];
        var dataInNextRightCell = data[rowIndex][cornersOfSelectedCells[3] + 1];

        if (!!dataInNextLeftCell || !!dataInNextRightCell) {
          lastFilledInRowIndex = rowIndex;
        }
      }
      return lastFilledInRowIndex;
    }

    /**
     * Add a selection from the start area to the specific row index.
     *
     * @private
     * @param {Array} selectStartArea selection area from which we start to create more comprehensive selection.
     * @param {Number} rowIndex
     */

  }, {
    key: 'addSelectionFromStartAreaToSpecificRowIndex',
    value: function addSelectionFromStartAreaToSpecificRowIndex(selectStartArea, rowIndex) {
      this.hot.view.wt.selections.fill.clear();
      this.hot.view.wt.selections.fill.add(new _src.CellCoords(selectStartArea[0], selectStartArea[1]));
      this.hot.view.wt.selections.fill.add(new _src.CellCoords(rowIndex, selectStartArea[3]));
    }

    /**
     * Set selection based on passed corners.
     *
     * @private
     * @param {Array} cornersOfArea
     */

  }, {
    key: 'setSelection',
    value: function setSelection(cornersOfArea) {
      this.hot.selection.setRangeStart(new _src.CellCoords(cornersOfArea[0], cornersOfArea[1]));
      this.hot.selection.setRangeEnd(new _src.CellCoords(cornersOfArea[2], cornersOfArea[3]));
    }

    /**
     * Try to select cells down to the last row in the left column and then returns if selection was applied.
     *
     * @private
     * @returns {Boolean}
     */

  }, {
    key: 'selectAdjacent',
    value: function selectAdjacent() {
      var cornersOfSelectedCells = this.getCornersOfSelectedCells();
      var lastFilledInRowIndex = this.getIndexOfLastAdjacentFilledInRow(cornersOfSelectedCells);

      if (lastFilledInRowIndex === -1) {
        return false;
      }
      this.addSelectionFromStartAreaToSpecificRowIndex(cornersOfSelectedCells, lastFilledInRowIndex);

      return true;
    }

    /**
     * Reset selection of dragged area.
     *
     * @private
     */

  }, {
    key: 'resetSelectionOfDraggedArea',
    value: function resetSelectionOfDraggedArea() {
      this.handleDraggedCells = 0;

      this.hot.view.wt.selections.fill.clear();
    }

    /**
     * Redraw borders.
     *
     * @private
     * @param {CellCoords} coords `CellCoords` coord object.
     */

  }, {
    key: 'redrawBorders',
    value: function redrawBorders(coords) {
      this.hot.view.wt.selections.fill.clear();
      this.hot.view.wt.selections.fill.add(this.hot.getSelectedRange().from);
      this.hot.view.wt.selections.fill.add(this.hot.getSelectedRange().to);
      this.hot.view.wt.selections.fill.add(coords);
      this.hot.view.render();
    }

    /**
     * Get if mouse was dragged outside.
     *
     * @private
     * @param {MouseEvent} event `mousemove` event properties.
     * @returns {Boolean}
     */

  }, {
    key: 'getIfMouseWasDraggedOutside',
    value: function getIfMouseWasDraggedOutside(event) {
      var tableBottom = (0, _element.offset)(this.hot.table).top - (window.pageYOffset || document.documentElement.scrollTop) + (0, _element.outerHeight)(this.hot.table);
      var tableRight = (0, _element.offset)(this.hot.table).left - (window.pageXOffset || document.documentElement.scrollLeft) + (0, _element.outerWidth)(this.hot.table);

      return event.clientY > tableBottom && event.clientX <= tableRight;
    }

    /**
     * Bind the events used by the plugin.
     *
     * @private
     */

  }, {
    key: 'registerEvents',
    value: function registerEvents() {
      var _this4 = this;

      this.eventManager.addEventListener(document.documentElement, 'mouseup', function () {
        return _this4.onMouseUp();
      });
      this.eventManager.addEventListener(document.documentElement, 'mousemove', function (event) {
        return _this4.onMouseMove(event);
      });
    }

    /**
     * On cell corner double click callback.
     *
     * @private
     */

  }, {
    key: 'onCellCornerDblClick',
    value: function onCellCornerDblClick() {
      var selectionApplied = this.selectAdjacent();

      if (selectionApplied) {
        this.fillIn();
      }
    }

    /**
     * On after cell corner mouse down listener.
     *
     * @private
     */

  }, {
    key: 'onAfterCellCornerMouseDown',
    value: function onAfterCellCornerMouseDown() {
      this.handleDraggedCells = 1;
      this.mouseDownOnCellCorner = true;
    }

    /**
     * On before cell mouse over listener.
     *
     * @private
     * @param {CellCoords} coords `CellCoords` coord object.
     */

  }, {
    key: 'onBeforeCellMouseOver',
    value: function onBeforeCellMouseOver(coords) {
      if (this.mouseDownOnCellCorner && !this.hot.view.isMouseDown() && this.handleDraggedCells) {
        this.handleDraggedCells++;

        this.showBorder(coords);
        this.addNewRowIfNeeded();
      }
    }

    /**
     * On mouse up listener.
     *
     * @private
     */

  }, {
    key: 'onMouseUp',
    value: function onMouseUp() {
      if (this.handleDraggedCells) {
        if (this.handleDraggedCells > 1) {
          this.fillIn();
        }

        this.handleDraggedCells = 0;
        this.mouseDownOnCellCorner = false;
      }
    }

    /**
     * On mouse move listener.
     *
     * @private
     * @param {MouseEvent} event `mousemove` event properties.
     */

  }, {
    key: 'onMouseMove',
    value: function onMouseMove(event) {
      var mouseWasDraggedOutside = this.getIfMouseWasDraggedOutside(event);

      if (this.addingStarted === false && this.handleDraggedCells > 0 && mouseWasDraggedOutside) {
        this.mouseDragOutside = true;
        this.addingStarted = true;
      } else {
        this.mouseDragOutside = false;
      }

      if (this.mouseDragOutside && this.autoInsertRow) {
        this.addRow();
      }
    }

    /**
     * Clear mapped settings.
     *
     * @private
     */

  }, {
    key: 'clearMappedSettings',
    value: function clearMappedSettings() {
      this.directions.length = 0;
      this.autoInsertRow = false;
    }

    /**
     * Map settings.
     *
     * @private
     */

  }, {
    key: 'mapSettings',
    value: function mapSettings() {
      var mappedSettings = (0, _utils.getMappedFillHandleSetting)(this.hot.getSettings().fillHandle);
      this.directions = mappedSettings.directions;
      this.autoInsertRow = mappedSettings.autoInsertRow;
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      _get(Autofill.prototype.__proto__ || Object.getPrototypeOf(Autofill.prototype), 'destroy', this).call(this);
    }
  }]);

  return Autofill;
}(_base2.default);

(0, _plugins.registerPlugin)('autofill', Autofill);

exports.default = Autofill;

/***/ }),
/* 391 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.DIRECTIONS = undefined;
exports.getDeltas = getDeltas;
exports.getDragDirectionAndRange = getDragDirectionAndRange;
exports.getMappedFillHandleSetting = getMappedFillHandleSetting;

var _object = __webpack_require__(1);

var _mixed = __webpack_require__(17);

var _src = __webpack_require__(15);

var DIRECTIONS = exports.DIRECTIONS = {
  horizontal: 'horizontal',
  vertical: 'vertical'
};

/**
 * Get deltas array.
 *
 * @param {CellCoords} start
 * @param {CellCoords} end
 * @param {Array} data
 * @param {String} direction
 * @returns {Array}
 */
function getDeltas(start, end, data, direction) {
  var rowsLength = data.length;
  var columnsLength = data ? data[0].length : 0;
  var deltas = [];
  var diffRow = end.row - start.row;
  var diffCol = end.col - start.col;

  if (['down', 'up'].indexOf(direction) !== -1) {
    var arr = [];

    for (var col = 0; col <= diffCol; col++) {
      var startValue = parseInt(data[0][col], 10);
      var endValue = parseInt(data[rowsLength - 1][col], 10);
      var delta = (direction === 'down' ? endValue - startValue : startValue - endValue) / (rowsLength - 1) || 0;

      arr.push(delta);
    }

    deltas.push(arr);
  }

  if (['right', 'left'].indexOf(direction) !== -1) {
    for (var row = 0; row <= diffRow; row++) {
      var _startValue = parseInt(data[row][0], 10);
      var _endValue = parseInt(data[row][columnsLength - 1], 10);
      var _delta = (direction === 'right' ? _endValue - _startValue : _startValue - _endValue) / (columnsLength - 1) || 0;

      deltas.push([_delta]);
    }
  }

  return deltas;
}

/**
 * Get direction between positions and cords of selections difference (drag area)
 *
 * @param {Array} startSelection
 * @param {Array} endSelection
 * @returns {{direction: String, start: CellCoords, end: CellCoords}}
 */
function getDragDirectionAndRange(startSelection, endSelection) {
  var startOfDragCoords = void 0,
      endOfDragCoords = void 0,
      directionOfDrag = void 0;

  if (endSelection[0] === startSelection[0] && endSelection[1] < startSelection[1]) {
    directionOfDrag = 'left';

    startOfDragCoords = new _src.CellCoords(endSelection[0], endSelection[1]);
    endOfDragCoords = new _src.CellCoords(endSelection[2], startSelection[1] - 1);
  } else if (endSelection[0] === startSelection[0] && endSelection[3] > startSelection[3]) {
    directionOfDrag = 'right';

    startOfDragCoords = new _src.CellCoords(endSelection[0], startSelection[3] + 1);
    endOfDragCoords = new _src.CellCoords(endSelection[2], endSelection[3]);
  } else if (endSelection[0] < startSelection[0] && endSelection[1] === startSelection[1]) {
    directionOfDrag = 'up';

    startOfDragCoords = new _src.CellCoords(endSelection[0], endSelection[1]);
    endOfDragCoords = new _src.CellCoords(startSelection[0] - 1, endSelection[3]);
  } else if (endSelection[2] > startSelection[2] && endSelection[1] === startSelection[1]) {
    directionOfDrag = 'down';

    startOfDragCoords = new _src.CellCoords(startSelection[2] + 1, endSelection[1]);
    endOfDragCoords = new _src.CellCoords(endSelection[2], endSelection[3]);
  }

  return {
    directionOfDrag: directionOfDrag,
    startOfDragCoords: startOfDragCoords,
    endOfDragCoords: endOfDragCoords
  };
}

/**
 * Get mapped FillHandle setting containing information about
 * allowed FillHandle directions and if allowed is automatic insertion of rows on drag
 *
 * @param {Boolean|Object} fillHandle property of Handsontable settings
 * @returns {{directions: Array, autoInsertRow: Boolean}} object allowing access to information
 * about FillHandle in more useful way
 */
function getMappedFillHandleSetting(fillHandle) {
  var mappedSettings = {};

  if (fillHandle === true) {
    mappedSettings.directions = Object.keys(DIRECTIONS);
    mappedSettings.autoInsertRow = true;
  } else if ((0, _object.isObject)(fillHandle)) {
    if ((0, _mixed.isDefined)(fillHandle.autoInsertRow)) {

      // autoInsertRow for horizontal direction will be always false

      if (fillHandle.direction === DIRECTIONS.horizontal) {
        mappedSettings.autoInsertRow = false;
      } else {
        mappedSettings.autoInsertRow = fillHandle.autoInsertRow;
      }
    } else {
      mappedSettings.autoInsertRow = false;
    }

    if ((0, _mixed.isDefined)(fillHandle.direction)) {
      mappedSettings.directions = [fillHandle.direction];
    } else {
      mappedSettings.directions = Object.keys(DIRECTIONS);
    }
  } else if (typeof fillHandle === 'string') {
    mappedSettings.directions = [fillHandle];
    mappedSettings.autoInsertRow = true;
  } else {
    mappedSettings.directions = [];
    mappedSettings.autoInsertRow = false;
  }

  return mappedSettings;
}

/***/ }),
/* 392 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _array = __webpack_require__(2);

var _feature = __webpack_require__(39);

var _element = __webpack_require__(0);

var _ghostTable = __webpack_require__(87);

var _ghostTable2 = _interopRequireDefault(_ghostTable);

var _object = __webpack_require__(1);

var _number = __webpack_require__(6);

var _plugins = __webpack_require__(7);

var _samplesGenerator = __webpack_require__(313);

var _samplesGenerator2 = _interopRequireDefault(_samplesGenerator);

var _string = __webpack_require__(36);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @plugin AutoRowSize
 *
 * @description
 * This plugin allows to set row heights based on their highest cells.
 *
 * By default, the plugin is declared as `undefined`, which makes it disabled (same as if it was declared as `false`).
 * Enabling this plugin may decrease the overall table performance, as it needs to calculate the heights of all cells to
 * resize the rows accordingly.
 * If you experience problems with the performance, try turning this feature off and declaring the row heights manually.
 *
 * Row height calculations are divided into sync and async part. Each of this parts has their own advantages and
 * disadvantages. Synchronous calculations are faster but they block the browser UI, while the slower asynchronous operations don't
 * block the browser UI.
 *
 * To configure the sync/async distribution, you can pass an absolute value (number of columns) or a percentage value to a config object:
 * ```js
 * ...
 * // as a number (300 columns in sync, rest async)
 * autoRowSize: {syncLimit: 300},
 * ...
 *
 * ...
 * // as a string (percent)
 * autoRowSize: {syncLimit: '40%'},
 * ...
 * ```
 *
 * You can also use the `allowSampleDuplicates` option to allow sampling duplicate values when calculating the row height. Note, that this might have
 * a negative impact on performance.
 *
 * To configure this plugin see {@link Options#autoRowSize}.
 *
 * @example
 *
 * ```js
 * ...
 * var hot = new Handsontable(document.getElementById('example'), {
 *   date: getData(),
 *   autoRowSize: true
 * });
 * // Access to plugin instance:
 * var plugin = hot.getPlugin('autoRowSize');
 *
 * plugin.getRowHeight(4);
 *
 * if (plugin.isEnabled()) {
 *   // code...
 * }
 * ...
 * ```
 */
var AutoRowSize = function (_BasePlugin) {
  _inherits(AutoRowSize, _BasePlugin);

  _createClass(AutoRowSize, null, [{
    key: 'CALCULATION_STEP',
    get: function get() {
      return 50;
    }
  }, {
    key: 'SYNC_CALCULATION_LIMIT',
    get: function get() {
      return 500;
    }
  }]);

  function AutoRowSize(hotInstance) {
    _classCallCheck(this, AutoRowSize);

    /**
     * Cached rows heights.
     *
     * @type {Array}
     */
    var _this = _possibleConstructorReturn(this, (AutoRowSize.__proto__ || Object.getPrototypeOf(AutoRowSize)).call(this, hotInstance));

    _this.heights = [];
    /**
     * Instance of {@link GhostTable} for rows and columns size calculations.
     *
     * @type {GhostTable}
     */
    _this.ghostTable = new _ghostTable2.default(_this.hot);
    /**
     * Instance of {@link SamplesGenerator} for generating samples necessary for rows height calculations.
     *
     * @type {SamplesGenerator}
     */
    _this.samplesGenerator = new _samplesGenerator2.default(function (row, col) {
      if (row >= 0) {
        return _this.hot.getDataAtCell(row, col);
      } else if (row === -1) {
        return _this.hot.getColHeader(col);
      }
      return null;
    });
    /**
     * `true` if only the first calculation was performed.
     *
     * @type {Boolean}
     */
    _this.firstCalculation = true;
    /**
     * `true` if the size calculation is in progress.
     *
     * @type {Boolean}
     */
    _this.inProgress = false;

    // moved to constructor to allow auto-sizing the rows when the plugin is disabled
    _this.addHook('beforeRowResize', function (row, size, isDblClick) {
      return _this.onBeforeRowResize(row, size, isDblClick);
    });
    return _this;
  }

  /**
   * Check if the plugin is enabled in the Handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(AutoRowSize, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return this.hot.getSettings().autoRowSize === true || (0, _object.isObject)(this.hot.getSettings().autoRowSize);
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.setSamplingOptions();

      this.addHook('afterLoadData', function () {
        return _this2.onAfterLoadData();
      });
      this.addHook('beforeChange', function (changes) {
        return _this2.onBeforeChange(changes);
      });
      this.addHook('beforeColumnMove', function () {
        return _this2.recalculateAllRowsHeight();
      });
      this.addHook('beforeColumnResize', function () {
        return _this2.recalculateAllRowsHeight();
      });
      this.addHook('beforeColumnSort', function () {
        return _this2.clearCache();
      });
      this.addHook('beforeRender', function (force) {
        return _this2.onBeforeRender(force);
      });
      this.addHook('beforeRowMove', function (rowStart, rowEnd) {
        return _this2.onBeforeRowMove(rowStart, rowEnd);
      });
      this.addHook('modifyRowHeight', function (height, row) {
        return _this2.getRowHeight(row, height);
      });
      this.addHook('modifyColumnHeaderHeight', function () {
        return _this2.getColumnHeaderHeight();
      });
      _get(AutoRowSize.prototype.__proto__ || Object.getPrototypeOf(AutoRowSize.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      _get(AutoRowSize.prototype.__proto__ || Object.getPrototypeOf(AutoRowSize.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Calculate a given rows height.
     *
     * @param {Number|Object} rowRange Row range object.
     * @param {Number|Object} colRange Column range object.
     * @param {Boolean} [force=false] If `true` force calculate height even when value was cached earlier.
     */

  }, {
    key: 'calculateRowsHeight',
    value: function calculateRowsHeight() {
      var rowRange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { from: 0, to: this.hot.countRows() - 1 };

      var _this3 = this;

      var colRange = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { from: 0, to: this.hot.countCols() - 1 };
      var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

      if (typeof rowRange === 'number') {
        rowRange = { from: rowRange, to: rowRange };
      }
      if (typeof colRange === 'number') {
        colRange = { from: colRange, to: colRange };
      }

      if (this.hot.getColHeader(0) !== null) {
        var samples = this.samplesGenerator.generateRowSamples(-1, colRange);

        this.ghostTable.addColumnHeadersRow(samples.get(-1));
      }

      (0, _number.rangeEach)(rowRange.from, rowRange.to, function (row) {
        // For rows we must calculate row height even when user had set height value manually.
        // We can shrink column but cannot shrink rows!
        if (force || _this3.heights[row] === void 0) {
          var _samples = _this3.samplesGenerator.generateRowSamples(row, colRange);

          _samples.forEach(function (sample, row) {
            _this3.ghostTable.addRow(row, sample);
          });
        }
      });
      if (this.ghostTable.rows.length) {
        this.ghostTable.getHeights(function (row, height) {
          _this3.heights[row] = height;
        });
        this.ghostTable.clean();
      }
    }

    /**
     * Calculate the height of all the rows.
     *
     * @param {Object|Number} colRange Column range object.
     */

  }, {
    key: 'calculateAllRowsHeight',
    value: function calculateAllRowsHeight() {
      var _this4 = this;

      var colRange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { from: 0, to: this.hot.countCols() - 1 };

      var current = 0;
      var length = this.hot.countRows() - 1;
      var timer = null;

      this.inProgress = true;

      var loop = function loop() {
        // When hot was destroyed after calculating finished cancel frame
        if (!_this4.hot) {
          (0, _feature.cancelAnimationFrame)(timer);
          _this4.inProgress = false;

          return;
        }
        _this4.calculateRowsHeight({ from: current, to: Math.min(current + AutoRowSize.CALCULATION_STEP, length) }, colRange);
        current = current + AutoRowSize.CALCULATION_STEP + 1;

        if (current < length) {
          timer = (0, _feature.requestAnimationFrame)(loop);
        } else {
          (0, _feature.cancelAnimationFrame)(timer);
          _this4.inProgress = false;

          // @TODO Should call once per render cycle, currently fired separately in different plugins
          _this4.hot.view.wt.wtOverlays.adjustElementsSize(true);
          // tmp
          if (_this4.hot.view.wt.wtOverlays.leftOverlay.needFullRender) {
            _this4.hot.view.wt.wtOverlays.leftOverlay.clone.draw();
          }
        }
      };
      // sync
      if (this.firstCalculation && this.getSyncCalculationLimit()) {
        this.calculateRowsHeight({ from: 0, to: this.getSyncCalculationLimit() }, colRange);
        this.firstCalculation = false;
        current = this.getSyncCalculationLimit() + 1;
      }
      // async
      if (current < length) {
        loop();
      } else {
        this.inProgress = false;
        this.hot.view.wt.wtOverlays.adjustElementsSize(false);
      }
    }

    /**
     * Set the sampling options.
     *
     * @private
     */

  }, {
    key: 'setSamplingOptions',
    value: function setSamplingOptions() {
      var setting = this.hot.getSettings().autoRowSize;
      var samplingRatio = setting && (0, _object.hasOwnProperty)(setting, 'samplingRatio') ? this.hot.getSettings().autoRowSize.samplingRatio : void 0;
      var allowSampleDuplicates = setting && (0, _object.hasOwnProperty)(setting, 'allowSampleDuplicates') ? this.hot.getSettings().autoRowSize.allowSampleDuplicates : void 0;

      if (samplingRatio && !isNaN(samplingRatio)) {
        this.samplesGenerator.setSampleCount(parseInt(samplingRatio, 10));
      }

      if (allowSampleDuplicates) {
        this.samplesGenerator.setAllowDuplicates(allowSampleDuplicates);
      }
    }

    /**
     * Recalculate all rows height (overwrite cache values).
     */

  }, {
    key: 'recalculateAllRowsHeight',
    value: function recalculateAllRowsHeight() {
      if ((0, _element.isVisible)(this.hot.view.wt.wtTable.TABLE)) {
        this.clearCache();
        this.calculateAllRowsHeight();
      }
    }

    /**
     * Get value which tells how much rows will be calculated synchronously. Rest rows will be calculated asynchronously.
     *
     * @returns {Number}
     */

  }, {
    key: 'getSyncCalculationLimit',
    value: function getSyncCalculationLimit() {
      /* eslint-disable no-bitwise */
      var limit = AutoRowSize.SYNC_CALCULATION_LIMIT;
      var rowsLimit = this.hot.countRows() - 1;

      if ((0, _object.isObject)(this.hot.getSettings().autoRowSize)) {
        limit = this.hot.getSettings().autoRowSize.syncLimit;

        if ((0, _string.isPercentValue)(limit)) {
          limit = (0, _number.valueAccordingPercent)(rowsLimit, limit);
        } else {
          // Force to Number
          limit >>= 0;
        }
      }

      return Math.min(limit, rowsLimit);
    }

    /**
     * Get the calculated row height.
     *
     * @param {Number} row Visual row index.
     * @param {Number} [defaultHeight] Default row height. It will be pick up if no calculated height found.
     * @returns {Number}
     */

  }, {
    key: 'getRowHeight',
    value: function getRowHeight(row) {
      var defaultHeight = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : void 0;

      var height = defaultHeight;

      if (this.heights[row] !== void 0 && this.heights[row] > (defaultHeight || 0)) {
        height = this.heights[row];
      }

      return height;
    }

    /**
     * Get the calculated column header height.
     *
     * @returns {Number|undefined}
     */

  }, {
    key: 'getColumnHeaderHeight',
    value: function getColumnHeaderHeight() {
      return this.heights[-1];
    }

    /**
     * Get the first visible row.
     *
     * @returns {Number} Returns row index or -1 if table is not rendered.
     */

  }, {
    key: 'getFirstVisibleRow',
    value: function getFirstVisibleRow() {
      var wot = this.hot.view.wt;

      if (wot.wtViewport.rowsVisibleCalculator) {
        return wot.wtTable.getFirstVisibleRow();
      }
      if (wot.wtViewport.rowsRenderCalculator) {
        return wot.wtTable.getFirstRenderedRow();
      }

      return -1;
    }

    /**
     * Get the last visible row.
     *
     * @returns {Number} Returns row index or -1 if table is not rendered.
     */

  }, {
    key: 'getLastVisibleRow',
    value: function getLastVisibleRow() {
      var wot = this.hot.view.wt;

      if (wot.wtViewport.rowsVisibleCalculator) {
        return wot.wtTable.getLastVisibleRow();
      }
      if (wot.wtViewport.rowsRenderCalculator) {
        return wot.wtTable.getLastRenderedRow();
      }

      return -1;
    }

    /**
     * Clear cached heights.
     */

  }, {
    key: 'clearCache',
    value: function clearCache() {
      this.heights.length = 0;
      this.heights[-1] = void 0;
    }

    /**
     * Clear cache by range.
     *
     * @param {Object|Number} range Row range object.
     */

  }, {
    key: 'clearCacheByRange',
    value: function clearCacheByRange(range) {
      var _this5 = this;

      if (typeof range === 'number') {
        range = { from: range, to: range };
      }
      (0, _number.rangeEach)(Math.min(range.from, range.to), Math.max(range.from, range.to), function (row) {
        _this5.heights[row] = void 0;
      });
    }

    /**
     * @returns {Boolean}
     */

  }, {
    key: 'isNeedRecalculate',
    value: function isNeedRecalculate() {
      return !!(0, _array.arrayFilter)(this.heights, function (item) {
        return item === void 0;
      }).length;
    }

    /**
     * On before render listener.
     *
     * @private
     */

  }, {
    key: 'onBeforeRender',
    value: function onBeforeRender() {
      var force = this.hot.renderCall;
      this.calculateRowsHeight({ from: this.getFirstVisibleRow(), to: this.getLastVisibleRow() }, void 0, force);

      var fixedRowsBottom = this.hot.getSettings().fixedRowsBottom;

      // Calculate rows height synchronously for bottom overlay
      if (fixedRowsBottom) {
        var totalRows = this.hot.countRows() - 1;
        this.calculateRowsHeight({ from: totalRows - fixedRowsBottom, to: totalRows });
      }

      if (this.isNeedRecalculate() && !this.inProgress) {
        this.calculateAllRowsHeight();
      }
    }

    /**
     * On before row move listener.
     *
     * @private
     * @param {Number} from Row index where was grabbed.
     * @param {Number} to Destination row index.
     */

  }, {
    key: 'onBeforeRowMove',
    value: function onBeforeRowMove(from, to) {
      this.clearCacheByRange({ from: from, to: to });
      this.calculateAllRowsHeight();
    }

    /**
     * On before row resize listener.
     *
     * @private
     * @param {Number} row
     * @param {Number} size
     * @param {Boolean} isDblClick
     * @returns {Number}
     */

  }, {
    key: 'onBeforeRowResize',
    value: function onBeforeRowResize(row, size, isDblClick) {
      if (isDblClick) {
        this.calculateRowsHeight(row, void 0, true);
        size = this.getRowHeight(row);
      }

      return size;
    }

    /**
     * On after load data listener.
     *
     * @private
     */

  }, {
    key: 'onAfterLoadData',
    value: function onAfterLoadData() {
      var _this6 = this;

      if (this.hot.view) {
        this.recalculateAllRowsHeight();
      } else {
        // first load - initialization
        setTimeout(function () {
          if (_this6.hot) {
            _this6.recalculateAllRowsHeight();
          }
        }, 0);
      }
    }

    /**
     * On before change listener.
     *
     * @private
     * @param {Array} changes
     */

  }, {
    key: 'onBeforeChange',
    value: function onBeforeChange(changes) {
      var range = null;

      if (changes.length === 1) {
        range = changes[0][0];
      } else if (changes.length > 1) {
        range = {
          from: changes[0][0],
          to: changes[changes.length - 1][0]
        };
      }
      if (range !== null) {
        this.clearCacheByRange(range);
      }
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.ghostTable.clean();
      _get(AutoRowSize.prototype.__proto__ || Object.getPrototypeOf(AutoRowSize.prototype), 'destroy', this).call(this);
    }
  }]);

  return AutoRowSize;
}(_base2.default);

(0, _plugins.registerPlugin)('autoRowSize', AutoRowSize);

exports.default = AutoRowSize;

/***/ }),
/* 393 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _moment = __webpack_require__(40);

var _moment2 = _interopRequireDefault(_moment);

var _element = __webpack_require__(0);

var _array = __webpack_require__(2);

var _mixed = __webpack_require__(17);

var _object = __webpack_require__(1);

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _plugins = __webpack_require__(7);

var _mergeSort = __webpack_require__(394);

var _mergeSort2 = _interopRequireDefault(_mergeSort);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

_pluginHooks2.default.getSingleton().register('beforeColumnSort');
_pluginHooks2.default.getSingleton().register('afterColumnSort');

// TODO: Implement mixin arrayMapper to ColumnSorting plugin.

/**
 * @plugin ColumnSorting
 *
 * @description
 * This plugin sorts the view by a column (but does not sort the data source!).
 * To enable the plugin, set the `columnSorting` property to either:
 * * a boolean value (`true`/`false`),
 * * an object defining the initial sorting order (see the example below).
 *
 * @example
 * ```js
 * ...
 * // as boolean
 * columnSorting: true
 * ...
 * // as a object with initial order (sort ascending column at index 2)
 * columnSorting: {
 *  column: 2,
 *  sortOrder: true, // true = ascending, false = descending, undefined = original order
 *  sortEmptyCells: true // true = the table sorts empty cells, false = the table moves all empty cells to the end of the table
 * }
 * ...
 * ```
 * @dependencies ObserveChanges
 */

var ColumnSorting = function (_BasePlugin) {
  _inherits(ColumnSorting, _BasePlugin);

  function ColumnSorting(hotInstance) {
    _classCallCheck(this, ColumnSorting);

    var _this2 = _possibleConstructorReturn(this, (ColumnSorting.__proto__ || Object.getPrototypeOf(ColumnSorting)).call(this, hotInstance));

    _this2.sortIndicators = [];
    _this2.lastSortedColumn = null;
    _this2.sortEmptyCells = false;
    return _this2;
  }

  /**
   * Check if the plugin is enabled in the handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(ColumnSorting, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return !!this.hot.getSettings().columnSorting;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this3 = this;

      if (this.enabled) {
        return;
      }

      this.setPluginOptions();

      var _this = this;
      this.hot.sortIndex = [];

      this.hot.sort = function () {
        var args = Array.prototype.slice.call(arguments);

        return _this.sortByColumn.apply(_this, _toConsumableArray(args));
      };

      if (typeof this.hot.getSettings().observeChanges === 'undefined') {
        this.enableObserveChangesPlugin();
      }

      this.addHook('afterTrimRow', function (row) {
        return _this3.sort();
      });
      this.addHook('afterUntrimRow', function (row) {
        return _this3.sort();
      });
      this.addHook('modifyRow', function (row) {
        return _this3.translateRow(row);
      });
      this.addHook('unmodifyRow', function (row) {
        return _this3.untranslateRow(row);
      });
      this.addHook('afterUpdateSettings', function () {
        return _this3.onAfterUpdateSettings();
      });
      this.addHook('afterGetColHeader', function (col, TH) {
        return _this3.getColHeader(col, TH);
      });
      this.addHook('afterOnCellMouseDown', function (event, target) {
        return _this3.onAfterOnCellMouseDown(event, target);
      });
      this.addHook('afterCreateRow', function () {
        _this.afterCreateRow.apply(_this, arguments);
      });
      this.addHook('afterRemoveRow', function () {
        _this.afterRemoveRow.apply(_this, arguments);
      });
      this.addHook('afterInit', function () {
        return _this3.sortBySettings();
      });
      this.addHook('afterLoadData', function () {
        _this3.hot.sortIndex = [];

        if (_this3.hot.view) {
          _this3.sortBySettings();
        }
      });
      if (this.hot.view) {
        this.sortBySettings();
      }
      _get(ColumnSorting.prototype.__proto__ || Object.getPrototypeOf(ColumnSorting.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      this.hot.sort = void 0;
      _get(ColumnSorting.prototype.__proto__ || Object.getPrototypeOf(ColumnSorting.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * afterUpdateSettings callback.
     *
     * @private
     */

  }, {
    key: 'onAfterUpdateSettings',
    value: function onAfterUpdateSettings() {
      this.sortBySettings();
    }
  }, {
    key: 'sortBySettings',
    value: function sortBySettings() {
      var sortingSettings = this.hot.getSettings().columnSorting;
      var loadedSortingState = this.loadSortingState();
      var sortingColumn = void 0;
      var sortingOrder = void 0;

      if (typeof loadedSortingState === 'undefined') {
        sortingColumn = sortingSettings.column;
        sortingOrder = sortingSettings.sortOrder;
      } else {
        sortingColumn = loadedSortingState.sortColumn;
        sortingOrder = loadedSortingState.sortOrder;
      }
      if (typeof sortingColumn === 'number') {
        this.lastSortedColumn = sortingColumn;
        this.sortByColumn(sortingColumn, sortingOrder);
      }
    }

    /**
     * Set sorted column and order info
     *
     * @param {number} col Sorted visual column index.
     * @param {boolean|undefined} order Sorting order (`true` for ascending, `false` for descending).
     */

  }, {
    key: 'setSortingColumn',
    value: function setSortingColumn(col, order) {
      if (typeof col == 'undefined') {
        this.hot.sortColumn = void 0;
        this.hot.sortOrder = void 0;

        return;
      } else if (this.hot.sortColumn === col && typeof order == 'undefined') {
        if (this.hot.sortOrder === false) {
          this.hot.sortOrder = void 0;
        } else {
          this.hot.sortOrder = !this.hot.sortOrder;
        }
      } else {
        this.hot.sortOrder = typeof order === 'undefined' ? true : order;
      }

      this.hot.sortColumn = col;
    }
  }, {
    key: 'sortByColumn',
    value: function sortByColumn(col, order) {
      this.setSortingColumn(col, order);

      if (typeof this.hot.sortColumn == 'undefined') {
        return;
      }

      var allowSorting = this.hot.runHooks('beforeColumnSort', this.hot.sortColumn, this.hot.sortOrder);

      if (allowSorting !== false) {
        this.sort();
      }
      this.updateOrderClass();
      this.updateSortIndicator();

      this.hot.runHooks('afterColumnSort', this.hot.sortColumn, this.hot.sortOrder);

      this.hot.render();
      this.saveSortingState();
    }

    /**
     * Save the sorting state
     */

  }, {
    key: 'saveSortingState',
    value: function saveSortingState() {
      var sortingState = {};

      if (typeof this.hot.sortColumn != 'undefined') {
        sortingState.sortColumn = this.hot.sortColumn;
      }

      if (typeof this.hot.sortOrder != 'undefined') {
        sortingState.sortOrder = this.hot.sortOrder;
      }

      if ((0, _object.hasOwnProperty)(sortingState, 'sortColumn') || (0, _object.hasOwnProperty)(sortingState, 'sortOrder')) {
        this.hot.runHooks('persistentStateSave', 'columnSorting', sortingState);
      }
    }

    /**
     * Load the sorting state.
     *
     * @returns {*} Previously saved sorting state.
     */

  }, {
    key: 'loadSortingState',
    value: function loadSortingState() {
      var storedState = {};
      this.hot.runHooks('persistentStateLoad', 'columnSorting', storedState);

      return storedState.value;
    }

    /**
     * Update sorting class name state.
     */

  }, {
    key: 'updateOrderClass',
    value: function updateOrderClass() {
      var orderClass = void 0;

      if (this.hot.sortOrder === true) {
        orderClass = 'ascending';
      } else if (this.hot.sortOrder === false) {
        orderClass = 'descending';
      }
      this.sortOrderClass = orderClass;
    }
  }, {
    key: 'enableObserveChangesPlugin',
    value: function enableObserveChangesPlugin() {
      var _this = this;

      this.hot._registerTimeout(setTimeout(function () {
        _this.hot.updateSettings({
          observeChanges: true
        });
      }, 0));
    }

    /**
     * Default sorting algorithm.
     *
     * @param {Boolean} sortOrder Sorting order - `true` for ascending, `false` for descending.
     * @param {Object} columnMeta Column meta object.
     * @returns {Function} The comparing function.
     */

  }, {
    key: 'defaultSort',
    value: function defaultSort(sortOrder, columnMeta) {
      return function (a, b) {
        if (typeof a[1] == 'string') {
          a[1] = a[1].toLowerCase();
        }
        if (typeof b[1] == 'string') {
          b[1] = b[1].toLowerCase();
        }

        if (a[1] === b[1]) {
          return 0;
        }

        if ((0, _mixed.isEmpty)(a[1])) {
          if ((0, _mixed.isEmpty)(b[1])) {
            return 0;
          }

          if (columnMeta.columnSorting.sortEmptyCells) {
            return sortOrder ? -1 : 1;
          }

          return 1;
        }
        if ((0, _mixed.isEmpty)(b[1])) {
          if ((0, _mixed.isEmpty)(a[1])) {
            return 0;
          }

          if (columnMeta.columnSorting.sortEmptyCells) {
            return sortOrder ? 1 : -1;
          }

          return -1;
        }

        if (isNaN(a[1]) && !isNaN(b[1])) {
          return sortOrder ? 1 : -1;
        } else if (!isNaN(a[1]) && isNaN(b[1])) {
          return sortOrder ? -1 : 1;
        } else if (!(isNaN(a[1]) || isNaN(b[1]))) {
          a[1] = parseFloat(a[1]);
          b[1] = parseFloat(b[1]);
        }
        if (a[1] < b[1]) {
          return sortOrder ? -1 : 1;
        }
        if (a[1] > b[1]) {
          return sortOrder ? 1 : -1;
        }

        return 0;
      };
    }

    /**
     * Date sorting algorithm
     * @param {Boolean} sortOrder Sorting order (`true` for ascending, `false` for descending).
     * @param {Object} columnMeta Column meta object.
     * @returns {Function} The compare function.
     */

  }, {
    key: 'dateSort',
    value: function dateSort(sortOrder, columnMeta) {
      return function (a, b) {
        if (a[1] === b[1]) {
          return 0;
        }

        if ((0, _mixed.isEmpty)(a[1])) {
          if ((0, _mixed.isEmpty)(b[1])) {
            return 0;
          }

          if (columnMeta.columnSorting.sortEmptyCells) {
            return sortOrder ? -1 : 1;
          }

          return 1;
        }

        if ((0, _mixed.isEmpty)(b[1])) {
          if ((0, _mixed.isEmpty)(a[1])) {
            return 0;
          }

          if (columnMeta.columnSorting.sortEmptyCells) {
            return sortOrder ? 1 : -1;
          }

          return -1;
        }

        var aDate = (0, _moment2.default)(a[1], columnMeta.dateFormat);
        var bDate = (0, _moment2.default)(b[1], columnMeta.dateFormat);

        if (!aDate.isValid()) {
          return 1;
        }
        if (!bDate.isValid()) {
          return -1;
        }

        if (bDate.isAfter(aDate)) {
          return sortOrder ? -1 : 1;
        }
        if (bDate.isBefore(aDate)) {
          return sortOrder ? 1 : -1;
        }

        return 0;
      };
    }

    /**
     * Numeric sorting algorithm.
     *
     * @param {Boolean} sortOrder Sorting order (`true` for ascending, `false` for descending).
     * @param {Object} columnMeta Column meta object.
     * @returns {Function} The compare function.
     */

  }, {
    key: 'numericSort',
    value: function numericSort(sortOrder, columnMeta) {
      return function (a, b) {
        var parsedA = parseFloat(a[1]);
        var parsedB = parseFloat(b[1]);

        // Watch out when changing this part of code!
        // Check below returns 0 (as expected) when comparing empty string, null, undefined
        if (parsedA === parsedB || isNaN(parsedA) && isNaN(parsedB)) {
          return 0;
        }

        if (columnMeta.columnSorting.sortEmptyCells) {
          if ((0, _mixed.isEmpty)(a[1])) {
            return sortOrder ? -1 : 1;
          }

          if ((0, _mixed.isEmpty)(b[1])) {
            return sortOrder ? 1 : -1;
          }
        }

        if (isNaN(parsedA)) {
          return 1;
        }

        if (isNaN(parsedB)) {
          return -1;
        }

        if (parsedA < parsedB) {
          return sortOrder ? -1 : 1;
        } else if (parsedA > parsedB) {
          return sortOrder ? 1 : -1;
        }

        return 0;
      };
    }

    /**
     * Perform the sorting.
     */

  }, {
    key: 'sort',
    value: function sort() {
      if (typeof this.hot.sortOrder == 'undefined') {
        this.hot.sortIndex.length = 0;

        return;
      }

      var colMeta = this.hot.getCellMeta(0, this.hot.sortColumn);
      var emptyRows = this.hot.countEmptyRows();
      var sortFunction = void 0;
      var nrOfRows = void 0;

      this.hot.sortingEnabled = false; // this is required by translateRow plugin hook
      this.hot.sortIndex.length = 0;

      if (typeof colMeta.columnSorting.sortEmptyCells === 'undefined') {
        colMeta.columnSorting = { sortEmptyCells: this.sortEmptyCells };
      }

      if (this.hot.getSettings().maxRows === Number.POSITIVE_INFINITY) {
        nrOfRows = this.hot.countRows() - this.hot.getSettings().minSpareRows;
      } else {
        nrOfRows = this.hot.countRows() - emptyRows;
      }

      for (var i = 0, ilen = nrOfRows; i < ilen; i++) {
        this.hot.sortIndex.push([i, this.hot.getDataAtCell(i, this.hot.sortColumn)]);
      }

      if (colMeta.sortFunction) {
        sortFunction = colMeta.sortFunction;
      } else {
        switch (colMeta.type) {
          case 'date':
            sortFunction = this.dateSort;
            break;
          case 'numeric':
            sortFunction = this.numericSort;
            break;
          default:
            sortFunction = this.defaultSort;
        }
      }

      (0, _mergeSort2.default)(this.hot.sortIndex, sortFunction(this.hot.sortOrder, colMeta));

      // Append spareRows
      for (var _i = this.hot.sortIndex.length; _i < this.hot.countRows(); _i++) {
        this.hot.sortIndex.push([_i, this.hot.getDataAtCell(_i, this.hot.sortColumn)]);
      }

      this.hot.sortingEnabled = true; // this is required by translateRow plugin hook
    }

    /**
     * Update indicator states.
     */

  }, {
    key: 'updateSortIndicator',
    value: function updateSortIndicator() {
      if (typeof this.hot.sortOrder == 'undefined') {
        return;
      }
      var colMeta = this.hot.getCellMeta(0, this.hot.sortColumn);

      this.sortIndicators[this.hot.sortColumn] = colMeta.sortIndicator;
    }

    /**
     * `modifyRow` hook callback. Translates physical row index to the sorted row index.
     *
     * @param {Number} row Row index.
     * @returns {Number} Sorted row index.
     */

  }, {
    key: 'translateRow',
    value: function translateRow(row) {
      if (this.hot.sortingEnabled && typeof this.hot.sortOrder !== 'undefined' && this.hot.sortIndex && this.hot.sortIndex.length && this.hot.sortIndex[row]) {
        return this.hot.sortIndex[row][0];
      }

      return row;
    }

    /**
     * Translates sorted row index to physical row index.
     *
     * @param {Number} row Sorted (visual) row index.
     * @returns {number} Physical row index.
     */

  }, {
    key: 'untranslateRow',
    value: function untranslateRow(row) {
      if (this.hot.sortingEnabled && this.hot.sortIndex && this.hot.sortIndex.length) {
        for (var i = 0; i < this.hot.sortIndex.length; i++) {
          if (this.hot.sortIndex[i][0] == row) {
            return i;
          }
        }
      }
    }

    /**
     * `afterGetColHeader` callback. Adds column sorting css classes to clickable headers.
     *
     * @private
     * @param {Number} col Visual column index.
     * @param {Element} TH TH HTML element.
     */

  }, {
    key: 'getColHeader',
    value: function getColHeader(col, TH) {
      if (col < 0 || !TH.parentNode) {
        return false;
      }

      var headerLink = TH.querySelector('.colHeader');
      var colspan = TH.getAttribute('colspan');
      var TRs = TH.parentNode.parentNode.childNodes;
      var headerLevel = Array.prototype.indexOf.call(TRs, TH.parentNode);
      headerLevel -= TRs.length;

      if (!headerLink) {
        return;
      }

      if (this.hot.getSettings().columnSorting && col >= 0 && headerLevel === -1) {
        (0, _element.addClass)(headerLink, 'columnSorting');
      }
      (0, _element.removeClass)(headerLink, 'descending');
      (0, _element.removeClass)(headerLink, 'ascending');

      if (this.sortIndicators[col]) {
        if (col === this.hot.sortColumn) {
          if (this.sortOrderClass === 'ascending') {
            (0, _element.addClass)(headerLink, 'ascending');
          } else if (this.sortOrderClass === 'descending') {
            (0, _element.addClass)(headerLink, 'descending');
          }
        }
      }
    }

    /**
     * Check if any column is in a sorted state.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isSorted',
    value: function isSorted() {
      return typeof this.hot.sortColumn != 'undefined';
    }

    /**
     * `afterCreateRow` callback. Updates the sorting state after a row have been created.
     *
     * @private
     * @param {Number} index Visual row index.
     * @param {Number} amount
     */

  }, {
    key: 'afterCreateRow',
    value: function afterCreateRow(index, amount) {
      if (!this.isSorted()) {
        return;
      }

      for (var i = 0; i < this.hot.sortIndex.length; i++) {
        if (this.hot.sortIndex[i][0] >= index) {
          this.hot.sortIndex[i][0] += amount;
        }
      }

      for (var _i2 = 0; _i2 < amount; _i2++) {
        this.hot.sortIndex.splice(index + _i2, 0, [index + _i2, this.hot.getSourceData()[index + _i2][this.hot.sortColumn + this.hot.colOffset()]]);
      }

      this.saveSortingState();
    }

    /**
     * `afterRemoveRow` hook callback.
     *
     * @private
     * @param {Number} index Visual row index.
     * @param {Number} amount
     */

  }, {
    key: 'afterRemoveRow',
    value: function afterRemoveRow(index, amount) {
      if (!this.isSorted()) {
        return;
      }
      var removedRows = this.hot.sortIndex.splice(index, amount);

      removedRows = (0, _array.arrayMap)(removedRows, function (row) {
        return row[0];
      });

      function countRowShift(logicalRow) {
        // Todo: compare perf between reduce vs sort->each->brake
        return (0, _array.arrayReduce)(removedRows, function (count, removedLogicalRow) {
          if (logicalRow > removedLogicalRow) {
            count++;
          }

          return count;
        }, 0);
      }

      this.hot.sortIndex = (0, _array.arrayMap)(this.hot.sortIndex, function (logicalRow, physicalRow) {
        var rowShift = countRowShift(logicalRow[0]);

        if (rowShift) {
          logicalRow[0] -= rowShift;
        }

        return logicalRow;
      });

      this.saveSortingState();
    }

    /**
     * Set options by passed settings
     *
     * @private
     */

  }, {
    key: 'setPluginOptions',
    value: function setPluginOptions() {
      var columnSorting = this.hot.getSettings().columnSorting;

      if ((typeof columnSorting === 'undefined' ? 'undefined' : _typeof(columnSorting)) === 'object') {
        this.sortEmptyCells = columnSorting.sortEmptyCells || false;
      } else {
        this.sortEmptyCells = false;
      }
    }

    /**
     * `onAfterOnCellMouseDown` hook callback.
     *
     * @private
     * @param {Event} event Event which are provided by hook.
     * @param {CellCoords} coords Visual coords of the selected cell.
     */

  }, {
    key: 'onAfterOnCellMouseDown',
    value: function onAfterOnCellMouseDown(event, coords) {
      if (coords.row > -1) {
        return;
      }

      if ((0, _element.hasClass)(event.realTarget, 'columnSorting')) {
        // reset order state on every new column header click
        if (coords.col !== this.lastSortedColumn) {
          this.hot.sortOrder = true;
        }

        this.lastSortedColumn = coords.col;

        this.sortByColumn(coords.col);
      }
    }
  }]);

  return ColumnSorting;
}(_base2.default);

(0, _plugins.registerPlugin)('columnSorting', ColumnSorting);

exports.default = ColumnSorting;

/***/ }),
/* 394 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = mergeSort;
exports.merge = merge;

var _linkedList = __webpack_require__(395);

var _linkedList2 = _interopRequireDefault(_linkedList);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Refactored implementation of mergeSort (part of javascript-algorithms project) by Github users:
 * mgechev, AndriiHeonia and lekkas (part of javascript-algorithms project - all project contributors
 * at repository website)
 *
 * Link to repository: https://github.com/mgechev/javascript-algorithms
 */

/**
 * Specifies a function that defines the sort order. The array is sorted according to each
 * character's Unicode code point value, according to the string conversion of each element.
 *
 * @param a {*} first compared element.
 * @param b {*} second compared element.
 * @returns {Number}
 */
var defaultCompareFunction = function defaultCompareFunction(a, b) {
  // sort lexically

  var firstValue = a.toString();
  var secondValue = b.toString();

  if (firstValue === secondValue) {
    return 0;
  } else if (firstValue < secondValue) {
    return -1;
  }
  return 1;
};

/**
 * Mergesort method which is recursively called for sorting the input array.
 *
 * @param {Array} array The array which should be sorted.
 * @param {Function} compareFunction Compares two items in an array. If compareFunction is not supplied,
 * elements are sorted by converting them to strings and comparing strings in Unicode code point order.
 * @param {Number} startIndex Left side of the subarray.
 * @param {Number} endIndex Right side of the subarray.
 * @returns {Array} Array with sorted subarray.
 */
function mergeSort(array) {
  var compareFunction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultCompareFunction;
  var startIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  var endIndex = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : array.length;

  if (Math.abs(endIndex - startIndex) <= 1) {
    return [];
  }

  var middleIndex = Math.ceil((startIndex + endIndex) / 2);

  mergeSort(array, compareFunction, startIndex, middleIndex);
  mergeSort(array, compareFunction, middleIndex, endIndex);

  return merge(array, compareFunction, startIndex, middleIndex, endIndex);
}

/**
 * Devides and sort merges two subarrays of given array
 *
 * @param {Array} array The array which subarrays should be sorted.
 * @param {Number} startIndex The start of the first subarray.
 *   This subarray is with end middle - 1.
 * @param {Number} middleIndex The start of the second array.
 * @param {Number} endIndex end - 1 is the end of the second array.
 * @returns {Array} The array with sorted subarray.
 */
function merge(array, compareFunction, startIndex, middleIndex, endIndex) {
  var leftElements = new _linkedList2.default();
  var rightElements = new _linkedList2.default();
  var leftSize = middleIndex - startIndex;
  var rightSize = endIndex - middleIndex;
  var maxSize = Math.max(leftSize, rightSize);
  var size = endIndex - startIndex;

  for (var _i = 0; _i < maxSize; _i += 1) {
    if (_i < leftSize) {
      leftElements.push(array[startIndex + _i]);
    }

    if (_i < rightSize) {
      rightElements.push(array[middleIndex + _i]);
    }
  }

  var i = 0;

  while (i < size) {
    if (leftElements.first && rightElements.first) {
      if (compareFunction(leftElements.first.data, rightElements.first.data) > 0) {
        array[startIndex + i] = rightElements.shift().data;
      } else {
        array[startIndex + i] = leftElements.shift().data;
      }
    } else if (leftElements.first) {

      array[startIndex + i] = leftElements.shift().data;
    } else {

      array[startIndex + i] = rightElements.shift().data;
    }

    i += 1;
  }

  return array;
};

/***/ }),
/* 395 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Refactored implementation of LinkedList (part of javascript-algorithms project) by Github users:
 * mgechev, AndriiHeonia, Microfed and Jakeh (part of javascript-algorithms project - all project contributors
 * at repository website)
 *
 * Link to repository: https://github.com/mgechev/javascript-algorithms
 */

/**
 * Linked list node.
 *
 * @class NodeStructure
 * @util
 */
var NodeStructure = function NodeStructure(data) {
  _classCallCheck(this, NodeStructure);

  /**
   * Data of the node.
   * @member {Object}
   */
  this.data = data;
  /**
   * Next node.
   * @member {NodeStructure}
   */
  this.next = null;
  /**
   * Previous node.
   * @member {NodeStructure}
   */
  this.prev = null;
};

/**
 * Linked list.
 *
 * @class LinkedList
 * @util
 */


var LinkedList = function () {
  function LinkedList() {
    _classCallCheck(this, LinkedList);

    this.first = null;
    this.last = null;
  }

  /**
   * Add data to the end of linked list.
   *
   * @param {Object} data Data which should be added.
   */


  _createClass(LinkedList, [{
    key: "push",
    value: function push(data) {
      var node = new NodeStructure(data);

      if (this.first === null) {
        this.first = node;
        this.last = node;
      } else {
        var temp = this.last;

        this.last = node;
        node.prev = temp;
        temp.next = node;
      }
    }

    /**
     * Add data to the beginning of linked list.
     *
     * @param {Object} data Data which should be added.
     */

  }, {
    key: "unshift",
    value: function unshift(data) {
      var node = new NodeStructure(data);

      if (this.first === null) {
        this.first = node;
        this.last = node;
      } else {
        var temp = this.first;

        this.first = node;
        node.next = temp;
        temp.prev = node;
      }
    }

    /**
     * In order traversal of the linked list.
     *
     * @param {Function} callback Callback which should be executed on each node.
     */

  }, {
    key: "inorder",
    value: function inorder(callback) {
      var temp = this.first;

      while (temp) {
        callback(temp);
        temp = temp.next;
      }
    }

    /**
     * Remove data from the linked list.
     *
     * @param {Object} data Data which should be removed.
     * @returns {Boolean} Returns true if data has been removed.
     */

  }, {
    key: "remove",
    value: function remove(data) {
      if (this.first === null) {
        return false;
      }

      var temp = this.first;
      var next = void 0;
      var prev = void 0;

      while (temp) {
        if (temp.data === data) {
          next = temp.next;
          prev = temp.prev;

          if (next) {
            next.prev = prev;
          }

          if (prev) {
            prev.next = next;
          }

          if (temp === this.first) {
            this.first = next;
          }

          if (temp === this.last) {
            this.last = prev;
          }

          return true;
        }

        temp = temp.next;
      }

      return false;
    }

    /**
     * Check if linked list contains cycle.
     *
     * @returns {Boolean} Returns true if linked list contains cycle.
     */

  }, {
    key: "hasCycle",
    value: function hasCycle() {
      var fast = this.first;
      var slow = this.first;

      while (true) {
        if (fast === null) {
          return false;
        }

        fast = fast.next;

        if (fast === null) {
          return false;
        }

        fast = fast.next;
        slow = slow.next;

        if (fast === slow) {
          return true;
        }
      }
    }
  }, {
    key: "pop",


    /**
     * Return last node from the linked list.
     *
     * @returns {NodeStructure} Last node.
     */
    value: function pop() {
      if (this.last === null) {
        return null;
      }

      var temp = this.last;
      this.last = this.last.prev;

      return temp;
    }
  }, {
    key: "shift",


    /**
     * Return first node from the linked list.
     *
     * @returns {NodeStructure} First node.
     */
    value: function shift() {
      if (this.first === null) {
        return null;
      }

      var temp = this.first;
      this.first = this.first.next;

      return temp;
    }
  }, {
    key: "recursiveReverse",


    /**
     * Reverses the linked list recursively
     */
    value: function recursiveReverse() {
      function inverse(current, next) {
        if (!next) {
          return;
        }
        inverse(next, next.next);
        next.next = current;
      }

      if (!this.first) {
        return;
      }

      inverse(this.first, this.first.next);

      this.first.next = null;
      var temp = this.first;
      this.first = this.last;
      this.last = temp;
    }
  }, {
    key: "reverse",


    /**
     * Reverses the linked list iteratively
     */
    value: function reverse() {
      if (!this.first || !this.first.next) {
        return;
      }

      var current = this.first.next;
      var prev = this.first;
      var temp = void 0;

      while (current) {
        temp = current.next;
        current.next = prev;
        prev.prev = current;
        prev = current;
        current = temp;
      }

      this.first.next = null;
      this.last.prev = null;
      temp = this.first;
      this.first = prev;
      this.last = temp;
    }
  }]);

  return LinkedList;
}();

;

exports.NodeStructure = NodeStructure;
exports.default = LinkedList;

/***/ }),
/* 396 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _element = __webpack_require__(0);

var _object = __webpack_require__(1);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _src = __webpack_require__(15);

var _plugins = __webpack_require__(7);

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _commentEditor = __webpack_require__(397);

var _commentEditor2 = _interopRequireDefault(_commentEditor);

var _utils = __webpack_require__(21);

var _displaySwitch = __webpack_require__(398);

var _displaySwitch2 = _interopRequireDefault(_displaySwitch);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

__webpack_require__(399);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var privatePool = new WeakMap();
var META_COMMENT = 'comment';
var META_COMMENT_VALUE = 'value';
var META_STYLE = 'style';
var META_READONLY = 'readOnly';

/**
 * @plugin Comments
 *
 * @description
 * This plugin allows setting and managing cell comments by either an option in the context menu or with the use of the API.
 *
 * To enable the plugin, you'll need to set the comments property of the config object to `true`:
 * ```js
 * ...
 * comments: true
 * ...
 * ```
 *
 * or object with extra predefined plugin config:
 *
 * ```js
 * ...
 * comments: {
 *   displayDelay: 1000
 * }
 * ...
 * ```
 *
 * To add comments at the table initialization, define the `comment` property in the `cell` config array as in an example below.
 *
 * @example
 *
 * ```js
 * ...
 * var hot = new Handsontable(document.getElementById('example'), {
 *   date: getData(),
 *   comments: true,
 *   cell: [
 *     {row: 1, col: 1, comment: {value: 'Foo'}},
 *     {row: 2, col: 2, comment: {value: 'Bar'}}
 *   ]
 * });
 *
 * // Access to the Comments plugin instance:
 * var commentsPlugin = hot.getPlugin('comments');
 *
 * // Manage comments programmatically:
 * commentsPlugin.setCommentAtCell(1, 6, 'Comment contents');
 * commentsPlugin.showAtCell(1, 6);
 * commentsPlugin.removeCommentAtCell(1, 6);
 *
 * // You can also set range once and use proper methods:
 * commentsPlugin.setRange({row: 1, col: 6});
 * commentsPlugin.setComment('Comment contents');
 * commentsPlugin.show();
 * commentsPlugin.removeComment();
 * ...
 * ```
 */

var Comments = function (_BasePlugin) {
  _inherits(Comments, _BasePlugin);

  function Comments(hotInstance) {
    _classCallCheck(this, Comments);

    /**
     * Instance of {@link CommentEditor}.
     *
     * @type {CommentEditor}
     */
    var _this = _possibleConstructorReturn(this, (Comments.__proto__ || Object.getPrototypeOf(Comments)).call(this, hotInstance));

    _this.editor = null;
    /**
     * Instance of {@link DisplaySwitch}.
     *
     * @type {DisplaySwitch}
     */
    _this.displaySwitch = null;
    /**
     * Instance of {@link EventManager}.
     *
     * @private
     * @type {EventManager}
     */
    _this.eventManager = null;
    /**
     * Current cell range.
     *
     * @type {Object}
     */
    _this.range = {};
    /**
     * @private
     * @type {Boolean}
     */
    _this.mouseDown = false;
    /**
     * @private
     * @type {Boolean}
     */
    _this.contextMenuEvent = false;
    /**
     * @private
     * @type {*}
     */
    _this.timer = null;

    privatePool.set(_this, {
      tempEditorDimensions: {},
      cellBelowCursor: null
    });
    return _this;
  }

  /**
   * Check if the plugin is enabled in the Handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(Comments, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return !!this.hot.getSettings().comments;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      if (!this.editor) {
        this.editor = new _commentEditor2.default();
      }

      if (!this.eventManager) {
        this.eventManager = new _eventManager2.default(this);
      }

      if (!this.displaySwitch) {
        this.displaySwitch = new _displaySwitch2.default(this.getDisplayDelaySetting());
      }

      this.addHook('afterContextMenuDefaultOptions', function (options) {
        return _this2.addToContextMenu(options);
      });
      this.addHook('afterRenderer', function (TD, row, col, prop, value, cellProperties) {
        return _this2.onAfterRenderer(TD, cellProperties);
      });
      this.addHook('afterScrollHorizontally', function () {
        return _this2.hide();
      });
      this.addHook('afterScrollVertically', function () {
        return _this2.hide();
      });
      this.addHook('afterBeginEditing', function (args) {
        return _this2.onAfterBeginEditing(args);
      });

      this.displaySwitch.addLocalHook('hide', function () {
        return _this2.hide();
      });
      this.displaySwitch.addLocalHook('show', function (row, col) {
        return _this2.showAtCell(row, col);
      });

      this.registerListeners();

      _get(Comments.prototype.__proto__ || Object.getPrototypeOf(Comments.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Update plugin for this Handsontable instance.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();
      _get(Comments.prototype.__proto__ || Object.getPrototypeOf(Comments.prototype), 'updatePlugin', this).call(this);

      this.displaySwitch.updateDelay(this.getDisplayDelaySetting());
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      _get(Comments.prototype.__proto__ || Object.getPrototypeOf(Comments.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Register all necessary DOM listeners.
     *
     * @private
     */

  }, {
    key: 'registerListeners',
    value: function registerListeners() {
      var _this3 = this;

      this.eventManager.addEventListener(document, 'mouseover', function (event) {
        return _this3.onMouseOver(event);
      });
      this.eventManager.addEventListener(document, 'mousedown', function (event) {
        return _this3.onMouseDown(event);
      });
      this.eventManager.addEventListener(document, 'mouseup', function (event) {
        return _this3.onMouseUp(event);
      });
      this.eventManager.addEventListener(this.editor.getInputElement(), 'blur', function (event) {
        return _this3.onEditorBlur(event);
      });
      this.eventManager.addEventListener(this.editor.getInputElement(), 'mousedown', function (event) {
        return _this3.onEditorMouseDown(event);
      });
      this.eventManager.addEventListener(this.editor.getInputElement(), 'mouseup', function (event) {
        return _this3.onEditorMouseUp(event);
      });
    }

    /**
     * Set current cell range to be able to use general methods like {@link Comments#setComment},
     * {@link Comments#removeComment}, {@link Comments#show}.
     *
     * @param {Object} range Object with `from` and `to` properties, each with `row` and `col` properties.
     */

  }, {
    key: 'setRange',
    value: function setRange(range) {
      this.range = range;
    }

    /**
     * Clear the currently selected cell.
     */

  }, {
    key: 'clearRange',
    value: function clearRange() {
      this.range = {};
    }

    /**
     * Check if the event target is a cell containing a comment.
     *
     * @param {Event} event DOM event
     * @returns {Boolean}
     */

  }, {
    key: 'targetIsCellWithComment',
    value: function targetIsCellWithComment(event) {
      var closestCell = (0, _element.closest)(event.target, 'TD', 'TBODY');

      return !!(closestCell && (0, _element.hasClass)(closestCell, 'htCommentCell') && (0, _element.closest)(closestCell, [this.hot.rootElement]));
    }

    /**
     * Check if the event target is a comment textarea.
     *
     * @param {Event} event DOM event.
     * @returns {Boolean}
     */

  }, {
    key: 'targetIsCommentTextArea',
    value: function targetIsCommentTextArea(event) {
      return this.editor.getInputElement() === event.target;
    }

    /**
     * Set a comment for a cell according to the previously set range (see {@link Comments#setRange}).
     *
     * @param {String} value Comment contents.
     */

  }, {
    key: 'setComment',
    value: function setComment(value) {
      if (!this.range.from) {
        throw new Error('Before using this method, first set cell range (hot.getPlugin("comment").setRange())');
      }
      var editorValue = this.editor.getValue();
      var comment = '';

      if (value != null) {
        comment = value;
      } else if (editorValue != null) {
        comment = editorValue;
      }

      var row = this.range.from.row;
      var col = this.range.from.col;

      this.updateCommentMeta(row, col, _defineProperty({}, META_COMMENT_VALUE, comment));
      this.hot.render();
    }

    /**
     * Set a comment for a cell.
     *
     * @param {Number} row Visual row index.
     * @param {Number} col Visual column index.
     * @param {String} value Comment contents.
     */

  }, {
    key: 'setCommentAtCell',
    value: function setCommentAtCell(row, col, value) {
      this.setRange({
        from: new _src.CellCoords(row, col)
      });
      this.setComment(value);
    }

    /**
     * Remove a comment from a cell according to previously set range (see {@link Comments#setRange}).
     *
     * @param {Boolean} [forceRender = true] If set to `true`, the table will be re-rendered at the end of the operation.
     */

  }, {
    key: 'removeComment',
    value: function removeComment() {
      var forceRender = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

      if (!this.range.from) {
        throw new Error('Before using this method, first set cell range (hot.getPlugin("comment").setRange())');
      }

      this.hot.setCellMeta(this.range.from.row, this.range.from.col, META_COMMENT, void 0);

      if (forceRender) {
        this.hot.render();
      }

      this.hide();
    }

    /**
     * Remove comment from a cell.
     *
     * @param {Number} row Visual row index.
     * @param {Number} col Visual column index.
     * @param {Boolean} [forceRender = true] If `true`, the table will be re-rendered at the end of the operation.
     */

  }, {
    key: 'removeCommentAtCell',
    value: function removeCommentAtCell(row, col) {
      var forceRender = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

      this.setRange({
        from: new _src.CellCoords(row, col)
      });
      this.removeComment(forceRender);
    }

    /**
     * Get comment from a cell at the predefined range.
     */

  }, {
    key: 'getComment',
    value: function getComment() {
      var row = this.range.from.row;
      var column = this.range.from.col;

      return this.getCommentMeta(row, column, META_COMMENT_VALUE);
    }

    /**
     * Get comment from a cell at the provided coordinates.
     *
     * @param {Number} row Visual row index.
     * @param {Number} column Visual column index.
     */

  }, {
    key: 'getCommentAtCell',
    value: function getCommentAtCell(row, column) {
      return this.getCommentMeta(row, column, META_COMMENT_VALUE);
    }

    /**
     * Show the comment editor accordingly to the previously set range (see {@link Comments#setRange}).
     *
     * @returns {Boolean} Returns `true` if comment editor was shown.
     */

  }, {
    key: 'show',
    value: function show() {
      if (!this.range.from) {
        throw new Error('Before using this method, first set cell range (hot.getPlugin("comment").setRange())');
      }
      var meta = this.hot.getCellMeta(this.range.from.row, this.range.from.col);

      this.refreshEditor(true);
      this.editor.setValue(meta[META_COMMENT] ? meta[META_COMMENT][META_COMMENT_VALUE] : null || '');

      if (this.editor.hidden) {
        this.editor.show();
      }

      return true;
    }

    /**
     * Show comment editor according to cell coordinates.
     *
     * @param {Number} row Visual row index.
     * @param {Number} col Visual column index.
     * @returns {Boolean} Returns `true` if comment editor was shown.
     */

  }, {
    key: 'showAtCell',
    value: function showAtCell(row, col) {
      this.setRange({
        from: new _src.CellCoords(row, col)
      });

      return this.show();
    }

    /**
     * Hide the comment editor.
     */

  }, {
    key: 'hide',
    value: function hide() {
      if (!this.editor.hidden) {
        this.editor.hide();
      }
    }

    /**
     * Refresh comment editor position and styling.
     *
     * @param {Boolean} [force=false] If `true` then recalculation will be forced.
     */

  }, {
    key: 'refreshEditor',
    value: function refreshEditor() {
      var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (!force && (!this.range.from || !this.editor.isVisible())) {
        return;
      }
      var scrollableElement = (0, _element.getScrollableElement)(this.hot.view.wt.wtTable.TABLE);
      var TD = this.hot.view.wt.wtTable.getCell(this.range.from);
      var row = this.range.from.row;
      var column = this.range.from.col;
      var cellOffset = (0, _element.offset)(TD);
      var lastColWidth = this.hot.view.wt.wtTable.getStretchedColumnWidth(column);
      var cellTopOffset = cellOffset.top < 0 ? 0 : cellOffset.top;
      var cellLeftOffset = cellOffset.left;

      if (this.hot.view.wt.wtViewport.hasVerticalScroll() && scrollableElement !== window) {
        cellTopOffset -= this.hot.view.wt.wtOverlays.topOverlay.getScrollPosition();
      }

      if (this.hot.view.wt.wtViewport.hasHorizontalScroll() && scrollableElement !== window) {
        cellLeftOffset -= this.hot.view.wt.wtOverlays.leftOverlay.getScrollPosition();
      }

      var x = cellLeftOffset + lastColWidth;
      var y = cellTopOffset;

      var commentStyle = this.getCommentMeta(row, column, META_STYLE);
      var readOnly = this.getCommentMeta(row, column, META_READONLY);

      if (commentStyle) {
        this.editor.setSize(commentStyle.width, commentStyle.height);
      } else {
        this.editor.resetSize();
      }

      this.editor.setReadOnlyState(readOnly);

      this.editor.setPosition(x, y);
    }

    /**
     * Check if there is a comment for selected range.
     *
     * @private
     * @returns {Boolean}
     */

  }, {
    key: 'checkSelectionCommentsConsistency',
    value: function checkSelectionCommentsConsistency() {
      var selected = this.hot.getSelectedRange();

      if (!selected) {
        return false;
      }
      var hasComment = false;
      var cell = selected.from; // IN EXCEL THERE IS COMMENT ONLY FOR TOP LEFT CELL IN SELECTION

      if (this.getCommentMeta(cell.row, cell.col, META_COMMENT_VALUE)) {
        hasComment = true;
      }

      return hasComment;
    }

    /**
     * Set or update the comment-related cell meta.
     *
     * @param {Number} row Visual row index.
     * @param {Number} column Visual column index.
     * @param {Object} metaObject Object defining all the comment-related meta information.
     */

  }, {
    key: 'updateCommentMeta',
    value: function updateCommentMeta(row, column, metaObject) {
      var oldComment = this.hot.getCellMeta(row, column)[META_COMMENT];
      var newComment = void 0;

      if (oldComment) {
        newComment = (0, _object.deepClone)(oldComment);
        (0, _object.deepExtend)(newComment, metaObject);
      } else {
        newComment = metaObject;
      }

      this.hot.setCellMeta(row, column, META_COMMENT, newComment);
    }

    /**
     * Get the comment related meta information.
     *
     * @param {Number} row Visual row index.
     * @param {Number} column Visual column index.
     * @param {String} property Cell meta property.
     * @returns {Mixed}
     */

  }, {
    key: 'getCommentMeta',
    value: function getCommentMeta(row, column, property) {
      var cellMeta = this.hot.getCellMeta(row, column);

      if (!cellMeta[META_COMMENT]) {
        return void 0;
      }

      return cellMeta[META_COMMENT][property];
    }

    /**
     * `mousedown` event callback.
     *
     * @private
     * @param {MouseEvent} event The `mousedown` event.
     */

  }, {
    key: 'onMouseDown',
    value: function onMouseDown(event) {
      this.mouseDown = true;

      if (!this.hot.view || !this.hot.view.wt) {
        return;
      }

      if (!this.contextMenuEvent && !this.targetIsCommentTextArea(event)) {
        var eventCell = (0, _element.closest)(event.target, 'TD', 'TBODY');
        var coordinates = null;

        if (eventCell) {
          coordinates = this.hot.view.wt.wtTable.getCoords(eventCell);
        }

        if (!eventCell || this.range.from && coordinates && (this.range.from.row !== coordinates.row || this.range.from.col !== coordinates.col)) {
          this.hide();
        }
      }
      this.contextMenuEvent = false;
    }

    /**
     * `mouseover` event callback.
     *
     * @private
     * @param {MouseEvent} event The `mouseover` event.
     */

  }, {
    key: 'onMouseOver',
    value: function onMouseOver(event) {
      var priv = privatePool.get(this);

      priv.cellBelowCursor = document.elementFromPoint(event.clientX, event.clientY);

      if (this.mouseDown || this.editor.isFocused() || (0, _element.hasClass)(event.target, 'wtBorder') || priv.cellBelowCursor !== event.target || !this.editor) {
        return;
      }

      if (this.targetIsCellWithComment(event)) {
        var coordinates = this.hot.view.wt.wtTable.getCoords(event.target);
        var range = {
          from: new _src.CellCoords(coordinates.row, coordinates.col)
        };

        this.displaySwitch.show(range);
      } else if ((0, _element.isChildOf)(event.target, document) && !this.targetIsCommentTextArea(event)) {
        this.displaySwitch.hide();
      }
    }

    /**
     * `mouseup` event callback.
     *
     * @private
     * @param {MouseEvent} event The `mouseup` event.
     */

  }, {
    key: 'onMouseUp',
    value: function onMouseUp(event) {
      this.mouseDown = false;
    }

    /** *
     * The `afterRenderer` hook callback..
     *
     * @private
     * @param {HTMLTableCellElement} TD The rendered `TD` element.
     * @param {Object} cellProperties The rendered cell's property object.
     */

  }, {
    key: 'onAfterRenderer',
    value: function onAfterRenderer(TD, cellProperties) {
      if (cellProperties[META_COMMENT] && cellProperties[META_COMMENT][META_COMMENT_VALUE]) {
        (0, _element.addClass)(TD, cellProperties.commentedCellClassName);
      }
    }

    /**
     * `blur` event callback for the comment editor.
     *
     * @private
     * @param {Event} event The `blur` event.
     */

  }, {
    key: 'onEditorBlur',
    value: function onEditorBlur(event) {
      this.setComment();
    }

    /**
     * `mousedown` hook. Along with `onEditorMouseUp` used to simulate the textarea resizing event.
     *
     * @private
     * @param {MouseEvent} event The `mousedown` event.
     */

  }, {
    key: 'onEditorMouseDown',
    value: function onEditorMouseDown(event) {
      var priv = privatePool.get(this);

      priv.tempEditorDimensions = {
        width: (0, _element.outerWidth)(event.target),
        height: (0, _element.outerHeight)(event.target)
      };
    }

    /**
     * `mouseup` hook. Along with `onEditorMouseDown` used to simulate the textarea resizing event.
     *
     * @private
     * @param {MouseEvent} event The `mouseup` event.
     */

  }, {
    key: 'onEditorMouseUp',
    value: function onEditorMouseUp(event) {
      var priv = privatePool.get(this);
      var currentWidth = (0, _element.outerWidth)(event.target);
      var currentHeight = (0, _element.outerHeight)(event.target);

      if (currentWidth !== priv.tempEditorDimensions.width + 1 || currentHeight !== priv.tempEditorDimensions.height + 2) {
        this.updateCommentMeta(this.range.from.row, this.range.from.col, _defineProperty({}, META_STYLE, {
          width: currentWidth,
          height: currentHeight
        }));
      }
    }

    /**
     * Context Menu's "Add comment" callback. Results in showing the comment editor.
     *
     * @private
     */

  }, {
    key: 'onContextMenuAddComment',
    value: function onContextMenuAddComment() {
      var _this4 = this;

      this.displaySwitch.cancelHiding();
      var coords = this.hot.getSelectedRange();

      this.contextMenuEvent = true;
      this.setRange({
        from: coords.from
      });
      this.show();
      setTimeout(function () {
        if (_this4.hot) {
          _this4.hot.deselectCell();
          _this4.editor.focus();
        }
      }, 10);
    }

    /**
     * Context Menu's "remove comment" callback.
     *
     * @private
     * @param {Object} selection The current selection.
     */

  }, {
    key: 'onContextMenuRemoveComment',
    value: function onContextMenuRemoveComment(selection) {
      this.contextMenuEvent = true;

      for (var i = selection.start.row; i <= selection.end.row; i++) {
        for (var j = selection.start.col; j <= selection.end.col; j++) {
          this.removeCommentAtCell(i, j, false);
        }
      }

      this.hot.render();
    }

    /**
     * Context Menu's "make comment read-only" callback.
     *
     * @private
     * @param {Object} selection The current selection.
     */

  }, {
    key: 'onContextMenuMakeReadOnly',
    value: function onContextMenuMakeReadOnly(selection) {
      this.contextMenuEvent = true;

      for (var i = selection.start.row; i <= selection.end.row; i++) {
        for (var j = selection.start.col; j <= selection.end.col; j++) {
          var currentState = !!this.getCommentMeta(i, j, META_READONLY);

          this.updateCommentMeta(i, j, _defineProperty({}, META_READONLY, !currentState));
        }
      }
    }

    /**
     * Add Comments plugin options to the Context Menu.
     *
     * @private
     * @param {Object} defaultOptions
     */

  }, {
    key: 'addToContextMenu',
    value: function addToContextMenu(defaultOptions) {
      var _this5 = this;

      defaultOptions.items.push({
        name: '---------'
      }, {
        key: 'commentsAddEdit',
        name: function name() {
          if (_this5.checkSelectionCommentsConsistency()) {
            return _this5.hot.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_EDIT_COMMENT);
          }

          return _this5.hot.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ADD_COMMENT);
        },
        callback: function callback() {
          return _this5.onContextMenuAddComment();
        },
        disabled: function disabled() {
          return !(this.getSelected() && !this.selection.selectedHeader.corner);
        }
      }, {
        key: 'commentsRemove',
        name: function name() {
          return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_REMOVE_COMMENT);
        },

        callback: function callback(key, selection) {
          return _this5.onContextMenuRemoveComment(selection);
        },
        disabled: function disabled() {
          return _this5.hot.selection.selectedHeader.corner;
        }
      }, {
        key: 'commentsReadOnly',
        name: function name() {
          var _this6 = this;

          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_READ_ONLY_COMMENT);
          var hasProperty = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
            var readOnlyProperty = _this6.getCellMeta(row, col)[META_COMMENT];
            if (readOnlyProperty) {
              readOnlyProperty = readOnlyProperty[META_READONLY];
            }

            if (readOnlyProperty) {
              return true;
            }
          });

          if (hasProperty) {
            label = (0, _utils.markLabelAsSelected)(label);
          }

          return label;
        },

        callback: function callback(key, selection) {
          return _this5.onContextMenuMakeReadOnly(selection);
        },
        disabled: function disabled() {
          return _this5.hot.selection.selectedHeader.corner || !_this5.checkSelectionCommentsConsistency();
        }
      });
    }

    /**
     * Get `displayDelay` setting of comment plugin.
     *
     * @returns {Number|undefined}
     */

  }, {
    key: 'getDisplayDelaySetting',
    value: function getDisplayDelaySetting() {
      var commentSetting = this.hot.getSettings().comments;

      if ((0, _object.isObject)(commentSetting)) {
        return commentSetting.displayDelay;
      }

      return void 0;
    }

    /**
     * `afterBeginEditing` hook callback.
     *
     * @private
     * @param {Number} row Visual row index of the currently edited cell.
     * @param {Number} column Visual column index of the currently edited cell.
     */

  }, {
    key: 'onAfterBeginEditing',
    value: function onAfterBeginEditing(row, column) {
      this.hide();
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      if (this.editor) {
        this.editor.destroy();
      }

      if (this.displaySwitch) {
        this.displaySwitch.destroy();
      }

      _get(Comments.prototype.__proto__ || Object.getPrototypeOf(Comments.prototype), 'destroy', this).call(this);
    }
  }]);

  return Comments;
}(_base2.default);

(0, _plugins.registerPlugin)('comments', Comments);

exports.default = Comments;

/***/ }),
/* 397 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Comment editor for the Comments plugin.
 *
 * @class CommentEditor
 * @plugin Comments
 */
var CommentEditor = function () {
  _createClass(CommentEditor, null, [{
    key: 'CLASS_EDITOR_CONTAINER',
    get: function get() {
      return 'htCommentsContainer';
    }
  }, {
    key: 'CLASS_EDITOR',
    get: function get() {
      return 'htComments';
    }
  }, {
    key: 'CLASS_INPUT',
    get: function get() {
      return 'htCommentTextArea';
    }
  }, {
    key: 'CLASS_CELL',
    get: function get() {
      return 'htCommentCell';
    }
  }]);

  function CommentEditor() {
    _classCallCheck(this, CommentEditor);

    this.editor = this.createEditor();
    this.editorStyle = this.editor.style;

    this.hidden = true;

    this.hide();
  }

  /**
   * Set position of the comments editor according to the  provided x and y coordinates.
   *
   * @param {Number} x X position (in pixels).
   * @param {Number} y Y position (in pixels).
   */


  _createClass(CommentEditor, [{
    key: 'setPosition',
    value: function setPosition(x, y) {
      this.editorStyle.left = x + 'px';
      this.editorStyle.top = y + 'px';
    }

    /**
     * Set the editor size according to the provided arguments.
     *
     * @param {Number} width Width in pixels.
     * @param {Number} height Height in pixels.
     */

  }, {
    key: 'setSize',
    value: function setSize(width, height) {
      if (width && height) {
        var input = this.getInputElement();

        input.style.width = width + 'px';
        input.style.height = height + 'px';
      }
    }

    /**
     * Reset the editor size to its initial state.
     */

  }, {
    key: 'resetSize',
    value: function resetSize() {
      var input = this.getInputElement();

      input.style.width = '';
      input.style.height = '';
    }

    /**
     * Set the read-only state for the comments editor.
     *
     * @param {Boolean} state The new read only state.
     */

  }, {
    key: 'setReadOnlyState',
    value: function setReadOnlyState(state) {
      var input = this.getInputElement();

      input.readOnly = state;
    }

    /**
     * Show the comments editor.
     */

  }, {
    key: 'show',
    value: function show() {
      this.editorStyle.display = 'block';
      this.hidden = false;
    }

    /**
     * Hide the comments editor.
     */

  }, {
    key: 'hide',
    value: function hide() {
      this.editorStyle.display = 'none';
      this.hidden = true;
    }

    /**
     * Checks if the editor is visible.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isVisible',
    value: function isVisible() {
      return this.editorStyle.display === 'block';
    }

    /**
     * Set the comment value.
     *
     * @param {String} [value] The value to use.
     */

  }, {
    key: 'setValue',
    value: function setValue() {
      var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

      value = value || '';
      this.getInputElement().value = value;
    }

    /**
     * Get the comment value.
     *
     * @returns {String}
     */

  }, {
    key: 'getValue',
    value: function getValue() {
      return this.getInputElement().value;
    }

    /**
     * Checks if the comment input element is focused.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isFocused',
    value: function isFocused() {
      return document.activeElement === this.getInputElement();
    }

    /**
     * Focus the comments input element.
     */

  }, {
    key: 'focus',
    value: function focus() {
      this.getInputElement().focus();
    }

    /**
     * Create the `textarea` to be used as a comments editor.
     *
     * @returns {HTMLElement}
     */

  }, {
    key: 'createEditor',
    value: function createEditor() {
      var container = document.querySelector('.' + CommentEditor.CLASS_EDITOR_CONTAINER);
      var editor = void 0;
      var textArea = void 0;

      if (!container) {
        container = document.createElement('div');
        (0, _element.addClass)(container, CommentEditor.CLASS_EDITOR_CONTAINER);
        document.body.appendChild(container);
      }
      editor = document.createElement('div');
      (0, _element.addClass)(editor, CommentEditor.CLASS_EDITOR);

      textArea = document.createElement('textarea');
      (0, _element.addClass)(textArea, CommentEditor.CLASS_INPUT);

      editor.appendChild(textArea);
      container.appendChild(editor);

      return editor;
    }

    /**
     * Get the input element.
     *
     * @returns {HTMLElement}
     */

  }, {
    key: 'getInputElement',
    value: function getInputElement() {
      return this.editor.querySelector('.' + CommentEditor.CLASS_INPUT);
    }

    /**
     * Destroy the comments editor.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.editor.parentNode.removeChild(this.editor);
      this.editor = null;
      this.editorStyle = null;
    }
  }]);

  return CommentEditor;
}();

exports.default = CommentEditor;

/***/ }),
/* 398 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _function = __webpack_require__(41);

var _object = __webpack_require__(1);

var _localHooks = __webpack_require__(89);

var _localHooks2 = _interopRequireDefault(_localHooks);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var DEFAULT_DISPLAY_DELAY = 250;
var DEFAULT_HIDE_DELAY = 250;

/**
 * Display switch for the Comments plugin. Manages the time of delayed displaying / hiding comments.
 *
 * @class DisplaySwitch
 * @plugin Comments
 */

var DisplaySwitch = function () {
  function DisplaySwitch(displayDelay) {
    _classCallCheck(this, DisplaySwitch);

    /**
     * Flag to determine if comment can be showed or hidden. State `true` mean that last performed action
     * was an attempt to show comment element. State `false` mean that it was attempt to hide comment element.
     *
     * @type {Boolean}
     */
    this.wasLastActionShow = true;
    /**
     * Show comment after predefined delay. It keeps reference to immutable `debounce` function.
     *
     * @type {Function}
     */
    this.showDebounced = null;
    /**
     * Reference to timer, run by `setTimeout`, which is hiding comment
     *
     * @type {Number}
     */
    this.hidingTimer = null;

    this.updateDelay(displayDelay);
  }

  /**
   * Responsible for hiding comment after proper delay.
   */


  _createClass(DisplaySwitch, [{
    key: 'hide',
    value: function hide() {
      var _this = this;

      this.wasLastActionShow = false;

      this.hidingTimer = setTimeout(function () {
        if (_this.wasLastActionShow === false) {
          _this.runLocalHooks('hide');
        }
      }, DEFAULT_HIDE_DELAY);
    }

    /**
     * Responsible for showing comment after proper delay.
     *
     * @param {Object} range Coordinates of selected cell.
     */

  }, {
    key: 'show',
    value: function show(range) {
      this.wasLastActionShow = true;
      this.showDebounced(range);
    }
  }, {
    key: 'cancelHiding',


    /**
     * Cancel hiding comment.
     */
    value: function cancelHiding() {
      this.wasLastActionShow = true;

      clearTimeout(this.hidingTimer);
      this.hidingTimer = null;
    }

    /**
     * Update the switch settings.
     *
     * @param {Number} displayDelay Delay of showing the comments (in milliseconds).
     */

  }, {
    key: 'updateDelay',
    value: function updateDelay() {
      var _this2 = this;

      var displayDelay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_DISPLAY_DELAY;

      this.showDebounced = (0, _function.debounce)(function (range) {
        if (_this2.wasLastActionShow) {
          _this2.runLocalHooks('show', range.from.row, range.from.col);
        }
      }, displayDelay);
    }

    /**
     * Destroy the switcher.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.clearLocalHooks();
    }
  }]);

  return DisplaySwitch;
}();

(0, _object.mixin)(DisplaySwitch, _localHooks2.default);

exports.default = DisplaySwitch;

/***/ }),
/* 399 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 400 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _array = __webpack_require__(2);

var _commandExecutor = __webpack_require__(401);

var _commandExecutor2 = _interopRequireDefault(_commandExecutor);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _itemsFactory = __webpack_require__(402);

var _itemsFactory2 = _interopRequireDefault(_itemsFactory);

var _menu = __webpack_require__(414);

var _menu2 = _interopRequireDefault(_menu);

var _plugins = __webpack_require__(7);

var _event = __webpack_require__(12);

var _element = __webpack_require__(0);

var _predefinedItems = __webpack_require__(90);

__webpack_require__(416);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

_pluginHooks2.default.getSingleton().register('afterContextMenuDefaultOptions');
_pluginHooks2.default.getSingleton().register('afterContextMenuShow');
_pluginHooks2.default.getSingleton().register('afterContextMenuHide');
_pluginHooks2.default.getSingleton().register('afterContextMenuExecute');

/**
 * @description
 * This plugin creates the Handsontable Context Menu. It allows to create a new row or
 * column at any place in the grid among [other features](http://docs.handsontable.com/demo-context-menu.html).
 * Possible values:
 * * `true` (to enable default options),
 * * `false` (to disable completely)
 *
 * or array of any available strings:
 * * `["row_above", "row_below", "col_left", "col_right",
 * "remove_row", "remove_col", "---------", "undo", "redo"]`.
 *
 * See [the context menu demo](http://docs.handsontable.com/demo-context-menu.html) for examples.
 *
 * @example
 * ```js
 * ...
 * // as a boolean
 * contextMenu: true
 * ...
 * // as a array
 * contextMenu: ['row_above', 'row_below', '---------', 'undo', 'redo']
 * ...
 * ```
 *
 * @plugin ContextMenu
 */

var ContextMenu = function (_BasePlugin) {
  _inherits(ContextMenu, _BasePlugin);

  _createClass(ContextMenu, null, [{
    key: 'DEFAULT_ITEMS',

    /**
     * Default menu items order when `contextMenu` is enabled by `true`.
     *
     * @returns {Array}
     */
    get: function get() {
      return [_predefinedItems.ROW_ABOVE, _predefinedItems.ROW_BELOW, _predefinedItems.SEPARATOR, _predefinedItems.COLUMN_LEFT, _predefinedItems.COLUMN_RIGHT, _predefinedItems.SEPARATOR, _predefinedItems.REMOVE_ROW, _predefinedItems.REMOVE_COLUMN, _predefinedItems.SEPARATOR, _predefinedItems.UNDO, _predefinedItems.REDO, _predefinedItems.SEPARATOR, _predefinedItems.READ_ONLY, _predefinedItems.SEPARATOR, _predefinedItems.ALIGNMENT];
    }
  }]);

  function ContextMenu(hotInstance) {
    _classCallCheck(this, ContextMenu);

    /**
     * Instance of {@link EventManager}.
     *
     * @type {EventManager}
     */
    var _this = _possibleConstructorReturn(this, (ContextMenu.__proto__ || Object.getPrototypeOf(ContextMenu)).call(this, hotInstance));

    _this.eventManager = new _eventManager2.default(_this);
    /**
     * Instance of {@link CommandExecutor}.
     *
     * @type {CommandExecutor}
     */
    _this.commandExecutor = new _commandExecutor2.default(_this.hot);
    /**
     * Instance of {@link ItemsFactory}.
     *
     * @type {ItemsFactory}
     */
    _this.itemsFactory = null;
    /**
     * Instance of {@link Menu}.
     *
     * @type {Menu}
     */
    _this.menu = null;
    return _this;
  }

  /**
   * Check if the plugin is enabled in the Handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(ContextMenu, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return this.hot.getSettings().contextMenu;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }
      this.itemsFactory = new _itemsFactory2.default(this.hot, ContextMenu.DEFAULT_ITEMS);

      var settings = this.hot.getSettings().contextMenu;
      var predefinedItems = {
        items: this.itemsFactory.getItems(settings)
      };
      this.registerEvents();

      if (typeof settings.callback === 'function') {
        this.commandExecutor.setCommonCallback(settings.callback);
      }
      _get(ContextMenu.prototype.__proto__ || Object.getPrototypeOf(ContextMenu.prototype), 'enablePlugin', this).call(this);

      var delayedInitialization = function delayedInitialization() {
        if (!_this2.hot) {
          return;
        }

        _this2.hot.runHooks('afterContextMenuDefaultOptions', predefinedItems);

        _this2.itemsFactory.setPredefinedItems(predefinedItems.items);
        var menuItems = _this2.itemsFactory.getItems(settings);

        _this2.menu = new _menu2.default(_this2.hot, {
          className: 'htContextMenu',
          keepInViewport: true
        });
        _this2.hot.runHooks('beforeContextMenuSetItems', menuItems);

        _this2.menu.setMenuItems(menuItems);

        _this2.menu.addLocalHook('afterOpen', function () {
          return _this2.onMenuAfterOpen();
        });
        _this2.menu.addLocalHook('afterClose', function () {
          return _this2.onMenuAfterClose();
        });
        _this2.menu.addLocalHook('executeCommand', function () {
          for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) {
            params[_key] = arguments[_key];
          }

          return _this2.executeCommand.apply(_this2, params);
        });

        // Register all commands. Predefined and added by user or by plugins
        (0, _array.arrayEach)(menuItems, function (command) {
          return _this2.commandExecutor.registerCommand(command.key, command);
        });
      };

      this.callOnPluginsReady(function () {
        if (_this2.isPluginsReady) {
          setTimeout(delayedInitialization, 0);
        } else {
          delayedInitialization();
        }
      });
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();

      _get(ContextMenu.prototype.__proto__ || Object.getPrototypeOf(ContextMenu.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      this.close();

      if (this.menu) {
        this.menu.destroy();
        this.menu = null;
      }
      _get(ContextMenu.prototype.__proto__ || Object.getPrototypeOf(ContextMenu.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Register dom listeners.
     *
     * @private
     */

  }, {
    key: 'registerEvents',
    value: function registerEvents() {
      var _this3 = this;

      this.eventManager.addEventListener(this.hot.rootElement, 'contextmenu', function (event) {
        return _this3.onContextMenu(event);
      });
    }

    /**
     * Open menu and re-position it based on dom event object.
     *
     * @param {Event} event The event object.
     */

  }, {
    key: 'open',
    value: function open(event) {
      if (!this.menu) {
        return;
      }
      this.menu.open();
      this.menu.setPosition({
        top: parseInt((0, _event.pageY)(event), 10) - (0, _element.getWindowScrollTop)(),
        left: parseInt((0, _event.pageX)(event), 10) - (0, _element.getWindowScrollLeft)()
      });

      // ContextMenu is not detected HotTableEnv correctly because is injected outside hot-table
      this.menu.hotMenu.isHotTableEnv = this.hot.isHotTableEnv;
      // Handsontable.eventManager.isHotTableEnv = this.hot.isHotTableEnv;
    }

    /**
     * Close menu.
     */

  }, {
    key: 'close',
    value: function close() {
      if (!this.menu) {
        return;
      }
      this.menu.close();
    }

    /**
     * Execute context menu command.
     *
     * You can execute all predefined commands:
     *  * `'row_above'` - Insert row above
     *  * `'row_below'` - Insert row below
     *  * `'col_left'` - Insert column left
     *  * `'col_right'` - Insert column right
     *  * `'clear_column'` - Clear selected column
     *  * `'remove_row'` - Remove row
     *  * `'remove_col'` - Remove column
     *  * `'undo'` - Undo last action
     *  * `'redo'` - Redo last action
     *  * `'make_read_only'` - Make cell read only
     *  * `'alignment:left'` - Alignment to the left
     *  * `'alignment:top'` - Alignment to the top
     *  * `'alignment:right'` - Alignment to the right
     *  * `'alignment:bottom'` - Alignment to the bottom
     *  * `'alignment:middle'` - Alignment to the middle
     *  * `'alignment:center'` - Alignment to the center (justify)
     *
     * Or you can execute command registered in settings where `key` is your command name.
     *
     * @param {String} commandName
     * @param {*} params
     */

  }, {
    key: 'executeCommand',
    value: function executeCommand() {
      for (var _len2 = arguments.length, params = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        params[_key2] = arguments[_key2];
      }

      this.commandExecutor.execute.apply(this.commandExecutor, params);
    }

    /**
     * On context menu listener.
     *
     * @private
     * @param {Event} event
     */

  }, {
    key: 'onContextMenu',
    value: function onContextMenu(event) {
      var settings = this.hot.getSettings();
      var showRowHeaders = settings.rowHeaders;
      var showColHeaders = settings.colHeaders;

      function isValidElement(element) {
        return element.nodeName === 'TD' || element.parentNode.nodeName === 'TD';
      }
      // if event is from hot-table we must get web component element not element inside him
      var element = event.realTarget;
      this.close();

      if ((0, _element.hasClass)(element, 'handsontableInput')) {
        return;
      }

      event.preventDefault();
      (0, _event.stopPropagation)(event);

      if (!(showRowHeaders || showColHeaders)) {
        if (!isValidElement(element) && !((0, _element.hasClass)(element, 'current') && (0, _element.hasClass)(element, 'wtBorder'))) {
          return;
        }
      }

      this.open(event);
    }

    /**
     * On menu after open listener.
     *
     * @private
     */

  }, {
    key: 'onMenuAfterOpen',
    value: function onMenuAfterOpen() {
      this.hot.runHooks('afterContextMenuShow', this);
    }

    /**
     * On menu after close listener.
     *
     * @private
     */

  }, {
    key: 'onMenuAfterClose',
    value: function onMenuAfterClose() {
      this.hot.listen();
      this.hot.runHooks('afterContextMenuHide', this);
    }

    /**
     * Destroy instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.close();

      if (this.menu) {
        this.menu.destroy();
      }
      _get(ContextMenu.prototype.__proto__ || Object.getPrototypeOf(ContextMenu.prototype), 'destroy', this).call(this);
    }
  }]);

  return ContextMenu;
}(_base2.default);

ContextMenu.SEPARATOR = {
  name: _predefinedItems.SEPARATOR
};

(0, _plugins.registerPlugin)('contextMenu', ContextMenu);

exports.default = ContextMenu;

/***/ }),
/* 401 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _array = __webpack_require__(2);

var _object = __webpack_require__(1);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Command executor for ContextMenu.
 *
 * @class CommandExecutor
 * @plugin ContextMenu
 */
var CommandExecutor = function () {
  function CommandExecutor(hotInstance) {
    _classCallCheck(this, CommandExecutor);

    this.hot = hotInstance;
    this.commands = {};
    this.commonCallback = null;
  }

  /**
   * Register command.
   *
   * @param {String} name Command name.
   * @param {Object} commandDescriptor Command descriptor object with properties like `key` (command id),
   *                                   `callback` (task to execute), `name` (command name), `disabled` (command availability).
   */


  _createClass(CommandExecutor, [{
    key: 'registerCommand',
    value: function registerCommand(name, commandDescriptor) {
      this.commands[name] = commandDescriptor;
    }

    /**
     * Set common callback which will be trigger on every executed command.
     *
     * @param {Function} callback Function which will be fired on every command execute.
     */

  }, {
    key: 'setCommonCallback',
    value: function setCommonCallback(callback) {
      this.commonCallback = callback;
    }

    /**
     * Execute command by its name.
     *
     * @param {String} commandName Command id.
     * @param {*} params Arguments passed to command task.
     */

  }, {
    key: 'execute',
    value: function execute(commandName) {
      var _this = this;

      for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        params[_key - 1] = arguments[_key];
      }

      var commandSplit = commandName.split(':');
      commandName = commandSplit[0];

      var subCommandName = commandSplit.length === 2 ? commandSplit[1] : null;
      var command = this.commands[commandName];

      if (!command) {
        throw new Error('Menu command \'' + commandName + '\' not exists.');
      }
      if (subCommandName && command.submenu) {
        command = findSubCommand(subCommandName, command.submenu.items);
      }
      if (command.disabled === true) {
        return;
      }
      if (typeof command.disabled == 'function' && command.disabled.call(this.hot) === true) {
        return;
      }
      if ((0, _object.hasOwnProperty)(command, 'submenu')) {
        return;
      }
      var callbacks = [];

      if (typeof command.callback === 'function') {
        callbacks.push(command.callback);
      }
      if (typeof this.commonCallback === 'function') {
        callbacks.push(this.commonCallback);
      }
      params.unshift(commandSplit.join(':'));
      (0, _array.arrayEach)(callbacks, function (callback) {
        return callback.apply(_this.hot, params);
      });
    }
  }]);

  return CommandExecutor;
}();

function findSubCommand(subCommandName, subCommands) {
  var command = void 0;

  (0, _array.arrayEach)(subCommands, function (cmd) {
    var cmds = cmd.key ? cmd.key.split(':') : null;

    if (Array.isArray(cmds) && cmds[1] === subCommandName) {
      command = cmd;

      return false;
    }
  });

  return command;
}

exports.default = CommandExecutor;

/***/ }),
/* 402 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _object = __webpack_require__(1);

var _array = __webpack_require__(2);

var _predefinedItems = __webpack_require__(90);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Predefined items class factory for menu items.
 *
 * @class ItemsFactory
 * @plugin ContextMenu
 */
var ItemsFactory = function () {
  function ItemsFactory(hotInstance) {
    var orderPattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

    _classCallCheck(this, ItemsFactory);

    this.hot = hotInstance;
    this.predefinedItems = (0, _predefinedItems.predefinedItems)();
    this.defaultOrderPattern = orderPattern;
  }

  /**
   * Set predefined items.
   *
   * @param {Array} predefinedItems Array of predefined items.
   */


  _createClass(ItemsFactory, [{
    key: 'setPredefinedItems',
    value: function setPredefinedItems(predefinedItems) {
      var _this = this;

      var items = {};

      this.defaultOrderPattern.length = 0;

      (0, _object.objectEach)(predefinedItems, function (value, key) {
        var menuItemKey = '';

        if (value.name === _predefinedItems.SEPARATOR) {
          items[_predefinedItems.SEPARATOR] = value;
          menuItemKey = _predefinedItems.SEPARATOR;

          // Menu item added as a property to array
        } else if (isNaN(parseInt(key, 10))) {
          value.key = value.key === void 0 ? key : value.key;
          items[key] = value;
          menuItemKey = value.key;
        } else {
          items[value.key] = value;
          menuItemKey = value.key;
        }
        _this.defaultOrderPattern.push(menuItemKey);
      });
      this.predefinedItems = items;
    }

    /**
     * Get all menu items based on pattern.
     *
     * @param {Array|Object|Boolean} pattern Pattern which you can define by displaying menu items order. If `true` default
     *                                       pattern will be used.
     * @returns {Array}
     */

  }, {
    key: 'getItems',
    value: function getItems() {
      var pattern = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

      return _getItems(pattern, this.defaultOrderPattern, this.predefinedItems);
    }
  }]);

  return ItemsFactory;
}();

function _getItems() {
  var pattern = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  var defaultPattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var items = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  var result = [];

  if (pattern && pattern.items) {
    pattern = pattern.items;
  } else if (!Array.isArray(pattern)) {
    pattern = defaultPattern;
  }
  if ((0, _object.isObject)(pattern)) {
    (0, _object.objectEach)(pattern, function (value, key) {
      var item = items[typeof value === 'string' ? value : key];

      if (!item) {
        item = value;
      }
      if ((0, _object.isObject)(value)) {
        (0, _object.extend)(item, value);
      } else if (typeof item === 'string') {
        item = { name: item };
      }
      if (item.key === void 0) {
        item.key = key;
      }
      result.push(item);
    });
  } else {
    (0, _array.arrayEach)(pattern, function (name, key) {
      var item = items[name];

      // Item deleted from settings `allowInsertRow: false` etc.
      if (!item && _predefinedItems.ITEMS.indexOf(name) >= 0) {
        return;
      }
      if (!item) {
        item = { name: name, key: '' + key };
      }
      if ((0, _object.isObject)(name)) {
        (0, _object.extend)(item, name);
      }
      if (item.key === void 0) {
        item.key = key;
      }
      result.push(item);
    });
  }

  return result;
}

exports.default = ItemsFactory;

/***/ }),
/* 403 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = alignmentItem;

var _utils = __webpack_require__(21);

var _separator = __webpack_require__(88);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'alignment';

function alignmentItem() {
  return {
    key: KEY,
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ALIGNMENT);
    },
    disabled: function disabled() {
      return !(this.getSelectedRange() && !this.selection.selectedHeader.corner);
    },

    submenu: {
      items: [{
        key: KEY + ':left',
        name: function name() {
          var _this = this;

          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ALIGNMENT_LEFT);
          var hasClass = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
            var className = _this.getCellMeta(row, col).className;

            if (className && className.indexOf('htLeft') !== -1) {
              return true;
            }
          });

          if (hasClass) {
            label = (0, _utils.markLabelAsSelected)(label);
          }

          return label;
        },
        callback: function callback() {
          var _this2 = this;

          var range = this.getSelectedRange();
          var stateBefore = (0, _utils.getAlignmentClasses)(range, function (row, col) {
            return _this2.getCellMeta(row, col).className;
          });
          var type = 'horizontal';
          var alignment = 'htLeft';

          this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
          (0, _utils.align)(range, type, alignment, function (row, col) {
            return _this2.getCellMeta(row, col);
          }, function (row, col, key, value) {
            return _this2.setCellMeta(row, col, key, value);
          });
          this.render();
        },

        disabled: false
      }, {
        key: KEY + ':center',
        name: function name() {
          var _this3 = this;

          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ALIGNMENT_CENTER);
          var hasClass = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
            var className = _this3.getCellMeta(row, col).className;

            if (className && className.indexOf('htCenter') !== -1) {
              return true;
            }
          });

          if (hasClass) {
            label = (0, _utils.markLabelAsSelected)(label);
          }

          return label;
        },
        callback: function callback() {
          var _this4 = this;

          var range = this.getSelectedRange();
          var stateBefore = (0, _utils.getAlignmentClasses)(range, function (row, col) {
            return _this4.getCellMeta(row, col).className;
          });
          var type = 'horizontal';
          var alignment = 'htCenter';

          this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
          (0, _utils.align)(range, type, alignment, function (row, col) {
            return _this4.getCellMeta(row, col);
          }, function (row, col, key, value) {
            return _this4.setCellMeta(row, col, key, value);
          });
          this.render();
        },

        disabled: false
      }, {
        key: KEY + ':right',
        name: function name() {
          var _this5 = this;

          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT);
          var hasClass = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
            var className = _this5.getCellMeta(row, col).className;

            if (className && className.indexOf('htRight') !== -1) {
              return true;
            }
          });

          if (hasClass) {
            label = (0, _utils.markLabelAsSelected)(label);
          }

          return label;
        },
        callback: function callback() {
          var _this6 = this;

          var range = this.getSelectedRange();
          var stateBefore = (0, _utils.getAlignmentClasses)(range, function (row, col) {
            return _this6.getCellMeta(row, col).className;
          });
          var type = 'horizontal';
          var alignment = 'htRight';

          this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
          (0, _utils.align)(range, type, alignment, function (row, col) {
            return _this6.getCellMeta(row, col);
          }, function (row, col, key, value) {
            return _this6.setCellMeta(row, col, key, value);
          });
          this.render();
        },

        disabled: false
      }, {
        key: KEY + ':justify',
        name: function name() {
          var _this7 = this;

          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY);
          var hasClass = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
            var className = _this7.getCellMeta(row, col).className;

            if (className && className.indexOf('htJustify') !== -1) {
              return true;
            }
          });

          if (hasClass) {
            label = (0, _utils.markLabelAsSelected)(label);
          }

          return label;
        },
        callback: function callback() {
          var _this8 = this;

          var range = this.getSelectedRange();
          var stateBefore = (0, _utils.getAlignmentClasses)(range, function (row, col) {
            return _this8.getCellMeta(row, col).className;
          });
          var type = 'horizontal';
          var alignment = 'htJustify';

          this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
          (0, _utils.align)(range, type, alignment, function (row, col) {
            return _this8.getCellMeta(row, col);
          }, function (row, col, key, value) {
            return _this8.setCellMeta(row, col, key, value);
          });
          this.render();
        },

        disabled: false
      }, {
        name: _separator.KEY
      }, {
        key: KEY + ':top',
        name: function name() {
          var _this9 = this;

          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ALIGNMENT_TOP);
          var hasClass = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
            var className = _this9.getCellMeta(row, col).className;

            if (className && className.indexOf('htTop') !== -1) {
              return true;
            }
          });

          if (hasClass) {
            label = (0, _utils.markLabelAsSelected)(label);
          }
          return label;
        },
        callback: function callback() {
          var _this10 = this;

          var range = this.getSelectedRange();
          var stateBefore = (0, _utils.getAlignmentClasses)(range, function (row, col) {
            return _this10.getCellMeta(row, col).className;
          });
          var type = 'vertical';
          var alignment = 'htTop';

          this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
          (0, _utils.align)(range, type, alignment, function (row, col) {
            return _this10.getCellMeta(row, col);
          }, function (row, col, key, value) {
            return _this10.setCellMeta(row, col, key, value);
          });
          this.render();
        },

        disabled: false
      }, {
        key: KEY + ':middle',
        name: function name() {
          var _this11 = this;

          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE);
          var hasClass = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
            var className = _this11.getCellMeta(row, col).className;

            if (className && className.indexOf('htMiddle') !== -1) {
              return true;
            }
          });

          if (hasClass) {
            label = (0, _utils.markLabelAsSelected)(label);
          }

          return label;
        },
        callback: function callback() {
          var _this12 = this;

          var range = this.getSelectedRange();
          var stateBefore = (0, _utils.getAlignmentClasses)(range, function (row, col) {
            return _this12.getCellMeta(row, col).className;
          });
          var type = 'vertical';
          var alignment = 'htMiddle';

          this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
          (0, _utils.align)(range, type, alignment, function (row, col) {
            return _this12.getCellMeta(row, col);
          }, function (row, col, key, value) {
            return _this12.setCellMeta(row, col, key, value);
          });
          this.render();
        },

        disabled: false
      }, {
        key: KEY + ':bottom',
        name: function name() {
          var _this13 = this;

          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM);
          var hasClass = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
            var className = _this13.getCellMeta(row, col).className;

            if (className && className.indexOf('htBottom') !== -1) {
              return true;
            }
          });

          if (hasClass) {
            label = (0, _utils.markLabelAsSelected)(label);
          }

          return label;
        },
        callback: function callback() {
          var _this14 = this;

          var range = this.getSelectedRange();
          var stateBefore = (0, _utils.getAlignmentClasses)(range, function (row, col) {
            return _this14.getCellMeta(row, col).className;
          });
          var type = 'vertical';
          var alignment = 'htBottom';

          this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment);
          (0, _utils.align)(range, type, alignment, function (row, col) {
            return _this14.getCellMeta(row, col);
          }, function (row, col, key, value) {
            return _this14.setCellMeta(row, col, key, value);
          });
          this.render();
        },

        disabled: false
      }]
    }
  };
}

/***/ }),
/* 404 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = clearColumnItem;

var _utils = __webpack_require__(21);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'clear_column';

function clearColumnItem() {
  return {
    key: KEY,
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_CLEAR_COLUMN);
    },
    callback: function callback(key, selection) {
      var column = selection.start.col;

      if (this.countRows()) {
        this.populateFromArray(0, column, [[null]], Math.max(selection.start.row, selection.end.row), column, 'ContextMenu.clearColumn');
      }
    },
    disabled: function disabled() {
      var selected = (0, _utils.getValidSelection)(this);

      if (!selected) {
        return true;
      }
      var entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      var rowSelected = entireRowSelection.join(',') === selected.join(',');

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
    }
  };
}

/***/ }),
/* 405 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = columnLeftItem;

var _utils = __webpack_require__(21);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'col_left';

function columnLeftItem() {
  return {
    key: KEY,
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_INSERT_LEFT);
    },
    callback: function callback(key, selection) {
      this.alter('insert_col', selection.start.col, 1, 'ContextMenu.columnLeft');
    },
    disabled: function disabled() {
      var selected = (0, _utils.getValidSelection)(this);

      if (!selected) {
        return true;
      }
      if (!this.isColumnModificationAllowed()) {
        return true;
      }
      var entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      var rowSelected = entireRowSelection.join(',') === selected.join(',');
      var onlyOneColumn = this.countCols() === 1;

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || !onlyOneColumn && rowSelected;
    },
    hidden: function hidden() {
      return !this.getSettings().allowInsertColumn;
    }
  };
}

/***/ }),
/* 406 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = columnRightItem;

var _utils = __webpack_require__(21);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'col_right';

function columnRightItem() {
  return {
    key: KEY,
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_INSERT_RIGHT);
    },
    callback: function callback(key, selection) {
      this.alter('insert_col', selection.end.col + 1, 1, 'ContextMenu.columnRight');
    },
    disabled: function disabled() {
      var selected = (0, _utils.getValidSelection)(this);

      if (!selected) {
        return true;
      }
      if (!this.isColumnModificationAllowed()) {
        return true;
      }
      var entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1];
      var rowSelected = entireRowSelection.join(',') === selected.join(',');
      var onlyOneColumn = this.countCols() === 1;

      return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || !onlyOneColumn && rowSelected;
    },
    hidden: function hidden() {
      return !this.getSettings().allowInsertColumn;
    }
  };
}

/***/ }),
/* 407 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = readOnlyItem;

var _utils = __webpack_require__(21);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'make_read_only';

function readOnlyItem() {
  return {
    key: KEY,
    name: function name() {
      var _this = this;

      var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_READ_ONLY);
      var atLeastOneReadOnly = (0, _utils.checkSelectionConsistency)(this.getSelectedRange(), function (row, col) {
        return _this.getCellMeta(row, col).readOnly;
      });

      if (atLeastOneReadOnly) {
        label = (0, _utils.markLabelAsSelected)(label);
      }

      return label;
    },
    callback: function callback() {
      var _this2 = this;

      var range = this.getSelectedRange();
      var atLeastOneReadOnly = (0, _utils.checkSelectionConsistency)(range, function (row, col) {
        return _this2.getCellMeta(row, col).readOnly;
      });

      range.forAll(function (row, col) {
        _this2.setCellMeta(row, col, 'readOnly', !atLeastOneReadOnly);
      });
      this.render();
    },
    disabled: function disabled() {
      return !(this.getSelectedRange() && !this.selection.selectedHeader.corner);
    }
  };
}

/***/ }),
/* 408 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = redoItem;

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'redo';

function redoItem() {
  return {
    key: KEY,
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_REDO);
    },
    callback: function callback() {
      this.redo();
    },
    disabled: function disabled() {
      return this.undoRedo && !this.undoRedo.isRedoAvailable();
    }
  };
}

/***/ }),
/* 409 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

exports.default = removeColumnItem;

var _utils = __webpack_require__(21);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'remove_col';

function removeColumnItem() {
  return {
    key: KEY,
    name: function name() {
      var selection = this.getSelected();
      var pluralForm = 0;

      if (Array.isArray(selection)) {
        var _selection = _slicedToArray(selection, 4),
            fromColumn = _selection[1],
            toColumn = _selection[3];

        if (fromColumn - toColumn !== 0) {
          pluralForm = 1;
        }
      }

      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_REMOVE_COLUMN, pluralForm);
    },
    callback: function callback(key, selection) {
      var amount = selection.end.col - selection.start.col + 1;

      this.alter('remove_col', selection.start.col, amount, 'ContextMenu.removeColumn');
    },
    disabled: function disabled() {
      var selected = (0, _utils.getValidSelection)(this);
      var totalColumns = this.countCols();

      return !selected || this.selection.selectedHeader.rows || this.selection.selectedHeader.corner || !this.isColumnModificationAllowed() || !totalColumns;
    },
    hidden: function hidden() {
      return !this.getSettings().allowRemoveColumn;
    }
  };
}

/***/ }),
/* 410 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

exports.default = removeRowItem;

var _utils = __webpack_require__(21);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'remove_row';

function removeRowItem() {
  return {
    key: KEY,
    name: function name() {
      var selection = this.getSelected();
      var pluralForm = 0;

      if (Array.isArray(selection)) {
        var _selection = _slicedToArray(selection, 3),
            fromRow = _selection[0],
            toRow = _selection[2];

        if (fromRow - toRow !== 0) {
          pluralForm = 1;
        }
      }

      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_REMOVE_ROW, pluralForm);
    },
    callback: function callback(key, selection) {
      var amount = selection.end.row - selection.start.row + 1;

      this.alter('remove_row', selection.start.row, amount, 'ContextMenu.removeRow');
    },
    disabled: function disabled() {
      var selected = (0, _utils.getValidSelection)(this);
      var totalRows = this.countRows();

      return !selected || this.selection.selectedHeader.cols || this.selection.selectedHeader.corner || !totalRows;
    },
    hidden: function hidden() {
      return !this.getSettings().allowRemoveRow;
    }
  };
}

/***/ }),
/* 411 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = rowAboveItem;

var _utils = __webpack_require__(21);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'row_above';

function rowAboveItem() {
  return {
    key: KEY,
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ROW_ABOVE);
    },
    callback: function callback(key, selection) {
      this.alter('insert_row', selection.start.row, 1, 'ContextMenu.rowAbove');
    },
    disabled: function disabled() {
      var selected = (0, _utils.getValidSelection)(this);

      return !selected || this.selection.selectedHeader.cols || this.countRows() >= this.getSettings().maxRows;
    },
    hidden: function hidden() {
      return !this.getSettings().allowInsertRow;
    }
  };
}

/***/ }),
/* 412 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = rowBelowItem;

var _utils = __webpack_require__(21);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'row_below';

function rowBelowItem() {
  return {
    key: KEY,
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_ROW_BELOW);
    },
    callback: function callback(key, selection) {
      this.alter('insert_row', selection.end.row + 1, 1, 'ContextMenu.rowBelow');
    },
    disabled: function disabled() {
      var selected = (0, _utils.getValidSelection)(this);

      return !selected || this.selection.selectedHeader.cols || this.countRows() >= this.getSettings().maxRows;
    },
    hidden: function hidden() {
      return !this.getSettings().allowInsertRow;
    }
  };
}

/***/ }),
/* 413 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.KEY = undefined;
exports.default = undoItem;

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var KEY = exports.KEY = 'undo';

function undoItem() {
  return {
    key: KEY,
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_UNDO);
    },
    callback: function callback() {
      this.undo();
    },
    disabled: function disabled() {
      return this.undoRedo && !this.undoRedo.isUndoAvailable();
    }
  };
}

/***/ }),
/* 414 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _core = __webpack_require__(84);

var _core2 = _interopRequireDefault(_core);

var _element = __webpack_require__(0);

var _array = __webpack_require__(2);

var _cursor = __webpack_require__(415);

var _cursor2 = _interopRequireDefault(_cursor);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _object = __webpack_require__(1);

var _mixed = __webpack_require__(17);

var _function = __webpack_require__(41);

var _utils = __webpack_require__(21);

var _unicode = __webpack_require__(20);

var _localHooks = __webpack_require__(89);

var _localHooks2 = _interopRequireDefault(_localHooks);

var _predefinedItems = __webpack_require__(90);

var _event = __webpack_require__(12);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Menu
 * @plugin ContextMenu
 */
var Menu = function () {
  function Menu(hotInstance, options) {
    _classCallCheck(this, Menu);

    this.hot = hotInstance;
    this.options = options || {
      parent: null,
      name: null,
      className: '',
      keepInViewport: true,
      standalone: false
    };
    this.eventManager = new _eventManager2.default(this);
    this.container = this.createContainer(this.options.name);
    this.hotMenu = null;
    this.hotSubMenus = {};
    this.parentMenu = this.options.parent || null;
    this.menuItems = null;
    this.origOutsideClickDeselects = null;
    this.keyEvent = false;

    this.offset = {
      above: 0,
      below: 0,
      left: 0,
      right: 0
    };
    this._afterScrollCallback = null;

    this.registerEvents();
  }

  /**
   * Register event listeners.
   *
   * @private
   */


  _createClass(Menu, [{
    key: 'registerEvents',
    value: function registerEvents() {
      var _this = this;

      this.eventManager.addEventListener(document.documentElement, 'mousedown', function (event) {
        return _this.onDocumentMouseDown(event);
      });
    }

    /**
     * Set array of objects which defines menu items.
     *
     * @param {Array} menuItems Menu items to display.
     */

  }, {
    key: 'setMenuItems',
    value: function setMenuItems(menuItems) {
      this.menuItems = menuItems;
    }

    /**
     * Set offset menu position for specified area (`above`, `below`, `left` or `right`).
     *
     * @param {String} area Specified area name (`above`, `below`, `left` or `right`).
     * @param {Number} offset Offset value.
     */

  }, {
    key: 'setOffset',
    value: function setOffset(area) {
      var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

      this.offset[area] = offset;
    }

    /**
     * Check if menu is using as sub-menu.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isSubMenu',
    value: function isSubMenu() {
      return this.parentMenu !== null;
    }

    /**
     * Open menu.
     */

  }, {
    key: 'open',
    value: function open() {
      var _this2 = this;

      this.container.removeAttribute('style');
      this.container.style.display = 'block';

      var delayedOpenSubMenu = (0, _function.debounce)(function (row) {
        return _this2.openSubMenu(row);
      }, 300);

      var filteredItems = (0, _array.arrayFilter)(this.menuItems, function (item) {
        return (0, _utils.isItemHidden)(item, _this2.hot);
      });

      filteredItems = (0, _utils.filterSeparators)(filteredItems, _predefinedItems.SEPARATOR);

      var settings = {
        data: filteredItems,
        colHeaders: false,
        colWidths: [215],
        autoRowSize: false,
        readOnly: true,
        copyPaste: false,
        columns: [{
          data: 'name',
          renderer: function renderer(hot, TD, row, col, prop, value) {
            return _this2.menuItemRenderer(hot, TD, row, col, prop, value);
          }
        }],
        renderAllRows: true,
        fragmentSelection: 'cell',
        disableVisualSelection: 'area',
        beforeKeyDown: function beforeKeyDown(event) {
          return _this2.onBeforeKeyDown(event);
        },
        afterOnCellMouseOver: function afterOnCellMouseOver(event, coords, TD) {
          if (_this2.isAllSubMenusClosed()) {
            delayedOpenSubMenu(coords.row);
          } else {
            _this2.openSubMenu(coords.row);
          }
        },
        rowHeights: function rowHeights(row) {
          return filteredItems[row].name === _predefinedItems.SEPARATOR ? 1 : 23;
        }
      };
      this.origOutsideClickDeselects = this.hot.getSettings().outsideClickDeselects;
      this.hot.getSettings().outsideClickDeselects = false;
      this.hotMenu = new _core2.default(this.container, settings);
      this.hotMenu.addHook('afterInit', function () {
        return _this2.onAfterInit();
      });
      this.hotMenu.addHook('afterSelection', function (r, c, r2, c2, preventScrolling) {
        return _this2.onAfterSelection(r, c, r2, c2, preventScrolling);
      });
      this.hotMenu.init();
      this.hotMenu.listen();
      this.blockMainTableCallbacks();
      this.runLocalHooks('afterOpen');
    }

    /**
     * Close menu.
     *
     * @param {Boolean} [closeParent=false] if `true` try to close parent menu if exists.
     */

  }, {
    key: 'close',
    value: function close() {
      var closeParent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (!this.isOpened()) {
        return;
      }
      if (closeParent && this.parentMenu) {
        this.parentMenu.close();
      } else {
        this.closeAllSubMenus();
        this.container.style.display = 'none';
        this.releaseMainTableCallbacks();
        this.hotMenu.destroy();
        this.hotMenu = null;
        this.hot.getSettings().outsideClickDeselects = this.origOutsideClickDeselects;
        this.runLocalHooks('afterClose');

        if (this.parentMenu) {
          this.parentMenu.hotMenu.listen();
        }
      }
    }

    /**
     * Open sub menu at the provided row index.
     *
     * @param {Number} row Row index.
     * @returns {Menu|Boolean} Returns created menu or `false` if no one menu was created.
     */

  }, {
    key: 'openSubMenu',
    value: function openSubMenu(row) {
      if (!this.hotMenu) {
        return false;
      }
      var cell = this.hotMenu.getCell(row, 0);

      this.closeAllSubMenus();

      if (!cell || !(0, _utils.hasSubMenu)(cell)) {
        return false;
      }
      var dataItem = this.hotMenu.getSourceDataAtRow(row);
      var subMenu = new Menu(this.hot, {
        parent: this,
        name: dataItem.name,
        className: this.options.className,
        keepInViewport: true
      });
      subMenu.setMenuItems(dataItem.submenu.items);
      subMenu.open();
      subMenu.setPosition(cell.getBoundingClientRect());
      this.hotSubMenus[dataItem.key] = subMenu;

      return subMenu;
    }

    /**
     * Close sub menu at row index.
     *
     * @param {Number} row Row index.
     */

  }, {
    key: 'closeSubMenu',
    value: function closeSubMenu(row) {
      var dataItem = this.hotMenu.getSourceDataAtRow(row);
      var menus = this.hotSubMenus[dataItem.key];

      if (menus) {
        menus.destroy();
        delete this.hotSubMenus[dataItem.key];
      }
    }

    /**
     * Close all opened sub menus.
     */

  }, {
    key: 'closeAllSubMenus',
    value: function closeAllSubMenus() {
      var _this3 = this;

      (0, _array.arrayEach)(this.hotMenu.getData(), function (value, row) {
        return _this3.closeSubMenu(row);
      });
    }

    /**
     * Checks if all created and opened sub menus are closed.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isAllSubMenusClosed',
    value: function isAllSubMenusClosed() {
      return Object.keys(this.hotSubMenus).length === 0;
    }

    /**
     * Destroy instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.clearLocalHooks();
      this.close();
      this.parentMenu = null;
      this.eventManager.destroy();
    }

    /**
     * Checks if menu was opened.
     *
     * @returns {Boolean} Returns `true` if menu was opened.
     */

  }, {
    key: 'isOpened',
    value: function isOpened() {
      return this.hotMenu !== null;
    }

    /**
     * Execute menu command.
     *
     * @param {Event} [event]
     */

  }, {
    key: 'executeCommand',
    value: function executeCommand(event) {
      if (!this.isOpened() || !this.hotMenu.getSelected()) {
        return;
      }
      var selectedItem = this.hotMenu.getSourceDataAtRow(this.hotMenu.getSelected()[0]);

      this.runLocalHooks('select', selectedItem, event);

      if (selectedItem.isCommand === false || selectedItem.name === _predefinedItems.SEPARATOR) {
        return;
      }
      var selRange = this.hot.getSelectedRange();
      var normalizedSelection = selRange ? (0, _utils.normalizeSelection)(selRange) : {};
      var autoClose = true;

      // Don't close context menu if item is disabled or it has submenu
      if (selectedItem.disabled === true || typeof selectedItem.disabled === 'function' && selectedItem.disabled.call(this.hot) === true || selectedItem.submenu) {
        autoClose = false;
      }

      this.runLocalHooks('executeCommand', selectedItem.key, normalizedSelection, event);

      if (this.isSubMenu()) {
        this.parentMenu.runLocalHooks('executeCommand', selectedItem.key, normalizedSelection, event);
      }

      if (autoClose) {
        this.close(true);
      }
    }

    /**
     * Set menu position based on dom event or based on literal object.
     *
     * @param {Event|Object} coords Event or literal Object with coordinates.
     */

  }, {
    key: 'setPosition',
    value: function setPosition(coords) {
      var cursor = new _cursor2.default(coords);

      if (this.options.keepInViewport) {
        if (cursor.fitsBelow(this.container)) {
          this.setPositionBelowCursor(cursor);
        } else if (cursor.fitsAbove(this.container)) {
          this.setPositionAboveCursor(cursor);
        } else {
          this.setPositionBelowCursor(cursor);
        }
        if (cursor.fitsOnRight(this.container)) {
          this.setPositionOnRightOfCursor(cursor);
        } else {
          this.setPositionOnLeftOfCursor(cursor);
        }
      } else {
        this.setPositionBelowCursor(cursor);
        this.setPositionOnRightOfCursor(cursor);
      }
    }

    /**
     * Set menu position above cursor object.
     *
     * @param {Cursor} cursor `Cursor` object.
     */

  }, {
    key: 'setPositionAboveCursor',
    value: function setPositionAboveCursor(cursor) {
      var top = this.offset.above + cursor.top - this.container.offsetHeight;

      if (this.isSubMenu()) {
        top = cursor.top + cursor.cellHeight - this.container.offsetHeight + 3;
      }
      this.container.style.top = top + 'px';
    }

    /**
     * Set menu position below cursor object.
     *
     * @param {Cursor} cursor `Cursor` object.
     */

  }, {
    key: 'setPositionBelowCursor',
    value: function setPositionBelowCursor(cursor) {
      var top = this.offset.below + cursor.top;

      if (this.isSubMenu()) {
        top = cursor.top - 1;
      }
      this.container.style.top = top + 'px';
    }

    /**
     * Set menu position on the right of cursor object.
     *
     * @param {Cursor} cursor `Cursor` object.
     */

  }, {
    key: 'setPositionOnRightOfCursor',
    value: function setPositionOnRightOfCursor(cursor) {
      var left = void 0;

      if (this.isSubMenu()) {
        left = 1 + cursor.left + cursor.cellWidth;
      } else {
        left = this.offset.right + 1 + cursor.left;
      }

      this.container.style.left = left + 'px';
    }

    /**
     * Set menu position on the left of cursor object.
     *
     * @param {Cursor} cursor `Cursor` object.
     */

  }, {
    key: 'setPositionOnLeftOfCursor',
    value: function setPositionOnLeftOfCursor(cursor) {
      var left = this.offset.left + cursor.left - this.container.offsetWidth + (0, _element.getScrollbarWidth)() + 4;

      this.container.style.left = left + 'px';
    }

    /**
     * Select first cell in opened menu.
     */

  }, {
    key: 'selectFirstCell',
    value: function selectFirstCell() {
      var cell = this.hotMenu.getCell(0, 0);

      if ((0, _utils.isSeparator)(cell) || (0, _utils.isDisabled)(cell) || (0, _utils.isSelectionDisabled)(cell)) {
        this.selectNextCell(0, 0);
      } else {
        this.hotMenu.selectCell(0, 0);
      }
    }

    /**
     * Select last cell in opened menu.
     */

  }, {
    key: 'selectLastCell',
    value: function selectLastCell() {
      var lastRow = this.hotMenu.countRows() - 1;
      var cell = this.hotMenu.getCell(lastRow, 0);

      if ((0, _utils.isSeparator)(cell) || (0, _utils.isDisabled)(cell) || (0, _utils.isSelectionDisabled)(cell)) {
        this.selectPrevCell(lastRow, 0);
      } else {
        this.hotMenu.selectCell(lastRow, 0);
      }
    }

    /**
     * Select next cell in opened menu.
     *
     * @param {Number} row Row index.
     * @param {Number} col Column index.
     */

  }, {
    key: 'selectNextCell',
    value: function selectNextCell(row, col) {
      var nextRow = row + 1;
      var cell = nextRow < this.hotMenu.countRows() ? this.hotMenu.getCell(nextRow, col) : null;

      if (!cell) {
        return;
      }
      if ((0, _utils.isSeparator)(cell) || (0, _utils.isDisabled)(cell) || (0, _utils.isSelectionDisabled)(cell)) {
        this.selectNextCell(nextRow, col);
      } else {
        this.hotMenu.selectCell(nextRow, col);
      }
    }

    /**
     * Select previous cell in opened menu.
     *
     * @param {Number} row Row index.
     * @param {Number} col Column index.
     */

  }, {
    key: 'selectPrevCell',
    value: function selectPrevCell(row, col) {
      var prevRow = row - 1;
      var cell = prevRow >= 0 ? this.hotMenu.getCell(prevRow, col) : null;

      if (!cell) {
        return;
      }
      if ((0, _utils.isSeparator)(cell) || (0, _utils.isDisabled)(cell) || (0, _utils.isSelectionDisabled)(cell)) {
        this.selectPrevCell(prevRow, col);
      } else {
        this.hotMenu.selectCell(prevRow, col);
      }
    }

    /**
     * Menu item renderer.
     *
     * @private
     */

  }, {
    key: 'menuItemRenderer',
    value: function menuItemRenderer(hot, TD, row, col, prop, value) {
      var _this4 = this;

      var item = hot.getSourceDataAtRow(row);
      var wrapper = document.createElement('div');

      var isSubMenu = function isSubMenu(item) {
        return (0, _object.hasOwnProperty)(item, 'submenu');
      };
      var itemIsSeparator = function itemIsSeparator(item) {
        return new RegExp(_predefinedItems.SEPARATOR, 'i').test(item.name);
      };
      var itemIsDisabled = function itemIsDisabled(item) {
        return item.disabled === true || typeof item.disabled == 'function' && item.disabled.call(_this4.hot) === true;
      };
      var itemIsSelectionDisabled = function itemIsSelectionDisabled(item) {
        return item.disableSelection;
      };

      if (typeof value === 'function') {
        value = value.call(this.hot);
      }
      (0, _element.empty)(TD);
      (0, _element.addClass)(wrapper, 'htItemWrapper');
      TD.appendChild(wrapper);

      if (itemIsSeparator(item)) {
        (0, _element.addClass)(TD, 'htSeparator');
      } else if (typeof item.renderer === 'function') {
        (0, _element.addClass)(TD, 'htCustomMenuRenderer');
        TD.appendChild(item.renderer(hot, wrapper, row, col, prop, value));
      } else {
        (0, _element.fastInnerHTML)(wrapper, value);
      }
      if (itemIsDisabled(item)) {
        (0, _element.addClass)(TD, 'htDisabled');
        this.eventManager.addEventListener(TD, 'mouseenter', function () {
          return hot.deselectCell();
        });
      } else if (itemIsSelectionDisabled(item)) {
        (0, _element.addClass)(TD, 'htSelectionDisabled');
        this.eventManager.addEventListener(TD, 'mouseenter', function () {
          return hot.deselectCell();
        });
      } else if (isSubMenu(item)) {
        (0, _element.addClass)(TD, 'htSubmenu');

        if (itemIsSelectionDisabled(item)) {
          this.eventManager.addEventListener(TD, 'mouseenter', function () {
            return hot.deselectCell();
          });
        } else {
          this.eventManager.addEventListener(TD, 'mouseenter', function () {
            return hot.selectCell(row, col, void 0, void 0, false, false);
          });
        }
      } else {
        (0, _element.removeClass)(TD, 'htSubmenu');
        (0, _element.removeClass)(TD, 'htDisabled');

        if (itemIsSelectionDisabled(item)) {
          this.eventManager.addEventListener(TD, 'mouseenter', function () {
            return hot.deselectCell();
          });
        } else {
          this.eventManager.addEventListener(TD, 'mouseenter', function () {
            return hot.selectCell(row, col, void 0, void 0, false, false);
          });
        }
      }
    }

    /**
     * Create container/wrapper for handsontable.
     *
     * @private
     * @param {String} [name] Class name.
     * @returns {HTMLElement}
     */

  }, {
    key: 'createContainer',
    value: function createContainer() {
      var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

      var container = void 0;

      if (name) {
        if ((0, _function.isFunction)(name)) {
          name = name.call(this.hot);

          if (name === null || (0, _mixed.isUndefined)(name)) {
            name = '';
          } else {
            name = name.toString();
          }
        }

        name = name.replace(/[^A-z0-9]/g, '_');
        name = this.options.className + 'Sub_' + name;

        container = document.querySelector('.' + this.options.className + '.' + name);
      } else {
        container = document.querySelector('.' + this.options.className);
      }

      if (!container) {
        container = document.createElement('div');

        (0, _element.addClass)(container, 'htMenu ' + this.options.className);

        if (name) {
          (0, _element.addClass)(container, name);
        }
        document.getElementsByTagName('body')[0].appendChild(container);
      }

      return container;
    }

    /**
     * @private
     */

  }, {
    key: 'blockMainTableCallbacks',
    value: function blockMainTableCallbacks() {
      this._afterScrollCallback = function () {};
      this.hot.addHook('afterScrollVertically', this._afterScrollCallback);
      this.hot.addHook('afterScrollHorizontally', this._afterScrollCallback);
    }

    /**
     * @private
     */

  }, {
    key: 'releaseMainTableCallbacks',
    value: function releaseMainTableCallbacks() {
      if (this._afterScrollCallback) {
        this.hot.removeHook('afterScrollVertically', this._afterScrollCallback);
        this.hot.removeHook('afterScrollHorizontally', this._afterScrollCallback);
        this._afterScrollCallback = null;
      }
    }

    /**
     * On before key down listener.
     *
     * @private
     * @param {Event} event
     */

  }, {
    key: 'onBeforeKeyDown',
    value: function onBeforeKeyDown(event) {
      var selection = this.hotMenu.getSelected();
      var stopEvent = false;
      this.keyEvent = true;

      switch (event.keyCode) {
        case _unicode.KEY_CODES.ESCAPE:
          this.close();
          stopEvent = true;
          break;

        case _unicode.KEY_CODES.ENTER:
          if (selection) {
            if (this.hotMenu.getSourceDataAtRow(selection[0]).submenu) {
              stopEvent = true;
            } else {
              this.executeCommand(event);
              this.close(true);
            }
          }
          break;

        case _unicode.KEY_CODES.ARROW_DOWN:
          if (selection) {
            this.selectNextCell(selection[0], selection[1]);
          } else {
            this.selectFirstCell();
          }
          stopEvent = true;
          break;

        case _unicode.KEY_CODES.ARROW_UP:
          if (selection) {
            this.selectPrevCell(selection[0], selection[1]);
          } else {
            this.selectLastCell();
          }
          stopEvent = true;
          break;

        case _unicode.KEY_CODES.ARROW_RIGHT:
          if (selection) {
            var menu = this.openSubMenu(selection[0]);

            if (menu) {
              menu.selectFirstCell();
            }
          }
          stopEvent = true;

          break;

        case _unicode.KEY_CODES.ARROW_LEFT:
          if (selection && this.isSubMenu()) {
            this.close();

            if (this.parentMenu) {
              this.parentMenu.hotMenu.listen();
            }
            stopEvent = true;
          }
          break;
        default:
          break;
      }
      if (stopEvent) {
        event.preventDefault();
        (0, _event.stopImmediatePropagation)(event);
      }

      this.keyEvent = false;
    }

    /**
     * On after init listener.
     *
     * @private
     */

  }, {
    key: 'onAfterInit',
    value: function onAfterInit() {
      var data = this.hotMenu.getSettings().data;
      var hiderStyle = this.hotMenu.view.wt.wtTable.hider.style;
      var holderStyle = this.hotMenu.view.wt.wtTable.holder.style;
      var currentHiderWidth = parseInt(hiderStyle.width, 10);

      var realHeight = (0, _array.arrayReduce)(data, function (accumulator, value) {
        return accumulator + (value.name === _predefinedItems.SEPARATOR ? 1 : 26);
      }, 0);

      holderStyle.width = currentHiderWidth + 22 + 'px';
      holderStyle.height = realHeight + 4 + 'px';
      hiderStyle.height = holderStyle.height;
    }

    /**
     * On after selection listener.
     *
     * @param {Number} r Selection start row index.
     * @param {Number} c Selection start column index.
     * @param {Number} r2 Selection end row index.
     * @param {Number} c2 Selection end column index.
     * @param {Object} preventScrolling Object with `value` property where its value change will be observed.
     */

  }, {
    key: 'onAfterSelection',
    value: function onAfterSelection(r, c, r2, c2, preventScrolling) {
      if (this.keyEvent === false) {
        preventScrolling.value = true;
      }
    }

    /**
     * Document mouse down listener.
     *
     * @private
     * @param {Event} event
     */

  }, {
    key: 'onDocumentMouseDown',
    value: function onDocumentMouseDown(event) {
      if (!this.isOpened()) {
        return;
      }
      if (this.container && (0, _element.isChildOf)(event.target, this.container)) {
        this.executeCommand(event);
      }
      // Close menu when clicked element is not belongs to menu itself
      if (this.options.standalone && this.hotMenu && !(0, _element.isChildOf)(event.target, this.hotMenu.rootElement)) {
        this.close(true);

        // Automatically close menu when clicked element is not belongs to menu or submenu (not necessarily to itself)
      } else if ((this.isAllSubMenusClosed() || this.isSubMenu()) && !(0, _element.isChildOf)(event.target, '.htMenu') && (0, _element.isChildOf)(event.target, document)) {
        this.close(true);
      }
    }
  }]);

  return Menu;
}();

(0, _object.mixin)(Menu, _localHooks2.default);

exports.default = Menu;

/***/ }),
/* 415 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _element = __webpack_require__(0);

var _event = __webpack_require__(12);

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Helper class for checking if element will fit at the desired side of cursor.
 *
 * @class Cursor
 * @plugin ContextMenu
 */
var Cursor = function () {
  function Cursor(object) {
    _classCallCheck(this, Cursor);

    var windowScrollTop = (0, _element.getWindowScrollTop)();
    var windowScrollLeft = (0, _element.getWindowScrollLeft)();
    var top = void 0,
        topRelative = void 0;
    var left = void 0,
        leftRelative = void 0;
    var cellHeight = void 0,
        cellWidth = void 0;

    this.type = this.getSourceType(object);

    if (this.type === 'literal') {
      top = parseInt(object.top, 10);
      left = parseInt(object.left, 10);
      cellHeight = object.height || 0;
      cellWidth = object.width || 0;
      topRelative = top;
      leftRelative = left;
      top += windowScrollTop;
      left += windowScrollLeft;
    } else if (this.type === 'event') {
      top = parseInt((0, _event.pageY)(object), 10);
      left = parseInt((0, _event.pageX)(object), 10);
      cellHeight = object.target.clientHeight;
      cellWidth = object.target.clientWidth;
      topRelative = top - windowScrollTop;
      leftRelative = left - windowScrollLeft;
    }

    this.top = top;
    this.topRelative = topRelative;
    this.left = left;
    this.leftRelative = leftRelative;
    this.scrollTop = windowScrollTop;
    this.scrollLeft = windowScrollLeft;
    this.cellHeight = cellHeight;
    this.cellWidth = cellWidth;
  }

  /**
   * Get source type name.
   *
   * @param {*} object Event or Object with coordinates.
   * @returns {String} Returns one of this values: `'literal'`, `'event'`.
   */


  _createClass(Cursor, [{
    key: 'getSourceType',
    value: function getSourceType(object) {
      var type = 'literal';

      if (object instanceof Event) {
        type = 'event';
      }

      return type;
    }

    /**
     * Checks if element can be placed above the cursor.
     *
     * @param {HTMLElement} element Element to check if it's size will fit above the cursor.
     * @returns {Boolean}
     */

  }, {
    key: 'fitsAbove',
    value: function fitsAbove(element) {
      return this.topRelative >= element.offsetHeight;
    }

    /**
     * Checks if element can be placed below the cursor.
     *
     * @param {HTMLElement} element Element to check if it's size will fit below the cursor.
     * @param {Number} [viewportHeight] The viewport height.
     * @returns {Boolean}
     */

  }, {
    key: 'fitsBelow',
    value: function fitsBelow(element) {
      var viewportHeight = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.innerHeight;

      return this.topRelative + element.offsetHeight <= viewportHeight;
    }

    /**
     * Checks if element can be placed on the right of the cursor.
     *
     * @param {HTMLElement} element Element to check if it's size will fit on the right of the cursor.
     * @param {Number} [viewportWidth] The viewport width.
     * @returns {Boolean}
     */

  }, {
    key: 'fitsOnRight',
    value: function fitsOnRight(element) {
      var viewportWidth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.innerWidth;

      return this.leftRelative + this.cellWidth + element.offsetWidth <= viewportWidth;
    }

    /**
     * Checks if element can be placed on the left on the cursor.
     *
     * @param {HTMLElement} element Element to check if it's size will fit on the left of the cursor.
     * @returns {Boolean}
     */

  }, {
    key: 'fitsOnLeft',
    value: function fitsOnLeft(element) {
      return this.leftRelative >= element.offsetWidth;
    }
  }]);

  return Cursor;
}();

exports.default = Cursor;

/***/ }),
/* 416 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 417 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _SheetClip = __webpack_require__(307);

var _SheetClip2 = _interopRequireDefault(_SheetClip);

var _src = __webpack_require__(15);

var _element = __webpack_require__(0);

var _array = __webpack_require__(2);

var _number = __webpack_require__(6);

var _plugins = __webpack_require__(7);

var _textarea = __webpack_require__(418);

var _textarea2 = _interopRequireDefault(_textarea);

var _copy = __webpack_require__(419);

var _copy2 = _interopRequireDefault(_copy);

var _cut = __webpack_require__(420);

var _cut2 = _interopRequireDefault(_cut);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _pasteEvent = __webpack_require__(421);

var _pasteEvent2 = _interopRequireDefault(_pasteEvent);

__webpack_require__(423);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

_pluginHooks2.default.getSingleton().register('afterCopyLimit');
_pluginHooks2.default.getSingleton().register('modifyCopyableRange');
_pluginHooks2.default.getSingleton().register('beforeCut');
_pluginHooks2.default.getSingleton().register('afterCut');
_pluginHooks2.default.getSingleton().register('beforePaste');
_pluginHooks2.default.getSingleton().register('afterPaste');
_pluginHooks2.default.getSingleton().register('beforeCopy');
_pluginHooks2.default.getSingleton().register('afterCopy');

var ROWS_LIMIT = 1000;
var COLUMNS_LIMIT = 1000;
var privatePool = new WeakMap();

/**
 * @description
 * This plugin enables the copy/paste functionality in the Handsontable.
 *
 * @example
 * ```js
 * ...
 * copyPaste: true,
 * ...
 * ```
 * @class CopyPaste
 * @plugin CopyPaste
 */

var CopyPaste = function (_BasePlugin) {
  _inherits(CopyPaste, _BasePlugin);

  function CopyPaste(hotInstance) {
    _classCallCheck(this, CopyPaste);

    /**
     * Event manager
     *
     * @type {EventManager}
     */
    var _this = _possibleConstructorReturn(this, (CopyPaste.__proto__ || Object.getPrototypeOf(CopyPaste)).call(this, hotInstance));

    _this.eventManager = new _eventManager2.default(_this);
    /**
     * Maximum number of columns than can be copied to clipboard using <kbd>CTRL</kbd> + <kbd>C</kbd>.
     *
     * @private
     * @type {Number}
     * @default 1000
     */
    _this.columnsLimit = COLUMNS_LIMIT;
    /**
     * Ranges of the cells coordinates, which should be used to copy/cut/paste actions.
     *
     * @private
     * @type {Array}
     */
    _this.copyableRanges = [];
    /**
     * Defines paste (<kbd>CTRL</kbd> + <kbd>V</kbd>) behavior.
     * * Default value `"overwrite"` will paste clipboard value over current selection.
     * * When set to `"shift_down"`, clipboard data will be pasted in place of current selection, while all selected cells are moved down.
     * * When set to `"shift_right"`, clipboard data will be pasted in place of current selection, while all selected cells are moved right.
     *
     * @private
     * @type {String}
     * @default 'overwrite'
     */
    _this.pasteMode = 'overwrite';
    /**
     * Maximum number of rows than can be copied to clipboard using <kbd>CTRL</kbd> + <kbd>C</kbd>.
     *
     * @private
     * @type {Number}
     * @default 1000
     */
    _this.rowsLimit = ROWS_LIMIT;
    /**
     * The `textarea` element which is necessary to process copying, cutting off and pasting.
     *
     * @private
     * @type {HTMLElement}
     * @default undefined
     */
    _this.textarea = void 0;

    privatePool.set(_this, {
      isTriggeredByCopy: false,
      isTriggeredByCut: false,
      isBeginEditing: false,
      isFragmentSelectionEnabled: false
    });
    return _this;
  }

  /**
   * Check if plugin is enabled.
   *
   * @returns {Boolean}
   */


  _createClass(CopyPaste, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return !!this.hot.getSettings().copyPaste;
    }

    /**
     * Enable the plugin.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }
      var settings = this.hot.getSettings();
      var priv = privatePool.get(this);

      this.textarea = _textarea2.default.getSingleton();
      priv.isFragmentSelectionEnabled = settings.fragmentSelection;

      if (_typeof(settings.copyPaste) === 'object') {
        this.pasteMode = settings.copyPaste.pasteMode || this.pasteMode;
        this.rowsLimit = settings.copyPaste.rowsLimit || this.rowsLimit;
        this.columnsLimit = settings.copyPaste.columnsLimit || this.columnsLimit;
      }

      this.addHook('afterContextMenuDefaultOptions', function (options) {
        return _this2.onAfterContextMenuDefaultOptions(options);
      });
      this.addHook('afterSelectionEnd', function () {
        return _this2.onAfterSelectionEnd();
      });

      this.registerEvents();

      _get(CopyPaste.prototype.__proto__ || Object.getPrototypeOf(CopyPaste.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();

      _get(CopyPaste.prototype.__proto__ || Object.getPrototypeOf(CopyPaste.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      if (this.textarea) {
        this.textarea.destroy();
      }

      _get(CopyPaste.prototype.__proto__ || Object.getPrototypeOf(CopyPaste.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Prepares copyable text from the cells selection in the invisible textarea.
     *
     * @function setCopyable
     * @memberof CopyPaste#
     */

  }, {
    key: 'setCopyableText',
    value: function setCopyableText() {
      var selRange = this.hot.getSelectedRange();

      if (!selRange) {
        return;
      }

      var topLeft = selRange.getTopLeftCorner();
      var bottomRight = selRange.getBottomRightCorner();
      var startRow = topLeft.row;
      var startCol = topLeft.col;
      var endRow = bottomRight.row;
      var endCol = bottomRight.col;
      var finalEndRow = Math.min(endRow, startRow + this.rowsLimit - 1);
      var finalEndCol = Math.min(endCol, startCol + this.columnsLimit - 1);

      this.copyableRanges.length = 0;

      this.copyableRanges.push({
        startRow: startRow,
        startCol: startCol,
        endRow: finalEndRow,
        endCol: finalEndCol
      });

      this.copyableRanges = this.hot.runHooks('modifyCopyableRange', this.copyableRanges);

      if (endRow !== finalEndRow || endCol !== finalEndCol) {
        this.hot.runHooks('afterCopyLimit', endRow - startRow + 1, endCol - startCol + 1, this.rowsLimit, this.columnsLimit);
      }
    }

    /**
     * Create copyable text releated to range objects.
     *
     * @since 0.19.0
     * @param {Array} ranges Array of Objects with properties `startRow`, `endRow`, `startCol` and `endCol`.
     * @returns {String} Returns string which will be copied into clipboard.
     */

  }, {
    key: 'getRangedCopyableData',
    value: function getRangedCopyableData(ranges) {
      var _this3 = this;

      var dataSet = [];
      var copyableRows = [];
      var copyableColumns = [];

      // Count all copyable rows and columns
      (0, _array.arrayEach)(ranges, function (range) {
        (0, _number.rangeEach)(range.startRow, range.endRow, function (row) {
          if (copyableRows.indexOf(row) === -1) {
            copyableRows.push(row);
          }
        });
        (0, _number.rangeEach)(range.startCol, range.endCol, function (column) {
          if (copyableColumns.indexOf(column) === -1) {
            copyableColumns.push(column);
          }
        });
      });
      // Concat all rows and columns data defined in ranges into one copyable string
      (0, _array.arrayEach)(copyableRows, function (row) {
        var rowSet = [];

        (0, _array.arrayEach)(copyableColumns, function (column) {
          rowSet.push(_this3.hot.getCopyableData(row, column));
        });

        dataSet.push(rowSet);
      });

      return _SheetClip2.default.stringify(dataSet);
    }

    /**
     * Create copyable text releated to range objects.
     *
     * @since 0.31.1
     * @param {Array} ranges Array of Objects with properties `startRow`, `startCol`, `endRow` and `endCol`.
     * @returns {Array} Returns array of arrays which will be copied into clipboard.
     */

  }, {
    key: 'getRangedData',
    value: function getRangedData(ranges) {
      var _this4 = this;

      var dataSet = [];
      var copyableRows = [];
      var copyableColumns = [];

      // Count all copyable rows and columns
      (0, _array.arrayEach)(ranges, function (range) {
        (0, _number.rangeEach)(range.startRow, range.endRow, function (row) {
          if (copyableRows.indexOf(row) === -1) {
            copyableRows.push(row);
          }
        });
        (0, _number.rangeEach)(range.startCol, range.endCol, function (column) {
          if (copyableColumns.indexOf(column) === -1) {
            copyableColumns.push(column);
          }
        });
      });
      // Concat all rows and columns data defined in ranges into one copyable string
      (0, _array.arrayEach)(copyableRows, function (row) {
        var rowSet = [];

        (0, _array.arrayEach)(copyableColumns, function (column) {
          rowSet.push(_this4.hot.getCopyableData(row, column));
        });

        dataSet.push(rowSet);
      });

      return dataSet;
    }

    /**
     * Copy action.
     */

  }, {
    key: 'copy',
    value: function copy() {
      var priv = privatePool.get(this);

      priv.isTriggeredByCopy = true;

      this.textarea.select();
      document.execCommand('copy');
    }

    /**
     * Cut action.
     */

  }, {
    key: 'cut',
    value: function cut() {
      var priv = privatePool.get(this);

      priv.isTriggeredByCut = true;

      this.textarea.select();
      document.execCommand('cut');
    }

    /**
     * Simulated paste action.
     *
     * @param {String} [value=''] New value, which should be `pasted`.
     */

  }, {
    key: 'paste',
    value: function paste() {
      var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

      var pasteData = new _pasteEvent2.default();
      pasteData.clipboardData.setData('text/plain', value);

      this.onPaste(pasteData);
    }

    /**
     * Register event listeners.
     *
     * @private
     */

  }, {
    key: 'registerEvents',
    value: function registerEvents() {
      var _this5 = this;

      this.eventManager.addEventListener(this.textarea.element, 'paste', function (event) {
        return _this5.onPaste(event);
      });
      this.eventManager.addEventListener(this.textarea.element, 'cut', function (event) {
        return _this5.onCut(event);
      });
      this.eventManager.addEventListener(this.textarea.element, 'copy', function (event) {
        return _this5.onCopy(event);
      });
    }

    /**
     * `copy` event callback on textarea element.
     *
     * @param {Event} event ClipboardEvent.
     * @private
     */

  }, {
    key: 'onCopy',
    value: function onCopy(event) {
      var priv = privatePool.get(this);

      if (!this.hot.isListening() && !priv.isTriggeredByCopy) {
        return;
      }

      this.setCopyableText();
      priv.isTriggeredByCopy = false;

      var rangedData = this.getRangedData(this.copyableRanges);
      var allowCopying = !!this.hot.runHooks('beforeCopy', rangedData, this.copyableRanges);
      var value = '';

      if (allowCopying) {
        value = _SheetClip2.default.stringify(rangedData);

        if (event && event.clipboardData) {
          event.clipboardData.setData('text/plain', value);
        } else if (typeof ClipboardEvent === 'undefined') {
          window.clipboardData.setData('Text', value);
        }

        this.hot.runHooks('afterCopy', rangedData, this.copyableRanges);
      }

      event.preventDefault();
    }

    /**
     * `cut` event callback on textarea element.
     *
     * @param {Event} event ClipboardEvent.
     * @private
     */

  }, {
    key: 'onCut',
    value: function onCut(event) {
      var priv = privatePool.get(this);

      if (!this.hot.isListening() && !priv.isTriggeredByCut) {
        return;
      }

      this.setCopyableText();
      priv.isTriggeredByCut = false;

      var rangedData = this.getRangedData(this.copyableRanges);
      var allowCuttingOut = !!this.hot.runHooks('beforeCut', rangedData, this.copyableRanges);
      var value = void 0;

      if (allowCuttingOut) {
        value = _SheetClip2.default.stringify(rangedData);

        if (event && event.clipboardData) {
          event.clipboardData.setData('text/plain', value);
        } else if (typeof ClipboardEvent === 'undefined') {
          window.clipboardData.setData('Text', value);
        }

        this.hot.selection.empty();
        this.hot.runHooks('afterCut', rangedData, this.copyableRanges);
      }

      event.preventDefault();
    }

    /**
     * `paste` event callback on textarea element.
     *
     * @param {Event} event ClipboardEvent or pseudo ClipboardEvent, if paste was called manually.
     * @private
     */

  }, {
    key: 'onPaste',
    value: function onPaste(event) {
      var _this6 = this;

      if (!this.hot.isListening()) {
        return;
      }
      if (event && event.preventDefault) {
        event.preventDefault();
      }

      var inputArray = void 0;

      if (event && typeof event.clipboardData !== 'undefined') {
        this.textarea.setValue(event.clipboardData.getData('text/plain'));
      } else if (typeof ClipboardEvent === 'undefined' && typeof window.clipboardData !== 'undefined') {
        this.textarea.setValue(window.clipboardData.getData('Text'));
      }

      inputArray = _SheetClip2.default.parse(this.textarea.getValue());
      this.textarea.setValue(' ');

      if (inputArray.length === 0) {
        return;
      }

      var allowPasting = !!this.hot.runHooks('beforePaste', inputArray, this.copyableRanges);

      if (!allowPasting) {
        return;
      }

      var selected = this.hot.getSelected();
      var coordsFrom = new _src.CellCoords(selected[0], selected[1]);
      var coordsTo = new _src.CellCoords(selected[2], selected[3]);
      var cellRange = new _src.CellRange(coordsFrom, coordsFrom, coordsTo);
      var topLeftCorner = cellRange.getTopLeftCorner();
      var bottomRightCorner = cellRange.getBottomRightCorner();
      var areaStart = topLeftCorner;
      var areaEnd = new _src.CellCoords(Math.max(bottomRightCorner.row, inputArray.length - 1 + topLeftCorner.row), Math.max(bottomRightCorner.col, inputArray[0].length - 1 + topLeftCorner.col));

      var isSelRowAreaCoverInputValue = coordsTo.row - coordsFrom.row >= inputArray.length - 1;
      var isSelColAreaCoverInputValue = coordsTo.col - coordsFrom.col >= inputArray[0].length - 1;

      this.hot.addHookOnce('afterChange', function (changes) {
        var changesLength = changes ? changes.length : 0;

        if (changesLength) {
          var offset = { row: 0, col: 0 };
          var highestColumnIndex = -1;

          (0, _array.arrayEach)(changes, function (change, index) {
            var nextChange = changesLength > index + 1 ? changes[index + 1] : null;

            if (nextChange) {
              if (!isSelRowAreaCoverInputValue) {
                offset.row += Math.max(nextChange[0] - change[0] - 1, 0);
              }
              if (!isSelColAreaCoverInputValue && change[1] > highestColumnIndex) {
                highestColumnIndex = change[1];
                offset.col += Math.max(nextChange[1] - change[1] - 1, 0);
              }
            }
          });
          _this6.hot.selectCell(areaStart.row, areaStart.col, areaEnd.row + offset.row, areaEnd.col + offset.col);
        }
      });

      this.hot.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'CopyPaste.paste', this.pasteMode);
      this.hot.runHooks('afterPaste', inputArray, this.copyableRanges);
    }

    /**
     * Add copy, cut and paste options to the Context Menu.
     *
     * @private
     * @param {Object} options Contains default added options of the Context Menu.
     */

  }, {
    key: 'onAfterContextMenuDefaultOptions',
    value: function onAfterContextMenuDefaultOptions(options) {
      options.items.push({
        name: '---------'
      }, (0, _copy2.default)(this), (0, _cut2.default)(this));
    }

    /**
     * We have to keep focus on textarea element, to make possible use of the browser tools (copy, cut, paste).
     *
     * @private
     */

  }, {
    key: 'onAfterSelectionEnd',
    value: function onAfterSelectionEnd() {
      var priv = privatePool.get(this);
      var editor = this.hot.getActiveEditor();

      if (editor && typeof editor.isOpened !== 'undefined' && editor.isOpened()) {
        return;
      }
      if (priv.isFragmentSelectionEnabled && !this.textarea.isActive() && (0, _element.getSelectionText)()) {
        return;
      }

      this.setCopyableText();
      this.textarea.select();
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      if (this.textarea) {
        this.textarea.destroy();
      }

      _get(CopyPaste.prototype.__proto__ || Object.getPrototypeOf(CopyPaste.prototype), 'destroy', this).call(this);
    }
  }]);

  return CopyPaste;
}(_base2.default);

(0, _plugins.registerPlugin)('CopyPaste', CopyPaste);

exports.default = CopyPaste;

/***/ }),
/* 418 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class Textarea
 *
 * @plugin CopyPaste
 */
var Textarea = function () {
  _createClass(Textarea, null, [{
    key: 'getSingleton',
    value: function getSingleton() {
      globalSingleton.append();

      return globalSingleton;
    }
  }]);

  function Textarea() {
    _classCallCheck(this, Textarea);

    /**
     * Main textarea element.
     *
     * @type {HTMLElement}
     */
    this.element = void 0;
    /**
     * Store information about append to the document.body.
     *
     * @type {Boolean}
     */
    this.isAppended = false;
    /**
     * Reference counter.
     *
     * @type {Number}
     */
    this.refCounter = 0;
  }

  /**
   * Apends textarea element to the `body`
   */


  _createClass(Textarea, [{
    key: 'append',
    value: function append() {
      if (this.hasBeenDestroyed()) {
        this.create();
      }

      this.refCounter++;

      if (!this.isAppended && document.body) {
        if (document.body) {
          this.isAppended = true;
          document.body.appendChild(this.element);
        }
      }
    }

    /**
     * Prepares textarea element with proper attributes.
     */

  }, {
    key: 'create',
    value: function create() {
      this.element = document.createElement('textarea');
      this.element.id = 'HandsontableCopyPaste';
      this.element.className = 'copyPaste';
      this.element.tabIndex = -1;
      this.element.autocomplete = 'off';
      this.element.wrap = 'hard';
      this.element.value = ' ';
    }

    /**
     * Deselects textarea element if is active.
     */

  }, {
    key: 'deselect',
    value: function deselect() {
      if (this.element === document.activeElement) {
        document.activeElement.blur();
      }
    }

    /**
     * Destroy instance
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.refCounter--;
      this.refCounter = this.refCounter < 0 ? 0 : this.refCounter;

      if (this.hasBeenDestroyed() && this.element && this.element.parentNode) {
        this.element.parentNode.removeChild(this.element);
        this.element = null;
        this.isAppended = false;
      }
    }

    /**
     * Getter for the element.
     *
     * @returns {String}
     */

  }, {
    key: 'getValue',
    value: function getValue() {
      return this.element.value;
    }

    /**
     * Check if instance has been destroyed
     *
     * @returns {Boolean}
     */

  }, {
    key: 'hasBeenDestroyed',
    value: function hasBeenDestroyed() {
      return this.refCounter < 1;
    }

    /**
     * Check if the element is an active element in frame.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isActive',
    value: function isActive() {
      return this.element === document.activeElement;
    }

    /**
     * Sets focus on the element and select content.
     */

  }, {
    key: 'select',
    value: function select() {
      this.element.focus();
      this.element.select();
    }

    /**
     * Setter for the element.
     *
     * @param {String} data Value which should be insert into the element.
     */

  }, {
    key: 'setValue',
    value: function setValue(data) {
      this.element.value = data;
    }
  }]);

  return Textarea;
}();

var globalSingleton = new Textarea();

exports.default = Textarea;

/***/ }),
/* 419 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = copyItem;

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function copyItem(copyPastePlugin) {
  return {
    key: 'copy',
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_COPY);
    },
    callback: function callback() {
      copyPastePlugin.copy();
    },
    disabled: function disabled() {
      return !copyPastePlugin.hot.getSelected();
    },

    hidden: false
  };
}

/***/ }),
/* 420 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = cutItem;

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function cutItem(copyPastePlugin) {
  return {
    key: 'cut',
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_CUT);
    },
    callback: function callback() {
      copyPastePlugin.cut();
    },
    disabled: function disabled() {
      return !copyPastePlugin.hot.getSelected();
    },

    hidden: false
  };
}

/***/ }),
/* 421 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _clipboardData = __webpack_require__(422);

var _clipboardData2 = _interopRequireDefault(_clipboardData);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var PasteEvent = function PasteEvent() {
  _classCallCheck(this, PasteEvent);

  this.clipboardData = new _clipboardData2.default();
};

exports.default = PasteEvent;

/***/ }),
/* 422 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var ClipboardData = function () {
  function ClipboardData() {
    _classCallCheck(this, ClipboardData);

    this.data = {};
  }

  _createClass(ClipboardData, [{
    key: "setData",
    value: function setData(type, value) {
      this.data[type] = value;
    }
  }, {
    key: "getData",
    value: function getData(type) {
      return this.data[type] || void 0;
    }
  }]);

  return ClipboardData;
}();

exports.default = ClipboardData;

/***/ }),
/* 423 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 424 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _object = __webpack_require__(1);

var _src = __webpack_require__(15);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function CustomBorders() {}
/** *
 * Current instance (table where borders should be placed)
 */
var instance;

/**
 * This plugin enables an option to apply custom borders through the context menu (configurable with context menu key `borders`).
 *
 * To initialize Handsontable with predefined custom borders, provide cell coordinates and border styles in a form of an array.
 *
 * See [Custom Borders](http://docs.handsontable.com/demo-custom-borders.html) demo for more examples.
 *
 * @example
 * ```js
 * ...
 * customBorders: [
 *   {range: {
   *     from: {row: 1, col: 1},
   *     to: {row: 3, col: 4}},
   *     left: {},
   *     right: {},
   *     top: {},
   *     bottom: {}
   *   }
 * ],
 * ...
 *
 * // or
 * ...
 * customBorders: [
 *   {row: 2, col: 2, left: {width: 2, color: 'red'},
 *     right: {width: 1, color: 'green'}, top: '', bottom: ''}
 * ],
 * ...
 * ```
 * @private
 * @class CustomBorders
 * @plugin CustomBorders
 */

/** *
 * Check if plugin should be enabled.
 */
var checkEnable = function checkEnable(customBorders) {
  if (typeof customBorders === 'boolean') {
    if (customBorders === true) {
      return true;
    }
  }
  if ((typeof customBorders === 'undefined' ? 'undefined' : _typeof(customBorders)) === 'object') {
    if (customBorders.length > 0) {
      return true;
    }
  }

  return false;
};

/** *
 * Initialize plugin.
 */
var init = function init() {
  if (checkEnable(this.getSettings().customBorders)) {
    if (!this.customBorders) {
      instance = this;
      this.customBorders = new CustomBorders();
    }
  }
};

/** *
 * Get index of border from the settings.
 *
 * @param {String} className
 * @returns {Number}
 */
var getSettingIndex = function getSettingIndex(className) {
  for (var i = 0; i < instance.view.wt.selections.length; i++) {
    if (instance.view.wt.selections[i].settings.className == className) {
      return i;
    }
  }

  return -1;
};

/** *
 * Insert WalkontableSelection instance into Walkontable settings.
 *
 * @param border
 */
var insertBorderIntoSettings = function insertBorderIntoSettings(border) {
  var coordinates = {
    row: border.row,
    col: border.col
  };
  var selection = new _src.Selection(border, new _src.CellRange(coordinates, coordinates, coordinates));
  var index = getSettingIndex(border.className);

  if (index >= 0) {
    instance.view.wt.selections[index] = selection;
  } else {
    instance.view.wt.selections.push(selection);
  }
};

/** *
 * Prepare borders from setting (single cell).
 *
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @param borderObj
 */
var prepareBorderFromCustomAdded = function prepareBorderFromCustomAdded(row, col, borderObj) {
  var border = createEmptyBorders(row, col);
  border = extendDefaultBorder(border, borderObj);
  this.setCellMeta(row, col, 'borders', border);

  insertBorderIntoSettings(border);
};

/** *
 * Prepare borders from setting (object).
 *
 * @param {Object} rowObj
 */
var prepareBorderFromCustomAddedRange = function prepareBorderFromCustomAddedRange(rowObj) {
  var range = rowObj.range;

  for (var row = range.from.row; row <= range.to.row; row++) {
    for (var col = range.from.col; col <= range.to.col; col++) {
      var border = createEmptyBorders(row, col);
      var add = 0;

      if (row == range.from.row) {
        add++;

        if ((0, _object.hasOwnProperty)(rowObj, 'top')) {
          border.top = rowObj.top;
        }
      }

      if (row == range.to.row) {
        add++;

        if ((0, _object.hasOwnProperty)(rowObj, 'bottom')) {
          border.bottom = rowObj.bottom;
        }
      }

      if (col == range.from.col) {
        add++;

        if ((0, _object.hasOwnProperty)(rowObj, 'left')) {
          border.left = rowObj.left;
        }
      }

      if (col == range.to.col) {
        add++;

        if ((0, _object.hasOwnProperty)(rowObj, 'right')) {
          border.right = rowObj.right;
        }
      }

      if (add > 0) {
        this.setCellMeta(row, col, 'borders', border);
        insertBorderIntoSettings(border);
      }
    }
  }
};

/** *
 * Create separated class name for borders for each cell.
 *
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @returns {String}
 */
var createClassName = function createClassName(row, col) {
  return 'border_row' + row + 'col' + col;
};

/** *
 * Create default single border for each position (top/right/bottom/left).
 *
 * @returns {Object} `{{width: number, color: string}}`
 */
var createDefaultCustomBorder = function createDefaultCustomBorder() {
  return {
    width: 1,
    color: '#000'
  };
};

/** *
 * Create default object for empty border.
 *
 * @returns {Object} `{{hide: boolean}}`
 */
var createSingleEmptyBorder = function createSingleEmptyBorder() {
  return {
    hide: true
  };
};

/** *
 * Create default Handsontable border object.
 *
 * @returns {Object} `{{width: number, color: string, cornerVisible: boolean}}`
 */
var createDefaultHtBorder = function createDefaultHtBorder() {
  return {
    width: 1,
    color: '#000',
    cornerVisible: false
  };
};

/** *
 * Prepare empty border for each cell with all custom borders hidden.
 *
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 * @returns {Object} `{{className: *, border: *, row: *, col: *, top: {hide: boolean}, right: {hide: boolean}, bottom: {hide: boolean}, left: {hide: boolean}}}`
 */
var createEmptyBorders = function createEmptyBorders(row, col) {
  return {
    className: createClassName(row, col),
    border: createDefaultHtBorder(),
    row: row,
    col: col,
    top: createSingleEmptyBorder(),
    right: createSingleEmptyBorder(),
    bottom: createSingleEmptyBorder(),
    left: createSingleEmptyBorder()
  };
};

var extendDefaultBorder = function extendDefaultBorder(defaultBorder, customBorder) {
  if ((0, _object.hasOwnProperty)(customBorder, 'border')) {
    defaultBorder.border = customBorder.border;
  }

  if ((0, _object.hasOwnProperty)(customBorder, 'top')) {
    defaultBorder.top = customBorder.top;
  }

  if ((0, _object.hasOwnProperty)(customBorder, 'right')) {
    defaultBorder.right = customBorder.right;
  }

  if ((0, _object.hasOwnProperty)(customBorder, 'bottom')) {
    defaultBorder.bottom = customBorder.bottom;
  }

  if ((0, _object.hasOwnProperty)(customBorder, 'left')) {
    defaultBorder.left = customBorder.left;
  }

  return defaultBorder;
};

/**
 * Remove borders divs from DOM.
 *
 * @param borderClassName
 */
var removeBordersFromDom = function removeBordersFromDom(borderClassName) {
  var borders = document.querySelectorAll('.' + borderClassName);

  for (var i = 0; i < borders.length; i++) {
    if (borders[i]) {
      if (borders[i].nodeName != 'TD') {
        var parent = borders[i].parentNode;

        if (parent.parentNode) {
          parent.parentNode.removeChild(parent);
        }
      }
    }
  }
};

/** *
 * Remove border (triggered from context menu).
 *
 * @param {Number} row Visual row index.
 * @param {Number} col Visual column index.
 */
var removeAllBorders = function removeAllBorders(row, col) {
  var borderClassName = createClassName(row, col);
  removeBordersFromDom(borderClassName);
  this.removeCellMeta(row, col, 'borders');
};

/** *
 * Set borders for each cell re. to border position
 *
 * @param row Visual row index.
 * @param col Visual column index.
 * @param place
 * @param remove
 */
var setBorder = function setBorder(row, col, place, remove) {

  var bordersMeta = this.getCellMeta(row, col).borders;

  if (!bordersMeta || bordersMeta.border == undefined) {
    bordersMeta = createEmptyBorders(row, col);
  }

  if (remove) {
    bordersMeta[place] = createSingleEmptyBorder();
  } else {
    bordersMeta[place] = createDefaultCustomBorder();
  }

  this.setCellMeta(row, col, 'borders', bordersMeta);

  var borderClassName = createClassName(row, col);
  removeBordersFromDom(borderClassName);
  insertBorderIntoSettings(bordersMeta);

  this.render();
};

/** *
 * Prepare borders based on cell and border position
 *
 * @param range
 * @param place
 * @param remove
 */
var prepareBorder = function prepareBorder(range, place, remove) {

  if (range.from.row == range.to.row && range.from.col == range.to.col) {
    if (place == 'noBorders') {
      removeAllBorders.call(this, range.from.row, range.from.col);
    } else {
      setBorder.call(this, range.from.row, range.from.col, place, remove);
    }
  } else {
    switch (place) {
      case 'noBorders':
        for (var column = range.from.col; column <= range.to.col; column++) {
          for (var row = range.from.row; row <= range.to.row; row++) {
            removeAllBorders.call(this, row, column);
          }
        }
        break;
      case 'top':
        for (var topCol = range.from.col; topCol <= range.to.col; topCol++) {
          setBorder.call(this, range.from.row, topCol, place, remove);
        }
        break;
      case 'right':
        for (var rowRight = range.from.row; rowRight <= range.to.row; rowRight++) {
          setBorder.call(this, rowRight, range.to.col, place);
        }
        break;
      case 'bottom':
        for (var bottomCol = range.from.col; bottomCol <= range.to.col; bottomCol++) {
          setBorder.call(this, range.to.row, bottomCol, place);
        }
        break;
      case 'left':
        for (var rowLeft = range.from.row; rowLeft <= range.to.row; rowLeft++) {
          setBorder.call(this, rowLeft, range.from.col, place);
        }
        break;
      default:
        break;
    }
  }
};

/** *
 * Check if selection has border by className
 *
 * @param hot
 * @param direction
 */
var checkSelectionBorders = function checkSelectionBorders(hot, direction) {
  var atLeastOneHasBorder = false;

  hot.getSelectedRange().forAll(function (r, c) {
    var metaBorders = hot.getCellMeta(r, c).borders;

    if (metaBorders) {
      if (direction) {
        if (!(0, _object.hasOwnProperty)(metaBorders[direction], 'hide')) {
          atLeastOneHasBorder = true;
          return false; // breaks forAll
        }
      } else {
        atLeastOneHasBorder = true;
        return false; // breaks forAll
      }
    }
  });
  return atLeastOneHasBorder;
};

/** *
 * Mark label in contextMenu as selected
 *
 * @param label
 * @returns {string}
 */
var markSelected = function markSelected(label) {
  return '<span class="selected">' + String.fromCharCode(10003) + '</span>' + label; // workaround for https://github.com/handsontable/handsontable/issues/1946
};

/** *
 * Add border options to context menu
 *
 * @param defaultOptions
 */
var addBordersOptionsToContextMenu = function addBordersOptionsToContextMenu(defaultOptions) {
  if (!this.getSettings().customBorders) {
    return;
  }

  defaultOptions.items.push({
    name: '---------'
  });
  defaultOptions.items.push({
    key: 'borders',
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_BORDERS);
    },
    disabled: function disabled() {
      return this.selection.selectedHeader.corner;
    },

    submenu: {
      items: [{
        key: 'borders:top',
        name: function name() {
          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_BORDERS_TOP);

          var hasBorder = checkSelectionBorders(this, 'top');
          if (hasBorder) {
            label = markSelected(label);
          }

          return label;
        },
        callback: function callback() {
          var hasBorder = checkSelectionBorders(this, 'top');
          prepareBorder.call(this, this.getSelectedRange(), 'top', hasBorder);
        }
      }, {
        key: 'borders:right',
        name: function name() {
          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_BORDERS_RIGHT);
          var hasBorder = checkSelectionBorders(this, 'right');
          if (hasBorder) {
            label = markSelected(label);
          }
          return label;
        },
        callback: function callback() {
          var hasBorder = checkSelectionBorders(this, 'right');
          prepareBorder.call(this, this.getSelectedRange(), 'right', hasBorder);
        }
      }, {
        key: 'borders:bottom',
        name: function name() {
          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_BORDERS_BOTTOM);
          var hasBorder = checkSelectionBorders(this, 'bottom');
          if (hasBorder) {
            label = markSelected(label);
          }
          return label;
        },
        callback: function callback() {
          var hasBorder = checkSelectionBorders(this, 'bottom');
          prepareBorder.call(this, this.getSelectedRange(), 'bottom', hasBorder);
        }
      }, {
        key: 'borders:left',
        name: function name() {
          var label = this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_BORDERS_LEFT);
          var hasBorder = checkSelectionBorders(this, 'left');
          if (hasBorder) {
            label = markSelected(label);
          }

          return label;
        },
        callback: function callback() {
          var hasBorder = checkSelectionBorders(this, 'left');
          prepareBorder.call(this, this.getSelectedRange(), 'left', hasBorder);
        }
      }, {
        key: 'borders:no_borders',
        name: function name() {
          return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_REMOVE_BORDERS);
        },
        callback: function callback() {
          prepareBorder.call(this, this.getSelectedRange(), 'noBorders');
        },
        disabled: function disabled() {
          return !checkSelectionBorders(this);
        }
      }]
    }
  });
};

_pluginHooks2.default.getSingleton().add('beforeInit', init);
_pluginHooks2.default.getSingleton().add('afterContextMenuDefaultOptions', addBordersOptionsToContextMenu);
_pluginHooks2.default.getSingleton().add('afterInit', function () {
  var customBorders = this.getSettings().customBorders;

  if (customBorders) {
    for (var i = 0; i < customBorders.length; i++) {
      if (customBorders[i].range) {
        prepareBorderFromCustomAddedRange.call(this, customBorders[i]);
      } else {
        prepareBorderFromCustomAdded.call(this, customBorders[i].row, customBorders[i].col, customBorders[i]);
      }
    }

    this.render();
    this.view.wt.draw(true);
  }
});

exports.default = CustomBorders;

/***/ }),
/* 425 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _plugins = __webpack_require__(7);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @description
 * Plugin used to scroll Handsontable by selecting a cell and dragging outside of the visible viewport.
 *
 *
 * @class DragToScroll
 * @plugin DragToScroll
 */
var DragToScroll = function (_BasePlugin) {
  _inherits(DragToScroll, _BasePlugin);

  function DragToScroll(hotInstance) {
    _classCallCheck(this, DragToScroll);

    /**
     * Instance of {@link EventManager}.
     *
     * @type {EventManager}
     */
    var _this = _possibleConstructorReturn(this, (DragToScroll.__proto__ || Object.getPrototypeOf(DragToScroll)).call(this, hotInstance));

    _this.eventManager = new _eventManager2.default(_this);
    /**
     * DOMRect - size of an element and its position relative to the viewport,
     * e.g. {bottom: 449, height: 441, left: 8, right: 814, top: 8, width: 806, x: 8, y:8}.
     *
     * @type {Object}
     */
    _this.boundaries = null;
    /**
     * Callback function.
     *
     * @type {Function}
     */
    _this.callback = null;
    /**
     * Flag indicates mouseDown/mouseUp.
     *
     * @type {Boolean}
     */
    _this.listening = false;
    return _this;
  }

  /**
   * Check if the plugin is enabled in the Handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(DragToScroll, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return !!this.hot.getSettings().dragToScroll;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.addHook('afterOnCellMouseDown', function () {
        return _this2.setupListening();
      });
      this.addHook('afterOnCellCornerMouseDown', function () {
        return _this2.setupListening();
      });

      this.registerEvents();

      _get(DragToScroll.prototype.__proto__ || Object.getPrototypeOf(DragToScroll.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();

      _get(DragToScroll.prototype.__proto__ || Object.getPrototypeOf(DragToScroll.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      this.unregisterEvents();

      _get(DragToScroll.prototype.__proto__ || Object.getPrototypeOf(DragToScroll.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Sets the value of the visible element.
     *
     * @param boundaries {Object} compatible with getBoundingClientRect
     */

  }, {
    key: 'setBoundaries',
    value: function setBoundaries(boundaries) {
      this.boundaries = boundaries;
    }

    /**
     * Change callback function.
     *
     * @param callback {Function}
     */

  }, {
    key: 'setCallback',
    value: function setCallback(callback) {
      this.callback = callback;
    }

    /**
     * Check if mouse position (x, y) is outside of the viewport.
     *
     * @param {Number} x
     * @param {Number} y
     */

  }, {
    key: 'check',
    value: function check(x, y) {
      var diffX = 0;
      var diffY = 0;

      if (y < this.boundaries.top) {
        // y is less than top
        diffY = y - this.boundaries.top;
      } else if (y > this.boundaries.bottom) {
        // y is more than bottom
        diffY = y - this.boundaries.bottom;
      }

      if (x < this.boundaries.left) {
        // x is less than left
        diffX = x - this.boundaries.left;
      } else if (x > this.boundaries.right) {
        // x is more than right
        diffX = x - this.boundaries.right;
      }

      this.callback(diffX, diffY);
    }

    /**
     * Register dom listeners.
     *
     * @private
     */

  }, {
    key: 'registerEvents',
    value: function registerEvents() {
      var _this3 = this;

      this.eventManager.addEventListener(document, 'mouseup', function () {
        return _this3.onMouseUp();
      });
      this.eventManager.addEventListener(document, 'mousemove', function (event) {
        return _this3.onMouseMove(event);
      });
    }

    /**
     * Unbind the events used by the plugin.
     *
     * @private
     */

  }, {
    key: 'unregisterEvents',
    value: function unregisterEvents() {
      this.eventManager.clear();
    }

    /**
     * On after on cell/cellCorner mouse down listener.
     *
     * @private
     */

  }, {
    key: 'setupListening',
    value: function setupListening() {
      var scrollHandler = this.hot.view.wt.wtTable.holder; // native scroll

      if (scrollHandler === window) {
        // not much we can do currently
        return;
      }

      this.setBoundaries(scrollHandler.getBoundingClientRect());
      this.setCallback(function (scrollX, scrollY) {
        if (scrollX < 0) {
          scrollHandler.scrollLeft -= 50;
        } else if (scrollX > 0) {
          scrollHandler.scrollLeft += 50;
        }

        if (scrollY < 0) {
          scrollHandler.scrollTop -= 20;
        } else if (scrollY > 0) {
          scrollHandler.scrollTop += 20;
        }
      });

      this.listening = true;
    }

    /**
     * 'mouseMove' event callback.
     *
     * @private
     * @param {MouseEvent} event `mousemove` event properties.
     */

  }, {
    key: 'onMouseMove',
    value: function onMouseMove(event) {
      if (this.listening) {
        this.check(event.clientX, event.clientY);
      }
    }

    /**
     * `onMouseUp` hook callback.
     *
     * @private
     */

  }, {
    key: 'onMouseUp',
    value: function onMouseUp() {
      this.listening = false;
    }

    /**
     * Destroy instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      _get(DragToScroll.prototype.__proto__ || Object.getPrototypeOf(DragToScroll.prototype), 'destroy', this).call(this);
    }
  }]);

  return DragToScroll;
}(_base2.default);

(0, _plugins.registerPlugin)('dragToScroll', DragToScroll);

exports.default = DragToScroll;

/***/ }),
/* 426 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _plugins = __webpack_require__(7);

var _array = __webpack_require__(2);

var _freezeColumn = __webpack_require__(427);

var _freezeColumn2 = _interopRequireDefault(_freezeColumn);

var _unfreezeColumn = __webpack_require__(428);

var _unfreezeColumn2 = _interopRequireDefault(_unfreezeColumn);

__webpack_require__(429);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var privatePool = new WeakMap();
/**
 * This plugin allows to manually "freeze" and "unfreeze" a column using an entry in the Context Menu.
 * You can turn it on by setting a `manualColumnFreeze` property to `true`.
 *
 * @plugin ManualColumnFreeze
 * @dependencies ManualColumnMove
 */

var ManualColumnFreeze = function (_BasePlugin) {
  _inherits(ManualColumnFreeze, _BasePlugin);

  function ManualColumnFreeze(hotInstance) {
    _classCallCheck(this, ManualColumnFreeze);

    var _this = _possibleConstructorReturn(this, (ManualColumnFreeze.__proto__ || Object.getPrototypeOf(ManualColumnFreeze)).call(this, hotInstance));

    privatePool.set(_this, {
      moveByFreeze: false,
      afterFirstUse: false
    });
    /**
     * Original column positions
     *
     * @type {Array}
     */
    _this.frozenColumnsBasePositions = [];
    /**
     * Reference to the `ManualColumnMove` plugin.
     */
    _this.manualColumnMovePlugin = void 0;
    return _this;
  }

  /**
   * Check if the plugin is enabled in the Handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(ManualColumnFreeze, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return !!this.hot.getSettings().manualColumnFreeze;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.addHook('afterContextMenuDefaultOptions', function (options) {
        return _this2.addContextMenuEntry(options);
      });
      this.addHook('afterInit', function () {
        return _this2.onAfterInit();
      });
      this.addHook('beforeColumnMove', function (rows, target) {
        return _this2.onBeforeColumnMove(rows, target);
      });

      _get(ManualColumnFreeze.prototype.__proto__ || Object.getPrototypeOf(ManualColumnFreeze.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      var priv = privatePool.get(this);

      priv.afterFirstUse = false;
      priv.moveByFreeze = false;

      _get(ManualColumnFreeze.prototype.__proto__ || Object.getPrototypeOf(ManualColumnFreeze.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();

      _get(ManualColumnFreeze.prototype.__proto__ || Object.getPrototypeOf(ManualColumnFreeze.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Freeze the given column (add it to fixed columns).
     *
     * @param {Number} column Visual column index.
     */

  }, {
    key: 'freezeColumn',
    value: function freezeColumn(column) {
      var priv = privatePool.get(this);
      var settings = this.hot.getSettings();

      if (!priv.afterFirstUse) {
        priv.afterFirstUse = true;
      }

      if (settings.fixedColumnsLeft === this.hot.countCols() || column <= settings.fixedColumnsLeft - 1) {
        return; // already fixed
      }

      priv.moveByFreeze = true;

      if (column !== this.getMovePlugin().columnsMapper.getValueByIndex(column)) {
        this.frozenColumnsBasePositions[settings.fixedColumnsLeft] = column;
      }

      this.getMovePlugin().moveColumn(column, settings.fixedColumnsLeft++);
    }

    /**
     * Unfreeze the given column (remove it from fixed columns and bring to it's previous position).
     *
     * @param {Number} column Visual column index.
     */

  }, {
    key: 'unfreezeColumn',
    value: function unfreezeColumn(column) {
      var priv = privatePool.get(this);
      var settings = this.hot.getSettings();

      if (!priv.afterFirstUse) {
        priv.afterFirstUse = true;
      }

      if (settings.fixedColumnsLeft <= 0 || column > settings.fixedColumnsLeft - 1) {
        return; // not fixed
      }

      var returnCol = this.getBestColumnReturnPosition(column);

      priv.moveByFreeze = true;
      settings.fixedColumnsLeft--;

      this.getMovePlugin().moveColumn(column, returnCol + 1);
    }

    /**
     * Get the reference to the ManualColumnMove plugin.
     *
     * @private
     * @returns {Object}
     */

  }, {
    key: 'getMovePlugin',
    value: function getMovePlugin() {
      if (!this.manualColumnMovePlugin) {
        this.manualColumnMovePlugin = this.hot.getPlugin('manualColumnMove');
      }

      return this.manualColumnMovePlugin;
    }

    /**
     * Estimates the most fitting return position for unfrozen column.
     *
     * @private
     * @param {Number} column Visual column index.
     */

  }, {
    key: 'getBestColumnReturnPosition',
    value: function getBestColumnReturnPosition(column) {
      var movePlugin = this.getMovePlugin();
      var settings = this.hot.getSettings();
      var i = settings.fixedColumnsLeft;
      var j = movePlugin.columnsMapper.getValueByIndex(i);
      var initialCol = void 0;

      if (this.frozenColumnsBasePositions[column] == null) {
        initialCol = movePlugin.columnsMapper.getValueByIndex(column);

        while (j < initialCol) {
          i++;
          j = movePlugin.columnsMapper.getValueByIndex(i);
        }
      } else {
        initialCol = this.frozenColumnsBasePositions[column];
        this.frozenColumnsBasePositions[column] = void 0;

        while (j <= initialCol) {
          i++;
          j = movePlugin.columnsMapper.getValueByIndex(i);
        }
        i = j;
      }

      return i - 1;
    }
    /**
     * Add the manualColumnFreeze context menu entries.
     *
     * @private
     * @param {Object} options Context menu options.
     */

  }, {
    key: 'addContextMenuEntry',
    value: function addContextMenuEntry(options) {
      options.items.push({ name: '---------' }, (0, _freezeColumn2.default)(this), (0, _unfreezeColumn2.default)(this));
    }

    /**
     * Enabling `manualColumnMove` plugin on `afterInit` hook.
     *
     * @private
     */

  }, {
    key: 'onAfterInit',
    value: function onAfterInit() {
      if (!this.getMovePlugin().isEnabled()) {
        this.getMovePlugin().enablePlugin();
      }
    }

    /**
     * Prevent moving the rows from/to fixed area.
     *
     * @private
     * @param {Array} rows
     * @param {Number} target
     */

  }, {
    key: 'onBeforeColumnMove',
    value: function onBeforeColumnMove(rows, target) {
      var priv = privatePool.get(this);

      if (priv.afterFirstUse && !priv.moveByFreeze) {
        var frozenLen = this.hot.getSettings().fixedColumnsLeft;
        var disallowMoving = target < frozenLen;

        if (!disallowMoving) {
          (0, _array.arrayEach)(rows, function (value, index, array) {
            if (value < frozenLen) {
              disallowMoving = true;
              return false;
            }
          });
        }

        if (disallowMoving) {
          return false;
        }
      }

      if (priv.moveByFreeze) {
        priv.moveByFreeze = false;
      }
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      _get(ManualColumnFreeze.prototype.__proto__ || Object.getPrototypeOf(ManualColumnFreeze.prototype), 'destroy', this).call(this);
    }
  }]);

  return ManualColumnFreeze;
}(_base2.default);

(0, _plugins.registerPlugin)('manualColumnFreeze', ManualColumnFreeze);

exports.default = ManualColumnFreeze;

/***/ }),
/* 427 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = freezeColumnItem;

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function freezeColumnItem(manualColumnFreezePlugin) {
  return {
    key: 'freeze_column',
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_FREEZE_COLUMN);
    },
    callback: function callback() {
      var selectedColumn = this.getSelectedRange().from.col;

      manualColumnFreezePlugin.freezeColumn(selectedColumn);

      this.render();
      this.view.wt.wtOverlays.adjustElementsSize(true);
    },
    hidden: function hidden() {
      var selection = this.getSelectedRange();
      var hide = false;

      if (selection === void 0) {
        hide = true;
      } else if (selection.from.col !== selection.to.col || selection.from.col <= this.getSettings().fixedColumnsLeft - 1) {
        hide = true;
      }

      return hide;
    }
  };
}

/***/ }),
/* 428 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;
exports.default = unfreezeColumnItem;

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function unfreezeColumnItem(manualColumnFreezePlugin) {
  return {
    key: 'unfreeze_column',
    name: function name() {
      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_UNFREEZE_COLUMN);
    },
    callback: function callback() {
      var selectedColumn = this.getSelectedRange().from.col;

      manualColumnFreezePlugin.unfreezeColumn(selectedColumn);

      this.render();
      this.view.wt.wtOverlays.adjustElementsSize(true);
    },
    hidden: function hidden() {
      var selection = this.getSelectedRange();
      var hide = false;

      if (selection === void 0) {
        hide = true;
      } else if (selection.from.col !== selection.to.col || selection.from.col >= this.getSettings().fixedColumnsLeft) {
        hide = true;
      }

      return hide;
    }
  };
}

/***/ }),
/* 429 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 430 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _array = __webpack_require__(2);

var _element = __webpack_require__(0);

var _number = __webpack_require__(6);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _plugins = __webpack_require__(7);

var _columnsMapper = __webpack_require__(431);

var _columnsMapper2 = _interopRequireDefault(_columnsMapper);

var _backlight = __webpack_require__(432);

var _backlight2 = _interopRequireDefault(_backlight);

var _guideline = __webpack_require__(433);

var _guideline2 = _interopRequireDefault(_guideline);

var _src = __webpack_require__(15);

__webpack_require__(434);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

_pluginHooks2.default.getSingleton().register('beforeColumnMove');
_pluginHooks2.default.getSingleton().register('afterColumnMove');
_pluginHooks2.default.getSingleton().register('unmodifyCol');

var privatePool = new WeakMap();
var CSS_PLUGIN = 'ht__manualColumnMove';
var CSS_SHOW_UI = 'show-ui';
var CSS_ON_MOVING = 'on-moving--columns';
var CSS_AFTER_SELECTION = 'after-selection--columns';

/**
 * @plugin ManualColumnMove
 *
 * @description
 * This plugin allows to change columns order.
 *
 * API:
 * - moveColumn - move single column to the new position.
 * - moveColumns - move many columns (as an array of indexes) to the new position.
 *
 * If you want apply visual changes, you have to call manually the render() method on the instance of Handsontable.
 *
 * UI components:
 * - backlight - highlight of selected columns.
 * - guideline - line which shows where rows has been moved.
 *
 * @class ManualColumnMove
 * @plugin ManualColumnMove
 */

var ManualColumnMove = function (_BasePlugin) {
  _inherits(ManualColumnMove, _BasePlugin);

  function ManualColumnMove(hotInstance) {
    _classCallCheck(this, ManualColumnMove);

    /**
     * Set up WeakMap of plugin to sharing private parameters;
     */
    var _this = _possibleConstructorReturn(this, (ManualColumnMove.__proto__ || Object.getPrototypeOf(ManualColumnMove)).call(this, hotInstance));

    privatePool.set(_this, {
      columnsToMove: [],
      countCols: 0,
      fixedColumns: 0,
      pressed: void 0,
      disallowMoving: void 0,
      target: {
        eventPageX: void 0,
        coords: void 0,
        TD: void 0,
        col: void 0
      }
    });

    /**
     * List of last removed row indexes.
     *
     * @type {Array}
     */
    _this.removedColumns = [];
    /**
     * Object containing visual row indexes mapped to data source indexes.
     *
     * @type {RowsMapper}
     */
    _this.columnsMapper = new _columnsMapper2.default(_this);
    /**
     * Event Manager object.
     *
     * @type {Object}
     */
    _this.eventManager = new _eventManager2.default(_this);
    /**
     * Backlight UI object.
     *
     * @type {Object}
     */
    _this.backlight = new _backlight2.default(hotInstance);
    /**
     * Guideline UI object.
     *
     * @type {Object}
     */
    _this.guideline = new _guideline2.default(hotInstance);
    return _this;
  }

  /**
   * Check if plugin is enabled.
   *
   * @returns {Boolean}
   */


  _createClass(ManualColumnMove, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return !!this.hot.getSettings().manualColumnMove;
    }

    /**
     * Enable the plugin.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.addHook('beforeOnCellMouseDown', function (event, coords, TD, blockCalculations) {
        return _this2.onBeforeOnCellMouseDown(event, coords, TD, blockCalculations);
      });
      this.addHook('beforeOnCellMouseOver', function (event, coords, TD, blockCalculations) {
        return _this2.onBeforeOnCellMouseOver(event, coords, TD, blockCalculations);
      });
      this.addHook('afterScrollVertically', function () {
        return _this2.onAfterScrollVertically();
      });
      this.addHook('modifyCol', function (row, source) {
        return _this2.onModifyCol(row, source);
      });
      this.addHook('beforeRemoveCol', function (index, amount) {
        return _this2.onBeforeRemoveCol(index, amount);
      });
      this.addHook('afterRemoveCol', function () {
        return _this2.onAfterRemoveCol();
      });
      this.addHook('afterCreateCol', function (index, amount) {
        return _this2.onAfterCreateCol(index, amount);
      });
      this.addHook('afterLoadData', function () {
        return _this2.onAfterLoadData();
      });
      this.addHook('unmodifyCol', function (column) {
        return _this2.onUnmodifyCol(column);
      });

      this.registerEvents();

      // TODO: move adding plugin classname to BasePlugin.
      (0, _element.addClass)(this.hot.rootElement, CSS_PLUGIN);

      _get(ManualColumnMove.prototype.__proto__ || Object.getPrototypeOf(ManualColumnMove.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();

      this.onAfterPluginsInitialized();

      _get(ManualColumnMove.prototype.__proto__ || Object.getPrototypeOf(ManualColumnMove.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      var pluginSettings = this.hot.getSettings().manualColumnMove;

      if (Array.isArray(pluginSettings)) {
        this.columnsMapper.clearMap();
      }

      (0, _element.removeClass)(this.hot.rootElement, CSS_PLUGIN);

      this.unregisterEvents();
      this.backlight.destroy();
      this.guideline.destroy();

      _get(ManualColumnMove.prototype.__proto__ || Object.getPrototypeOf(ManualColumnMove.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Move a single column.
     *
     * @param {Number} column Visual column index to be moved.
     * @param {Number} target Visual column index being a target for the moved column.
     */

  }, {
    key: 'moveColumn',
    value: function moveColumn(column, target) {
      this.moveColumns([column], target);
    }

    /**
     * Move multiple columns.
     *
     * @param {Array} columns Array of visual column indexes to be moved.
     * @param {Number} target Visual column index being a target for the moved columns.
     */

  }, {
    key: 'moveColumns',
    value: function moveColumns(columns, target) {
      var _this3 = this;

      var priv = privatePool.get(this);
      var beforeColumnHook = this.hot.runHooks('beforeColumnMove', columns, target);

      priv.disallowMoving = !beforeColumnHook;

      if (beforeColumnHook !== false) {
        // first we need to rewrite an visual indexes to physical for save reference after move
        (0, _array.arrayEach)(columns, function (column, index, array) {
          array[index] = _this3.columnsMapper.getValueByIndex(column);
        });

        // next, when we have got an physical indexes, we can move columns
        (0, _array.arrayEach)(columns, function (column, index) {
          var actualPosition = _this3.columnsMapper.getIndexByValue(column);

          if (actualPosition !== target) {
            _this3.columnsMapper.moveColumn(actualPosition, target + index);
          }
        });

        // after moving we have to clear columnsMapper from null entries
        this.columnsMapper.clearNull();
      }

      this.hot.runHooks('afterColumnMove', columns, target);
    }

    /**
     * Correct the cell selection after the move action. Fired only when action was made with a mouse.
     * That means that changing the column order using the API won't correct the selection.
     *
     * @private
     * @param {Number} startColumn Visual column index for the start of the selection.
     * @param {Number} endColumn Visual column index for the end of the selection.
     */

  }, {
    key: 'changeSelection',
    value: function changeSelection(startColumn, endColumn) {
      var selection = this.hot.selection;
      var lastRowIndex = this.hot.countRows() - 1;

      selection.setRangeStartOnly(new _src.CellCoords(0, startColumn));
      selection.setRangeEnd(new _src.CellCoords(lastRowIndex, endColumn), false);
    }

    /**
     * Get the sum of the widths of columns in the provided range.
     *
     * @private
     * @param {Number} from Visual column index.
     * @param {Number} to Visual column index.
     * @returns {Number}
     */

  }, {
    key: 'getColumnsWidth',
    value: function getColumnsWidth(from, to) {
      var width = 0;

      for (var i = from; i < to; i++) {
        var columnWidth = 0;

        if (i < 0) {
          columnWidth = this.hot.view.wt.wtViewport.getRowHeaderWidth() || 0;
        } else {
          columnWidth = this.hot.view.wt.wtTable.getStretchedColumnWidth(i) || 0;
        }

        width += columnWidth;
      }

      return width;
    }

    /**
     * Load initial settings when persistent state is saved or when plugin was initialized as an array.
     *
     * @private
     */

  }, {
    key: 'initialSettings',
    value: function initialSettings() {
      var pluginSettings = this.hot.getSettings().manualColumnMove;

      if (Array.isArray(pluginSettings)) {
        this.moveColumns(pluginSettings, 0);
      } else if (pluginSettings !== void 0) {
        this.persistentStateLoad();
      }
    }

    /**
     * Check if the provided column is in the fixedColumnsLeft section.
     *
     * @private
     * @param {Number} column Visual column index to check.
     * @returns {Boolean}
     */

  }, {
    key: 'isFixedColumnsLeft',
    value: function isFixedColumnsLeft(column) {
      return column < this.hot.getSettings().fixedColumnsLeft;
    }

    /**
     * Save the manual column positions to the persistent state.
     *
     * @private
     */

  }, {
    key: 'persistentStateSave',
    value: function persistentStateSave() {
      this.hot.runHooks('persistentStateSave', 'manualColumnMove', this.columnsMapper._arrayMap);
    }

    /**
     * Load the manual column positions from the persistent state.
     *
     * @private
     */

  }, {
    key: 'persistentStateLoad',
    value: function persistentStateLoad() {
      var storedState = {};

      this.hot.runHooks('persistentStateLoad', 'manualColumnMove', storedState);

      if (storedState.value) {
        this.columnsMapper._arrayMap = storedState.value;
      }
    }

    /**
     * Prepare array of indexes based on actual selection.
     *
     * @private
     * @returns {Array}
     */

  }, {
    key: 'prepareColumnsToMoving',
    value: function prepareColumnsToMoving(start, end) {
      var selectedColumns = [];

      (0, _number.rangeEach)(start, end, function (i) {
        selectedColumns.push(i);
      });

      return selectedColumns;
    }

    /**
     * Update the UI visual position.
     *
     * @private
     */

  }, {
    key: 'refreshPositions',
    value: function refreshPositions() {
      var priv = privatePool.get(this);
      var firstVisible = this.hot.view.wt.wtTable.getFirstVisibleColumn();
      var lastVisible = this.hot.view.wt.wtTable.getLastVisibleColumn();
      var wtTable = this.hot.view.wt.wtTable;
      var scrollableElement = this.hot.view.wt.wtOverlays.scrollableElement;
      var scrollLeft = typeof scrollableElement.scrollX === 'number' ? scrollableElement.scrollX : scrollableElement.scrollLeft;
      var tdOffsetLeft = this.hot.view.THEAD.offsetLeft + this.getColumnsWidth(0, priv.coordsColumn);
      var mouseOffsetLeft = priv.target.eventPageX - (priv.rootElementOffset - (scrollableElement.scrollX === void 0 ? scrollLeft : 0));
      var hiderWidth = wtTable.hider.offsetWidth;
      var tbodyOffsetLeft = wtTable.TBODY.offsetLeft;
      var backlightElemMarginLeft = this.backlight.getOffset().left;
      var backlightElemWidth = this.backlight.getSize().width;
      var rowHeaderWidth = 0;

      if (priv.rootElementOffset + wtTable.holder.offsetWidth + scrollLeft < priv.target.eventPageX) {
        if (priv.coordsColumn < priv.countCols) {
          priv.coordsColumn++;
        }
      }

      if (priv.hasRowHeaders) {
        rowHeaderWidth = this.hot.view.wt.wtOverlays.leftOverlay.clone.wtTable.getColumnHeader(-1).offsetWidth;
      }
      if (this.isFixedColumnsLeft(priv.coordsColumn)) {
        tdOffsetLeft += scrollLeft;
      }
      tdOffsetLeft += rowHeaderWidth;

      if (priv.coordsColumn < 0) {
        // if hover on rowHeader
        if (priv.fixedColumns > 0) {
          priv.target.col = 0;
        } else {
          priv.target.col = firstVisible > 0 ? firstVisible - 1 : firstVisible;
        }
      } else if (priv.target.TD.offsetWidth / 2 + tdOffsetLeft <= mouseOffsetLeft) {
        var newCoordsCol = priv.coordsColumn >= priv.countCols ? priv.countCols - 1 : priv.coordsColumn;
        // if hover on right part of TD
        priv.target.col = newCoordsCol + 1;
        // unfortunately first column is bigger than rest
        tdOffsetLeft += priv.target.TD.offsetWidth;

        if (priv.target.col > lastVisible) {
          this.hot.scrollViewportTo(void 0, lastVisible + 1, void 0, true);
        }
      } else {
        // elsewhere on table
        priv.target.col = priv.coordsColumn;

        if (priv.target.col <= firstVisible && priv.target.col >= priv.fixedColumns) {
          this.hot.scrollViewportTo(void 0, firstVisible - 1);
        }
      }

      if (priv.target.col <= firstVisible && priv.target.col >= priv.fixedColumns) {
        this.hot.scrollViewportTo(void 0, firstVisible - 1);
      }

      var backlightLeft = mouseOffsetLeft;
      var guidelineLeft = tdOffsetLeft;

      if (mouseOffsetLeft + backlightElemWidth + backlightElemMarginLeft >= hiderWidth) {
        // prevent display backlight on the right side of the table
        backlightLeft = hiderWidth - backlightElemWidth - backlightElemMarginLeft;
      } else if (mouseOffsetLeft + backlightElemMarginLeft < tbodyOffsetLeft + rowHeaderWidth) {
        // prevent display backlight on the left side of the table
        backlightLeft = tbodyOffsetLeft + rowHeaderWidth + Math.abs(backlightElemMarginLeft);
      }

      if (tdOffsetLeft >= hiderWidth - 1) {
        // prevent display guideline outside the table
        guidelineLeft = hiderWidth - 1;
      } else if (guidelineLeft === 0) {
        // guideline has got `margin-left: -1px` as default
        guidelineLeft = 1;
      } else if (scrollableElement.scrollX !== void 0 && priv.coordsColumn < priv.fixedColumns) {
        guidelineLeft -= priv.rootElementOffset <= scrollableElement.scrollX ? priv.rootElementOffset : 0;
      }

      this.backlight.setPosition(null, backlightLeft);
      this.guideline.setPosition(null, guidelineLeft);
    }

    /**
     * This method checks arrayMap from columnsMapper and updates the columnsMapper if it's necessary.
     *
     * @private
     */

  }, {
    key: 'updateColumnsMapper',
    value: function updateColumnsMapper() {
      var countCols = this.hot.countSourceCols();
      var columnsMapperLen = this.columnsMapper._arrayMap.length;

      if (columnsMapperLen === 0) {
        this.columnsMapper.createMap(countCols || this.hot.getSettings().startCols);
      } else if (columnsMapperLen < countCols) {
        var diff = countCols - columnsMapperLen;

        this.columnsMapper.insertItems(columnsMapperLen, diff);
      } else if (columnsMapperLen > countCols) {
        var maxIndex = countCols - 1;
        var columnsToRemove = [];

        (0, _array.arrayEach)(this.columnsMapper._arrayMap, function (value, index) {
          if (value > maxIndex) {
            columnsToRemove.push(index);
          }
        });

        this.columnsMapper.removeItems(columnsToRemove);
      }
    }

    /**
     * Bind the events used by the plugin.
     *
     * @private
     */

  }, {
    key: 'registerEvents',
    value: function registerEvents() {
      var _this4 = this;

      this.eventManager.addEventListener(document.documentElement, 'mousemove', function (event) {
        return _this4.onMouseMove(event);
      });
      this.eventManager.addEventListener(document.documentElement, 'mouseup', function () {
        return _this4.onMouseUp();
      });
    }

    /**
     * Unbind the events used by the plugin.
     *
     * @private
     */

  }, {
    key: 'unregisterEvents',
    value: function unregisterEvents() {
      this.eventManager.clear();
    }

    /**
     * Change the behavior of selection / dragging.
     *
     * @private
     * @param {MouseEvent} event `mousedown` event properties.
     * @param {CellCoords} coords Visual cell coordinates where was fired event.
     * @param {HTMLElement} TD Cell represented as HTMLElement.
     * @param {Object} blockCalculations Object which contains information about blockCalculation for row, column or cells.
     */

  }, {
    key: 'onBeforeOnCellMouseDown',
    value: function onBeforeOnCellMouseDown(event, coords, TD, blockCalculations) {
      var wtTable = this.hot.view.wt.wtTable;
      var isHeaderSelection = this.hot.selection.selectedHeader.cols;
      var selection = this.hot.getSelectedRange();
      var priv = privatePool.get(this);
      var isSortingElement = event.realTarget.className.indexOf('columnSorting') > -1;

      if (!selection || !isHeaderSelection || priv.pressed || event.button !== 0 || isSortingElement) {
        priv.pressed = false;
        priv.columnsToMove.length = 0;
        (0, _element.removeClass)(this.hot.rootElement, [CSS_ON_MOVING, CSS_SHOW_UI]);
        return;
      }

      var guidelineIsNotReady = this.guideline.isBuilt() && !this.guideline.isAppended();
      var backlightIsNotReady = this.backlight.isBuilt() && !this.backlight.isAppended();

      if (guidelineIsNotReady && backlightIsNotReady) {
        this.guideline.appendTo(wtTable.hider);
        this.backlight.appendTo(wtTable.hider);
      }

      var from = selection.from,
          to = selection.to;

      var start = Math.min(from.col, to.col);
      var end = Math.max(from.col, to.col);

      if (coords.row < 0 && coords.col >= start && coords.col <= end) {
        blockCalculations.column = true;
        priv.pressed = true;
        priv.target.eventPageX = event.pageX;
        priv.coordsColumn = coords.col;
        priv.target.TD = TD;
        priv.target.col = coords.col;
        priv.columnsToMove = this.prepareColumnsToMoving(start, end);
        priv.hasRowHeaders = !!this.hot.getSettings().rowHeaders;
        priv.countCols = this.hot.countCols();
        priv.fixedColumns = this.hot.getSettings().fixedColumnsLeft;
        priv.rootElementOffset = (0, _element.offset)(this.hot.rootElement).left;

        var countColumnsFrom = priv.hasRowHeaders ? -1 : 0;
        var topPos = wtTable.holder.scrollTop + wtTable.getColumnHeaderHeight(0) + 1;
        var fixedColumns = coords.col < priv.fixedColumns;
        var scrollableElement = this.hot.view.wt.wtOverlays.scrollableElement;
        var wrapperIsWindow = scrollableElement.scrollX ? scrollableElement.scrollX - priv.rootElementOffset : 0;

        var mouseOffset = event.layerX - (fixedColumns ? wrapperIsWindow : 0);
        var leftOffset = Math.abs(this.getColumnsWidth(start, coords.col) + mouseOffset);

        this.backlight.setPosition(topPos, this.getColumnsWidth(countColumnsFrom, start) + leftOffset);
        this.backlight.setSize(this.getColumnsWidth(start, end + 1), wtTable.hider.offsetHeight - topPos);
        this.backlight.setOffset(null, leftOffset * -1);

        (0, _element.addClass)(this.hot.rootElement, CSS_ON_MOVING);
      } else {
        (0, _element.removeClass)(this.hot.rootElement, CSS_AFTER_SELECTION);
        priv.pressed = false;
        priv.columnsToMove.length = 0;
      }
    }

    /**
     * 'mouseMove' event callback. Fired when pointer move on document.documentElement.
     *
     * @private
     * @param {MouseEvent} event `mousemove` event properties.
     */

  }, {
    key: 'onMouseMove',
    value: function onMouseMove(event) {
      var priv = privatePool.get(this);

      if (!priv.pressed) {
        return;
      }

      // callback for browser which doesn't supports CSS pointer-event: none
      if (event.realTarget === this.backlight.element) {
        var width = this.backlight.getSize().width;
        this.backlight.setSize(0);

        setTimeout(function () {
          this.backlight.setPosition(width);
        });
      }

      priv.target.eventPageX = event.pageX;
      this.refreshPositions();
    }

    /**
     * 'beforeOnCellMouseOver' hook callback. Fired when pointer was over cell.
     *
     * @private
     * @param {MouseEvent} event `mouseover` event properties.
     * @param {CellCoords} coords Visual cell coordinates where was fired event.
     * @param {HTMLElement} TD Cell represented as HTMLElement.
     * @param {Object} blockCalculations Object which contains information about blockCalculation for row, column or cells.
     */

  }, {
    key: 'onBeforeOnCellMouseOver',
    value: function onBeforeOnCellMouseOver(event, coords, TD, blockCalculations) {
      var selectedRange = this.hot.getSelectedRange();
      var priv = privatePool.get(this);

      if (!selectedRange || !priv.pressed) {
        return;
      }

      if (priv.columnsToMove.indexOf(coords.col) > -1) {
        (0, _element.removeClass)(this.hot.rootElement, CSS_SHOW_UI);
      } else {
        (0, _element.addClass)(this.hot.rootElement, CSS_SHOW_UI);
      }

      blockCalculations.row = true;
      blockCalculations.column = true;
      blockCalculations.cell = true;
      priv.coordsColumn = coords.col;
      priv.target.TD = TD;
    }

    /**
     * `onMouseUp` hook callback.
     *
     * @private
     */

  }, {
    key: 'onMouseUp',
    value: function onMouseUp() {
      var priv = privatePool.get(this);

      priv.coordsColumn = void 0;
      priv.pressed = false;
      priv.backlightWidth = 0;

      (0, _element.removeClass)(this.hot.rootElement, [CSS_ON_MOVING, CSS_SHOW_UI, CSS_AFTER_SELECTION]);

      if (this.hot.selection.selectedHeader.cols) {
        (0, _element.addClass)(this.hot.rootElement, CSS_AFTER_SELECTION);
      }
      if (priv.columnsToMove.length < 1 || priv.target.col === void 0 || priv.columnsToMove.indexOf(priv.target.col) > -1) {
        return;
      }

      this.moveColumns(priv.columnsToMove, priv.target.col);
      this.persistentStateSave();
      this.hot.render();
      this.hot.view.wt.wtOverlays.adjustElementsSize(true);

      if (!priv.disallowMoving) {
        var selectionStart = this.columnsMapper.getIndexByValue(priv.columnsToMove[0]);
        var selectionEnd = this.columnsMapper.getIndexByValue(priv.columnsToMove[priv.columnsToMove.length - 1]);
        this.changeSelection(selectionStart, selectionEnd);
      }

      priv.columnsToMove.length = 0;
    }

    /**
     * `afterScrollHorizontally` hook callback. Fired the table was scrolled horizontally.
     *
     * @private
     */

  }, {
    key: 'onAfterScrollVertically',
    value: function onAfterScrollVertically() {
      var wtTable = this.hot.view.wt.wtTable;
      var headerHeight = wtTable.getColumnHeaderHeight(0) + 1;
      var scrollTop = wtTable.holder.scrollTop;
      var posTop = headerHeight + scrollTop;

      this.backlight.setPosition(posTop);
      this.backlight.setSize(null, wtTable.hider.offsetHeight - posTop);
    }

    /**
     * `afterCreateCol` hook callback.
     *
     * @private
     * @param {Number} index Visual index of the created column.
     * @param {Number} amount Amount of created columns.
     */

  }, {
    key: 'onAfterCreateCol',
    value: function onAfterCreateCol(index, amount) {
      this.columnsMapper.shiftItems(index, amount);
    }

    /**
     * On before remove column listener.
     *
     * @private
     * @param {Number} index Visual column index.
     * @param {Number} amount Defines how many columns removed.
     */

  }, {
    key: 'onBeforeRemoveCol',
    value: function onBeforeRemoveCol(index, amount) {
      var _this5 = this;

      this.removedColumns.length = 0;

      if (index !== false) {
        // Collect physical row index.
        (0, _number.rangeEach)(index, index + amount - 1, function (removedIndex) {
          _this5.removedColumns.push(_this5.hot.runHooks('modifyCol', removedIndex, _this5.pluginName));
        });
      }
    }

    /**
     * `afterRemoveCol` hook callback.
     *
     * @private
     */

  }, {
    key: 'onAfterRemoveCol',
    value: function onAfterRemoveCol() {
      this.columnsMapper.unshiftItems(this.removedColumns);
    }

    /**
     * `afterLoadData` hook callback.
     *
     * @private
     */

  }, {
    key: 'onAfterLoadData',
    value: function onAfterLoadData() {
      this.updateColumnsMapper();
    }

    /**
     * 'modifyRow' hook callback.
     *
     * @private
     * @param {Number} column Visual column index.
     * @returns {Number} Physical column index.
     */

  }, {
    key: 'onModifyCol',
    value: function onModifyCol(column, source) {
      if (source !== this.pluginName) {
        // ugly fix for try to insert new, needed columns after pasting data
        var columnInMapper = this.columnsMapper.getValueByIndex(column);
        column = columnInMapper === null ? column : columnInMapper;
      }

      return column;
    }

    /**
     * 'unmodifyCol' hook callback.
     *
     * @private
     * @param {Number} column Physical column index.
     * @returns {Number} Visual column index.
     */

  }, {
    key: 'onUnmodifyCol',
    value: function onUnmodifyCol(column) {
      var indexInMapper = this.columnsMapper.getIndexByValue(column);

      return indexInMapper === null ? column : indexInMapper;
    }

    /**
     * `afterPluginsInitialized` hook callback.
     *
     * @private
     */

  }, {
    key: 'onAfterPluginsInitialized',
    value: function onAfterPluginsInitialized() {
      this.updateColumnsMapper();
      this.initialSettings();
      this.backlight.build();
      this.guideline.build();
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.backlight.destroy();
      this.guideline.destroy();

      _get(ManualColumnMove.prototype.__proto__ || Object.getPrototypeOf(ManualColumnMove.prototype), 'destroy', this).call(this);
    }
  }]);

  return ManualColumnMove;
}(_base2.default);

(0, _plugins.registerPlugin)('ManualColumnMove', ManualColumnMove);

exports.default = ManualColumnMove;

/***/ }),
/* 431 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _arrayMapper = __webpack_require__(314);

var _arrayMapper2 = _interopRequireDefault(_arrayMapper);

var _array = __webpack_require__(2);

var _object = __webpack_require__(1);

var _number = __webpack_require__(6);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class ColumnsMapper
 * @plugin ManualColumnMove
 */
var ColumnsMapper = function () {
  function ColumnsMapper(manualColumnMove) {
    _classCallCheck(this, ColumnsMapper);

    /**
     * Instance of ManualColumnMove plugin.
     *
     * @type {ManualColumnMove}
     */
    this.manualColumnMove = manualColumnMove;
  }

  /**
   * Reset current map array and create new one.
   *
   * @param {Number} [length] Custom generated map length.
   */


  _createClass(ColumnsMapper, [{
    key: 'createMap',
    value: function createMap(length) {
      var _this = this;

      var originLength = length === void 0 ? this._arrayMap.length : length;

      this._arrayMap.length = 0;

      (0, _number.rangeEach)(originLength - 1, function (itemIndex) {
        _this._arrayMap[itemIndex] = itemIndex;
      });
    }

    /**
     * Destroy class.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this._arrayMap = null;
    }

    /**
     * Moving elements in columnsMapper.
     *
     * @param {Number} from Column index to move.
     * @param {Number} to Target index.
     */

  }, {
    key: 'moveColumn',
    value: function moveColumn(from, to) {
      var indexToMove = this._arrayMap[from];
      this._arrayMap[from] = null;
      this._arrayMap.splice(to, 0, indexToMove);
    }

    /**
     * Clearing arrayMap from `null` entries.
     */

  }, {
    key: 'clearNull',
    value: function clearNull() {
      this._arrayMap = (0, _array.arrayFilter)(this._arrayMap, function (i) {
        return i !== null;
      });
    }
  }]);

  return ColumnsMapper;
}();

(0, _object.mixin)(ColumnsMapper, _arrayMapper2.default);

exports.default = ColumnsMapper;

/***/ }),
/* 432 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(315);

var _base2 = _interopRequireDefault(_base);

var _element = __webpack_require__(0);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CSS_CLASSNAME = 'ht__manualColumnMove--backlight';

/**
 * @class BacklightUI
 * @util
 */

var BacklightUI = function (_BaseUI) {
  _inherits(BacklightUI, _BaseUI);

  function BacklightUI() {
    _classCallCheck(this, BacklightUI);

    return _possibleConstructorReturn(this, (BacklightUI.__proto__ || Object.getPrototypeOf(BacklightUI)).apply(this, arguments));
  }

  _createClass(BacklightUI, [{
    key: 'build',

    /**
     * Custom className on build process.
     */
    value: function build() {
      _get(BacklightUI.prototype.__proto__ || Object.getPrototypeOf(BacklightUI.prototype), 'build', this).call(this);

      (0, _element.addClass)(this._element, CSS_CLASSNAME);
    }
  }]);

  return BacklightUI;
}(_base2.default);

exports.default = BacklightUI;

/***/ }),
/* 433 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(315);

var _base2 = _interopRequireDefault(_base);

var _element = __webpack_require__(0);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CSS_CLASSNAME = 'ht__manualColumnMove--guideline';

/**
 * @class GuidelineUI
 * @util
 */

var GuidelineUI = function (_BaseUI) {
  _inherits(GuidelineUI, _BaseUI);

  function GuidelineUI() {
    _classCallCheck(this, GuidelineUI);

    return _possibleConstructorReturn(this, (GuidelineUI.__proto__ || Object.getPrototypeOf(GuidelineUI)).apply(this, arguments));
  }

  _createClass(GuidelineUI, [{
    key: 'build',

    /**
     * Custom className on build process.
     */
    value: function build() {
      _get(GuidelineUI.prototype.__proto__ || Object.getPrototypeOf(GuidelineUI.prototype), 'build', this).call(this);

      (0, _element.addClass)(this._element, CSS_CLASSNAME);
    }
  }]);

  return GuidelineUI;
}(_base2.default);

exports.default = GuidelineUI;

/***/ }),
/* 434 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 435 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _element = __webpack_require__(0);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _event = __webpack_require__(12);

var _array = __webpack_require__(2);

var _number = __webpack_require__(6);

var _plugins = __webpack_require__(7);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// Developer note! Whenever you make a change in this file, make an analogous change in manualRowResize.js

/**
 * @description
 * ManualColumnResize Plugin.
 *
 * Has 2 UI components:
 * - handle - the draggable element that sets the desired width of the column.
 * - guide - the helper guide that shows the desired width as a vertical guide.
 *
 * @plugin ManualColumnResize
 */
var ManualColumnResize = function (_BasePlugin) {
  _inherits(ManualColumnResize, _BasePlugin);

  function ManualColumnResize(hotInstance) {
    _classCallCheck(this, ManualColumnResize);

    var _this = _possibleConstructorReturn(this, (ManualColumnResize.__proto__ || Object.getPrototypeOf(ManualColumnResize)).call(this, hotInstance));

    _this.currentTH = null;
    _this.currentCol = null;
    _this.selectedCols = [];
    _this.currentWidth = null;
    _this.newSize = null;
    _this.startY = null;
    _this.startWidth = null;
    _this.startOffset = null;
    _this.handle = document.createElement('DIV');
    _this.guide = document.createElement('DIV');
    _this.eventManager = new _eventManager2.default(_this);
    _this.pressed = null;
    _this.dblclick = 0;
    _this.autoresizeTimeout = null;
    _this.manualColumnWidths = [];

    (0, _element.addClass)(_this.handle, 'manualColumnResizer');
    (0, _element.addClass)(_this.guide, 'manualColumnResizerGuide');
    return _this;
  }

  /**
   * Check if the plugin is enabled in the handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(ManualColumnResize, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return this.hot.getSettings().manualColumnResize;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.manualColumnWidths = [];
      var initialColumnWidth = this.hot.getSettings().manualColumnResize;
      var loadedManualColumnWidths = this.loadManualColumnWidths();

      this.addHook('modifyColWidth', function (width, col) {
        return _this2.onModifyColWidth(width, col);
      });
      this.addHook('beforeStretchingColumnWidth', function (stretchedWidth, column) {
        return _this2.onBeforeStretchingColumnWidth(stretchedWidth, column);
      });
      this.addHook('beforeColumnResize', function (currentColumn, newSize, isDoubleClick) {
        return _this2.onBeforeColumnResize(currentColumn, newSize, isDoubleClick);
      });

      if (typeof loadedManualColumnWidths != 'undefined') {
        this.manualColumnWidths = loadedManualColumnWidths;
      } else if (Array.isArray(initialColumnWidth)) {
        this.manualColumnWidths = initialColumnWidth;
      } else {
        this.manualColumnWidths = [];
      }

      // Handsontable.hooks.register('beforeColumnResize');
      // Handsontable.hooks.register('afterColumnResize');

      this.bindEvents();

      _get(ManualColumnResize.prototype.__proto__ || Object.getPrototypeOf(ManualColumnResize.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      var initialColumnWidth = this.hot.getSettings().manualColumnResize;

      if (Array.isArray(initialColumnWidth)) {
        this.manualColumnWidths = initialColumnWidth;
      } else if (!initialColumnWidth) {
        this.manualColumnWidths = [];
      }
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      _get(ManualColumnResize.prototype.__proto__ || Object.getPrototypeOf(ManualColumnResize.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Save the current sizes using the persistentState plugin.
     */

  }, {
    key: 'saveManualColumnWidths',
    value: function saveManualColumnWidths() {
      this.hot.runHooks('persistentStateSave', 'manualColumnWidths', this.manualColumnWidths);
    }

    /**
     * Load the previously saved sizes using the persistentState plugin.
     *
     * @returns {Array}
     */

  }, {
    key: 'loadManualColumnWidths',
    value: function loadManualColumnWidths() {
      var storedState = {};

      this.hot.runHooks('persistentStateLoad', 'manualColumnWidths', storedState);

      return storedState.value;
    }

    /**
     * Set the resize handle position.
     *
     * @param {HTMLCellElement} TH TH HTML element.
     */

  }, {
    key: 'setupHandlePosition',
    value: function setupHandlePosition(TH) {
      var _this3 = this;

      if (!TH.parentNode) {
        return false;
      }

      this.currentTH = TH;

      var col = this.hot.view.wt.wtTable.getCoords(TH).col; // getCoords returns CellCoords
      var headerHeight = (0, _element.outerHeight)(this.currentTH);

      if (col >= 0) {
        // if not col header
        var box = this.currentTH.getBoundingClientRect();

        this.currentCol = col;
        this.selectedCols = [];

        if (this.hot.selection.isSelected() && this.hot.selection.selectedHeader.cols) {
          var _hot$getSelectedRange = this.hot.getSelectedRange(),
              from = _hot$getSelectedRange.from,
              to = _hot$getSelectedRange.to;

          var start = from.col;
          var end = to.col;

          if (start >= end) {
            start = to.col;
            end = from.col;
          }

          if (this.currentCol >= start && this.currentCol <= end) {
            (0, _number.rangeEach)(start, end, function (i) {
              return _this3.selectedCols.push(i);
            });
          } else {
            this.selectedCols.push(this.currentCol);
          }
        } else {
          this.selectedCols.push(this.currentCol);
        }

        this.startOffset = box.left - 6;
        this.startWidth = parseInt(box.width, 10);
        this.handle.style.top = box.top + 'px';
        this.handle.style.left = this.startOffset + this.startWidth + 'px';
        this.handle.style.height = headerHeight + 'px';
        this.hot.rootElement.appendChild(this.handle);
      }
    }

    /**
     * Refresh the resize handle position.
     */

  }, {
    key: 'refreshHandlePosition',
    value: function refreshHandlePosition() {
      this.handle.style.left = this.startOffset + this.currentWidth + 'px';
    }

    /**
     * Set the resize guide position.
     */

  }, {
    key: 'setupGuidePosition',
    value: function setupGuidePosition() {
      var handleHeight = parseInt((0, _element.outerHeight)(this.handle), 10);
      var handleBottomPosition = parseInt(this.handle.style.top, 10) + handleHeight;
      var maximumVisibleElementHeight = parseInt(this.hot.view.maximumVisibleElementHeight(0), 10);

      (0, _element.addClass)(this.handle, 'active');
      (0, _element.addClass)(this.guide, 'active');

      this.guide.style.top = handleBottomPosition + 'px';
      this.guide.style.left = this.handle.style.left;
      this.guide.style.height = maximumVisibleElementHeight - handleHeight + 'px';
      this.hot.rootElement.appendChild(this.guide);
    }

    /**
     * Refresh the resize guide position.
     */

  }, {
    key: 'refreshGuidePosition',
    value: function refreshGuidePosition() {
      this.guide.style.left = this.handle.style.left;
    }

    /**
     * Hide both the resize handle and resize guide.
     */

  }, {
    key: 'hideHandleAndGuide',
    value: function hideHandleAndGuide() {
      (0, _element.removeClass)(this.handle, 'active');
      (0, _element.removeClass)(this.guide, 'active');
    }

    /**
     * Check if provided element is considered a column header.
     *
     * @param {HTMLElement} element HTML element.
     * @returns {Boolean}
     */

  }, {
    key: 'checkIfColumnHeader',
    value: function checkIfColumnHeader(element) {
      if (element != this.hot.rootElement) {
        var parent = element.parentNode;

        if (parent.tagName === 'THEAD') {
          return true;
        }

        return this.checkIfColumnHeader(parent);
      }

      return false;
    }

    /**
     * Get the TH element from the provided element.
     *
     * @param {HTMLElement} element HTML element.
     * @returns {HTMLElement}
     */

  }, {
    key: 'getTHFromTargetElement',
    value: function getTHFromTargetElement(element) {
      if (element.tagName != 'TABLE') {
        if (element.tagName == 'TH') {
          return element;
        }
        return this.getTHFromTargetElement(element.parentNode);
      }

      return null;
    }

    /**
     * 'mouseover' event callback - set the handle position.
     *
     * @private
     * @param {MouseEvent} event
     */

  }, {
    key: 'onMouseOver',
    value: function onMouseOver(event) {
      if (this.checkIfColumnHeader(event.target)) {
        var th = this.getTHFromTargetElement(event.target);

        if (!th) {
          return;
        }

        var colspan = th.getAttribute('colspan');

        if (th && (colspan === null || colspan === 1)) {
          if (!this.pressed) {
            this.setupHandlePosition(th);
          }
        }
      }
    }

    /**
     * Auto-size row after doubleclick - callback.
     *
     * @private
     */

  }, {
    key: 'afterMouseDownTimeout',
    value: function afterMouseDownTimeout() {
      var _this4 = this;

      var render = function render() {
        _this4.hot.forceFullRender = true;
        _this4.hot.view.render(); // updates all
        _this4.hot.view.wt.wtOverlays.adjustElementsSize(true);
      };
      var resize = function resize(selectedCol, forceRender) {
        var hookNewSize = _this4.hot.runHooks('beforeColumnResize', selectedCol, _this4.newSize, true);

        if (hookNewSize !== void 0) {
          _this4.newSize = hookNewSize;
        }

        if (_this4.hot.getSettings().stretchH === 'all') {
          _this4.clearManualSize(selectedCol);
        } else {
          _this4.setManualSize(selectedCol, _this4.newSize); // double click sets by auto row size plugin
        }

        if (forceRender) {
          render();
        }

        _this4.saveManualColumnWidths();

        _this4.hot.runHooks('afterColumnResize', selectedCol, _this4.newSize, true);
      };

      if (this.dblclick >= 2) {
        var selectedColsLength = this.selectedCols.length;

        if (selectedColsLength > 1) {
          (0, _array.arrayEach)(this.selectedCols, function (selectedCol) {
            resize(selectedCol);
          });
          render();
        } else {
          (0, _array.arrayEach)(this.selectedCols, function (selectedCol) {
            resize(selectedCol, true);
          });
        }
      }
      this.dblclick = 0;
      this.autoresizeTimeout = null;
    }

    /**
     * 'mousedown' event callback.
     *
     * @private
     * @param {MouseEvent} e
     */

  }, {
    key: 'onMouseDown',
    value: function onMouseDown(event) {
      var _this5 = this;

      if ((0, _element.hasClass)(event.target, 'manualColumnResizer')) {
        this.setupGuidePosition();
        this.pressed = this.hot;

        if (this.autoresizeTimeout === null) {
          this.autoresizeTimeout = setTimeout(function () {
            return _this5.afterMouseDownTimeout();
          }, 500);

          this.hot._registerTimeout(this.autoresizeTimeout);
        }
        this.dblclick++;

        this.startX = (0, _event.pageX)(event);
        this.newSize = this.startWidth;
      }
    }

    /**
     * 'mousemove' event callback - refresh the handle and guide positions, cache the new column width.
     *
     * @private
     * @param {MouseEvent} e
     */

  }, {
    key: 'onMouseMove',
    value: function onMouseMove(event) {
      var _this6 = this;

      if (this.pressed) {
        this.currentWidth = this.startWidth + ((0, _event.pageX)(event) - this.startX);

        (0, _array.arrayEach)(this.selectedCols, function (selectedCol) {
          _this6.newSize = _this6.setManualSize(selectedCol, _this6.currentWidth);
        });

        this.refreshHandlePosition();
        this.refreshGuidePosition();
      }
    }

    /**
     * 'mouseup' event callback - apply the column resizing.
     *
     * @private
     * @param {MouseEvent} e
     */

  }, {
    key: 'onMouseUp',
    value: function onMouseUp(event) {
      var _this7 = this;

      var render = function render() {
        _this7.hot.forceFullRender = true;
        _this7.hot.view.render(); // updates all
        _this7.hot.view.wt.wtOverlays.adjustElementsSize(true);
      };
      var resize = function resize(selectedCol, forceRender) {
        _this7.hot.runHooks('beforeColumnResize', selectedCol, _this7.newSize);

        if (forceRender) {
          render();
        }

        _this7.saveManualColumnWidths();

        _this7.hot.runHooks('afterColumnResize', selectedCol, _this7.newSize);
      };

      if (this.pressed) {
        this.hideHandleAndGuide();
        this.pressed = false;

        if (this.newSize != this.startWidth) {
          var selectedColsLength = this.selectedCols.length;

          if (selectedColsLength > 1) {
            (0, _array.arrayEach)(this.selectedCols, function (selectedCol) {
              resize(selectedCol);
            });
            render();
          } else {
            (0, _array.arrayEach)(this.selectedCols, function (selectedCol) {
              resize(selectedCol, true);
            });
          }
        }

        this.setupHandlePosition(this.currentTH);
      }
    }

    /**
     * Bind the mouse events.
     *
     * @private
     */

  }, {
    key: 'bindEvents',
    value: function bindEvents() {
      var _this8 = this;

      this.eventManager.addEventListener(this.hot.rootElement, 'mouseover', function (e) {
        return _this8.onMouseOver(e);
      });
      this.eventManager.addEventListener(this.hot.rootElement, 'mousedown', function (e) {
        return _this8.onMouseDown(e);
      });
      this.eventManager.addEventListener(window, 'mousemove', function (e) {
        return _this8.onMouseMove(e);
      });
      this.eventManager.addEventListener(window, 'mouseup', function (e) {
        return _this8.onMouseUp(e);
      });
    }

    /**
     * Cache the current column width.
     *
     * @param {Number} column Visual column index.
     * @param {Number} width Column width.
     * @returns {Number}
     */

  }, {
    key: 'setManualSize',
    value: function setManualSize(column, width) {
      width = Math.max(width, 20);

      /**
       *  We need to run col through modifyCol hook, in case the order of displayed columns is different than the order
       *  in data source. For instance, this order can be modified by manualColumnMove plugin.
       */
      column = this.hot.runHooks('modifyCol', column);

      this.manualColumnWidths[column] = width;

      return width;
    }

    /**
     * Clear cache for the current column index.
     *
     * @param {Number} column Visual column index.
     */

  }, {
    key: 'clearManualSize',
    value: function clearManualSize(column) {
      column = this.hot.runHooks('modifyCol', column);

      this.manualColumnWidths[column] = void 0;
    }

    /**
     * Modify the provided column width, based on the plugin settings
     *
     * @private
     * @param {Number} width Column width.
     * @param {Number} column Visual column index.
     * @returns {Number}
     */

  }, {
    key: 'onModifyColWidth',
    value: function onModifyColWidth(width, column) {
      if (this.enabled) {
        column = this.hot.runHooks('modifyCol', column);

        if (this.hot.getSettings().manualColumnResize && this.manualColumnWidths[column]) {
          return this.manualColumnWidths[column];
        }
      }

      return width;
    }

    /**
     * Modify the provided column stretched width. This hook decides if specified column should be stretched or not.
     *
     * @private
     * @param {Number} stretchedWidth Stretched width.
     * @param {Number} column Physical column index.
     * @returns {Number}
     */

  }, {
    key: 'onBeforeStretchingColumnWidth',
    value: function onBeforeStretchingColumnWidth(stretchedWidth, column) {
      var width = this.manualColumnWidths[column];

      if (width === void 0) {
        width = stretchedWidth;
      }

      return width;
    }

    /**
     * `beforeColumnResize` hook callback.
     *
     * @private
     * @param {Number} currentColumn Index of the resized column.
     * @param {Number} newSize Calculated new column width.
     * @param {Boolean} isDoubleClick Flag that determines whether there was a double-click.
     */

  }, {
    key: 'onBeforeColumnResize',
    value: function onBeforeColumnResize() {
      // clear the header height cache information
      this.hot.view.wt.wtViewport.hasOversizedColumnHeadersMarked = {};
    }
  }]);

  return ManualColumnResize;
}(_base2.default);

(0, _plugins.registerPlugin)('manualColumnResize', ManualColumnResize);

exports.default = ManualColumnResize;

/***/ }),
/* 436 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _array = __webpack_require__(2);

var _element = __webpack_require__(0);

var _number = __webpack_require__(6);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _plugins = __webpack_require__(7);

var _rowsMapper = __webpack_require__(437);

var _rowsMapper2 = _interopRequireDefault(_rowsMapper);

var _backlight = __webpack_require__(438);

var _backlight2 = _interopRequireDefault(_backlight);

var _guideline = __webpack_require__(439);

var _guideline2 = _interopRequireDefault(_guideline);

var _src = __webpack_require__(15);

__webpack_require__(440);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

_pluginHooks2.default.getSingleton().register('beforeRowMove');
_pluginHooks2.default.getSingleton().register('afterRowMove');
_pluginHooks2.default.getSingleton().register('unmodifyRow');

var privatePool = new WeakMap();
var CSS_PLUGIN = 'ht__manualRowMove';
var CSS_SHOW_UI = 'show-ui';
var CSS_ON_MOVING = 'on-moving--rows';
var CSS_AFTER_SELECTION = 'after-selection--rows';

/**
 * @plugin ManualRowMove
 *
 * @description
 * This plugin allows to change rows order.
 *
 * API:
 * - moveRow - move single row to the new position.
 * - moveRows - move many rows (as an array of indexes) to the new position.
 *
 * If you want apply visual changes, you have to call manually the render() method on the instance of handsontable.
 *
 * UI components:
 * - backlight - highlight of selected rows.
 * - guideline - line which shows where rows has been moved.
 *
 * @class ManualRowMove
 * @plugin ManualRowMove
 */

var ManualRowMove = function (_BasePlugin) {
  _inherits(ManualRowMove, _BasePlugin);

  function ManualRowMove(hotInstance) {
    _classCallCheck(this, ManualRowMove);

    /**
     * Set up WeakMap of plugin to sharing private parameters;
     */
    var _this = _possibleConstructorReturn(this, (ManualRowMove.__proto__ || Object.getPrototypeOf(ManualRowMove)).call(this, hotInstance));

    privatePool.set(_this, {
      rowsToMove: [],
      pressed: void 0,
      disallowMoving: void 0,
      target: {
        eventPageY: void 0,
        coords: void 0,
        TD: void 0,
        row: void 0
      }
    });

    /**
     * List of last removed row indexes.
     *
     * @type {Array}
     */
    _this.removedRows = [];
    /**
     * Object containing visual row indexes mapped to data source indexes.
     *
     * @type {RowsMapper}
     */
    _this.rowsMapper = new _rowsMapper2.default(_this);
    /**
     * Event Manager object.
     *
     * @type {Object}
     */
    _this.eventManager = new _eventManager2.default(_this);
    /**
     * Backlight UI object.
     *
     * @type {Object}
     */
    _this.backlight = new _backlight2.default(hotInstance);
    /**
     * Guideline UI object.
     *
     * @type {Object}
     */
    _this.guideline = new _guideline2.default(hotInstance);
    return _this;
  }

  /**
   * Check if plugin is enabled.
   *
   * @returns {Boolean}
   */


  _createClass(ManualRowMove, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return !!this.hot.getSettings().manualRowMove;
    }

    /**
     * Enable the plugin.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.addHook('beforeOnCellMouseDown', function (event, coords, TD, blockCalculations) {
        return _this2.onBeforeOnCellMouseDown(event, coords, TD, blockCalculations);
      });
      this.addHook('beforeOnCellMouseOver', function (event, coords, TD, blockCalculations) {
        return _this2.onBeforeOnCellMouseOver(event, coords, TD, blockCalculations);
      });
      this.addHook('afterScrollHorizontally', function () {
        return _this2.onAfterScrollHorizontally();
      });
      this.addHook('modifyRow', function (row, source) {
        return _this2.onModifyRow(row, source);
      });
      this.addHook('beforeRemoveRow', function (index, amount) {
        return _this2.onBeforeRemoveRow(index, amount);
      });
      this.addHook('afterRemoveRow', function () {
        return _this2.onAfterRemoveRow();
      });
      this.addHook('afterCreateRow', function (index, amount) {
        return _this2.onAfterCreateRow(index, amount);
      });
      this.addHook('afterLoadData', function () {
        return _this2.onAfterLoadData();
      });
      this.addHook('beforeColumnSort', function (column, order) {
        return _this2.onBeforeColumnSort(column, order);
      });
      this.addHook('unmodifyRow', function (row) {
        return _this2.onUnmodifyRow(row);
      });

      this.registerEvents();

      // TODO: move adding plugin classname to BasePlugin.
      (0, _element.addClass)(this.hot.rootElement, CSS_PLUGIN);

      _get(ManualRowMove.prototype.__proto__ || Object.getPrototypeOf(ManualRowMove.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.disablePlugin();
      this.enablePlugin();

      this.onAfterPluginsInitialized();

      _get(ManualRowMove.prototype.__proto__ || Object.getPrototypeOf(ManualRowMove.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      var pluginSettings = this.hot.getSettings().manualRowMove;

      if (Array.isArray(pluginSettings)) {
        this.rowsMapper.clearMap();
      }

      (0, _element.removeClass)(this.hot.rootElement, CSS_PLUGIN);

      this.unregisterEvents();
      this.backlight.destroy();
      this.guideline.destroy();

      _get(ManualRowMove.prototype.__proto__ || Object.getPrototypeOf(ManualRowMove.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Move a single row.
     *
     * @param {Number} row Visual row index to be moved.
     * @param {Number} target Visual row index being a target for the moved row.
     */

  }, {
    key: 'moveRow',
    value: function moveRow(row, target) {
      this.moveRows([row], target);
    }

    /**
     * Move multiple rows.
     *
     * @param {Array} rows Array of visual row indexes to be moved.
     * @param {Number} target Visual row index being a target for the moved rows.
     */

  }, {
    key: 'moveRows',
    value: function moveRows(rows, target) {
      var _this3 = this;

      var priv = privatePool.get(this);
      var beforeMoveHook = this.hot.runHooks('beforeRowMove', rows, target);

      priv.disallowMoving = beforeMoveHook === false;

      if (!priv.disallowMoving) {
        // first we need to rewrite an visual indexes to physical for save reference after move
        (0, _array.arrayEach)(rows, function (row, index, array) {
          array[index] = _this3.rowsMapper.getValueByIndex(row);
        });

        // next, when we have got an physical indexes, we can move rows
        (0, _array.arrayEach)(rows, function (row, index) {
          var actualPosition = _this3.rowsMapper.getIndexByValue(row);

          if (actualPosition !== target) {
            _this3.rowsMapper.moveRow(actualPosition, target + index);
          }
        });

        // after moving we have to clear rowsMapper from null entries
        this.rowsMapper.clearNull();
      }

      this.hot.runHooks('afterRowMove', rows, target);
    }

    /**
     * Correct the cell selection after the move action. Fired only when action was made with a mouse.
     * That means that changing the row order using the API won't correct the selection.
     *
     * @private
     * @param {Number} startRow Visual row index for the start of the selection.
     * @param {Number} endRow Visual row index for the end of the selection.
     */

  }, {
    key: 'changeSelection',
    value: function changeSelection(startRow, endRow) {
      var selection = this.hot.selection;
      var lastColIndex = this.hot.countCols() - 1;

      selection.setRangeStartOnly(new _src.CellCoords(startRow, 0));
      selection.setRangeEnd(new _src.CellCoords(endRow, lastColIndex), false);
    }

    /**
     * Get the sum of the heights of rows in the provided range.
     *
     * @private
     * @param {Number} from Visual row index.
     * @param {Number} to Visual row index.
     * @returns {Number}
     */

  }, {
    key: 'getRowsHeight',
    value: function getRowsHeight(from, to) {
      var height = 0;

      for (var i = from; i < to; i++) {
        var rowHeight = this.hot.view.wt.wtTable.getRowHeight(i) || 23;

        height += rowHeight;
      }

      return height;
    }

    /**
     * Load initial settings when persistent state is saved or when plugin was initialized as an array.
     *
     * @private
     */

  }, {
    key: 'initialSettings',
    value: function initialSettings() {
      var pluginSettings = this.hot.getSettings().manualRowMove;

      if (Array.isArray(pluginSettings)) {
        this.moveRows(pluginSettings, 0);
      } else if (pluginSettings !== void 0) {
        var persistentState = this.persistentStateLoad();

        if (persistentState.length) {
          this.moveRows(persistentState, 0);
        }
      }
    }

    /**
     * Check if the provided row is in the fixedRowsTop section.
     *
     * @private
     * @param {Number} row Visual row index to check.
     * @returns {Boolean}
     */

  }, {
    key: 'isFixedRowTop',
    value: function isFixedRowTop(row) {
      return row < this.hot.getSettings().fixedRowsTop;
    }

    /**
     * Check if the provided row is in the fixedRowsBottom section.
     *
     * @private
     * @param {Number} row Visual row index to check.
     * @returns {Boolean}
     */

  }, {
    key: 'isFixedRowBottom',
    value: function isFixedRowBottom(row) {
      return row > this.hot.getSettings().fixedRowsBottom;
    }

    /**
     * Save the manual row positions to the persistent state.
     *
     * @private
     */

  }, {
    key: 'persistentStateSave',
    value: function persistentStateSave() {
      this.hot.runHooks('persistentStateSave', 'manualRowMove', this.rowsMapper._arrayMap);
    }

    /**
     * Load the manual row positions from the persistent state.
     *
     * @private
     * @returns {Array} Stored state.
     */

  }, {
    key: 'persistentStateLoad',
    value: function persistentStateLoad() {
      var storedState = {};

      this.hot.runHooks('persistentStateLoad', 'manualRowMove', storedState);

      return storedState.value ? storedState.value : [];
    }

    /**
     * Prepare array of indexes based on actual selection.
     *
     * @private
     * @returns {Array}
     */

  }, {
    key: 'prepareRowsToMoving',
    value: function prepareRowsToMoving() {
      var selection = this.hot.getSelectedRange();
      var selectedRows = [];

      if (!selection) {
        return selectedRows;
      }

      var from = selection.from,
          to = selection.to;

      var start = Math.min(from.row, to.row);
      var end = Math.max(from.row, to.row);

      (0, _number.rangeEach)(start, end, function (i) {
        selectedRows.push(i);
      });

      return selectedRows;
    }

    /**
     * Update the UI visual position.
     *
     * @private
     */

  }, {
    key: 'refreshPositions',
    value: function refreshPositions() {
      var priv = privatePool.get(this);
      var coords = priv.target.coords;
      var firstVisible = this.hot.view.wt.wtTable.getFirstVisibleRow();
      var lastVisible = this.hot.view.wt.wtTable.getLastVisibleRow();
      var fixedRows = this.hot.getSettings().fixedRowsTop;
      var countRows = this.hot.countRows();

      if (coords.row < fixedRows && firstVisible > 0) {
        this.hot.scrollViewportTo(firstVisible - 1);
      }
      if (coords.row >= lastVisible && lastVisible < countRows) {
        this.hot.scrollViewportTo(lastVisible + 1, undefined, true);
      }

      var wtTable = this.hot.view.wt.wtTable;
      var TD = priv.target.TD;
      var rootElementOffset = (0, _element.offset)(this.hot.rootElement);
      var tdOffsetTop = this.hot.view.THEAD.offsetHeight + this.getRowsHeight(0, coords.row);
      var mouseOffsetTop = priv.target.eventPageY - rootElementOffset.top + wtTable.holder.scrollTop;
      var hiderHeight = wtTable.hider.offsetHeight;
      var tbodyOffsetTop = wtTable.TBODY.offsetTop;
      var backlightElemMarginTop = this.backlight.getOffset().top;
      var backlightElemHeight = this.backlight.getSize().height;

      if (this.isFixedRowTop(coords.row)) {
        tdOffsetTop += wtTable.holder.scrollTop;
      }

      // todo: fixedRowsBottom
      // if (this.isFixedRowBottom(coords.row)) {
      //
      // }

      if (coords.row < 0) {
        // if hover on colHeader
        priv.target.row = firstVisible > 0 ? firstVisible - 1 : firstVisible;
      } else if (TD.offsetHeight / 2 + tdOffsetTop <= mouseOffsetTop) {
        // if hover on lower part of TD
        priv.target.row = coords.row + 1;
        // unfortunately first row is bigger than rest
        tdOffsetTop += coords.row === 0 ? TD.offsetHeight - 1 : TD.offsetHeight;
      } else {
        // elsewhere on table
        priv.target.row = coords.row;
      }

      var backlightTop = mouseOffsetTop;
      var guidelineTop = tdOffsetTop;

      if (mouseOffsetTop + backlightElemHeight + backlightElemMarginTop >= hiderHeight) {
        // prevent display backlight below table
        backlightTop = hiderHeight - backlightElemHeight - backlightElemMarginTop;
      } else if (mouseOffsetTop + backlightElemMarginTop < tbodyOffsetTop) {
        // prevent display above below table
        backlightTop = tbodyOffsetTop + Math.abs(backlightElemMarginTop);
      }

      if (tdOffsetTop >= hiderHeight - 1) {
        // prevent display guideline below table
        guidelineTop = hiderHeight - 1;
      }

      var topOverlayHeight = 0;
      if (this.hot.view.wt.wtOverlays.topOverlay) {
        topOverlayHeight = this.hot.view.wt.wtOverlays.topOverlay.clone.wtTable.TABLE.offsetHeight;
      }

      if (coords.row >= fixedRows && guidelineTop - wtTable.holder.scrollTop < topOverlayHeight) {
        this.hot.scrollViewportTo(coords.row);
      }

      this.backlight.setPosition(backlightTop);
      this.guideline.setPosition(guidelineTop);
    }

    /**
     * This method checks arrayMap from rowsMapper and updates the rowsMapper if it's necessary.
     *
     * @private
     */

  }, {
    key: 'updateRowsMapper',
    value: function updateRowsMapper() {
      var countRows = this.hot.countSourceRows();
      var rowsMapperLen = this.rowsMapper._arrayMap.length;

      if (rowsMapperLen === 0) {
        this.rowsMapper.createMap(countRows || this.hot.getSettings().startRows);
      } else if (rowsMapperLen < countRows) {
        var diff = countRows - rowsMapperLen;

        this.rowsMapper.insertItems(rowsMapperLen, diff);
      } else if (rowsMapperLen > countRows) {
        var maxIndex = countRows - 1;
        var rowsToRemove = [];

        (0, _array.arrayEach)(this.rowsMapper._arrayMap, function (value, index) {
          if (value > maxIndex) {
            rowsToRemove.push(index);
          }
        });

        this.rowsMapper.removeItems(rowsToRemove);
      }
    }

    /**
     * Bind the events used by the plugin.
     *
     * @private
     */

  }, {
    key: 'registerEvents',
    value: function registerEvents() {
      var _this4 = this;

      this.eventManager.addEventListener(document.documentElement, 'mousemove', function (event) {
        return _this4.onMouseMove(event);
      });
      this.eventManager.addEventListener(document.documentElement, 'mouseup', function () {
        return _this4.onMouseUp();
      });
    }

    /**
     * Unbind the events used by the plugin.
     *
     * @private
     */

  }, {
    key: 'unregisterEvents',
    value: function unregisterEvents() {
      this.eventManager.clear();
    }

    /**
     * `beforeColumnSort` hook callback. If user uses the sorting, manual row moving is disabled.
     *
     * @private
     * @param {Number} column Column index where soring is present
     * @param {*} order State of sorting. ASC/DESC/None
     */

  }, {
    key: 'onBeforeColumnSort',
    value: function onBeforeColumnSort(column, order) {
      var priv = privatePool.get(this);

      priv.disallowMoving = order !== void 0;
    }

    /**
     * Change the behavior of selection / dragging.
     *
     * @private
     * @param {MouseEvent} event
     * @param {CellCoords} coords Visual coordinates.
     * @param {HTMLElement} TD
     * @param {Object} blockCalculations
     */

  }, {
    key: 'onBeforeOnCellMouseDown',
    value: function onBeforeOnCellMouseDown(event, coords, TD, blockCalculations) {
      var wtTable = this.hot.view.wt.wtTable;
      var isHeaderSelection = this.hot.selection.selectedHeader.rows;
      var selection = this.hot.getSelectedRange();
      var priv = privatePool.get(this);

      if (!selection || !isHeaderSelection || priv.pressed || event.button !== 0) {
        priv.pressed = false;
        priv.rowsToMove.length = 0;
        (0, _element.removeClass)(this.hot.rootElement, [CSS_ON_MOVING, CSS_SHOW_UI]);
        return;
      }

      var guidelineIsNotReady = this.guideline.isBuilt() && !this.guideline.isAppended();
      var backlightIsNotReady = this.backlight.isBuilt() && !this.backlight.isAppended();

      if (guidelineIsNotReady && backlightIsNotReady) {
        this.guideline.appendTo(wtTable.hider);
        this.backlight.appendTo(wtTable.hider);
      }

      var from = selection.from,
          to = selection.to;

      var start = Math.min(from.row, to.row);
      var end = Math.max(from.row, to.row);

      if (coords.col < 0 && coords.row >= start && coords.row <= end) {
        blockCalculations.row = true;
        priv.pressed = true;
        priv.target.eventPageY = event.pageY;
        priv.target.coords = coords;
        priv.target.TD = TD;
        priv.rowsToMove = this.prepareRowsToMoving();

        var leftPos = wtTable.holder.scrollLeft + this.hot.view.wt.wtViewport.getRowHeaderWidth();

        this.backlight.setPosition(null, leftPos);
        this.backlight.setSize(wtTable.hider.offsetWidth - leftPos, this.getRowsHeight(start, end + 1));
        this.backlight.setOffset((this.getRowsHeight(start, coords.row) + event.layerY) * -1, null);

        (0, _element.addClass)(this.hot.rootElement, CSS_ON_MOVING);

        this.refreshPositions();
      } else {
        (0, _element.removeClass)(this.hot.rootElement, CSS_AFTER_SELECTION);
        priv.pressed = false;
        priv.rowsToMove.length = 0;
      }
    }

    /**
     * 'mouseMove' event callback. Fired when pointer move on document.documentElement.
     *
     * @private
     * @param {MouseEvent} event `mousemove` event properties.
     */

  }, {
    key: 'onMouseMove',
    value: function onMouseMove(event) {
      var priv = privatePool.get(this);

      if (!priv.pressed) {
        return;
      }

      // callback for browser which doesn't supports CSS pointer-event: none
      if (event.realTarget === this.backlight.element) {
        var height = this.backlight.getSize().height;
        this.backlight.setSize(null, 0);

        setTimeout(function () {
          this.backlight.setPosition(null, height);
        });
      }

      priv.target.eventPageY = event.pageY;
      this.refreshPositions();
    }

    /**
     * 'beforeOnCellMouseOver' hook callback. Fired when pointer was over cell.
     *
     * @private
     * @param {MouseEvent} event `mouseover` event properties.
     * @param {CellCoords} coords Visual cell coordinates where was fired event.
     * @param {HTMLElement} TD Cell represented as HTMLElement.
     * @param {Object} blockCalculations Object which contains information about blockCalculation for row, column or cells.
     */

  }, {
    key: 'onBeforeOnCellMouseOver',
    value: function onBeforeOnCellMouseOver(event, coords, TD, blockCalculations) {
      var selectedRange = this.hot.getSelectedRange();
      var priv = privatePool.get(this);

      if (!selectedRange || !priv.pressed) {
        return;
      }

      if (priv.rowsToMove.indexOf(coords.row) > -1) {
        (0, _element.removeClass)(this.hot.rootElement, CSS_SHOW_UI);
      } else {
        (0, _element.addClass)(this.hot.rootElement, CSS_SHOW_UI);
      }

      blockCalculations.row = true;
      blockCalculations.column = true;
      blockCalculations.cell = true;
      priv.target.coords = coords;
      priv.target.TD = TD;
    }

    /**
     * `onMouseUp` hook callback.
     *
     * @private
     */

  }, {
    key: 'onMouseUp',
    value: function onMouseUp() {
      var priv = privatePool.get(this);
      var target = priv.target.row;
      var rowsLen = priv.rowsToMove.length;

      priv.pressed = false;
      priv.backlightHeight = 0;

      (0, _element.removeClass)(this.hot.rootElement, [CSS_ON_MOVING, CSS_SHOW_UI, CSS_AFTER_SELECTION]);

      if (this.hot.selection.selectedHeader.rows) {
        (0, _element.addClass)(this.hot.rootElement, CSS_AFTER_SELECTION);
      }

      if (rowsLen < 1 || target === void 0 || priv.rowsToMove.indexOf(target) > -1 || priv.rowsToMove[rowsLen - 1] === target - 1) {
        return;
      }

      this.moveRows(priv.rowsToMove, target);

      this.persistentStateSave();
      this.hot.render();

      if (!priv.disallowMoving) {
        var selectionStart = this.rowsMapper.getIndexByValue(priv.rowsToMove[0]);
        var selectionEnd = this.rowsMapper.getIndexByValue(priv.rowsToMove[rowsLen - 1]);
        this.changeSelection(selectionStart, selectionEnd);
      }

      priv.rowsToMove.length = 0;
    }

    /**
     * `afterScrollHorizontally` hook callback. Fired the table was scrolled horizontally.
     *
     * @private
     */

  }, {
    key: 'onAfterScrollHorizontally',
    value: function onAfterScrollHorizontally() {
      var wtTable = this.hot.view.wt.wtTable;
      var headerWidth = this.hot.view.wt.wtViewport.getRowHeaderWidth();
      var scrollLeft = wtTable.holder.scrollLeft;
      var posLeft = headerWidth + scrollLeft;

      this.backlight.setPosition(null, posLeft);
      this.backlight.setSize(wtTable.hider.offsetWidth - posLeft);
    }

    /**
     * `afterCreateRow` hook callback.
     *
     * @private
     * @param {Number} index Visual index of the created row.
     * @param {Number} amount Amount of created rows.
     */

  }, {
    key: 'onAfterCreateRow',
    value: function onAfterCreateRow(index, amount) {
      this.rowsMapper.shiftItems(index, amount);
    }

    /**
     * On before remove row listener.
     *
     * @private
     * @param {Number} index Visual row index.
     * @param {Number} amount Defines how many rows removed.
     */

  }, {
    key: 'onBeforeRemoveRow',
    value: function onBeforeRemoveRow(index, amount) {
      var _this5 = this;

      this.removedRows.length = 0;

      if (index !== false) {
        // Collect physical row index.
        (0, _number.rangeEach)(index, index + amount - 1, function (removedIndex) {
          _this5.removedRows.push(_this5.hot.runHooks('modifyRow', removedIndex, _this5.pluginName));
        });
      }
    }

    /**
     * `afterRemoveRow` hook callback.
     *
     * @private
     */

  }, {
    key: 'onAfterRemoveRow',
    value: function onAfterRemoveRow() {
      this.rowsMapper.unshiftItems(this.removedRows);
    }

    /**
     * `afterLoadData` hook callback.
     *
     * @private
     */

  }, {
    key: 'onAfterLoadData',
    value: function onAfterLoadData() {
      this.updateRowsMapper();
    }

    /**
     * 'modifyRow' hook callback.
     *
     * @private
     * @param {Number} row Visual Row index.
     * @returns {Number} Physical row index.
     */

  }, {
    key: 'onModifyRow',
    value: function onModifyRow(row, source) {
      if (source !== this.pluginName) {
        var rowInMapper = this.rowsMapper.getValueByIndex(row);
        row = rowInMapper === null ? row : rowInMapper;
      }

      return row;
    }

    /**
     * 'unmodifyRow' hook callback.
     *
     * @private
     * @param {Number} row Physical row index.
     * @returns {Number} Visual row index.
     */

  }, {
    key: 'onUnmodifyRow',
    value: function onUnmodifyRow(row) {
      var indexInMapper = this.rowsMapper.getIndexByValue(row);

      return indexInMapper === null ? row : indexInMapper;
    }

    /**
     * `afterPluginsInitialized` hook callback.
     *
     * @private
     */

  }, {
    key: 'onAfterPluginsInitialized',
    value: function onAfterPluginsInitialized() {
      this.updateRowsMapper();
      this.initialSettings();
      this.backlight.build();
      this.guideline.build();
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this.backlight.destroy();
      this.guideline.destroy();

      _get(ManualRowMove.prototype.__proto__ || Object.getPrototypeOf(ManualRowMove.prototype), 'destroy', this).call(this);
    }
  }]);

  return ManualRowMove;
}(_base2.default);

(0, _plugins.registerPlugin)('ManualRowMove', ManualRowMove);

exports.default = ManualRowMove;

/***/ }),
/* 437 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _arrayMapper = __webpack_require__(314);

var _arrayMapper2 = _interopRequireDefault(_arrayMapper);

var _array = __webpack_require__(2);

var _object = __webpack_require__(1);

var _number = __webpack_require__(6);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class RowsMapper
 * @plugin ManualRowMove
 */
var RowsMapper = function () {
  function RowsMapper(manualRowMove) {
    _classCallCheck(this, RowsMapper);

    /**
     * Instance of ManualRowMove plugin.
     *
     * @type {ManualRowMove}
     */
    this.manualRowMove = manualRowMove;
  }

  /**
   * Reset current map array and create new one.
   *
   * @param {Number} [length] Custom generated map length.
   */


  _createClass(RowsMapper, [{
    key: 'createMap',
    value: function createMap(length) {
      var _this = this;

      var originLength = length === void 0 ? this._arrayMap.length : length;

      this._arrayMap.length = 0;

      (0, _number.rangeEach)(originLength - 1, function (itemIndex) {
        _this._arrayMap[itemIndex] = itemIndex;
      });
    }

    /**
     * Destroy class.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      this._arrayMap = null;
    }

    /**
     * Moving elements in rowsMapper.
     *
     * @param {Number} from Row index to move.
     * @param {Number} to Target index.
     */

  }, {
    key: 'moveRow',
    value: function moveRow(from, to) {
      var indexToMove = this._arrayMap[from];
      this._arrayMap[from] = null;
      this._arrayMap.splice(to, 0, indexToMove);
    }

    /**
     * Clearing arrayMap from `null` entries.
     */

  }, {
    key: 'clearNull',
    value: function clearNull() {
      this._arrayMap = (0, _array.arrayFilter)(this._arrayMap, function (i) {
        return i !== null;
      });
    }
  }]);

  return RowsMapper;
}();

(0, _object.mixin)(RowsMapper, _arrayMapper2.default);

exports.default = RowsMapper;

/***/ }),
/* 438 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(316);

var _base2 = _interopRequireDefault(_base);

var _element = __webpack_require__(0);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CSS_CLASSNAME = 'ht__manualRowMove--backlight';

/**
 * @class BacklightUI
 * @util
 */

var BacklightUI = function (_BaseUI) {
  _inherits(BacklightUI, _BaseUI);

  function BacklightUI() {
    _classCallCheck(this, BacklightUI);

    return _possibleConstructorReturn(this, (BacklightUI.__proto__ || Object.getPrototypeOf(BacklightUI)).apply(this, arguments));
  }

  _createClass(BacklightUI, [{
    key: 'build',

    /**
     * Custom className on build process.
     */
    value: function build() {
      _get(BacklightUI.prototype.__proto__ || Object.getPrototypeOf(BacklightUI.prototype), 'build', this).call(this);

      (0, _element.addClass)(this._element, CSS_CLASSNAME);
    }
  }]);

  return BacklightUI;
}(_base2.default);

exports.default = BacklightUI;

/***/ }),
/* 439 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(316);

var _base2 = _interopRequireDefault(_base);

var _element = __webpack_require__(0);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var CSS_CLASSNAME = 'ht__manualRowMove--guideline';

/**
 * @class GuidelineUI
 * @util
 */

var GuidelineUI = function (_BaseUI) {
  _inherits(GuidelineUI, _BaseUI);

  function GuidelineUI() {
    _classCallCheck(this, GuidelineUI);

    return _possibleConstructorReturn(this, (GuidelineUI.__proto__ || Object.getPrototypeOf(GuidelineUI)).apply(this, arguments));
  }

  _createClass(GuidelineUI, [{
    key: 'build',

    /**
     * Custom className on build process.
     */
    value: function build() {
      _get(GuidelineUI.prototype.__proto__ || Object.getPrototypeOf(GuidelineUI.prototype), 'build', this).call(this);

      (0, _element.addClass)(this._element, CSS_CLASSNAME);
    }
  }]);

  return GuidelineUI;
}(_base2.default);

exports.default = GuidelineUI;

/***/ }),
/* 440 */
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),
/* 441 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _element = __webpack_require__(0);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _event = __webpack_require__(12);

var _array = __webpack_require__(2);

var _number = __webpack_require__(6);

var _plugins = __webpack_require__(7);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// Developer note! Whenever you make a change in this file, make an analogous change in manualRowResize.js

/**
 * @description
 * ManualRowResize Plugin.
 *
 * Has 2 UI components:
 * - handle - the draggable element that sets the desired height of the row.
 * - guide - the helper guide that shows the desired height as a horizontal guide.
 *
 * @plugin ManualRowResize
 */
var ManualRowResize = function (_BasePlugin) {
  _inherits(ManualRowResize, _BasePlugin);

  function ManualRowResize(hotInstance) {
    _classCallCheck(this, ManualRowResize);

    var _this = _possibleConstructorReturn(this, (ManualRowResize.__proto__ || Object.getPrototypeOf(ManualRowResize)).call(this, hotInstance));

    _this.currentTH = null;
    _this.currentRow = null;
    _this.selectedRows = [];
    _this.currentHeight = null;
    _this.newSize = null;
    _this.startY = null;
    _this.startHeight = null;
    _this.startOffset = null;
    _this.handle = document.createElement('DIV');
    _this.guide = document.createElement('DIV');
    _this.eventManager = new _eventManager2.default(_this);
    _this.pressed = null;
    _this.dblclick = 0;
    _this.autoresizeTimeout = null;
    _this.manualRowHeights = [];

    (0, _element.addClass)(_this.handle, 'manualRowResizer');
    (0, _element.addClass)(_this.guide, 'manualRowResizerGuide');
    return _this;
  }

  /**
   * Check if the plugin is enabled in the handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(ManualRowResize, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return this.hot.getSettings().manualRowResize;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.manualRowHeights = [];

      var initialRowHeights = this.hot.getSettings().manualRowResize;
      var loadedManualRowHeights = this.loadManualRowHeights();

      if (typeof loadedManualRowHeights != 'undefined') {
        this.manualRowHeights = loadedManualRowHeights;
      } else if (Array.isArray(initialRowHeights)) {
        this.manualRowHeights = initialRowHeights;
      } else {
        this.manualRowHeights = [];
      }

      this.addHook('modifyRowHeight', function (height, row) {
        return _this2.onModifyRowHeight(height, row);
      });

      // Handsontable.hooks.register('beforeRowResize');
      // Handsontable.hooks.register('afterRowResize');

      this.bindEvents();

      _get(ManualRowResize.prototype.__proto__ || Object.getPrototypeOf(ManualRowResize.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      var initialRowHeights = this.hot.getSettings().manualRowResize;

      if (Array.isArray(initialRowHeights)) {
        this.manualRowHeights = initialRowHeights;
      } else if (!initialRowHeights) {
        this.manualRowHeights = [];
      }
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      _get(ManualRowResize.prototype.__proto__ || Object.getPrototypeOf(ManualRowResize.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Save the current sizes using the persistentState plugin.
     */

  }, {
    key: 'saveManualRowHeights',
    value: function saveManualRowHeights() {
      this.hot.runHooks('persistentStateSave', 'manualRowHeights', this.manualRowHeights);
    }

    /**
     * Load the previously saved sizes using the persistentState plugin.
     *
     * @returns {Array}
     */

  }, {
    key: 'loadManualRowHeights',
    value: function loadManualRowHeights() {
      var storedState = {};

      this.hot.runHooks('persistentStateLoad', 'manualRowHeights', storedState);

      return storedState.value;
    }

    /**
     * Set the resize handle position.
     *
     * @param {HTMLCellElement} TH TH HTML element.
     */

  }, {
    key: 'setupHandlePosition',
    value: function setupHandlePosition(TH) {
      var _this3 = this;

      this.currentTH = TH;
      var row = this.hot.view.wt.wtTable.getCoords(TH).row; // getCoords returns CellCoords
      var headerWidth = (0, _element.outerWidth)(this.currentTH);

      if (row >= 0) {
        // if not col header
        var box = this.currentTH.getBoundingClientRect();

        this.currentRow = row;
        this.selectedRows = [];

        if (this.hot.selection.isSelected() && this.hot.selection.selectedHeader.rows) {
          var _hot$getSelectedRange = this.hot.getSelectedRange(),
              from = _hot$getSelectedRange.from,
              to = _hot$getSelectedRange.to;

          var start = from.row;
          var end = to.row;

          if (start >= end) {
            start = to.row;
            end = from.row;
          }

          if (this.currentRow >= start && this.currentRow <= end) {
            (0, _number.rangeEach)(start, end, function (i) {
              return _this3.selectedRows.push(i);
            });
          } else {
            this.selectedRows.push(this.currentRow);
          }
        } else {
          this.selectedRows.push(this.currentRow);
        }

        this.startOffset = box.top - 6;
        this.startHeight = parseInt(box.height, 10);
        this.handle.style.left = box.left + 'px';
        this.handle.style.top = this.startOffset + this.startHeight + 'px';
        this.handle.style.width = headerWidth + 'px';
        this.hot.rootElement.appendChild(this.handle);
      }
    }

    /**
     * Refresh the resize handle position.
     */

  }, {
    key: 'refreshHandlePosition',
    value: function refreshHandlePosition() {
      this.handle.style.top = this.startOffset + this.currentHeight + 'px';
    }

    /**
     * Set the resize guide position.
     */

  }, {
    key: 'setupGuidePosition',
    value: function setupGuidePosition() {
      var handleWidth = parseInt((0, _element.outerWidth)(this.handle), 10);
      var handleRightPosition = parseInt(this.handle.style.left, 10) + handleWidth;
      var maximumVisibleElementWidth = parseInt(this.hot.view.maximumVisibleElementWidth(0), 10);
      (0, _element.addClass)(this.handle, 'active');
      (0, _element.addClass)(this.guide, 'active');

      this.guide.style.top = this.handle.style.top;
      this.guide.style.left = handleRightPosition + 'px';
      this.guide.style.width = maximumVisibleElementWidth - handleWidth + 'px';
      this.hot.rootElement.appendChild(this.guide);
    }

    /**
     * Refresh the resize guide position.
     */

  }, {
    key: 'refreshGuidePosition',
    value: function refreshGuidePosition() {
      this.guide.style.top = this.handle.style.top;
    }

    /**
     * Hide both the resize handle and resize guide.
     */

  }, {
    key: 'hideHandleAndGuide',
    value: function hideHandleAndGuide() {
      (0, _element.removeClass)(this.handle, 'active');
      (0, _element.removeClass)(this.guide, 'active');
    }

    /**
     * Check if provided element is considered as a row header.
     *
     * @param {HTMLElement} element HTML element.
     * @returns {Boolean}
     */

  }, {
    key: 'checkIfRowHeader',
    value: function checkIfRowHeader(element) {
      if (element != this.hot.rootElement) {
        var parent = element.parentNode;

        if (parent.tagName === 'TBODY') {
          return true;
        }

        return this.checkIfRowHeader(parent);
      }

      return false;
    }

    /**
     * Get the TH element from the provided element.
     *
     * @param {HTMLElement} element HTML element.
     * @returns {HTMLElement}
     */

  }, {
    key: 'getTHFromTargetElement',
    value: function getTHFromTargetElement(element) {
      if (element.tagName != 'TABLE') {
        if (element.tagName == 'TH') {
          return element;
        }
        return this.getTHFromTargetElement(element.parentNode);
      }

      return null;
    }

    /**
     * 'mouseover' event callback - set the handle position.
     *
     * @private
     * @param {MouseEvent} event
     */

  }, {
    key: 'onMouseOver',
    value: function onMouseOver(event) {
      if (this.checkIfRowHeader(event.target)) {
        var th = this.getTHFromTargetElement(event.target);

        if (th) {
          if (!this.pressed) {
            this.setupHandlePosition(th);
          }
        }
      }
    }

    /**
     * Auto-size row after doubleclick - callback.
     *
     * @private
     */

  }, {
    key: 'afterMouseDownTimeout',
    value: function afterMouseDownTimeout() {
      var _this4 = this;

      var render = function render() {
        _this4.hot.forceFullRender = true;
        _this4.hot.view.render(); // updates all
        _this4.hot.view.wt.wtOverlays.adjustElementsSize(true);
      };
      var resize = function resize(selectedRow, forceRender) {
        var hookNewSize = _this4.hot.runHooks('beforeRowResize', selectedRow, _this4.newSize, true);

        if (hookNewSize !== void 0) {
          _this4.newSize = hookNewSize;
        }

        _this4.setManualSize(selectedRow, _this4.newSize); // double click sets auto row size

        if (forceRender) {
          render();
        }

        _this4.hot.runHooks('afterRowResize', selectedRow, _this4.newSize, true);
      };

      if (this.dblclick >= 2) {
        var selectedRowsLength = this.selectedRows.length;

        if (selectedRowsLength > 1) {
          (0, _array.arrayEach)(this.selectedRows, function (selectedRow) {
            resize(selectedRow);
          });
          render();
        } else {
          (0, _array.arrayEach)(this.selectedRows, function (selectedRow) {
            resize(selectedRow, true);
          });
        }
      }
      this.dblclick = 0;
      this.autoresizeTimeout = null;
    }

    /**
     * 'mousedown' event callback.
     *
     * @private
     * @param {MouseEvent} event
     */

  }, {
    key: 'onMouseDown',
    value: function onMouseDown(event) {
      var _this5 = this;

      if ((0, _element.hasClass)(event.target, 'manualRowResizer')) {
        this.setupGuidePosition();
        this.pressed = this.hot;

        if (this.autoresizeTimeout == null) {
          this.autoresizeTimeout = setTimeout(function () {
            return _this5.afterMouseDownTimeout();
          }, 500);

          this.hot._registerTimeout(this.autoresizeTimeout);
        }
        this.dblclick++;

        this.startY = (0, _event.pageY)(event);
        this.newSize = this.startHeight;
      }
    }

    /**
     * 'mousemove' event callback - refresh the handle and guide positions, cache the new row height.
     *
     * @private
     * @param {MouseEvent} event
     */

  }, {
    key: 'onMouseMove',
    value: function onMouseMove(event) {
      var _this6 = this;

      if (this.pressed) {
        this.currentHeight = this.startHeight + ((0, _event.pageY)(event) - this.startY);

        (0, _array.arrayEach)(this.selectedRows, function (selectedRow) {
          _this6.newSize = _this6.setManualSize(selectedRow, _this6.currentHeight);
        });

        this.refreshHandlePosition();
        this.refreshGuidePosition();
      }
    }

    /**
     * 'mouseup' event callback - apply the row resizing.
     *
     * @private
     * @param {MouseEvent} event
     */

  }, {
    key: 'onMouseUp',
    value: function onMouseUp(event) {
      var _this7 = this;

      var render = function render() {
        _this7.hot.forceFullRender = true;
        _this7.hot.view.render(); // updates all
        _this7.hot.view.wt.wtOverlays.adjustElementsSize(true);
      };
      var runHooks = function runHooks(selectedRow, forceRender) {
        _this7.hot.runHooks('beforeRowResize', selectedRow, _this7.newSize);

        if (forceRender) {
          render();
        }

        _this7.saveManualRowHeights();

        _this7.hot.runHooks('afterRowResize', selectedRow, _this7.newSize);
      };
      if (this.pressed) {
        this.hideHandleAndGuide();
        this.pressed = false;

        if (this.newSize != this.startHeight) {
          var selectedRowsLength = this.selectedRows.length;

          if (selectedRowsLength > 1) {
            (0, _array.arrayEach)(this.selectedRows, function (selectedRow) {
              runHooks(selectedRow);
            });
            render();
          } else {
            (0, _array.arrayEach)(this.selectedRows, function (selectedRow) {
              runHooks(selectedRow, true);
            });
          }
        }

        this.setupHandlePosition(this.currentTH);
      }
    }

    /**
     * Bind the mouse events.
     *
     * @private
     */

  }, {
    key: 'bindEvents',
    value: function bindEvents() {
      var _this8 = this;

      this.eventManager.addEventListener(this.hot.rootElement, 'mouseover', function (e) {
        return _this8.onMouseOver(e);
      });
      this.eventManager.addEventListener(this.hot.rootElement, 'mousedown', function (e) {
        return _this8.onMouseDown(e);
      });
      this.eventManager.addEventListener(window, 'mousemove', function (e) {
        return _this8.onMouseMove(e);
      });
      this.eventManager.addEventListener(window, 'mouseup', function (e) {
        return _this8.onMouseUp(e);
      });
    }

    /**
     * Cache the current row height.
     *
     * @param {Number} row Visual row index.
     * @param {Number} height Row height.
     * @returns {Number}
     */

  }, {
    key: 'setManualSize',
    value: function setManualSize(row, height) {
      row = this.hot.runHooks('modifyRow', row);
      this.manualRowHeights[row] = height;

      return height;
    }

    /**
     * Modify the provided row height, based on the plugin settings.
     *
     * @private
     * @param {Number} height Row height.
     * @param {Number} row Visual row index.
     * @returns {Number}
     */

  }, {
    key: 'onModifyRowHeight',
    value: function onModifyRowHeight(height, row) {
      if (this.enabled) {
        var autoRowSizePlugin = this.hot.getPlugin('autoRowSize');
        var autoRowHeightResult = autoRowSizePlugin ? autoRowSizePlugin.heights[row] : null;

        row = this.hot.runHooks('modifyRow', row);

        var manualRowHeight = this.manualRowHeights[row];

        if (manualRowHeight !== void 0 && (manualRowHeight === autoRowHeightResult || manualRowHeight > (height || 0))) {
          return manualRowHeight;
        }
      }

      return height;
    }
  }]);

  return ManualRowResize;
}(_base2.default);

(0, _plugins.registerPlugin)('manualRowResize', ManualRowResize);

exports.default = ManualRowResize;

/***/ }),
/* 442 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _event = __webpack_require__(12);

var _src = __webpack_require__(15);

var _constants = __webpack_require__(8);

var C = _interopRequireWildcard(_constants);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function CellInfoCollection() {
  var collection = [];

  collection.getInfo = function (row, col) {
    for (var i = 0, ilen = this.length; i < ilen; i++) {
      if (this[i].row <= row && this[i].row + this[i].rowspan - 1 >= row && this[i].col <= col && this[i].col + this[i].colspan - 1 >= col) {
        return this[i];
      }
    }
  };

  collection.setInfo = function (info) {
    for (var i = 0, ilen = this.length; i < ilen; i++) {
      if (this[i].row === info.row && this[i].col === info.col) {
        this[i] = info;
        return;
      }
    }
    this.push(info);
  };

  collection.removeInfo = function (row, col) {
    for (var i = 0, ilen = this.length; i < ilen; i++) {
      if (this[i].row === row && this[i].col === col) {
        this.splice(i, 1);
        break;
      }
    }
  };

  return collection;
}

/**
 * Plugin used to merge cells in Handsontable.
 *
 * @private
 * @plugin MergeCells
 * @class MergeCells
 */
function MergeCells(mergeCellsSetting) {
  this.mergedCellInfoCollection = new CellInfoCollection();

  if (Array.isArray(mergeCellsSetting)) {
    for (var i = 0, ilen = mergeCellsSetting.length; i < ilen; i++) {
      this.mergedCellInfoCollection.setInfo(mergeCellsSetting[i]);
    }
  }
}

/**
 * @param cellRange (CellRange)
 */
MergeCells.prototype.canMergeRange = function (cellRange) {
  // is more than one cell selected
  return !cellRange.isSingle();
};

MergeCells.prototype.mergeRange = function (cellRange) {
  if (!this.canMergeRange(cellRange)) {
    return;
  }

  // normalize top left corner
  var topLeft = cellRange.getTopLeftCorner();
  var bottomRight = cellRange.getBottomRightCorner();

  var mergeParent = {};
  mergeParent.row = topLeft.row;
  mergeParent.col = topLeft.col;
  // TD has rowspan == 1 by default. rowspan == 2 means spread over 2 cells
  mergeParent.rowspan = bottomRight.row - topLeft.row + 1;
  mergeParent.colspan = bottomRight.col - topLeft.col + 1;
  this.mergedCellInfoCollection.setInfo(mergeParent);
};

MergeCells.prototype.mergeOrUnmergeSelection = function (cellRange) {
  var info = this.mergedCellInfoCollection.getInfo(cellRange.from.row, cellRange.from.col);
  if (info) {
    // unmerge
    this.unmergeSelection(cellRange.from);
  } else {
    // merge
    this.mergeSelection(cellRange);
  }
};

MergeCells.prototype.mergeSelection = function (cellRange) {
  this.mergeRange(cellRange);
};

MergeCells.prototype.unmergeSelection = function (cellRange) {
  var info = this.mergedCellInfoCollection.getInfo(cellRange.row, cellRange.col);
  this.mergedCellInfoCollection.removeInfo(info.row, info.col);
};

MergeCells.prototype.applySpanProperties = function (TD, row, col) {
  var info = this.mergedCellInfoCollection.getInfo(row, col);

  if (info) {
    if (info.row === row && info.col === col) {
      TD.setAttribute('rowspan', info.rowspan);
      TD.setAttribute('colspan', info.colspan);
    } else {
      TD.removeAttribute('rowspan');
      TD.removeAttribute('colspan');

      TD.style.display = 'none';
    }
  } else {
    TD.removeAttribute('rowspan');
    TD.removeAttribute('colspan');
  }
};

MergeCells.prototype.modifyTransform = function (hook, currentSelectedRange, delta) {
  var sameRowspan = function sameRowspan(merged, coords) {
    if (coords.row >= merged.row && coords.row <= merged.row + merged.rowspan - 1) {
      return true;
    }
    return false;
  },
      sameColspan = function sameColspan(merged, coords) {
    if (coords.col >= merged.col && coords.col <= merged.col + merged.colspan - 1) {
      return true;
    }
    return false;
  },
      getNextPosition = function getNextPosition(newDelta) {
    return new _src.CellCoords(currentSelectedRange.to.row + newDelta.row, currentSelectedRange.to.col + newDelta.col);
  };

  var newDelta = {
    row: delta.row,
    col: delta.col
  };

  if (hook == 'modifyTransformStart') {
    /* eslint-disable block-scoped-var */
    var nextPosition;

    if (!this.lastDesiredCoords) {
      this.lastDesiredCoords = new _src.CellCoords(null, null);
    }
    var currentPosition = new _src.CellCoords(currentSelectedRange.highlight.row, currentSelectedRange.highlight.col),

    // if current position's parent is a merged range, returns it
    mergedParent = this.mergedCellInfoCollection.getInfo(currentPosition.row, currentPosition.col),
        currentRangeContainsMerge; // if current range contains a merged range

    for (var i = 0, mergesLength = this.mergedCellInfoCollection.length; i < mergesLength; i++) {
      var range = this.mergedCellInfoCollection[i];
      range = new _src.CellCoords(range.row + range.rowspan - 1, range.col + range.colspan - 1);
      if (currentSelectedRange.includes(range)) {
        currentRangeContainsMerge = true;
        break;
      }
    }

    if (mergedParent) {
      // only merge selected
      var mergeTopLeft = new _src.CellCoords(mergedParent.row, mergedParent.col);
      var mergeBottomRight = new _src.CellCoords(mergedParent.row + mergedParent.rowspan - 1, mergedParent.col + mergedParent.colspan - 1);
      var mergeRange = new _src.CellRange(mergeTopLeft, mergeTopLeft, mergeBottomRight);

      if (!mergeRange.includes(this.lastDesiredCoords)) {
        this.lastDesiredCoords = new _src.CellCoords(null, null); // reset outdated version of lastDesiredCoords
      }

      newDelta.row = this.lastDesiredCoords.row ? this.lastDesiredCoords.row - currentPosition.row : newDelta.row;
      newDelta.col = this.lastDesiredCoords.col ? this.lastDesiredCoords.col - currentPosition.col : newDelta.col;

      if (delta.row > 0) {
        // moving down
        newDelta.row = mergedParent.row + mergedParent.rowspan - 1 - currentPosition.row + delta.row;
      } else if (delta.row < 0) {
        // moving up
        newDelta.row = currentPosition.row - mergedParent.row + delta.row;
      }
      if (delta.col > 0) {
        // moving right
        newDelta.col = mergedParent.col + mergedParent.colspan - 1 - currentPosition.col + delta.col;
      } else if (delta.col < 0) {
        // moving left
        newDelta.col = currentPosition.col - mergedParent.col + delta.col;
      }
    }

    nextPosition = new _src.CellCoords(currentSelectedRange.highlight.row + newDelta.row, currentSelectedRange.highlight.col + newDelta.col);

    var nextParentIsMerged = this.mergedCellInfoCollection.getInfo(nextPosition.row, nextPosition.col);

    if (nextParentIsMerged) {
      // skipping the invisible cells in the merge range
      this.lastDesiredCoords = nextPosition;
      newDelta = {
        row: nextParentIsMerged.row - currentPosition.row,
        col: nextParentIsMerged.col - currentPosition.col
      };
    }
  } else if (hook == 'modifyTransformEnd') {
    for (var _i = 0, _mergesLength = this.mergedCellInfoCollection.length; _i < _mergesLength; _i++) {
      var currentMerge = this.mergedCellInfoCollection[_i];
      var _mergeTopLeft = new _src.CellCoords(currentMerge.row, currentMerge.col);
      var _mergeBottomRight = new _src.CellCoords(currentMerge.row + currentMerge.rowspan - 1, currentMerge.col + currentMerge.colspan - 1);
      var mergedRange = new _src.CellRange(_mergeTopLeft, _mergeTopLeft, _mergeBottomRight);
      var sharedBorders = currentSelectedRange.getBordersSharedWith(mergedRange);

      if (mergedRange.isEqual(currentSelectedRange)) {
        // only the merged range is selected
        currentSelectedRange.setDirection('NW-SE');
      } else if (sharedBorders.length > 0) {
        var mergeHighlighted = currentSelectedRange.highlight.isEqual(mergedRange.from);

        if (sharedBorders.indexOf('top') > -1) {
          // if range shares a border with the merged section, change range direction accordingly
          if (currentSelectedRange.to.isSouthEastOf(mergedRange.from) && mergeHighlighted) {
            currentSelectedRange.setDirection('NW-SE');
          } else if (currentSelectedRange.to.isSouthWestOf(mergedRange.from) && mergeHighlighted) {
            currentSelectedRange.setDirection('NE-SW');
          }
        } else if (sharedBorders.indexOf('bottom') > -1) {
          if (currentSelectedRange.to.isNorthEastOf(mergedRange.from) && mergeHighlighted) {
            currentSelectedRange.setDirection('SW-NE');
          } else if (currentSelectedRange.to.isNorthWestOf(mergedRange.from) && mergeHighlighted) {
            currentSelectedRange.setDirection('SE-NW');
          }
        }
      }

      nextPosition = getNextPosition(newDelta);
      var withinRowspan = sameRowspan(currentMerge, nextPosition),
          withinColspan = sameColspan(currentMerge, nextPosition);

      if (currentSelectedRange.includesRange(mergedRange) && (mergedRange.includes(nextPosition) || withinRowspan || withinColspan)) {
        // if next step overlaps a merged range, jump past it
        if (withinRowspan) {
          if (newDelta.row < 0) {
            newDelta.row -= currentMerge.rowspan - 1;
          } else if (newDelta.row > 0) {
            newDelta.row += currentMerge.rowspan - 1;
          }
        }
        if (withinColspan) {
          if (newDelta.col < 0) {
            newDelta.col -= currentMerge.colspan - 1;
          } else if (newDelta.col > 0) {
            newDelta.col += currentMerge.colspan - 1;
          }
        }
      }
    }
  }

  if (newDelta.row !== 0) {
    delta.row = newDelta.row;
  }
  if (newDelta.col !== 0) {
    delta.col = newDelta.col;
  }
};

MergeCells.prototype.shiftCollection = function (direction, index, count) {
  var shiftVector = [0, 0];

  switch (direction) {
    case 'right':
      shiftVector[0] += 1;

      break;
    case 'left':
      shiftVector[0] -= 1;

      break;
    case 'down':
      shiftVector[1] += 1;

      break;
    case 'up':
      shiftVector[1] -= 1;

      break;
    default:
      break;
  }

  for (var i = 0; i < this.mergedCellInfoCollection.length; i++) {
    var currentMerge = this.mergedCellInfoCollection[i];

    if (direction === 'right' || direction === 'left') {
      if (index <= currentMerge.col) {
        currentMerge.col += shiftVector[0];
      }
    } else if (index <= currentMerge.row) {
      currentMerge.row += shiftVector[1];
    }
  }
};

var beforeInit = function beforeInit() {
  var instance = this;
  var mergeCellsSetting = instance.getSettings().mergeCells;

  if (mergeCellsSetting) {
    if (!instance.mergeCells) {
      instance.mergeCells = new MergeCells(mergeCellsSetting);
    }
  }
};

var afterInit = function afterInit() {
  var instance = this;
  if (instance.mergeCells) {
    /**
     * Monkey patch Table.prototype.getCell to return TD for merged cell parent if asked for TD of a cell that is
     * invisible due to the merge. This is not the cleanest solution but there is a test case for it (merged cells scroll) so feel free to refactor it!
     */
    instance.view.wt.wtTable.getCell = function (coords) {
      if (instance.getSettings().mergeCells) {
        var mergeParent = instance.mergeCells.mergedCellInfoCollection.getInfo(coords.row, coords.col);
        if (mergeParent) {
          coords = mergeParent;
        }
      }
      return _src.Table.prototype.getCell.call(this, coords);
    };
  }
};

var afterUpdateSettings = function afterUpdateSettings() {
  var instance = this;
  var mergeCellsSetting = instance.getSettings().mergeCells;

  if (mergeCellsSetting) {
    if (instance.mergeCells) {
      instance.mergeCells.mergedCellInfoCollection = new CellInfoCollection();

      if (Array.isArray(mergeCellsSetting)) {
        for (var i = 0, ilen = mergeCellsSetting.length; i < ilen; i++) {
          instance.mergeCells.mergedCellInfoCollection.setInfo(mergeCellsSetting[i]);
        }
      }
    } else {
      instance.mergeCells = new MergeCells(mergeCellsSetting);
    }
  } else if (instance.mergeCells) {
    // it doesn't actually turn off the plugin, just resets the settings. Need to refactor.
    instance.mergeCells.mergedCellInfoCollection = new CellInfoCollection();
  }
};

var onBeforeKeyDown = function onBeforeKeyDown(event) {
  if (!this.mergeCells) {
    return;
  }

  var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;

  if (ctrlDown) {
    if (event.keyCode === 77) {
      // CTRL + M
      this.mergeCells.mergeOrUnmergeSelection(this.getSelectedRange());
      this.render();
      (0, _event.stopImmediatePropagation)(event);
    }
  }
};

var addMergeActionsToContextMenu = function addMergeActionsToContextMenu(defaultOptions) {
  if (!this.getSettings().mergeCells) {
    return;
  }

  defaultOptions.items.push({ name: '---------' });
  defaultOptions.items.push({
    key: 'mergeCells',
    name: function name() {
      var sel = this.getSelected();
      var info = this.mergeCells.mergedCellInfoCollection.getInfo(sel[0], sel[1]);

      if (info) {
        return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_UNMERGE_CELLS);
      }

      return this.getTranslatedPhrase(C.CONTEXTMENU_ITEMS_MERGE_CELLS);
    },
    callback: function callback() {
      this.mergeCells.mergeOrUnmergeSelection(this.getSelectedRange());
      this.render();
    },
    disabled: function disabled() {
      return this.selection.selectedHeader.corner;
    }
  });
};

var afterRenderer = function afterRenderer(TD, row, col, prop, value, cellProperties) {
  if (this.mergeCells) {
    this.mergeCells.applySpanProperties(TD, row, col);
  }
};

var modifyTransformFactory = function modifyTransformFactory(hook) {
  return function (delta) {
    var mergeCellsSetting = this.getSettings().mergeCells;
    if (mergeCellsSetting) {
      var currentSelectedRange = this.getSelectedRange();
      this.mergeCells.modifyTransform(hook, currentSelectedRange, delta);

      if (hook === 'modifyTransformEnd') {
        // sanitize "from" (core.js will sanitize to)
        var totalRows = this.countRows();
        var totalCols = this.countCols();
        if (currentSelectedRange.from.row < 0) {
          currentSelectedRange.from.row = 0;
        } else if (currentSelectedRange.from.row > 0 && currentSelectedRange.from.row >= totalRows) {
          currentSelectedRange.from.row = currentSelectedRange.from - 1;
        }

        if (currentSelectedRange.from.col < 0) {
          currentSelectedRange.from.col = 0;
        } else if (currentSelectedRange.from.col > 0 && currentSelectedRange.from.col >= totalCols) {
          currentSelectedRange.from.col = totalCols - 1;
        }
      }
    }
  };
};

/**
 * While selecting cells with keyboard or mouse, make sure that rectangular area is expanded to the extent of the merged cell
 * @param coords
 */
var beforeSetRangeEnd = function beforeSetRangeEnd(coords) {

  this.lastDesiredCoords = null; // unset lastDesiredCoords when selection is changed with mouse
  var mergeCellsSetting = this.getSettings().mergeCells;
  if (mergeCellsSetting) {
    var selRange = this.getSelectedRange();
    selRange.highlight = new _src.CellCoords(selRange.highlight.row, selRange.highlight.col); // clone in case we will modify its reference
    selRange.to = coords;

    var rangeExpanded = false;
    do {
      rangeExpanded = false;

      for (var i = 0, ilen = this.mergeCells.mergedCellInfoCollection.length; i < ilen; i++) {
        var cellInfo = this.mergeCells.mergedCellInfoCollection[i];
        var mergedCellTopLeft = new _src.CellCoords(cellInfo.row, cellInfo.col);
        var mergedCellBottomRight = new _src.CellCoords(cellInfo.row + cellInfo.rowspan - 1, cellInfo.col + cellInfo.colspan - 1);

        var mergedCellRange = new _src.CellRange(mergedCellTopLeft, mergedCellTopLeft, mergedCellBottomRight);
        if (selRange.expandByRange(mergedCellRange)) {
          coords.row = selRange.to.row;
          coords.col = selRange.to.col;

          rangeExpanded = true;
        }
      }
    } while (rangeExpanded);
  }
};

/**
 * Returns correct coordinates for merged start / end cells in selection for area borders
 * @param corners
 * @param className
 */
var beforeDrawAreaBorders = function beforeDrawAreaBorders(corners, className) {
  if (className && className == 'area') {
    var mergeCellsSetting = this.getSettings().mergeCells;
    if (mergeCellsSetting) {
      var selRange = this.getSelectedRange();
      var startRange = new _src.CellRange(selRange.from, selRange.from, selRange.from);
      var stopRange = new _src.CellRange(selRange.to, selRange.to, selRange.to);

      for (var i = 0, ilen = this.mergeCells.mergedCellInfoCollection.length; i < ilen; i++) {
        var cellInfo = this.mergeCells.mergedCellInfoCollection[i];
        var mergedCellTopLeft = new _src.CellCoords(cellInfo.row, cellInfo.col);
        var mergedCellBottomRight = new _src.CellCoords(cellInfo.row + cellInfo.rowspan - 1, cellInfo.col + cellInfo.colspan - 1);
        var mergedCellRange = new _src.CellRange(mergedCellTopLeft, mergedCellTopLeft, mergedCellBottomRight);

        if (startRange.expandByRange(mergedCellRange)) {
          corners[0] = startRange.from.row;
          corners[1] = startRange.from.col;
        }

        if (stopRange.expandByRange(mergedCellRange)) {
          corners[2] = stopRange.from.row;
          corners[3] = stopRange.from.col;
        }
      }
    }
  }
};

var afterGetCellMeta = function afterGetCellMeta(row, col, cellProperties) {
  var mergeCellsSetting = this.getSettings().mergeCells;
  if (mergeCellsSetting) {
    var mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(row, col);
    if (mergeParent && (mergeParent.row != row || mergeParent.col != col)) {
      cellProperties.copyable = false;
    }
  }
};

var afterViewportRowCalculatorOverride = function afterViewportRowCalculatorOverride(calc) {
  var mergeCellsSetting = this.getSettings().mergeCells;
  if (mergeCellsSetting) {
    var colCount = this.countCols();
    var mergeParent;
    for (var c = 0; c < colCount; c++) {
      mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(calc.startRow, c);
      if (mergeParent) {
        if (mergeParent.row < calc.startRow) {
          calc.startRow = mergeParent.row;
          return afterViewportRowCalculatorOverride.call(this, calc); // recursively search upwards
        }
      }
      mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(calc.endRow, c);
      if (mergeParent) {
        var mergeEnd = mergeParent.row + mergeParent.rowspan - 1;
        if (mergeEnd > calc.endRow) {
          calc.endRow = mergeEnd;
          return afterViewportRowCalculatorOverride.call(this, calc); // recursively search upwards
        }
      }
    }
  }
};

var afterViewportColumnCalculatorOverride = function afterViewportColumnCalculatorOverride(calc) {
  var mergeCellsSetting = this.getSettings().mergeCells;
  if (mergeCellsSetting) {
    var rowCount = this.countRows();
    var mergeParent;
    for (var r = 0; r < rowCount; r++) {
      mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(r, calc.startColumn);

      if (mergeParent) {
        if (mergeParent.col < calc.startColumn) {
          calc.startColumn = mergeParent.col;
          return afterViewportColumnCalculatorOverride.call(this, calc); // recursively search upwards
        }
      }
      mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(r, calc.endColumn);
      if (mergeParent) {
        var mergeEnd = mergeParent.col + mergeParent.colspan - 1;
        if (mergeEnd > calc.endColumn) {
          calc.endColumn = mergeEnd;
          return afterViewportColumnCalculatorOverride.call(this, calc); // recursively search upwards
        }
      }
    }
  }
};

var isMultipleSelection = function isMultipleSelection(isMultiple) {
  if (isMultiple && this.mergeCells) {
    var mergedCells = this.mergeCells.mergedCellInfoCollection,
        selectionRange = this.getSelectedRange();

    for (var group in mergedCells) {
      if (selectionRange.highlight.row == mergedCells[group].row && selectionRange.highlight.col == mergedCells[group].col && selectionRange.to.row == mergedCells[group].row + mergedCells[group].rowspan - 1 && selectionRange.to.col == mergedCells[group].col + mergedCells[group].colspan - 1) {
        return false;
      }
    }
  }
  return isMultiple;
};

function modifyAutofillRange(select, drag) {
  var mergeCellsSetting = this.getSettings().mergeCells;

  if (!mergeCellsSetting || this.selection.isMultiple()) {
    return;
  }
  var info = this.mergeCells.mergedCellInfoCollection.getInfo(select[0], select[1]);

  if (info) {
    select[0] = info.row;
    select[1] = info.col;
    select[2] = info.row + info.rowspan - 1;
    select[3] = info.col + info.colspan - 1;
  }
}

function onAfterCreateCol(col, count) {
  if (this.mergeCells) {
    this.mergeCells.shiftCollection('right', col, count);
  }
}

function onAfterRemoveCol(col, count) {
  if (this.mergeCells) {
    this.mergeCells.shiftCollection('left', col, count);
  }
}

function onAfterCreateRow(row, count) {
  if (this.mergeCells) {
    this.mergeCells.shiftCollection('down', row, count);
  }
}

function onAfterRemoveRow(row, count) {
  if (this.mergeCells) {
    this.mergeCells.shiftCollection('up', row, count);
  }
}

var hook = _pluginHooks2.default.getSingleton();

hook.add('beforeInit', beforeInit);
hook.add('afterInit', afterInit);
hook.add('afterUpdateSettings', afterUpdateSettings);
hook.add('beforeKeyDown', onBeforeKeyDown);
hook.add('modifyTransformStart', modifyTransformFactory('modifyTransformStart'));
hook.add('modifyTransformEnd', modifyTransformFactory('modifyTransformEnd'));
hook.add('beforeSetRangeEnd', beforeSetRangeEnd);
hook.add('beforeDrawBorders', beforeDrawAreaBorders);
hook.add('afterIsMultipleSelection', isMultipleSelection);
hook.add('afterRenderer', afterRenderer);
hook.add('afterContextMenuDefaultOptions', addMergeActionsToContextMenu);
hook.add('afterGetCellMeta', afterGetCellMeta);
hook.add('afterViewportRowCalculatorOverride', afterViewportRowCalculatorOverride);
hook.add('afterViewportColumnCalculatorOverride', afterViewportColumnCalculatorOverride);
hook.add('modifyAutofillRange', modifyAutofillRange);
hook.add('afterCreateCol', onAfterCreateCol);
hook.add('afterRemoveCol', onAfterRemoveCol);
hook.add('afterCreateRow', onAfterCreateRow);
hook.add('afterRemoveRow', onAfterRemoveRow);

exports.default = MergeCells;

/***/ }),
/* 443 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _element = __webpack_require__(0);

var _browser = __webpack_require__(28);

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _eventManager = __webpack_require__(4);

var _eventManager2 = _interopRequireDefault(_eventManager);

var _plugins = __webpack_require__(7);

var _src = __webpack_require__(15);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @private
 * @plugin MultipleSelectionHandles
 */
var MultipleSelectionHandles = function (_BasePlugin) {
  _inherits(MultipleSelectionHandles, _BasePlugin);

  /**
   * @param {Object} hotInstance
   */
  function MultipleSelectionHandles(hotInstance) {
    _classCallCheck(this, MultipleSelectionHandles);

    /**
     * @type {Array}
     */
    var _this2 = _possibleConstructorReturn(this, (MultipleSelectionHandles.__proto__ || Object.getPrototypeOf(MultipleSelectionHandles)).call(this, hotInstance));

    _this2.dragged = [];
    /**
     * Instance of EventManager.
     *
     * @type {EventManager}
     */
    _this2.eventManager = null;
    /**
     * @type {null}
     */
    _this2.lastSetCell = null;
    return _this2;
  }

  /**
   * Check if the plugin is enabled in the handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(MultipleSelectionHandles, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return (0, _browser.isMobileBrowser)();
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      if (this.enabled) {
        return;
      }
      if (!this.eventManager) {
        this.eventManager = new _eventManager2.default(this);
      }
      this.registerListeners();
      _get(MultipleSelectionHandles.prototype.__proto__ || Object.getPrototypeOf(MultipleSelectionHandles.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Bind the touch events
     * @private
     */

  }, {
    key: 'registerListeners',
    value: function registerListeners() {
      var _this = this;

      function removeFromDragged(query) {

        if (_this.dragged.length === 1) {
          // clear array
          _this.dragged.splice(0, _this.dragged.length);

          return true;
        }

        var entryPosition = _this.dragged.indexOf(query);

        if (entryPosition == -1) {
          return false;
        } else if (entryPosition === 0) {
          _this.dragged = _this.dragged.slice(0, 1);
        } else if (entryPosition == 1) {
          _this.dragged = _this.dragged.slice(-1);
        }
      }

      this.eventManager.addEventListener(this.hot.rootElement, 'touchstart', function (event) {
        var selectedRange = void 0;

        if ((0, _element.hasClass)(event.target, 'topLeftSelectionHandle-HitArea')) {
          selectedRange = _this.hot.getSelectedRange();

          _this.dragged.push('topLeft');

          _this.touchStartRange = {
            width: selectedRange.getWidth(),
            height: selectedRange.getHeight(),
            direction: selectedRange.getDirection()
          };

          event.preventDefault();
          return false;
        } else if ((0, _element.hasClass)(event.target, 'bottomRightSelectionHandle-HitArea')) {
          selectedRange = _this.hot.getSelectedRange();

          _this.dragged.push('bottomRight');

          _this.touchStartRange = {
            width: selectedRange.getWidth(),
            height: selectedRange.getHeight(),
            direction: selectedRange.getDirection()
          };

          event.preventDefault();
          return false;
        }
      });

      this.eventManager.addEventListener(this.hot.rootElement, 'touchend', function (event) {
        if ((0, _element.hasClass)(event.target, 'topLeftSelectionHandle-HitArea')) {
          removeFromDragged.call(_this, 'topLeft');

          _this.touchStartRange = void 0;

          event.preventDefault();
          return false;
        } else if ((0, _element.hasClass)(event.target, 'bottomRightSelectionHandle-HitArea')) {
          removeFromDragged.call(_this, 'bottomRight');

          _this.touchStartRange = void 0;

          event.preventDefault();
          return false;
        }
      });

      this.eventManager.addEventListener(this.hot.rootElement, 'touchmove', function (event) {
        var scrollTop = (0, _element.getWindowScrollTop)(),
            scrollLeft = (0, _element.getWindowScrollLeft)(),
            endTarget = void 0,
            targetCoords = void 0,
            selectedRange = void 0,
            rangeWidth = void 0,
            rangeHeight = void 0,
            rangeDirection = void 0,
            newRangeCoords = void 0;

        if (_this.dragged.length === 0) {
          return;
        }

        endTarget = document.elementFromPoint(event.touches[0].screenX - scrollLeft, event.touches[0].screenY - scrollTop);

        if (!endTarget || endTarget === _this.lastSetCell) {
          return;
        }

        if (endTarget.nodeName == 'TD' || endTarget.nodeName == 'TH') {
          targetCoords = _this.hot.getCoords(endTarget);

          if (targetCoords.col == -1) {
            targetCoords.col = 0;
          }

          selectedRange = _this.hot.getSelectedRange();
          rangeWidth = selectedRange.getWidth();
          rangeHeight = selectedRange.getHeight();
          rangeDirection = selectedRange.getDirection();

          if (rangeWidth == 1 && rangeHeight == 1) {
            _this.hot.selection.setRangeEnd(targetCoords);
          }

          newRangeCoords = _this.getCurrentRangeCoords(selectedRange, targetCoords, _this.touchStartRange.direction, rangeDirection, _this.dragged[0]);

          if (newRangeCoords.start !== null) {
            _this.hot.selection.setRangeStart(newRangeCoords.start);
          }

          _this.hot.selection.setRangeEnd(newRangeCoords.end);

          _this.lastSetCell = endTarget;
        }

        event.preventDefault();
      });
    }
  }, {
    key: 'getCurrentRangeCoords',
    value: function getCurrentRangeCoords(selectedRange, currentTouch, touchStartDirection, currentDirection, draggedHandle) {
      var topLeftCorner = selectedRange.getTopLeftCorner(),
          bottomRightCorner = selectedRange.getBottomRightCorner(),
          bottomLeftCorner = selectedRange.getBottomLeftCorner(),
          topRightCorner = selectedRange.getTopRightCorner();

      var newCoords = {
        start: null,
        end: null
      };

      switch (touchStartDirection) {
        case 'NE-SW':
          switch (currentDirection) {
            case 'NE-SW':
            case 'NW-SE':
              if (draggedHandle == 'topLeft') {
                newCoords = {
                  start: new _src.CellCoords(currentTouch.row, selectedRange.highlight.col),
                  end: new _src.CellCoords(bottomLeftCorner.row, currentTouch.col)
                };
              } else {
                newCoords = {
                  start: new _src.CellCoords(selectedRange.highlight.row, currentTouch.col),
                  end: new _src.CellCoords(currentTouch.row, topLeftCorner.col)
                };
              }
              break;
            case 'SE-NW':
              if (draggedHandle == 'bottomRight') {
                newCoords = {
                  start: new _src.CellCoords(bottomRightCorner.row, currentTouch.col),
                  end: new _src.CellCoords(currentTouch.row, topLeftCorner.col)
                };
              }
              break;
            default:
              break;
          }
          break;
        case 'NW-SE':
          switch (currentDirection) {
            case 'NE-SW':
              if (draggedHandle == 'topLeft') {
                newCoords = {
                  start: currentTouch,
                  end: bottomLeftCorner
                };
              } else {
                newCoords.end = currentTouch;
              }
              break;
            case 'NW-SE':
              if (draggedHandle == 'topLeft') {
                newCoords = {
                  start: currentTouch,
                  end: bottomRightCorner
                };
              } else {
                newCoords.end = currentTouch;
              }
              break;
            case 'SE-NW':
              if (draggedHandle == 'topLeft') {
                newCoords = {
                  start: currentTouch,
                  end: topLeftCorner
                };
              } else {
                newCoords.end = currentTouch;
              }
              break;
            case 'SW-NE':
              if (draggedHandle == 'topLeft') {
                newCoords = {
                  start: currentTouch,
                  end: topRightCorner
                };
              } else {
                newCoords.end = currentTouch;
              }
              break;
            default:
              break;
          }
          break;
        case 'SW-NE':
          switch (currentDirection) {
            case 'NW-SE':
              if (draggedHandle == 'bottomRight') {
                newCoords = {
                  start: new _src.CellCoords(currentTouch.row, topLeftCorner.col),
                  end: new _src.CellCoords(bottomLeftCorner.row, currentTouch.col)
                };
              } else {
                newCoords = {
                  start: new _src.CellCoords(topLeftCorner.row, currentTouch.col),
                  end: new _src.CellCoords(currentTouch.row, bottomRightCorner.col)
                };
              }
              break;
            // case 'NE-SW':
            //
            //  break;
            case 'SW-NE':
              if (draggedHandle == 'topLeft') {
                newCoords = {
                  start: new _src.CellCoords(selectedRange.highlight.row, currentTouch.col),
                  end: new _src.CellCoords(currentTouch.row, bottomRightCorner.col)
                };
              } else {
                newCoords = {
                  start: new _src.CellCoords(currentTouch.row, topLeftCorner.col),
                  end: new _src.CellCoords(topLeftCorner.row, currentTouch.col)
                };
              }
              break;
            case 'SE-NW':
              if (draggedHandle == 'bottomRight') {
                newCoords = {
                  start: new _src.CellCoords(currentTouch.row, topRightCorner.col),
                  end: new _src.CellCoords(topLeftCorner.row, currentTouch.col)
                };
              } else if (draggedHandle == 'topLeft') {
                newCoords = {
                  start: bottomLeftCorner,
                  end: currentTouch
                };
              }
              break;
            default:
              break;
          }
          break;
        case 'SE-NW':
          switch (currentDirection) {
            case 'NW-SE':
            case 'NE-SW':
            case 'SW-NE':
              if (draggedHandle == 'topLeft') {
                newCoords.end = currentTouch;
              }
              break;
            case 'SE-NW':
              if (draggedHandle == 'topLeft') {
                newCoords.end = currentTouch;
              } else {
                newCoords = {
                  start: currentTouch,
                  end: topLeftCorner
                };
              }
              break;
            default:
              break;
          }
          break;
        default:
          break;
      }

      return newCoords;
    }

    /**
     * Check if user is currently dragging the handle.
     *
     * @returns {boolean} Dragging state
     */

  }, {
    key: 'isDragged',
    value: function isDragged() {
      return this.dragged.length > 0;
    }
  }]);

  return MultipleSelectionHandles;
}(_base2.default);

(0, _plugins.registerPlugin)('multipleSelectionHandles', MultipleSelectionHandles);

exports.default = MultipleSelectionHandles;

/***/ }),
/* 444 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _jsonPatchDuplex = __webpack_require__(317);

var _jsonPatchDuplex2 = _interopRequireDefault(_jsonPatchDuplex);

var _dataObserver = __webpack_require__(445);

var _dataObserver2 = _interopRequireDefault(_dataObserver);

var _array = __webpack_require__(2);

var _plugins = __webpack_require__(7);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// Handsontable.hooks.register('afterChangesObserved');

/**
 * @plugin ObserveChanges
 *
 * @description
 * This plugin allows to observe data source changes.
 *
 * By default, the plugin is declared as `undefined`, which makes it disabled.
 * Enabling this plugin switches the table into one-way data binding where changes are applied into the data source (outside from the table)
 * will be automatically reflected in the table.
 *
 * ```js
 * ...
 * // as a boolean
 * observeChanges: true,
 * ...
 * ```
 *
 * To configure this plugin see {@link Options#observeChanges}.
 */
var ObserveChanges = function (_BasePlugin) {
  _inherits(ObserveChanges, _BasePlugin);

  function ObserveChanges(hotInstance) {
    _classCallCheck(this, ObserveChanges);

    /**
     * Instance of {@link DataObserver}.
     *
     * @type {DataObserver}
     */
    var _this = _possibleConstructorReturn(this, (ObserveChanges.__proto__ || Object.getPrototypeOf(ObserveChanges)).call(this, hotInstance));

    _this.observer = null;
    return _this;
  }

  /**
   * Check if the plugin is enabled in the handsontable settings.
   *
   * @returns {Boolean}
   */


  _createClass(ObserveChanges, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return this.hot.getSettings().observeChanges;
    }

    /**
     * Enable plugin for this Handsontable instance.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }
      if (!this.observer) {
        this.observer = new _dataObserver2.default(this.hot.getSourceData());
        this._exposePublicApi();
      }

      this.observer.addLocalHook('change', function (patches) {
        return _this2.onDataChange(patches);
      });
      this.addHook('afterCreateRow', function () {
        return _this2.onAfterTableAlter();
      });
      this.addHook('afterRemoveRow', function () {
        return _this2.onAfterTableAlter();
      });
      this.addHook('afterCreateCol', function () {
        return _this2.onAfterTableAlter();
      });
      this.addHook('afterRemoveCol', function () {
        return _this2.onAfterTableAlter();
      });
      this.addHook('afterChange', function (changes, source) {
        return _this2.onAfterTableAlter(source);
      });
      this.addHook('afterLoadData', function (firstRun) {
        return _this2.onAfterLoadData(firstRun);
      });

      _get(ObserveChanges.prototype.__proto__ || Object.getPrototypeOf(ObserveChanges.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      if (this.observer) {
        this.observer.destroy();
        this.observer = null;
        this._deletePublicApi();
      }

      _get(ObserveChanges.prototype.__proto__ || Object.getPrototypeOf(ObserveChanges.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Data change observer.
     *
     * @private
     * @param {Array} patches An array of objects which every item defines coordinates where data was changed.
     */

  }, {
    key: 'onDataChange',
    value: function onDataChange(patches) {
      var _this3 = this;

      if (!this.observer.isPaused()) {
        var sourceName = this.pluginName + '.change';
        var actions = {
          add: function add(patch) {
            if (isNaN(patch.col)) {
              _this3.hot.runHooks('afterCreateRow', patch.row, 1, sourceName);
            } else {
              _this3.hot.runHooks('afterCreateCol', patch.col, 1, sourceName);
            }
          },
          remove: function remove(patch) {
            if (isNaN(patch.col)) {
              _this3.hot.runHooks('afterRemoveRow', patch.row, 1, sourceName);
            } else {
              _this3.hot.runHooks('afterRemoveCol', patch.col, 1, sourceName);
            }
          },
          replace: function replace(patch) {
            _this3.hot.runHooks('afterChange', [patch.row, patch.col, null, patch.value], sourceName);
          }
        };

        (0, _array.arrayEach)(patches, function (patch) {
          if (actions[patch.op]) {
            actions[patch.op](patch);
          }
        });
        this.hot.render();
      }

      this.hot.runHooks('afterChangesObserved');
    }

    /**
     * On after table alter listener. Prevents infinity loop between internal and external data changing.
     *
     * @private
     * @param source
     */

  }, {
    key: 'onAfterTableAlter',
    value: function onAfterTableAlter(source) {
      var _this4 = this;

      if (source !== 'loadData') {
        this.observer.pause();
        this.hot.addHookOnce('afterChangesObserved', function () {
          return _this4.observer.resume();
        });
      }
    }

    /**
     * On after load data listener.
     *
     * @private
     * @param {Boolean} firstRun `true` if event was fired first time.
     */

  }, {
    key: 'onAfterLoadData',
    value: function onAfterLoadData(firstRun) {
      if (!firstRun) {
        this.observer.setObservedData(this.hot.getSourceData());
      }
    }

    /**
     * Destroy plugin instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      if (this.observer) {
        this.observer.destroy();
        this._deletePublicApi();
      }
      _get(ObserveChanges.prototype.__proto__ || Object.getPrototypeOf(ObserveChanges.prototype), 'destroy', this).call(this);
    }

    /**
     * Expose plugins methods to the core.
     *
     * @private
     */

  }, {
    key: '_exposePublicApi',
    value: function _exposePublicApi() {
      var _this5 = this;

      var hot = this.hot;

      hot.pauseObservingChanges = function () {
        return _this5.observer.pause();
      };
      hot.resumeObservingChanges = function () {
        return _this5.observer.resume();
      };
      hot.isPausedObservingChanges = function () {
        return _this5.observer.isPaused();
      };
    }

    /**
     * Delete all previously exposed methods.
     *
     * @private
     */

  }, {
    key: '_deletePublicApi',
    value: function _deletePublicApi() {
      var hot = this.hot;

      delete hot.pauseObservingChanges;
      delete hot.resumeObservingChanges;
      delete hot.isPausedObservingChanges;
    }
  }]);

  return ObserveChanges;
}(_base2.default);

exports.default = ObserveChanges;


(0, _plugins.registerPlugin)('observeChanges', ObserveChanges);

/***/ }),
/* 445 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _jsonPatchDuplex = __webpack_require__(317);

var _jsonPatchDuplex2 = _interopRequireDefault(_jsonPatchDuplex);

var _localHooks = __webpack_require__(89);

var _localHooks2 = _interopRequireDefault(_localHooks);

var _object = __webpack_require__(1);

var _utils = __webpack_require__(446);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * @class DataObserver
 * @plugin ObserveChanges
 */
var DataObserver = function () {
  function DataObserver(observedData) {
    _classCallCheck(this, DataObserver);

    /**
     * Observed source data.
     *
     * @type {Array}
     */
    this.observedData = null;
    /**
     * JsonPatch observer.
     *
     * @type {Object}
     */
    this.observer = null;
    /**
     * Flag which determines if observer is paused or not. Paused observer doesn't emit `change` hooks.
     *
     * @type {Boolean}
     * @default false
     */
    this.paused = false;

    this.setObservedData(observedData);
  }

  /**
   * Set data to observe.
   *
   * @param {*} observedData
   */


  _createClass(DataObserver, [{
    key: 'setObservedData',
    value: function setObservedData(observedData) {
      var _this = this;

      if (this.observer) {
        _jsonPatchDuplex2.default.unobserve(this.observedData, this.observer);
      }
      this.observedData = observedData;
      this.observer = _jsonPatchDuplex2.default.observe(this.observedData, function (patches) {
        return _this.onChange(patches);
      });
    }

    /**
     * Check if observer was paused.
     *
     * @returns {Boolean}
     */

  }, {
    key: 'isPaused',
    value: function isPaused() {
      return this.paused;
    }

    /**
     * Pause observer (stop emitting all detected changes).
     */

  }, {
    key: 'pause',
    value: function pause() {
      this.paused = true;
    }

    /**
     * Resume observer (emit all detected changes).
     */

  }, {
    key: 'resume',
    value: function resume() {
      this.paused = false;
    }

    /**
     * JsonPatch on change listener.
     *
     * @private
     * @param {Array} patches An array of object passed from jsonpatch.
     */

  }, {
    key: 'onChange',
    value: function onChange(patches) {
      this.runLocalHooks('change', (0, _utils.cleanPatches)(patches));
    }

    /**
     * Destroy observer instance.
     */

  }, {
    key: 'destroy',
    value: function destroy() {
      _jsonPatchDuplex2.default.unobserve(this.observedData, this.observer);
      this.observedData = null;
      this.observer = null;
    }
  }]);

  return DataObserver;
}();

(0, _object.mixin)(DataObserver, _localHooks2.default);

exports.default = DataObserver;

/***/ }),
/* 446 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

exports.cleanPatches = cleanPatches;
exports.parsePath = parsePath;

var _array = __webpack_require__(2);

/**
 * Clean and extend patches from jsonpatch observer.
 *
 * @param {Array} patches
 * @returns {Array}
 */
function cleanPatches(patches) {
  var newOrRemovedColumns = [];

  /**
   * If observeChanges uses native Object.observe method, then it produces patches for length property. Filter them.
   * If path can't be parsed. Filter it.
   */
  patches = (0, _array.arrayFilter)(patches, function (patch) {
    if (/[/]length/ig.test(patch.path)) {
      return false;
    }
    if (!parsePath(patch.path)) {
      return false;
    }

    return true;
  });
  /**
   * Extend patches with changed cells coords
   */
  patches = (0, _array.arrayMap)(patches, function (patch) {
    var coords = parsePath(patch.path);

    patch.row = coords.row;
    patch.col = coords.col;

    return patch;
  });
  /**
   * Removing or adding column will produce one patch for each table row.
   * Leaves only one patch for each column add/remove operation.
   */
  patches = (0, _array.arrayFilter)(patches, function (patch) {
    if (['add', 'remove'].indexOf(patch.op) !== -1 && !isNaN(patch.col)) {
      if (newOrRemovedColumns.indexOf(patch.col) !== -1) {
        return false;
      }
      newOrRemovedColumns.push(patch.col);
    }

    return true;
  });
  newOrRemovedColumns.length = 0;

  return patches;
}

/**
 * Extract coordinates from path where data was changed.
 *
 * @param {String} path Path describing where data was changed.
 * @returns {Object|null} Returns an object with `row` and `col` properties or `null` if path doesn't have necessary information.
 */
function parsePath(path) {
  var match = path.match(/^\/(\d+)\/?(.*)?$/);

  if (!match) {
    return null;
  }

  var _match = _slicedToArray(match, 3),
      row = _match[1],
      column = _match[2];

  return {
    row: parseInt(row, 10),
    col: /^\d*$/.test(column) ? parseInt(column, 10) : column
  };
}

/***/ }),
/* 447 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _plugins = __webpack_require__(7);

var _object = __webpack_require__(1);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function Storage(prefix) {
  var savedKeys;

  var saveSavedKeys = function saveSavedKeys() {
    window.localStorage[prefix + '__persistentStateKeys'] = JSON.stringify(savedKeys);
  };

  var loadSavedKeys = function loadSavedKeys() {
    var keysJSON = window.localStorage[prefix + '__persistentStateKeys'];
    var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0;
    savedKeys = keys ? keys : [];
  };

  var clearSavedKeys = function clearSavedKeys() {
    savedKeys = [];
    saveSavedKeys();
  };

  loadSavedKeys();

  this.saveValue = function (key, value) {
    window.localStorage[prefix + '_' + key] = JSON.stringify(value);
    if (savedKeys.indexOf(key) == -1) {
      savedKeys.push(key);
      saveSavedKeys();
    }
  };

  this.loadValue = function (key, defaultValue) {

    key = typeof key === 'undefined' ? defaultValue : key;

    var value = window.localStorage[prefix + '_' + key];

    return typeof value == 'undefined' ? void 0 : JSON.parse(value);
  };

  this.reset = function (key) {
    window.localStorage.removeItem(prefix + '_' + key);
  };

  this.resetAll = function () {
    for (var index = 0; index < savedKeys.length; index++) {
      window.localStorage.removeItem(prefix + '_' + savedKeys[index]);
    }

    clearSavedKeys();
  };
}

/**
 * @private
 * @class PersistentState
 * @plugin PersistentState
 */
function HandsontablePersistentState() {
  var plugin = this;

  this.init = function () {
    var instance = this,
        pluginSettings = instance.getSettings().persistentState;

    plugin.enabled = !!pluginSettings;

    if (!plugin.enabled) {
      removeHooks.call(instance);
      return;
    }

    if (!instance.storage) {
      instance.storage = new Storage(instance.rootElement.id);
    }

    instance.resetState = plugin.resetValue;

    addHooks.call(instance);
  };

  this.saveValue = function (key, value) {
    var instance = this;

    instance.storage.saveValue(key, value);
  };

  this.loadValue = function (key, saveTo) {
    var instance = this;

    saveTo.value = instance.storage.loadValue(key);
  };

  this.resetValue = function (key) {
    var instance = this;

    if (typeof key === 'undefined') {
      instance.storage.resetAll();
    } else {
      instance.storage.reset(key);
    }
  };

  var hooks = {
    persistentStateSave: plugin.saveValue,
    persistentStateLoad: plugin.loadValue,
    persistentStateReset: plugin.resetValue
  };

  for (var hookName in hooks) {
    if ((0, _object.hasOwnProperty)(hooks, hookName)) {
      _pluginHooks2.default.getSingleton().register(hookName);
    }
  }

  function addHooks() {
    var instance = this;

    for (var hookName in hooks) {
      if ((0, _object.hasOwnProperty)(hooks, hookName)) {
        instance.addHook(hookName, hooks[hookName]);
      }
    }
  }

  function removeHooks() {
    var instance = this;

    for (var hookName in hooks) {
      if ((0, _object.hasOwnProperty)(hooks, hookName)) {
        instance.removeHook(hookName, hooks[hookName]);
      }
    }
  }
}

var htPersistentState = new HandsontablePersistentState();

_pluginHooks2.default.getSingleton().add('beforeInit', htPersistentState.init);
_pluginHooks2.default.getSingleton().add('afterUpdateSettings', htPersistentState.init);

exports.default = HandsontablePersistentState;

/***/ }),
/* 448 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _element = __webpack_require__(0);

var _renderers = __webpack_require__(9);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @private
 * @plugin Search
 */
function Search(instance) {
  this.query = function (queryStr, callback, queryMethod) {
    var rowCount = instance.countRows();
    var colCount = instance.countCols();
    var queryResult = [];

    if (!callback) {
      callback = Search.global.getDefaultCallback();
    }

    if (!queryMethod) {
      queryMethod = Search.global.getDefaultQueryMethod();
    }

    for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
      for (var colIndex = 0; colIndex < colCount; colIndex++) {
        var cellData = instance.getDataAtCell(rowIndex, colIndex);
        var cellProperties = instance.getCellMeta(rowIndex, colIndex);
        var cellCallback = cellProperties.search.callback || callback;
        var cellQueryMethod = cellProperties.search.queryMethod || queryMethod;
        var testResult = cellQueryMethod(queryStr, cellData);

        if (testResult) {
          var singleResult = {
            row: rowIndex,
            col: colIndex,
            data: cellData
          };

          queryResult.push(singleResult);
        }

        if (cellCallback) {
          cellCallback(instance, rowIndex, colIndex, cellData, testResult);
        }
      }
    }

    return queryResult;
  };
};

Search.DEFAULT_CALLBACK = function (instance, row, col, data, testResult) {
  instance.getCellMeta(row, col).isSearchResult = testResult;
};

Search.DEFAULT_QUERY_METHOD = function (query, value) {
  if (typeof query == 'undefined' || query == null || !query.toLowerCase || query.length === 0) {
    return false;
  }
  if (typeof value == 'undefined' || value == null) {
    return false;
  }

  return value.toString().toLowerCase().indexOf(query.toLowerCase()) != -1;
};

Search.DEFAULT_SEARCH_RESULT_CLASS = 'htSearchResult';

Search.global = function () {

  var defaultCallback = Search.DEFAULT_CALLBACK;
  var defaultQueryMethod = Search.DEFAULT_QUERY_METHOD;
  var defaultSearchResultClass = Search.DEFAULT_SEARCH_RESULT_CLASS;

  return {
    getDefaultCallback: function getDefaultCallback() {
      return defaultCallback;
    },
    setDefaultCallback: function setDefaultCallback(newDefaultCallback) {
      defaultCallback = newDefaultCallback;
    },
    getDefaultQueryMethod: function getDefaultQueryMethod() {
      return defaultQueryMethod;
    },
    setDefaultQueryMethod: function setDefaultQueryMethod(newDefaultQueryMethod) {
      defaultQueryMethod = newDefaultQueryMethod;
    },
    getDefaultSearchResultClass: function getDefaultSearchResultClass() {
      return defaultSearchResultClass;
    },
    setDefaultSearchResultClass: function setDefaultSearchResultClass(newSearchResultClass) {
      defaultSearchResultClass = newSearchResultClass;
    }
  };
}();

function SearchCellDecorator(instance, TD, row, col, prop, value, cellProperties) {
  var searchResultClass = cellProperties.search !== null && _typeof(cellProperties.search) == 'object' && cellProperties.search.searchResultClass || Search.global.getDefaultSearchResultClass();

  if (cellProperties.isSearchResult) {
    (0, _element.addClass)(TD, searchResultClass);
  } else {
    (0, _element.removeClass)(TD, searchResultClass);
  }
};

var originalBaseRenderer = (0, _renderers.getRenderer)('base');

(0, _renderers.registerRenderer)('base', function (instance, TD, row, col, prop, value, cellProperties) {
  originalBaseRenderer.apply(this, arguments);
  SearchCellDecorator.apply(this, arguments);
});

function init() {
  var instance = this;

  var pluginEnabled = !!instance.getSettings().search;

  if (pluginEnabled) {
    instance.search = new Search(instance);
  } else {
    delete instance.search;
  }
}

_pluginHooks2.default.getSingleton().add('afterInit', init);
_pluginHooks2.default.getSingleton().add('afterUpdateSettings', init);

exports.default = Search;

/***/ }),
/* 449 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _element = __webpack_require__(0);

var _array = __webpack_require__(2);

var _base = __webpack_require__(14);

var _base2 = _interopRequireDefault(_base);

var _plugins = __webpack_require__(7);

var _feature = __webpack_require__(39);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * @private
 * @plugin TouchScroll
 * @class TouchScroll
 */
var TouchScroll = function (_BasePlugin) {
  _inherits(TouchScroll, _BasePlugin);

  function TouchScroll(hotInstance) {
    _classCallCheck(this, TouchScroll);

    /**
     * Collection of scrollbars to update.
     *
     * @type {Array}
     */
    var _this = _possibleConstructorReturn(this, (TouchScroll.__proto__ || Object.getPrototypeOf(TouchScroll)).call(this, hotInstance));

    _this.scrollbars = [];
    /**
     * Collection of overlays to update.
     *
     * @type {Array}
     */
    _this.clones = [];
    /**
     * Flag which determines if collection of overlays should be refilled on every table render.
     *
     * @type {Boolean}
     * @default false
     */
    _this.lockedCollection = false;
    /**
     * Flag which determines if walkontable should freeze overlays while scrolling.
     *
     * @type {Boolean}
     * @default false
     */
    _this.freezeOverlays = false;
    return _this;
  }

  /**
   * Check if plugin is enabled.
   *
   * @returns {Boolean}
   */


  _createClass(TouchScroll, [{
    key: 'isEnabled',
    value: function isEnabled() {
      return (0, _feature.isTouchSupported)();
    }

    /**
     * Enable the plugin.
     */

  }, {
    key: 'enablePlugin',
    value: function enablePlugin() {
      var _this2 = this;

      if (this.enabled) {
        return;
      }

      this.addHook('afterRender', function () {
        return _this2.onAfterRender();
      });
      this.registerEvents();

      _get(TouchScroll.prototype.__proto__ || Object.getPrototypeOf(TouchScroll.prototype), 'enablePlugin', this).call(this);
    }

    /**
     * Updates the plugin to use the latest options you have specified.
     */

  }, {
    key: 'updatePlugin',
    value: function updatePlugin() {
      this.lockedCollection = false;

      _get(TouchScroll.prototype.__proto__ || Object.getPrototypeOf(TouchScroll.prototype), 'updatePlugin', this).call(this);
    }

    /**
     * Disable plugin for this Handsontable instance.
     */

  }, {
    key: 'disablePlugin',
    value: function disablePlugin() {
      _get(TouchScroll.prototype.__proto__ || Object.getPrototypeOf(TouchScroll.prototype), 'disablePlugin', this).call(this);
    }

    /**
     * Register all necessary events.
     *
     * @private
     */

  }, {
    key: 'registerEvents',
    value: function registerEvents() {
      var _this3 = this;

      this.addHook('beforeTouchScroll', function () {
        return _this3.onBeforeTouchScroll();
      });
      this.addHook('afterMomentumScroll', function () {
        return _this3.onAfterMomentumScroll();
      });
    }

    /**
     * After render listener.
     *
     * @private
     */

  }, {
    key: 'onAfterRender',
    value: function onAfterRender() {
      if (this.lockedCollection) {
        return;
      }

      var _hot$view$wt$wtOverla = this.hot.view.wt.wtOverlays,
          topOverlay = _hot$view$wt$wtOverla.topOverlay,
          bottomOverlay = _hot$view$wt$wtOverla.bottomOverlay,
          leftOverlay = _hot$view$wt$wtOverla.leftOverlay,
          topLeftCornerOverlay = _hot$view$wt$wtOverla.topLeftCornerOverlay,
          bottomLeftCornerOverlay = _hot$view$wt$wtOverla.bottomLeftCornerOverlay;


      this.lockedCollection = true;
      this.scrollbars.length = 0;
      this.scrollbars.push(topOverlay);

      if (bottomOverlay.clone) {
        this.scrollbars.push(bottomOverlay);
      }
      this.scrollbars.push(leftOverlay);

      if (topLeftCornerOverlay) {
        this.scrollbars.push(topLeftCornerOverlay);
      }
      if (bottomLeftCornerOverlay && bottomLeftCornerOverlay.clone) {
        this.scrollbars.push(bottomLeftCornerOverlay);
      }

      this.clones.length = 0;

      if (topOverlay.needFullRender) {
        this.clones.push(topOverlay.clone.wtTable.holder.parentNode);
      }
      if (bottomOverlay.needFullRender) {
        this.clones.push(bottomOverlay.clone.wtTable.holder.parentNode);
      }
      if (leftOverlay.needFullRender) {
        this.clones.push(leftOverlay.clone.wtTable.holder.parentNode);
      }
      if (topLeftCornerOverlay) {
        this.clones.push(topLeftCornerOverlay.clone.wtTable.holder.parentNode);
      }
      if (bottomLeftCornerOverlay && bottomLeftCornerOverlay.clone) {
        this.clones.push(bottomLeftCornerOverlay.clone.wtTable.holder.parentNode);
      }
    }

    /**
     * Touch scroll listener.
     *
     * @private
     */

  }, {
    key: 'onBeforeTouchScroll',
    value: function onBeforeTouchScroll() {
      this.freezeOverlays = true;

      (0, _array.arrayEach)(this.clones, function (clone) {
        (0, _element.addClass)(clone, 'hide-tween');
      });
    }

    /**
     * After momentum scroll listener.
     *
     * @private
     */

  }, {
    key: 'onAfterMomentumScroll',
    value: function onAfterMomentumScroll() {
      var _this4 = this;

      this.freezeOverlays = false;

      (0, _array.arrayEach)(this.clones, function (clone) {
        (0, _element.removeClass)(clone, 'hide-tween');
        (0, _element.addClass)(clone, 'show-tween');
      });

      setTimeout(function () {
        (0, _array.arrayEach)(_this4.clones, function (clone) {
          (0, _element.removeClass)(clone, 'show-tween');
        });
      }, 400);

      (0, _array.arrayEach)(this.scrollbars, function (scrollbar) {
        scrollbar.refresh();
        scrollbar.resetFixedPosition();
      });

      this.hot.view.wt.wtOverlays.syncScrollWithMaster();
    }
  }]);

  return TouchScroll;
}(_base2.default);

(0, _plugins.registerPlugin)('touchScroll', TouchScroll);

exports.default = TouchScroll;

/***/ }),
/* 450 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _pluginHooks = __webpack_require__(11);

var _pluginHooks2 = _interopRequireDefault(_pluginHooks);

var _array = __webpack_require__(2);

var _number = __webpack_require__(6);

var _object = __webpack_require__(1);

var _event = __webpack_require__(12);

var _src = __webpack_require__(15);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @description
 * Handsontable UndoRedo plugin. It allows to undo and redo certain actions done in the table.
 * Please note, that not all actions are currently undo-able.
 *
 * @example
 * ```js
 * ...
 * undo: true
 * ...
 * ```
 * @class UndoRedo
 * @plugin UndoRedo
 */
/**
 * Handsontable UndoRedo class
 */
function UndoRedo(instance) {
  var plugin = this;
  this.instance = instance;
  this.doneActions = [];
  this.undoneActions = [];
  this.ignoreNewActions = false;

  instance.addHook('afterChange', function (changes, source) {
    if (changes && source !== 'UndoRedo.undo' && source !== 'UndoRedo.redo') {
      plugin.done(new UndoRedo.ChangeAction(changes));
    }
  });

  instance.addHook('afterCreateRow', function (index, amount, source) {
    if (source === 'UndoRedo.undo' || source === 'UndoRedo.undo' || source === 'auto') {
      return;
    }

    var action = new UndoRedo.CreateRowAction(index, amount);
    plugin.done(action);
  });

  instance.addHook('beforeRemoveRow', function (index, amount, logicRows, source) {
    if (source === 'UndoRedo.undo' || source === 'UndoRedo.redo' || source === 'auto') {
      return;
    }

    var originalData = plugin.instance.getSourceDataArray();

    index = (originalData.length + index) % originalData.length;

    var removedData = (0, _object.deepClone)(originalData.slice(index, index + amount));

    plugin.done(new UndoRedo.RemoveRowAction(index, removedData));
  });

  instance.addHook('afterCreateCol', function (index, amount, source) {
    if (source === 'UndoRedo.undo' || source === 'UndoRedo.redo' || source === 'auto') {
      return;
    }

    plugin.done(new UndoRedo.CreateColumnAction(index, amount));
  });

  instance.addHook('beforeRemoveCol', function (index, amount, logicColumns, source) {
    if (source === 'UndoRedo.undo' || source === 'UndoRedo.redo' || source === 'auto') {
      return;
    }

    var originalData = plugin.instance.getSourceDataArray();

    index = (plugin.instance.countCols() + index) % plugin.instance.countCols();

    var removedData = [];
    var headers = [];
    var indexes = [];

    (0, _number.rangeEach)(originalData.length - 1, function (i) {
      var column = [];
      var origRow = originalData[i];

      (0, _number.rangeEach)(index, index + (amount - 1), function (j) {
        column.push(origRow[instance.runHooks('modifyCol', j)]);
      });
      removedData.push(column);
    });

    (0, _number.rangeEach)(amount - 1, function (i) {
      indexes.push(instance.runHooks('modifyCol', index + i));
    });

    if (Array.isArray(instance.getSettings().colHeaders)) {
      (0, _number.rangeEach)(amount - 1, function (i) {
        headers.push(instance.getSettings().colHeaders[instance.runHooks('modifyCol', index + i)] || null);
      });
    }

    var manualColumnMovePlugin = plugin.instance.getPlugin('manualColumnMove');

    var columnsMap = manualColumnMovePlugin.isEnabled() ? manualColumnMovePlugin.columnsMapper.__arrayMap : [];
    var action = new UndoRedo.RemoveColumnAction(index, indexes, removedData, headers, columnsMap);

    plugin.done(action);
  });

  instance.addHook('beforeCellAlignment', function (stateBefore, range, type, alignment) {
    var action = new UndoRedo.CellAlignmentAction(stateBefore, range, type, alignment);
    plugin.done(action);
  });

  instance.addHook('beforeFilter', function (conditionsStack) {
    plugin.done(new UndoRedo.FiltersAction(conditionsStack));
  });

  instance.addHook('beforeRowMove', function (movedRows, target) {
    if (movedRows === false) {
      return;
    }

    plugin.done(new UndoRedo.RowMoveAction(movedRows, target));
  });
};

UndoRedo.prototype.done = function (action) {
  if (!this.ignoreNewActions) {
    this.doneActions.push(action);
    this.undoneActions.length = 0;
  }
};

/**
 * Undo last edit.
 *
 * @function undo
 * @memberof UndoRedo#
 */
UndoRedo.prototype.undo = function () {
  if (this.isUndoAvailable()) {
    var action = this.doneActions.pop();
    var actionClone = (0, _object.deepClone)(action);
    var instance = this.instance;

    var continueAction = instance.runHooks('beforeUndo', actionClone);

    if (continueAction === false) {
      return;
    }

    this.ignoreNewActions = true;
    var that = this;
    action.undo(this.instance, function () {
      that.ignoreNewActions = false;
      that.undoneActions.push(action);
    });

    instance.runHooks('afterUndo', actionClone);
  }
};

/**
 * Redo edit (used to reverse an undo).
 *
 * @function redo
 * @memberof UndoRedo#
 */
UndoRedo.prototype.redo = function () {
  if (this.isRedoAvailable()) {
    var action = this.undoneActions.pop();
    var actionClone = (0, _object.deepClone)(action);
    var instance = this.instance;

    var continueAction = instance.runHooks('beforeRedo', actionClone);

    if (continueAction === false) {
      return;
    }

    this.ignoreNewActions = true;
    var that = this;
    action.redo(this.instance, function () {
      that.ignoreNewActions = false;
      that.doneActions.push(action);
    });

    instance.runHooks('afterRedo', actionClone);
  }
};

/**
 * Check if undo action is available.
 *
 * @function isUndoAvailable
 * @memberof UndoRedo#
 * @return {Boolean} Return `true` if undo can be performed, `false` otherwise
 */
UndoRedo.prototype.isUndoAvailable = function () {
  return this.doneActions.length > 0;
};

/**
 * Check if redo action is available.
 *
 * @function isRedoAvailable
 * @memberof UndoRedo#
 * @return {Boolean} Return `true` if redo can be performed, `false` otherwise.
 */
UndoRedo.prototype.isRedoAvailable = function () {
  return this.undoneActions.length > 0;
};

/**
 * Clears undo history.
 *
 * @function clear
 * @memberof UndoRedo#
 */
UndoRedo.prototype.clear = function () {
  this.doneActions.length = 0;
  this.undoneActions.length = 0;
};

UndoRedo.Action = function () {};
UndoRedo.Action.prototype.undo = function () {};
UndoRedo.Action.prototype.redo = function () {};

/**
 * Change action.
 */
UndoRedo.ChangeAction = function (changes) {
  this.changes = changes;
  this.actionType = 'change';
};
(0, _object.inherit)(UndoRedo.ChangeAction, UndoRedo.Action);

UndoRedo.ChangeAction.prototype.undo = function (instance, undoneCallback) {
  var data = (0, _object.deepClone)(this.changes),
      emptyRowsAtTheEnd = instance.countEmptyRows(true),
      emptyColsAtTheEnd = instance.countEmptyCols(true);

  for (var i = 0, len = data.length; i < len; i++) {
    data[i].splice(3, 1);
  }

  instance.addHookOnce('afterChange', undoneCallback);

  instance.setDataAtRowProp(data, null, null, 'UndoRedo.undo');

  for (var _i = 0, _len = data.length; _i < _len; _i++) {
    if (instance.getSettings().minSpareRows && data[_i][0] + 1 + instance.getSettings().minSpareRows === instance.countRows() && emptyRowsAtTheEnd == instance.getSettings().minSpareRows) {

      instance.alter('remove_row', parseInt(data[_i][0] + 1, 10), instance.getSettings().minSpareRows);
      instance.undoRedo.doneActions.pop();
    }

    if (instance.getSettings().minSpareCols && data[_i][1] + 1 + instance.getSettings().minSpareCols === instance.countCols() && emptyColsAtTheEnd == instance.getSettings().minSpareCols) {

      instance.alter('remove_col', parseInt(data[_i][1] + 1, 10), instance.getSettings().minSpareCols);
      instance.undoRedo.doneActions.pop();
    }
  }
};
UndoRedo.ChangeAction.prototype.redo = function (instance, onFinishCallback) {
  var data = (0, _object.deepClone)(this.changes);

  for (var i = 0, len = data.length; i < len; i++) {
    data[i].splice(2, 1);
  }

  instance.addHookOnce('afterChange', onFinishCallback);
  instance.setDataAtRowProp(data, null, null, 'UndoRedo.redo');
};

/**
 * Create row action.
 */
UndoRedo.CreateRowAction = function (index, amount) {
  this.index = index;
  this.amount = amount;
  this.actionType = 'insert_row';
};
(0, _object.inherit)(UndoRedo.CreateRowAction, UndoRedo.Action);

UndoRedo.CreateRowAction.prototype.undo = function (instance, undoneCallback) {
  var rowCount = instance.countRows(),
      minSpareRows = instance.getSettings().minSpareRows;

  if (this.index >= rowCount && this.index - minSpareRows < rowCount) {
    this.index -= minSpareRows; // work around the situation where the needed row was removed due to an 'undo' of a made change
  }

  instance.addHookOnce('afterRemoveRow', undoneCallback);
  instance.alter('remove_row', this.index, this.amount, 'UndoRedo.undo');
};
UndoRedo.CreateRowAction.prototype.redo = function (instance, redoneCallback) {
  instance.addHookOnce('afterCreateRow', redoneCallback);
  instance.alter('insert_row', this.index, this.amount, 'UndoRedo.redo');
};

/**
 * Remove row action.
 */
UndoRedo.RemoveRowAction = function (index, data) {
  this.index = index;
  this.data = data;
  this.actionType = 'remove_row';
};
(0, _object.inherit)(UndoRedo.RemoveRowAction, UndoRedo.Action);

UndoRedo.RemoveRowAction.prototype.undo = function (instance, undoneCallback) {
  instance.alter('insert_row', this.index, this.data.length, 'UndoRedo.undo');
  instance.addHookOnce('afterRender', undoneCallback);
  instance.populateFromArray(this.index, 0, this.data, void 0, void 0, 'UndoRedo.undo');
};
UndoRedo.RemoveRowAction.prototype.redo = function (instance, redoneCallback) {
  instance.addHookOnce('afterRemoveRow', redoneCallback);
  instance.alter('remove_row', this.index, this.data.length, 'UndoRedo.redo');
};

/**
 * Create column action.
 */
UndoRedo.CreateColumnAction = function (index, amount) {
  this.index = index;
  this.amount = amount;
  this.actionType = 'insert_col';
};
(0, _object.inherit)(UndoRedo.CreateColumnAction, UndoRedo.Action);

UndoRedo.CreateColumnAction.prototype.undo = function (instance, undoneCallback) {
  instance.addHookOnce('afterRemoveCol', undoneCallback);
  instance.alter('remove_col', this.index, this.amount, 'UndoRedo.undo');
};
UndoRedo.CreateColumnAction.prototype.redo = function (instance, redoneCallback) {
  instance.addHookOnce('afterCreateCol', redoneCallback);
  instance.alter('insert_col', this.index, this.amount, 'UndoRedo.redo');
};

/**
 * Remove column action.
 */
UndoRedo.RemoveColumnAction = function (index, indexes, data, headers, columnPositions) {
  this.index = index;
  this.indexes = indexes;
  this.data = data;
  this.amount = this.data[0].length;
  this.headers = headers;
  this.columnPositions = columnPositions.slice(0);
  this.actionType = 'remove_col';
};
(0, _object.inherit)(UndoRedo.RemoveColumnAction, UndoRedo.Action);

UndoRedo.RemoveColumnAction.prototype.undo = function (instance, undoneCallback) {
  var _this = this;

  var row = void 0;
  var ascendingIndexes = this.indexes.slice(0).sort();
  var sortByIndexes = function sortByIndexes(elem, j, arr) {
    return arr[_this.indexes.indexOf(ascendingIndexes[j])];
  };

  var sortedData = [];
  (0, _number.rangeEach)(this.data.length - 1, function (i) {
    sortedData[i] = (0, _array.arrayMap)(_this.data[i], sortByIndexes);
  });

  var sortedHeaders = [];
  sortedHeaders = (0, _array.arrayMap)(this.headers, sortByIndexes);

  var changes = [];

  // TODO: Temporary hook for undo/redo mess
  instance.runHooks('beforeCreateCol', this.indexes[0], this.indexes[this.indexes.length - 1], 'UndoRedo.undo');

  (0, _number.rangeEach)(this.data.length - 1, function (i) {
    row = instance.getSourceDataAtRow(i);

    (0, _number.rangeEach)(ascendingIndexes.length - 1, function (j) {
      row.splice(ascendingIndexes[j], 0, sortedData[i][j]);
      changes.push([i, ascendingIndexes[j], null, sortedData[i][j]]);
    });
  });

  // TODO: Temporary hook for undo/redo mess
  if (instance.getPlugin('formulas')) {
    instance.getPlugin('formulas').onAfterSetDataAtCell(changes);
  }

  if (typeof this.headers !== 'undefined') {
    (0, _number.rangeEach)(sortedHeaders.length - 1, function (j) {
      instance.getSettings().colHeaders.splice(ascendingIndexes[j], 0, sortedHeaders[j]);
    });
  }

  if (instance.getPlugin('manualColumnMove')) {
    instance.getPlugin('manualColumnMove').columnsMapper.__arrayMap = this.columnPositions;
  }

  instance.addHookOnce('afterRender', undoneCallback);

  // TODO: Temporary hook for undo/redo mess
  instance.runHooks('afterCreateCol', this.indexes[0], this.indexes[this.indexes.length - 1], 'UndoRedo.undo');

  if (instance.getPlugin('formulas')) {
    instance.getPlugin('formulas').recalculateFull();
  }

  instance.render();
};

UndoRedo.RemoveColumnAction.prototype.redo = function (instance, redoneCallback) {
  instance.addHookOnce('afterRemoveCol', redoneCallback);
  instance.alter('remove_col', this.index, this.amount, 'UndoRedo.redo');
};

/**
 * Cell alignment action.
 */
UndoRedo.CellAlignmentAction = function (stateBefore, range, type, alignment) {
  this.stateBefore = stateBefore;
  this.range = range;
  this.type = type;
  this.alignment = alignment;
};
UndoRedo.CellAlignmentAction.prototype.undo = function (instance, undoneCallback) {
  if (!instance.getPlugin('contextMenu').isEnabled()) {
    return;
  }
  for (var row = this.range.from.row; row <= this.range.to.row; row++) {
    for (var col = this.range.from.col; col <= this.range.to.col; col++) {
      instance.setCellMeta(row, col, 'className', this.stateBefore[row][col] || ' htLeft');
    }
  }

  instance.addHookOnce('afterRender', undoneCallback);
  instance.render();
};
UndoRedo.CellAlignmentAction.prototype.redo = function (instance, undoneCallback) {
  if (!instance.getPlugin('contextMenu').isEnabled()) {
    return;
  }
  instance.selectCell(this.range.from.row, this.range.from.col, this.range.to.row, this.range.to.col);
  instance.getPlugin('contextMenu').executeCommand('alignment:' + this.alignment.replace('ht', '').toLowerCase());

  instance.addHookOnce('afterRender', undoneCallback);
  instance.render();
};

/**
 * Filters action.
 */
UndoRedo.FiltersAction = function (conditionsStack) {
  this.conditionsStack = conditionsStack;
  this.actionType = 'filter';
};
(0, _object.inherit)(UndoRedo.FiltersAction, UndoRedo.Action);

UndoRedo.FiltersAction.prototype.undo = function (instance, undoneCallback) {
  var filters = instance.getPlugin('filters');

  instance.addHookOnce('afterRender', undoneCallback);

  filters.conditionCollection.importAllConditions(this.conditionsStack.slice(0, this.conditionsStack.length - 1));
  filters.filter();
};
UndoRedo.FiltersAction.prototype.redo = function (instance, redoneCallback) {
  var filters = instance.getPlugin('filters');

  instance.addHookOnce('afterRender', redoneCallback);

  filters.conditionCollection.importAllConditions(this.conditionsStack);
  filters.filter();
};

/**
 * ManualRowMove action.
 * @TODO: removeRow undo should works on logical index
 */
UndoRedo.RowMoveAction = function (movedRows, target) {
  this.rows = movedRows.slice();
  this.target = target;
};
(0, _object.inherit)(UndoRedo.RowMoveAction, UndoRedo.Action);

UndoRedo.RowMoveAction.prototype.undo = function (instance, undoneCallback) {
  var manualRowMove = instance.getPlugin('manualRowMove');

  instance.addHookOnce('afterRender', undoneCallback);
  var mod = this.rows[0] < this.target ? -1 * this.rows.length : 0;
  var newTarget = this.rows[0] > this.target ? this.rows[0] + this.rows.length : this.rows[0];
  var newRows = [];
  var rowsLen = this.rows.length + mod;

  for (var i = mod; i < rowsLen; i++) {
    newRows.push(this.target + i);
  }
  manualRowMove.moveRows(newRows.slice(), newTarget);
  instance.render();

  instance.selection.setRangeStartOnly(new _src.CellCoords(this.rows[0], 0));
  instance.selection.setRangeEnd(new _src.CellCoords(this.rows[this.rows.length - 1], instance.countCols() - 1));
};
UndoRedo.RowMoveAction.prototype.redo = function (instance, redoneCallback) {
  var manualRowMove = instance.getPlugin('manualRowMove');

  instance.addHookOnce('afterRender', redoneCallback);
  manualRowMove.moveRows(this.rows.slice(), this.target);
  instance.render();
  var startSelection = this.rows[0] < this.target ? this.target - this.rows.length : this.target;
  instance.selection.setRangeStartOnly(new _src.CellCoords(startSelection, 0));
  instance.selection.setRangeEnd(new _src.CellCoords(startSelection + this.rows.length - 1, instance.countCols() - 1));
};

function init() {
  var instance = this;
  var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo;

  if (pluginEnabled) {
    if (!instance.undoRedo) {
      /**
       * Instance of Handsontable.UndoRedo Plugin {@link Handsontable.UndoRedo}
       *
       * @alias undoRedo
       * @memberof! Handsontable.Core#
       * @type {UndoRedo}
       */
      instance.undoRedo = new UndoRedo(instance);

      exposeUndoRedoMethods(instance);

      instance.addHook('beforeKeyDown', onBeforeKeyDown);
      instance.addHook('afterChange', onAfterChange);
    }
  } else if (instance.undoRedo) {
    delete instance.undoRedo;

    removeExposedUndoRedoMethods(instance);

    instance.removeHook('beforeKeyDown', onBeforeKeyDown);
    instance.removeHook('afterChange', onAfterChange);
  }
}

function onBeforeKeyDown(event) {
  var instance = this;

  var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;

  if (ctrlDown) {
    if (event.keyCode === 89 || event.shiftKey && event.keyCode === 90) {
      // CTRL + Y or CTRL + SHIFT + Z
      instance.undoRedo.redo();
      (0, _event.stopImmediatePropagation)(event);
    } else if (event.keyCode === 90) {
      // CTRL + Z
      instance.undoRedo.undo();
      (0, _event.stopImmediatePropagation)(event);
    }
  }
}

function onAfterChange(changes, source) {
  var instance = this;
  if (source === 'loadData') {
    return instance.undoRedo.clear();
  }
}

function exposeUndoRedoMethods(instance) {
  /**
   * {@link UndoRedo#undo}
   * @alias undo
   * @memberof! Handsontable.Core#
   */
  instance.undo = function () {
    return instance.undoRedo.undo();
  };

  /**
   * {@link UndoRedo#redo}
   * @alias redo
   * @memberof! Handsontable.Core#
   */
  instance.redo = function () {
    return instance.undoRedo.redo();
  };

  /**
   * {@link UndoRedo#isUndoAvailable}
   * @alias isUndoAvailable
   * @memberof! Handsontable.Core#
   */
  instance.isUndoAvailable = function () {
    return instance.undoRedo.isUndoAvailable();
  };

  /**
   * {@link UndoRedo#isRedoAvailable}
   * @alias isRedoAvailable
   * @memberof! Handsontable.Core#
   */
  instance.isRedoAvailable = function () {
    return instance.undoRedo.isRedoAvailable();
  };

  /**
   * {@link UndoRedo#clear}
   * @alias clearUndo
   * @memberof! Handsontable.Core#
   */
  instance.clearUndo = function () {
    return instance.undoRedo.clear();
  };
}

function removeExposedUndoRedoMethods(instance) {
  delete instance.undo;
  delete instance.redo;
  delete instance.isUndoAvailable;
  delete instance.isRedoAvailable;
  delete instance.clearUndo;
}

var hook = _pluginHooks2.default.getSingleton();

hook.add('afterInit', init);
hook.add('afterUpdateSettings', init);

hook.register('beforeUndo');
hook.register('afterUndo');
hook.register('beforeRedo');
hook.register('afterRedo');

exports.default = UndoRedo;

/***/ })
/******/ ])["default"];
});
/*globals jQuery, define, exports, require, window, document, postMessage */

(function (factory) {
	"use strict";
	if (typeof define === 'function' && define.amd) {
		define(['jquery'], factory);
	}
	else if(typeof exports === 'object') {
		factory(require('jquery'));
	}
	else {
		factory(jQuery);
	}
}(function ($, undefined) {
	"use strict";
/*!
 * jsTree 3.0.9
 * http://jstree.com/
 *
 * Copyright (c) 2014 Ivan Bozhanov (http://vakata.com)
 *
 * Licensed same as jquery - under the terms of the MIT License
 *   http://www.opensource.org/licenses/mit-license.php
 */
/*!
 * if using jslint please allow for the jQuery global and use following options: 
 * jslint: browser: true, ass: true, bitwise: true, continue: true, nomen: true, plusplus: true, regexp: true, unparam: true, todo: true, white: true
 */

	// prevent another load? maybe there is a better way?
	if($.jstree) {
		return;
	}

	/**
	 * ### jsTree core functionality
	 */

	// internal variables
	var instance_counter = 0,
		ccp_node = false,
		ccp_mode = false,
		ccp_inst = false,
		themes_loaded = [],
		src = $('script:last').attr('src'),
		_d = document, _node = _d.createElement('LI'), _temp1, _temp2;

	_node.setAttribute('role', 'treeitem');
	_temp1 = _d.createElement('I');
	_temp1.className = 'jstree-icon jstree-ocl';
	_temp1.setAttribute('role', 'presentation');
	_node.appendChild(_temp1);
	_temp1 = _d.createElement('A');
	_temp1.className = 'jstree-anchor';
	_temp1.setAttribute('href','#');
	_temp1.setAttribute('tabindex','-1');
	_temp2 = _d.createElement('I');
	_temp2.className = 'jstree-icon jstree-themeicon';
	_temp2.setAttribute('role', 'presentation');
	_temp1.appendChild(_temp2);
	_node.appendChild(_temp1);
	_temp1 = _temp2 = null;


	/**
	 * holds all jstree related functions and variables, including the actual class and methods to create, access and manipulate instances.
	 * @name $.jstree
	 */
	$.jstree = {
		/** 
		 * specifies the jstree version in use
		 * @name $.jstree.version
		 */
		version : '3.0.9',
		/**
		 * holds all the default options used when creating new instances
		 * @name $.jstree.defaults
		 */
		defaults : {
			/**
			 * configure which plugins will be active on an instance. Should be an array of strings, where each element is a plugin name. The default is `[]`
			 * @name $.jstree.defaults.plugins
			 */
			plugins : []
		},
		/**
		 * stores all loaded jstree plugins (used internally)
		 * @name $.jstree.plugins
		 */
		plugins : {},
		path : src && src.indexOf('/') !== -1 ? src.replace(/\/[^\/]+$/,'') : '',
		idregex : /[\\:&!^|()\[\]<>@*'+~#";.,=\- \/${}%?`]/g
	};
	/**
	 * creates a jstree instance
	 * @name $.jstree.create(el [, options])
	 * @param {DOMElement|jQuery|String} el the element to create the instance on, can be jQuery extended or a selector
	 * @param {Object} options options for this instance (extends `$.jstree.defaults`)
	 * @return {jsTree} the new instance
	 */
	$.jstree.create = function (el, options) {
		var tmp = new $.jstree.core(++instance_counter),
			opt = options;
		options = $.extend(true, {}, $.jstree.defaults, options);
		if(opt && opt.plugins) {
			options.plugins = opt.plugins;
		}
		$.each(options.plugins, function (i, k) {
			if(i !== 'core') {
				tmp = tmp.plugin(k, options[k]);
			}
		});
		tmp.init(el, options);
		return tmp;
	};
	/**
	 * remove all traces of jstree from the DOM and destroy all instances
	 * @name $.jstree.destroy()
	 */
	$.jstree.destroy = function () {
		$('.jstree:jstree').jstree('destroy');
		$(document).off('.jstree');
	};
	/**
	 * the jstree class constructor, used only internally
	 * @private
	 * @name $.jstree.core(id)
	 * @param {Number} id this instance's index
	 */
	$.jstree.core = function (id) {
		this._id = id;
		this._cnt = 0;
		this._wrk = null;
		this._data = {
			core : {
				themes : {
					name : false,
					dots : false,
					icons : false
				},
				selected : [],
				last_error : {},
				working : false,
				worker_queue : [],
				focused : null
			}
		};
	};
	/**
	 * get a reference to an existing instance
	 *
	 * __Examples__
	 *
	 *	// provided a container with an ID of "tree", and a nested node with an ID of "branch"
	 *	// all of there will return the same instance
	 *	$.jstree.reference('tree');
	 *	$.jstree.reference('#tree');
	 *	$.jstree.reference($('#tree'));
	 *	$.jstree.reference(document.getElementByID('tree'));
	 *	$.jstree.reference('branch');
	 *	$.jstree.reference('#branch');
	 *	$.jstree.reference($('#branch'));
	 *	$.jstree.reference(document.getElementByID('branch'));
	 *
	 * @name $.jstree.reference(needle)
	 * @param {DOMElement|jQuery|String} needle
	 * @return {jsTree|null} the instance or `null` if not found
	 */
	$.jstree.reference = function (needle) {
		var tmp = null,
			obj = null;
		if(needle && needle.id) { needle = needle.id; }

		if(!obj || !obj.length) {
			try { obj = $(needle); } catch (ignore) { }
		}
		if(!obj || !obj.length) {
			try { obj = $('#' + needle.replace($.jstree.idregex,'\\$&')); } catch (ignore) { }
		}
		if(obj && obj.length && (obj = obj.closest('.jstree')).length && (obj = obj.data('jstree'))) {
			tmp = obj;
		}
		else {
			$('.jstree').each(function () {
				var inst = $(this).data('jstree');
				if(inst && inst._model.data[needle]) {
					tmp = inst;
					return false;
				}
			});
		}
		return tmp;
	};
	/**
	 * Create an instance, get an instance or invoke a command on a instance. 
	 * 
	 * If there is no instance associated with the current node a new one is created and `arg` is used to extend `$.jstree.defaults` for this new instance. There would be no return value (chaining is not broken).
	 * 
	 * If there is an existing instance and `arg` is a string the command specified by `arg` is executed on the instance, with any additional arguments passed to the function. If the function returns a value it will be returned (chaining could break depending on function).
	 * 
	 * If there is an existing instance and `arg` is not a string the instance itself is returned (similar to `$.jstree.reference`).
	 * 
	 * In any other case - nothing is returned and chaining is not broken.
	 *
	 * __Examples__
	 *
	 *	$('#tree1').jstree(); // creates an instance
	 *	$('#tree2').jstree({ plugins : [] }); // create an instance with some options
	 *	$('#tree1').jstree('open_node', '#branch_1'); // call a method on an existing instance, passing additional arguments
	 *	$('#tree2').jstree(); // get an existing instance (or create an instance)
	 *	$('#tree2').jstree(true); // get an existing instance (will not create new instance)
	 *	$('#branch_1').jstree().select_node('#branch_1'); // get an instance (using a nested element and call a method)
	 *
	 * @name $().jstree([arg])
	 * @param {String|Object} arg
	 * @return {Mixed}
	 */
	$.fn.jstree = function (arg) {
		// check for string argument
		var is_method	= (typeof arg === 'string'),
			args		= Array.prototype.slice.call(arguments, 1),
			result		= null;
		if(arg === true && !this.length) { return false; }
		this.each(function () {
			// get the instance (if there is one) and method (if it exists)
			var instance = $.jstree.reference(this),
				method = is_method && instance ? instance[arg] : null;
			// if calling a method, and method is available - execute on the instance
			result = is_method && method ?
				method.apply(instance, args) :
				null;
			// if there is no instance and no method is being called - create one
			if(!instance && !is_method && (arg === undefined || $.isPlainObject(arg))) {
				$(this).data('jstree', new $.jstree.create(this, arg));
			}
			// if there is an instance and no method is called - return the instance
			if( (instance && !is_method) || arg === true ) {
				result = instance || false;
			}
			// if there was a method call which returned a result - break and return the value
			if(result !== null && result !== undefined) {
				return false;
			}
		});
		// if there was a method call with a valid return value - return that, otherwise continue the chain
		return result !== null && result !== undefined ?
			result : this;
	};
	/**
	 * used to find elements containing an instance
	 *
	 * __Examples__
	 *
	 *	$('div:jstree').each(function () {
	 *		$(this).jstree('destroy');
	 *	});
	 *
	 * @name $(':jstree')
	 * @return {jQuery}
	 */
	$.expr[':'].jstree = $.expr.createPseudo(function(search) {
		return function(a) {
			return $(a).hasClass('jstree') &&
				$(a).data('jstree') !== undefined;
		};
	});

	/**
	 * stores all defaults for the core
	 * @name $.jstree.defaults.core
	 */
	$.jstree.defaults.core = {
		/**
		 * data configuration
		 * 
		 * If left as `false` the HTML inside the jstree container element is used to populate the tree (that should be an unordered list with list items).
		 *
		 * You can also pass in a HTML string or a JSON array here.
		 * 
		 * It is possible to pass in a standard jQuery-like AJAX config and jstree will automatically determine if the response is JSON or HTML and use that to populate the tree. 
		 * In addition to the standard jQuery ajax options here you can suppy functions for `data` and `url`, the functions will be run in the current instance's scope and a param will be passed indicating which node is being loaded, the return value of those functions will be used.
		 * 
		 * The last option is to specify a function, that function will receive the node being loaded as argument and a second param which is a function which should be called with the result.
		 *
		 * __Examples__
		 *
		 *	// AJAX
		 *	$('#tree').jstree({
		 *		'core' : {
		 *			'data' : {
		 *				'url' : '/get/children/',
		 *				'data' : function (node) {
		 *					return { 'id' : node.id };
		 *				}
		 *			}
		 *		});
		 *
		 *	// direct data
		 *	$('#tree').jstree({
		 *		'core' : {
		 *			'data' : [
		 *				'Simple root node',
		 *				{
		 *					'id' : 'node_2',
		 *					'text' : 'Root node with options',
		 *					'state' : { 'opened' : true, 'selected' : true },
		 *					'children' : [ { 'text' : 'Child 1' }, 'Child 2']
		 *				}
		 *			]
		 *		});
		 *	
		 *	// function
		 *	$('#tree').jstree({
		 *		'core' : {
		 *			'data' : function (obj, callback) {
		 *				callback.call(this, ['Root 1', 'Root 2']);
		 *			}
		 *		});
		 * 
		 * @name $.jstree.defaults.core.data
		 */
		data			: false,
		/**
		 * configure the various strings used throughout the tree
		 *
		 * You can use an object where the key is the string you need to replace and the value is your replacement.
		 * Another option is to specify a function which will be called with an argument of the needed string and should return the replacement.
		 * If left as `false` no replacement is made.
		 *
		 * __Examples__
		 *
		 *	$('#tree').jstree({
		 *		'core' : {
		 *			'strings' : {
		 *				'Loading ...' : 'Please wait ...'
		 *			}
		 *		}
		 *	});
		 *
		 * @name $.jstree.defaults.core.strings
		 */
		strings			: false,
		/**
		 * determines what happens when a user tries to modify the structure of the tree
		 * If left as `false` all operations like create, rename, delete, move or copy are prevented.
		 * You can set this to `true` to allow all interactions or use a function to have better control.
		 *
		 * __Examples__
		 *
		 *	$('#tree').jstree({
		 *		'core' : {
		 *			'check_callback' : function (operation, node, node_parent, node_position, more) {
		 *				// operation can be 'create_node', 'rename_node', 'delete_node', 'move_node' or 'copy_node'
		 *				// in case of 'rename_node' node_position is filled with the new node name
		 *				return operation === 'rename_node' ? true : false;
		 *			}
		 *		}
		 *	});
		 * 
		 * @name $.jstree.defaults.core.check_callback
		 */
		check_callback	: false,
		/**
		 * a callback called with a single object parameter in the instance's scope when something goes wrong (operation prevented, ajax failed, etc)
		 * @name $.jstree.defaults.core.error
		 */
		error			: $.noop,
		/**
		 * the open / close animation duration in milliseconds - set this to `false` to disable the animation (default is `200`)
		 * @name $.jstree.defaults.core.animation
		 */
		animation		: 200,
		/**
		 * a boolean indicating if multiple nodes can be selected
		 * @name $.jstree.defaults.core.multiple
		 */
		multiple		: true,
		/**
		 * theme configuration object
		 * @name $.jstree.defaults.core.themes
		 */
		themes			: {
			/**
			 * the name of the theme to use (if left as `false` the default theme is used)
			 * @name $.jstree.defaults.core.themes.name
			 */
			name			: false,
			/**
			 * the URL of the theme's CSS file, leave this as `false` if you have manually included the theme CSS (recommended). You can set this to `true` too which will try to autoload the theme.
			 * @name $.jstree.defaults.core.themes.url
			 */
			url				: false,
			/**
			 * the location of all jstree themes - only used if `url` is set to `true`
			 * @name $.jstree.defaults.core.themes.dir
			 */
			dir				: false,
			/**
			 * a boolean indicating if connecting dots are shown
			 * @name $.jstree.defaults.core.themes.dots
			 */
			dots			: true,
			/**
			 * a boolean indicating if node icons are shown
			 * @name $.jstree.defaults.core.themes.icons
			 */
			icons			: true,
			/**
			 * a boolean indicating if the tree background is striped
			 * @name $.jstree.defaults.core.themes.stripes
			 */
			stripes			: false,
			/**
			 * a string (or boolean `false`) specifying the theme variant to use (if the theme supports variants)
			 * @name $.jstree.defaults.core.themes.variant
			 */
			variant			: false,
			/**
			 * a boolean specifying if a reponsive version of the theme should kick in on smaller screens (if the theme supports it). Defaults to `false`.
			 * @name $.jstree.defaults.core.themes.responsive
			 */
			responsive		: false
		},
		/**
		 * if left as `true` all parents of all selected nodes will be opened once the tree loads (so that all selected nodes are visible to the user)
		 * @name $.jstree.defaults.core.expand_selected_onload
		 */
		expand_selected_onload : true,
		/**
		 * if left as `true` web workers will be used to parse incoming JSON data where possible, so that the UI will not be blocked by large requests. Workers are however about 30% slower. Defaults to `true`
		 * @name $.jstree.defaults.core.worker
		 */
		worker : true,
		/**
		 * Force node text to plain text (and escape HTML). Defaults to `false`
		 * @name $.jstree.defaults.core.force_text
		 */
		force_text : false,
		/**
		 * Should the node should be toggled if the text is double clicked . Defaults to `true`
		 * @name $.jstree.defaults.core.dblclick_toggle
		 */
		dblclick_toggle : true
	};
	$.jstree.core.prototype = {
		/**
		 * used to decorate an instance with a plugin. Used internally.
		 * @private
		 * @name plugin(deco [, opts])
		 * @param  {String} deco the plugin to decorate with
		 * @param  {Object} opts options for the plugin
		 * @return {jsTree}
		 */
		plugin : function (deco, opts) {
			var Child = $.jstree.plugins[deco];
			if(Child) {
				this._data[deco] = {};
				Child.prototype = this;
				return new Child(opts, this);
			}
			return this;
		},
		/**
		 * used to decorate an instance with a plugin. Used internally.
		 * @private
		 * @name init(el, optons)
		 * @param {DOMElement|jQuery|String} el the element we are transforming
		 * @param {Object} options options for this instance
		 * @trigger init.jstree, loading.jstree, loaded.jstree, ready.jstree, changed.jstree
		 */
		init : function (el, options) {
			this._model = {
				data : {
					'#' : {
						id : '#',
						parent : null,
						parents : [],
						children : [],
						children_d : [],
						state : { loaded : false }
					}
				},
				changed : [],
				force_full_redraw : false,
				redraw_timeout : false,
				default_state : {
					loaded : true,
					opened : false,
					selected : false,
					disabled : false
				}
			};

			this.element = $(el).addClass('jstree jstree-' + this._id);
			this.settings = options;

			this._data.core.ready = false;
			this._data.core.loaded = false;
			this._data.core.rtl = (this.element.css("direction") === "rtl");
			this.element[this._data.core.rtl ? 'addClass' : 'removeClass']("jstree-rtl");
			this.element.attr('role','tree');
			if(this.settings.core.multiple) {
				this.element.attr('aria-multiselectable', true);
			}
			if(!this.element.attr('tabindex')) {
				this.element.attr('tabindex','0');
			}

			this.bind();
			/**
			 * triggered after all events are bound
			 * @event
			 * @name init.jstree
			 */
			this.trigger("init");

			this._data.core.original_container_html = this.element.find(" > ul > li").clone(true);
			this._data.core.original_container_html
				.find("li").addBack()
				.contents().filter(function() {
					return this.nodeType === 3 && (!this.nodeValue || /^\s+$/.test(this.nodeValue));
				})
				.remove();
			this.element.html("<"+"ul class='jstree-container-ul jstree-children' role='group'><"+"li id='j"+this._id+"_loading' class='jstree-initial-node jstree-loading jstree-leaf jstree-last' role='tree-item'><i class='jstree-icon jstree-ocl'></i><"+"a class='jstree-anchor' href='#'><i class='jstree-icon jstree-themeicon-hidden'></i>" + this.get_string("Loading ...") + "</a></li></ul>");
			this.element.attr('aria-activedescendant','j' + this._id + '_loading');
			this._data.core.li_height = this.get_container_ul().children("li").first().height() || 24;
			/**
			 * triggered after the loading text is shown and before loading starts
			 * @event
			 * @name loading.jstree
			 */
			this.trigger("loading");
			this.load_node('#');
		},
		/**
		 * destroy an instance
		 * @name destroy()
		 * @param  {Boolean} keep_html if not set to `true` the container will be emptied, otherwise the current DOM elements will be kept intact
		 */
		destroy : function (keep_html) {
			if(this._wrk) {
				try {
					window.URL.revokeObjectURL(this._wrk);
					this._wrk = null;
				}
				catch (ignore) { }
			}
			if(!keep_html) { this.element.empty(); }
			this.teardown();
		},
		/**
		 * part of the destroying of an instance. Used internally.
		 * @private
		 * @name teardown()
		 */
		teardown : function () {
			this.unbind();
			this.element
				.removeClass('jstree')
				.removeData('jstree')
				.find("[class^='jstree']")
					.addBack()
					.attr("class", function () { return this.className.replace(/jstree[^ ]*|$/ig,''); });
			this.element = null;
		},
		/**
		 * bind all events. Used internally.
		 * @private
		 * @name bind()
		 */
		bind : function () {
			var word = '',
				tout = null,
				was_click = 0;
			this.element
				.on("dblclick.jstree", function () {
						if(document.selection && document.selection.empty) {
							document.selection.empty();
						}
						else {
							if(window.getSelection) {
								var sel = window.getSelection();
								try {
									sel.removeAllRanges();
									sel.collapse();
								} catch (ignore) { }
							}
						}
					})
				.on("mousedown.jstree", $.proxy(function (e) {
						if(e.target === this.element[0]) {
							e.preventDefault(); // prevent losing focus when clicking scroll arrows (FF, Chrome)
							was_click = +(new Date()); // ie does not allow to prevent losing focus
						}
					}, this))
				.on("mousedown.jstree", ".jstree-ocl", function (e) {
						e.preventDefault(); // prevent any node inside from losing focus when clicking the open/close icon
					})
				.on("click.jstree", ".jstree-ocl", $.proxy(function (e) {
						this.toggle_node(e.target);
					}, this))
				.on("dblclick.jstree", ".jstree-anchor", $.proxy(function (e) {
						if(this.settings.core.dblclick_toggle) {
							this.toggle_node(e.target);
						}
					}, this))
				.on("click.jstree", ".jstree-anchor", $.proxy(function (e) {
						e.preventDefault();
						if(e.currentTarget !== document.activeElement) { $(e.currentTarget).focus(); }
						this.activate_node(e.currentTarget, e);
					}, this))
				.on('keydown.jstree', '.jstree-anchor', $.proxy(function (e) {
						if(e.target.tagName === "INPUT") { return true; }
						var o = null;
						if(this._data.core.rtl) {
							if(e.which === 37) { e.which = 39; }
							else if(e.which === 39) { e.which = 37; }
						}
						switch(e.which) {
							case 32: // aria defines space only with Ctrl
								if(e.ctrlKey) {
									e.type = "click";
									$(e.currentTarget).trigger(e);
								}
								break;
							case 13: // enter
								e.type = "click";
								$(e.currentTarget).trigger(e);
								break;
							case 37: // right
								e.preventDefault();
								if(this.is_open(e.currentTarget)) {
									this.close_node(e.currentTarget);
								}
								else {
									o = this.get_parent(e.currentTarget);
									if(o && o.id !== '#') { this.get_node(o, true).children('.jstree-anchor').focus(); }
								}
								break;
							case 38: // up
								e.preventDefault();
								o = this.get_prev_dom(e.currentTarget);
								if(o && o.length) { o.children('.jstree-anchor').focus(); }
								break;
							case 39: // left
								e.preventDefault();
								if(this.is_closed(e.currentTarget)) {
									this.open_node(e.currentTarget, function (o) { this.get_node(o, true).children('.jstree-anchor').focus(); });
								}
								else if (this.is_open(e.currentTarget)) {
									o = this.get_node(e.currentTarget, true).children('.jstree-children')[0];
									if(o) { $(this._firstChild(o)).children('.jstree-anchor').focus(); }
								}
								break;
							case 40: // down
								e.preventDefault();
								o = this.get_next_dom(e.currentTarget);
								if(o && o.length) { o.children('.jstree-anchor').focus(); }
								break;
							case 106: // aria defines * on numpad as open_all - not very common
								this.open_all();
								break;
							case 36: // home
								e.preventDefault();
								o = this._firstChild(this.get_container_ul()[0]);
								if(o) { $(o).children('.jstree-anchor').filter(':visible').focus(); }
								break;
							case 35: // end
								e.preventDefault();
								this.element.find('.jstree-anchor').filter(':visible').last().focus();
								break;
							/*
							// delete
							case 46:
								e.preventDefault();
								o = this.get_node(e.currentTarget);
								if(o && o.id && o.id !== '#') {
									o = this.is_selected(o) ? this.get_selected() : o;
									this.delete_node(o);
								}
								break;
							// f2
							case 113:
								e.preventDefault();
								o = this.get_node(e.currentTarget);
								if(o && o.id && o.id !== '#') {
									// this.edit(o);
								}
								break;
							default:
								// console.log(e.which);
								break;
							*/
						}
					}, this))
				.on("load_node.jstree", $.proxy(function (e, data) {
						if(data.status) {
							if(data.node.id === '#' && !this._data.core.loaded) {
								this._data.core.loaded = true;
								if(this._firstChild(this.get_container_ul()[0])) {
									this.element.attr('aria-activedescendant',this._firstChild(this.get_container_ul()[0]).id);
								}
								/**
								 * triggered after the root node is loaded for the first time
								 * @event
								 * @name loaded.jstree
								 */
								this.trigger("loaded");
							}
							if(!this._data.core.ready) {
								setTimeout($.proxy(function() {
									if(!this.get_container_ul().find('.jstree-loading').length) {
										this._data.core.ready = true;
										if(this._data.core.selected.length) {
											if(this.settings.core.expand_selected_onload) {
												var tmp = [], i, j;
												for(i = 0, j = this._data.core.selected.length; i < j; i++) {
													tmp = tmp.concat(this._model.data[this._data.core.selected[i]].parents);
												}
												tmp = $.vakata.array_unique(tmp);
												for(i = 0, j = tmp.length; i < j; i++) {
													this.open_node(tmp[i], false, 0);
												}
											}
											this.trigger('changed', { 'action' : 'ready', 'selected' : this._data.core.selected });
										}
										/**
										 * triggered after all nodes are finished loading
										 * @event
										 * @name ready.jstree
										 */
										this.trigger("ready");
									}
								}, this), 0);
							}
						}
					}, this))
				// quick searching when the tree is focused
				.on('keypress.jstree', $.proxy(function (e) {
						if(e.target.tagName === "INPUT") { return true; }
						if(tout) { clearTimeout(tout); }
						tout = setTimeout(function () {
							word = '';
						}, 500);

						var chr = String.fromCharCode(e.which).toLowerCase(),
							col = this.element.find('.jstree-anchor').filter(':visible'),
							ind = col.index(document.activeElement) || 0,
							end = false;
						word += chr;

						// match for whole word from current node down (including the current node)
						if(word.length > 1) {
							col.slice(ind).each($.proxy(function (i, v) {
								if($(v).text().toLowerCase().indexOf(word) === 0) {
									$(v).focus();
									end = true;
									return false;
								}
							}, this));
							if(end) { return; }

							// match for whole word from the beginning of the tree
							col.slice(0, ind).each($.proxy(function (i, v) {
								if($(v).text().toLowerCase().indexOf(word) === 0) {
									$(v).focus();
									end = true;
									return false;
								}
							}, this));
							if(end) { return; }
						}
						// list nodes that start with that letter (only if word consists of a single char)
						if(new RegExp('^' + chr + '+$').test(word)) {
							// search for the next node starting with that letter
							col.slice(ind + 1).each($.proxy(function (i, v) {
								if($(v).text().toLowerCase().charAt(0) === chr) {
									$(v).focus();
									end = true;
									return false;
								}
							}, this));
							if(end) { return; }

							// search from the beginning
							col.slice(0, ind + 1).each($.proxy(function (i, v) {
								if($(v).text().toLowerCase().charAt(0) === chr) {
									$(v).focus();
									end = true;
									return false;
								}
							}, this));
							if(end) { return; }
						}
					}, this))
				// THEME RELATED
				.on("init.jstree", $.proxy(function () {
						var s = this.settings.core.themes;
						this._data.core.themes.dots			= s.dots;
						this._data.core.themes.stripes		= s.stripes;
						this._data.core.themes.icons		= s.icons;
						this.set_theme(s.name || "default", s.url);
						this.set_theme_variant(s.variant);
					}, this))
				.on("loading.jstree", $.proxy(function () {
						this[ this._data.core.themes.dots ? "show_dots" : "hide_dots" ]();
						this[ this._data.core.themes.icons ? "show_icons" : "hide_icons" ]();
						this[ this._data.core.themes.stripes ? "show_stripes" : "hide_stripes" ]();
					}, this))
				.on('blur.jstree', '.jstree-anchor', $.proxy(function (e) {
						this._data.core.focused = null;
						$(e.currentTarget).filter('.jstree-hovered').mouseleave();
						this.element.attr('tabindex', '0');
					}, this))
				.on('focus.jstree', '.jstree-anchor', $.proxy(function (e) {
						var tmp = this.get_node(e.currentTarget);
						if(tmp && tmp.id) {
							this._data.core.focused = tmp.id;
						}
						this.element.find('.jstree-hovered').not(e.currentTarget).mouseleave();
						$(e.currentTarget).mouseenter();
						this.element.attr('tabindex', '-1');
					}, this))
				.on('focus.jstree', $.proxy(function () {
						if(+(new Date()) - was_click > 500 && !this._data.core.focused) {
							was_click = 0;
							this.get_node(this.element.attr('aria-activedescendant'), true).find('> .jstree-anchor').focus();
						}
					}, this))
				.on('mouseenter.jstree', '.jstree-anchor', $.proxy(function (e) {
						this.hover_node(e.currentTarget);
					}, this))
				.on('mouseleave.jstree', '.jstree-anchor', $.proxy(function (e) {
						this.dehover_node(e.currentTarget);
					}, this));
		},
		/**
		 * part of the destroying of an instance. Used internally.
		 * @private
		 * @name unbind()
		 */
		unbind : function () {
			this.element.off('.jstree');
			$(document).off('.jstree-' + this._id);
		},
		/**
		 * trigger an event. Used internally.
		 * @private
		 * @name trigger(ev [, data])
		 * @param  {String} ev the name of the event to trigger
		 * @param  {Object} data additional data to pass with the event
		 */
		trigger : function (ev, data) {
			if(!data) {
				data = {};
			}
			data.instance = this;
			this.element.triggerHandler(ev.replace('.jstree','') + '.jstree', data);
		},
		/**
		 * returns the jQuery extended instance container
		 * @name get_container()
		 * @return {jQuery}
		 */
		get_container : function () {
			return this.element;
		},
		/**
		 * returns the jQuery extended main UL node inside the instance container. Used internally.
		 * @private
		 * @name get_container_ul()
		 * @return {jQuery}
		 */
		get_container_ul : function () {
			return this.element.children(".jstree-children").first();
		},
		/**
		 * gets string replacements (localization). Used internally.
		 * @private
		 * @name get_string(key)
		 * @param  {String} key
		 * @return {String}
		 */
		get_string : function (key) {
			var a = this.settings.core.strings;
			if($.isFunction(a)) { return a.call(this, key); }
			if(a && a[key]) { return a[key]; }
			return key;
		},
		/**
		 * gets the first child of a DOM node. Used internally.
		 * @private
		 * @name _firstChild(dom)
		 * @param  {DOMElement} dom
		 * @return {DOMElement}
		 */
		_firstChild : function (dom) {
			dom = dom ? dom.firstChild : null;
			while(dom !== null && dom.nodeType !== 1) {
				dom = dom.nextSibling;
			}
			return dom;
		},
		/**
		 * gets the next sibling of a DOM node. Used internally.
		 * @private
		 * @name _nextSibling(dom)
		 * @param  {DOMElement} dom
		 * @return {DOMElement}
		 */
		_nextSibling : function (dom) {
			dom = dom ? dom.nextSibling : null;
			while(dom !== null && dom.nodeType !== 1) {
				dom = dom.nextSibling;
			}
			return dom;
		},
		/**
		 * gets the previous sibling of a DOM node. Used internally.
		 * @private
		 * @name _previousSibling(dom)
		 * @param  {DOMElement} dom
		 * @return {DOMElement}
		 */
		_previousSibling : function (dom) {
			dom = dom ? dom.previousSibling : null;
			while(dom !== null && dom.nodeType !== 1) {
				dom = dom.previousSibling;
			}
			return dom;
		},
		/**
		 * get the JSON representation of a node (or the actual jQuery extended DOM node) by using any input (child DOM element, ID string, selector, etc)
		 * @name get_node(obj [, as_dom])
		 * @param  {mixed} obj
		 * @param  {Boolean} as_dom
		 * @return {Object|jQuery}
		 */
		get_node : function (obj, as_dom) {
			if(obj && obj.id) {
				obj = obj.id;
			}
			var dom;
			try {
				if(this._model.data[obj]) {
					obj = this._model.data[obj];
				}
				else if(typeof obj === "string" && this._model.data[obj.replace(/^#/, '')]) {
					obj = this._model.data[obj.replace(/^#/, '')];
				}
				else if(typeof obj === "string" && (dom = $('#' + obj.replace($.jstree.idregex,'\\$&'), this.element)).length && this._model.data[dom.closest('.jstree-node').attr('id')]) {
					obj = this._model.data[dom.closest('.jstree-node').attr('id')];
				}
				else if((dom = $(obj, this.element)).length && this._model.data[dom.closest('.jstree-node').attr('id')]) {
					obj = this._model.data[dom.closest('.jstree-node').attr('id')];
				}
				else if((dom = $(obj, this.element)).length && dom.hasClass('jstree')) {
					obj = this._model.data['#'];
				}
				else {
					return false;
				}

				if(as_dom) {
					obj = obj.id === '#' ? this.element : $('#' + obj.id.replace($.jstree.idregex,'\\$&'), this.element);
				}
				return obj;
			} catch (ex) { return false; }
		},
		/**
		 * get the path to a node, either consisting of node texts, or of node IDs, optionally glued together (otherwise an array)
		 * @name get_path(obj [, glue, ids])
		 * @param  {mixed} obj the node
		 * @param  {String} glue if you want the path as a string - pass the glue here (for example '/'), if a falsy value is supplied here, an array is returned
		 * @param  {Boolean} ids if set to true build the path using ID, otherwise node text is used
		 * @return {mixed}
		 */
		get_path : function (obj, glue, ids) {
			obj = obj.parents ? obj : this.get_node(obj);
			if(!obj || obj.id === '#' || !obj.parents) {
				return false;
			}
			var i, j, p = [];
			p.push(ids ? obj.id : obj.text);
			for(i = 0, j = obj.parents.length; i < j; i++) {
				p.push(ids ? obj.parents[i] : this.get_text(obj.parents[i]));
			}
			p = p.reverse().slice(1);
			return glue ? p.join(glue) : p;
		},
		/**
		 * get the next visible node that is below the `obj` node. If `strict` is set to `true` only sibling nodes are returned.
		 * @name get_next_dom(obj [, strict])
		 * @param  {mixed} obj
		 * @param  {Boolean} strict
		 * @return {jQuery}
		 */
		get_next_dom : function (obj, strict) {
			var tmp;
			obj = this.get_node(obj, true);
			if(obj[0] === this.element[0]) {
				tmp = this._firstChild(this.get_container_ul()[0]);
				while (tmp && tmp.offsetHeight === 0) {
					tmp = this._nextSibling(tmp);
				}
				return tmp ? $(tmp) : false;
			}
			if(!obj || !obj.length) {
				return false;
			}
			if(strict) {
				tmp = obj[0];
				do {
					tmp = this._nextSibling(tmp);
				} while (tmp && tmp.offsetHeight === 0);
				return tmp ? $(tmp) : false;
			}
			if(obj.hasClass("jstree-open")) {
				tmp = this._firstChild(obj.children('.jstree-children')[0]);
				while (tmp && tmp.offsetHeight === 0) {
					tmp = this._nextSibling(tmp);
				}
				if(tmp !== null) {
					return $(tmp);
				}
			}
			tmp = obj[0];
			do {
				tmp = this._nextSibling(tmp);
			} while (tmp && tmp.offsetHeight === 0);
			if(tmp !== null) {
				return $(tmp);
			}
			return obj.parentsUntil(".jstree",".jstree-node").next(".jstree-node:visible").first();
		},
		/**
		 * get the previous visible node that is above the `obj` node. If `strict` is set to `true` only sibling nodes are returned.
		 * @name get_prev_dom(obj [, strict])
		 * @param  {mixed} obj
		 * @param  {Boolean} strict
		 * @return {jQuery}
		 */
		get_prev_dom : function (obj, strict) {
			var tmp;
			obj = this.get_node(obj, true);
			if(obj[0] === this.element[0]) {
				tmp = this.get_container_ul()[0].lastChild;
				while (tmp && tmp.offsetHeight === 0) {
					tmp = this._previousSibling(tmp);
				}
				return tmp ? $(tmp) : false;
			}
			if(!obj || !obj.length) {
				return false;
			}
			if(strict) {
				tmp = obj[0];
				do {
					tmp = this._previousSibling(tmp);
				} while (tmp && tmp.offsetHeight === 0);
				return tmp ? $(tmp) : false;
			}
			tmp = obj[0];
			do {
				tmp = this._previousSibling(tmp);
			} while (tmp && tmp.offsetHeight === 0);
			if(tmp !== null) {
				obj = $(tmp);
				while(obj.hasClass("jstree-open")) {
					obj = obj.children(".jstree-children").first().children(".jstree-node:visible:last");
				}
				return obj;
			}
			tmp = obj[0].parentNode.parentNode;
			return tmp && tmp.className && tmp.className.indexOf('jstree-node') !== -1 ? $(tmp) : false;
		},
		/**
		 * get the parent ID of a node
		 * @name get_parent(obj)
		 * @param  {mixed} obj
		 * @return {String}
		 */
		get_parent : function (obj) {
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			return obj.parent;
		},
		/**
		 * get a jQuery collection of all the children of a node (node must be rendered)
		 * @name get_children_dom(obj)
		 * @param  {mixed} obj
		 * @return {jQuery}
		 */
		get_children_dom : function (obj) {
			obj = this.get_node(obj, true);
			if(obj[0] === this.element[0]) {
				return this.get_container_ul().children(".jstree-node");
			}
			if(!obj || !obj.length) {
				return false;
			}
			return obj.children(".jstree-children").children(".jstree-node");
		},
		/**
		 * checks if a node has children
		 * @name is_parent(obj)
		 * @param  {mixed} obj
		 * @return {Boolean}
		 */
		is_parent : function (obj) {
			obj = this.get_node(obj);
			return obj && (obj.state.loaded === false || obj.children.length > 0);
		},
		/**
		 * checks if a node is loaded (its children are available)
		 * @name is_loaded(obj)
		 * @param  {mixed} obj
		 * @return {Boolean}
		 */
		is_loaded : function (obj) {
			obj = this.get_node(obj);
			return obj && obj.state.loaded;
		},
		/**
		 * check if a node is currently loading (fetching children)
		 * @name is_loading(obj)
		 * @param  {mixed} obj
		 * @return {Boolean}
		 */
		is_loading : function (obj) {
			obj = this.get_node(obj);
			return obj && obj.state && obj.state.loading;
		},
		/**
		 * check if a node is opened
		 * @name is_open(obj)
		 * @param  {mixed} obj
		 * @return {Boolean}
		 */
		is_open : function (obj) {
			obj = this.get_node(obj);
			return obj && obj.state.opened;
		},
		/**
		 * check if a node is in a closed state
		 * @name is_closed(obj)
		 * @param  {mixed} obj
		 * @return {Boolean}
		 */
		is_closed : function (obj) {
			obj = this.get_node(obj);
			return obj && this.is_parent(obj) && !obj.state.opened;
		},
		/**
		 * check if a node has no children
		 * @name is_leaf(obj)
		 * @param  {mixed} obj
		 * @return {Boolean}
		 */
		is_leaf : function (obj) {
			return !this.is_parent(obj);
		},
		/**
		 * loads a node (fetches its children using the `core.data` setting). Multiple nodes can be passed to by using an array.
		 * @name load_node(obj [, callback])
		 * @param  {mixed} obj
		 * @param  {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives two arguments - the node and a boolean status
		 * @return {Boolean}
		 * @trigger load_node.jstree
		 */
		load_node : function (obj, callback) {
			var k, l, i, j, c;
			if($.isArray(obj)) {
				this._load_nodes(obj.slice(), callback);
				return true;
			}
			obj = this.get_node(obj);
			if(!obj) {
				if(callback) { callback.call(this, obj, false); }
				return false;
			}
			// if(obj.state.loading) { } // the node is already loading - just wait for it to load and invoke callback? but if called implicitly it should be loaded again?
			if(obj.state.loaded) {
				obj.state.loaded = false;
				for(k = 0, l = obj.children_d.length; k < l; k++) {
					for(i = 0, j = obj.parents.length; i < j; i++) {
						this._model.data[obj.parents[i]].children_d = $.vakata.array_remove_item(this._model.data[obj.parents[i]].children_d, obj.children_d[k]);
					}
					if(this._model.data[obj.children_d[k]].state.selected) {
						c = true;
						this._data.core.selected = $.vakata.array_remove_item(this._data.core.selected, obj.children_d[k]);
					}
					delete this._model.data[obj.children_d[k]];
				}
				obj.children = [];
				obj.children_d = [];
				if(c) {
					this.trigger('changed', { 'action' : 'load_node', 'node' : obj, 'selected' : this._data.core.selected });
				}
			}
			obj.state.loading = true;
			this.get_node(obj, true).addClass("jstree-loading").attr('aria-busy',true);
			this._load_node(obj, $.proxy(function (status) {
				obj = this._model.data[obj.id];
				obj.state.loading = false;
				obj.state.loaded = status;
				var dom = this.get_node(obj, true);
				if(obj.state.loaded && !obj.children.length && dom && dom.length && !dom.hasClass('jstree-leaf')) {
					dom.removeClass('jstree-closed jstree-open').addClass('jstree-leaf');
				}
				dom.removeClass("jstree-loading").attr('aria-busy',false);
				/**
				 * triggered after a node is loaded
				 * @event
				 * @name load_node.jstree
				 * @param {Object} node the node that was loading
				 * @param {Boolean} status was the node loaded successfully
				 */
				this.trigger('load_node', { "node" : obj, "status" : status });
				if(callback) {
					callback.call(this, obj, status);
				}
			}, this));
			return true;
		},
		/**
		 * load an array of nodes (will also load unavailable nodes as soon as the appear in the structure). Used internally.
		 * @private
		 * @name _load_nodes(nodes [, callback])
		 * @param  {array} nodes
		 * @param  {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives one argument - the array passed to _load_nodes
		 */
		_load_nodes : function (nodes, callback, is_callback) {
			var r = true,
				c = function () { this._load_nodes(nodes, callback, true); },
				m = this._model.data, i, j;
			for(i = 0, j = nodes.length; i < j; i++) {
				if(m[nodes[i]] && (!m[nodes[i]].state.loaded || !is_callback)) {
					if(!this.is_loading(nodes[i])) {
						this.load_node(nodes[i], c);
					}
					r = false;
				}
			}
			if(r) {
				if(callback && !callback.done) {
					callback.call(this, nodes);
					callback.done = true;
				}
			}
		},
		/**
		 * loads all unloaded nodes
		 * @name load_all([obj, callback])
		 * @param {mixed} obj the node to load recursively, omit to load all nodes in the tree
		 * @param {function} callback a function to be executed once loading all the nodes is complete,
		 * @trigger load_all.jstree
		 */
		load_all : function (obj, callback) {
			if(!obj) { obj = '#'; }
			obj = this.get_node(obj);
			if(!obj) { return false; }
			var to_load = [],
				m = this._model.data,
				c = m[obj.id].children_d,
				i, j;
			if(obj.state && !obj.state.loaded) {
				to_load.push(obj.id);
			}
			for(i = 0, j = c.length; i < j; i++) {
				if(m[c[i]] && m[c[i]].state && !m[c[i]].state.loaded) {
					to_load.push(c[i]);
				}
			}
			if(to_load.length) {
				this._load_nodes(to_load, function () {
					this.load_all(obj, callback);
				});
			}
			else {
				/**
				 * triggered after a load_all call completes
				 * @event
				 * @name load_all.jstree
				 * @param {Object} node the recursively loaded node
				 */
				if(callback) { callback.call(this, obj); }
				this.trigger('load_all', { "node" : obj });
			}
		},
		/**
		 * handles the actual loading of a node. Used only internally.
		 * @private
		 * @name _load_node(obj [, callback])
		 * @param  {mixed} obj
		 * @param  {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives one argument - a boolean status
		 * @return {Boolean}
		 */
		_load_node : function (obj, callback) {
			var s = this.settings.core.data, t;
			// use original HTML
			if(!s) {
				if(obj.id === '#') {
					return this._append_html_data(obj, this._data.core.original_container_html.clone(true), function (status) {
						callback.call(this, status);
					});
				}
				else {
					return callback.call(this, false);
				}
				// return callback.call(this, obj.id === '#' ? this._append_html_data(obj, this._data.core.original_container_html.clone(true)) : false);
			}
			if($.isFunction(s)) {
				return s.call(this, obj, $.proxy(function (d) {
					if(d === false) {
						callback.call(this, false);
					}
					this[typeof d === 'string' ? '_append_html_data' : '_append_json_data'](obj, typeof d === 'string' ? $(d) : d, function (status) {
						callback.call(this, status);
					});
					// return d === false ? callback.call(this, false) : callback.call(this, this[typeof d === 'string' ? '_append_html_data' : '_append_json_data'](obj, typeof d === 'string' ? $(d) : d));
				}, this));
			}
			if(typeof s === 'object') {
				if(s.url) {
					s = $.extend(true, {}, s);
					if($.isFunction(s.url)) {
						s.url = s.url.call(this, obj);
					}
					if($.isFunction(s.data)) {
						s.data = s.data.call(this, obj);
					}
					return $.ajax(s)
						.done($.proxy(function (d,t,x) {
								var type = x.getResponseHeader('Content-Type');
								if(type.indexOf('json') !== -1 || typeof d === "object") {
									return this._append_json_data(obj, d, function (status) { callback.call(this, status); });
									//return callback.call(this, this._append_json_data(obj, d));
								}
								if(type.indexOf('html') !== -1 || typeof d === "string") {
									return this._append_html_data(obj, $(d), function (status) { callback.call(this, status); });
									// return callback.call(this, this._append_html_data(obj, $(d)));
								}
								this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'core', 'id' : 'core_04', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id, 'xhr' : x }) };
								this.settings.core.error.call(this, this._data.core.last_error);
								return callback.call(this, false);
							}, this))
						.fail($.proxy(function (f) {
								callback.call(this, false);
								this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'core', 'id' : 'core_04', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id, 'xhr' : f }) };
								this.settings.core.error.call(this, this._data.core.last_error);
							}, this));
				}
				t = ($.isArray(s) || $.isPlainObject(s)) ? JSON.parse(JSON.stringify(s)) : s;
				if(obj.id === '#') {
					return this._append_json_data(obj, t, function (status) {
						callback.call(this, status);
					});
				}
				else {
					this._data.core.last_error = { 'error' : 'nodata', 'plugin' : 'core', 'id' : 'core_05', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id }) };
					this.settings.core.error.call(this, this._data.core.last_error);
					return callback.call(this, false);
				}
				//return callback.call(this, (obj.id === "#" ? this._append_json_data(obj, t) : false) );
			}
			if(typeof s === 'string') {
				if(obj.id === '#') {
					return this._append_html_data(obj, $(s), function (status) {
						callback.call(this, status);
					});
				}
				else {
					this._data.core.last_error = { 'error' : 'nodata', 'plugin' : 'core', 'id' : 'core_06', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id }) };
					this.settings.core.error.call(this, this._data.core.last_error);
					return callback.call(this, false);
				}
				//return callback.call(this, (obj.id === "#" ? this._append_html_data(obj, $(s)) : false) );
			}
			return callback.call(this, false);
		},
		/**
		 * adds a node to the list of nodes to redraw. Used only internally.
		 * @private
		 * @name _node_changed(obj [, callback])
		 * @param  {mixed} obj
		 */
		_node_changed : function (obj) {
			obj = this.get_node(obj);
			if(obj) {
				this._model.changed.push(obj.id);
			}
		},
		/**
		 * appends HTML content to the tree. Used internally.
		 * @private
		 * @name _append_html_data(obj, data)
		 * @param  {mixed} obj the node to append to
		 * @param  {String} data the HTML string to parse and append
		 * @trigger model.jstree, changed.jstree
		 */
		_append_html_data : function (dom, data, cb) {
			dom = this.get_node(dom);
			dom.children = [];
			dom.children_d = [];
			var dat = data.is('ul') ? data.children() : data,
				par = dom.id,
				chd = [],
				dpc = [],
				m = this._model.data,
				p = m[par],
				s = this._data.core.selected.length,
				tmp, i, j;
			dat.each($.proxy(function (i, v) {
				tmp = this._parse_model_from_html($(v), par, p.parents.concat());
				if(tmp) {
					chd.push(tmp);
					dpc.push(tmp);
					if(m[tmp].children_d.length) {
						dpc = dpc.concat(m[tmp].children_d);
					}
				}
			}, this));
			p.children = chd;
			p.children_d = dpc;
			for(i = 0, j = p.parents.length; i < j; i++) {
				m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc);
			}
			/**
			 * triggered when new data is inserted to the tree model
			 * @event
			 * @name model.jstree
			 * @param {Array} nodes an array of node IDs
			 * @param {String} parent the parent ID of the nodes
			 */
			this.trigger('model', { "nodes" : dpc, 'parent' : par });
			if(par !== '#') {
				this._node_changed(par);
				this.redraw();
			}
			else {
				this.get_container_ul().children('.jstree-initial-node').remove();
				this.redraw(true);
			}
			if(this._data.core.selected.length !== s) {
				this.trigger('changed', { 'action' : 'model', 'selected' : this._data.core.selected });
			}
			cb.call(this, true);
		},
		/**
		 * appends JSON content to the tree. Used internally.
		 * @private
		 * @name _append_json_data(obj, data)
		 * @param  {mixed} obj the node to append to
		 * @param  {String} data the JSON object to parse and append
		 * @param  {Boolean} force_processing internal param - do not set
		 * @trigger model.jstree, changed.jstree
		 */
		_append_json_data : function (dom, data, cb, force_processing) {
			dom = this.get_node(dom);
			dom.children = [];
			dom.children_d = [];
			// *%$@!!!
			if(data.d) {
				data = data.d;
				if(typeof data === "string") {
					data = JSON.parse(data);
				}
			}
			if(!$.isArray(data)) { data = [data]; }
			var w = null,
				args = {
					'df'	: this._model.default_state,
					'dat'	: data,
					'par'	: dom.id,
					'm'		: this._model.data,
					't_id'	: this._id,
					't_cnt'	: this._cnt,
					'sel'	: this._data.core.selected
				},
				func = function (data, undefined) {
					if(data.data) { data = data.data; }
					var dat = data.dat,
						par = data.par,
						chd = [],
						dpc = [],
						add = [],
						df = data.df,
						t_id = data.t_id,
						t_cnt = data.t_cnt,
						m = data.m,
						p = m[par],
						sel = data.sel,
						tmp, i, j, rslt,
						parse_flat = function (d, p, ps) {
							if(!ps) { ps = []; }
							else { ps = ps.concat(); }
							if(p) { ps.unshift(p); }
							var tid = d.id.toString(),
								i, j, c, e,
								tmp = {
									id			: tid,
									text		: d.text || '',
									icon		: d.icon !== undefined ? d.icon : true,
									parent		: p,
									parents		: ps,
									children	: d.children || [],
									children_d	: d.children_d || [],
									data		: d.data,
									state		: { },
									li_attr		: { id : false },
									a_attr		: { href : '#' },
									original	: false
								};
							for(i in df) {
								if(df.hasOwnProperty(i)) {
									tmp.state[i] = df[i];
								}
							}
							if(d && d.data && d.data.jstree && d.data.jstree.icon) {
								tmp.icon = d.data.jstree.icon;
							}
							if(d && d.data) {
								tmp.data = d.data;
								if(d.data.jstree) {
									for(i in d.data.jstree) {
										if(d.data.jstree.hasOwnProperty(i)) {
											tmp.state[i] = d.data.jstree[i];
										}
									}
								}
							}
							if(d && typeof d.state === 'object') {
								for (i in d.state) {
									if(d.state.hasOwnProperty(i)) {
										tmp.state[i] = d.state[i];
									}
								}
							}
							if(d && typeof d.li_attr === 'object') {
								for (i in d.li_attr) {
									if(d.li_attr.hasOwnProperty(i)) {
										tmp.li_attr[i] = d.li_attr[i];
									}
								}
							}
							if(!tmp.li_attr.id) {
								tmp.li_attr.id = tid;
							}
							if(d && typeof d.a_attr === 'object') {
								for (i in d.a_attr) {
									if(d.a_attr.hasOwnProperty(i)) {
										tmp.a_attr[i] = d.a_attr[i];
									}
								}
							}
							if(d && d.children && d.children === true) {
								tmp.state.loaded = false;
								tmp.children = [];
								tmp.children_d = [];
							}
							m[tmp.id] = tmp;
							for(i = 0, j = tmp.children.length; i < j; i++) {
								c = parse_flat(m[tmp.children[i]], tmp.id, ps);
								e = m[c];
								tmp.children_d.push(c);
								if(e.children_d.length) {
									tmp.children_d = tmp.children_d.concat(e.children_d);
								}
							}
							delete d.data;
							delete d.children;
							m[tmp.id].original = d;
							if(tmp.state.selected) {
								add.push(tmp.id);
							}
							return tmp.id;
						},
						parse_nest = function (d, p, ps) {
							if(!ps) { ps = []; }
							else { ps = ps.concat(); }
							if(p) { ps.unshift(p); }
							var tid = false, i, j, c, e, tmp;
							do {
								tid = 'j' + t_id + '_' + (++t_cnt);
							} while(m[tid]);

							tmp = {
								id			: false,
								text		: typeof d === 'string' ? d : '',
								icon		: typeof d === 'object' && d.icon !== undefined ? d.icon : true,
								parent		: p,
								parents		: ps,
								children	: [],
								children_d	: [],
								data		: null,
								state		: { },
								li_attr		: { id : false },
								a_attr		: { href : '#' },
								original	: false
							};
							for(i in df) {
								if(df.hasOwnProperty(i)) {
									tmp.state[i] = df[i];
								}
							}
							if(d && d.id) { tmp.id = d.id.toString(); }
							if(d && d.text) { tmp.text = d.text; }
							if(d && d.data && d.data.jstree && d.data.jstree.icon) {
								tmp.icon = d.data.jstree.icon;
							}
							if(d && d.data) {
								tmp.data = d.data;
								if(d.data.jstree) {
									for(i in d.data.jstree) {
										if(d.data.jstree.hasOwnProperty(i)) {
											tmp.state[i] = d.data.jstree[i];
										}
									}
								}
							}
							if(d && typeof d.state === 'object') {
								for (i in d.state) {
									if(d.state.hasOwnProperty(i)) {
										tmp.state[i] = d.state[i];
									}
								}
							}
							if(d && typeof d.li_attr === 'object') {
								for (i in d.li_attr) {
									if(d.li_attr.hasOwnProperty(i)) {
										tmp.li_attr[i] = d.li_attr[i];
									}
								}
							}
							if(tmp.li_attr.id && !tmp.id) {
								tmp.id = tmp.li_attr.id.toString();
							}
							if(!tmp.id) {
								tmp.id = tid;
							}
							if(!tmp.li_attr.id) {
								tmp.li_attr.id = tmp.id;
							}
							if(d && typeof d.a_attr === 'object') {
								for (i in d.a_attr) {
									if(d.a_attr.hasOwnProperty(i)) {
										tmp.a_attr[i] = d.a_attr[i];
									}
								}
							}
							if(d && d.children && d.children.length) {
								for(i = 0, j = d.children.length; i < j; i++) {
									c = parse_nest(d.children[i], tmp.id, ps);
									e = m[c];
									tmp.children.push(c);
									if(e.children_d.length) {
										tmp.children_d = tmp.children_d.concat(e.children_d);
									}
								}
								tmp.children_d = tmp.children_d.concat(tmp.children);
							}
							if(d && d.children && d.children === true) {
								tmp.state.loaded = false;
								tmp.children = [];
								tmp.children_d = [];
							}
							delete d.data;
							delete d.children;
							tmp.original = d;
							m[tmp.id] = tmp;
							if(tmp.state.selected) {
								add.push(tmp.id);
							}
							return tmp.id;
						};

					if(dat.length && dat[0].id !== undefined && dat[0].parent !== undefined) {
						// Flat JSON support (for easy import from DB):
						// 1) convert to object (foreach)
						for(i = 0, j = dat.length; i < j; i++) {
							if(!dat[i].children) {
								dat[i].children = [];
							}
							m[dat[i].id.toString()] = dat[i];
						}
						// 2) populate children (foreach)
						for(i = 0, j = dat.length; i < j; i++) {
							m[dat[i].parent.toString()].children.push(dat[i].id.toString());
							// populate parent.children_d
							p.children_d.push(dat[i].id.toString());
						}
						// 3) normalize && populate parents and children_d with recursion
						for(i = 0, j = p.children.length; i < j; i++) {
							tmp = parse_flat(m[p.children[i]], par, p.parents.concat());
							dpc.push(tmp);
							if(m[tmp].children_d.length) {
								dpc = dpc.concat(m[tmp].children_d);
							}
						}
						for(i = 0, j = p.parents.length; i < j; i++) {
							m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc);
						}
						// ?) three_state selection - p.state.selected && t - (if three_state foreach(dat => ch) -> foreach(parents) if(parent.selected) child.selected = true;
						rslt = {
							'cnt' : t_cnt,
							'mod' : m,
							'sel' : sel,
							'par' : par,
							'dpc' : dpc,
							'add' : add
						};
					}
					else {
						for(i = 0, j = dat.length; i < j; i++) {
							tmp = parse_nest(dat[i], par, p.parents.concat());
							if(tmp) {
								chd.push(tmp);
								dpc.push(tmp);
								if(m[tmp].children_d.length) {
									dpc = dpc.concat(m[tmp].children_d);
								}
							}
						}
						p.children = chd;
						p.children_d = dpc;
						for(i = 0, j = p.parents.length; i < j; i++) {
							m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc);
						}
						rslt = {
							'cnt' : t_cnt,
							'mod' : m,
							'sel' : sel,
							'par' : par,
							'dpc' : dpc,
							'add' : add
						};
					}
					if(typeof window === 'undefined' || typeof window.document === 'undefined') {
						postMessage(rslt);
					}
					else {
						return rslt;
					}
				},
				rslt = function (rslt, worker) {
					this._cnt = rslt.cnt;
					this._model.data = rslt.mod; // breaks the reference in load_node - careful

					if(worker) {
						var i, j, a = rslt.add, r = rslt.sel, s = this._data.core.selected.slice(), m = this._model.data;
						// if selection was changed while calculating in worker
						if(r.length !== s.length || $.vakata.array_unique(r.concat(s)).length !== r.length) {
							// deselect nodes that are no longer selected
							for(i = 0, j = r.length; i < j; i++) {
								if($.inArray(r[i], a) === -1 && $.inArray(r[i], s) === -1) {
									m[r[i]].state.selected = false;
								}
							}
							// select nodes that were selected in the mean time
							for(i = 0, j = s.length; i < j; i++) {
								if($.inArray(s[i], r) === -1) {
									m[s[i]].state.selected = true;
								}
							}
						}
					}
					if(rslt.add.length) {
						this._data.core.selected = this._data.core.selected.concat(rslt.add);
					}

					this.trigger('model', { "nodes" : rslt.dpc, 'parent' : rslt.par });

					if(rslt.par !== '#') {
						this._node_changed(rslt.par);
						this.redraw();
					}
					else {
						// this.get_container_ul().children('.jstree-initial-node').remove();
						this.redraw(true);
					}
					if(rslt.add.length) {
						this.trigger('changed', { 'action' : 'model', 'selected' : this._data.core.selected });
					}
					cb.call(this, true);
				};
			if(this.settings.core.worker && window.Blob && window.URL && window.Worker) {
				try {
					if(this._wrk === null) {
						this._wrk = window.URL.createObjectURL(
							new window.Blob(
								['self.onmessage = ' + func.toString()],
								{type:"text/javascript"}
							)
						);
					}
					if(!this._data.core.working || force_processing) {
						this._data.core.working = true;
						w = new window.Worker(this._wrk);
						w.onmessage = $.proxy(function (e) {
							rslt.call(this, e.data, true);
							try { w.terminate(); w = null; } catch(ignore) { }
							if(this._data.core.worker_queue.length) {
								this._append_json_data.apply(this, this._data.core.worker_queue.shift());
							}
							else {
								this._data.core.working = false;
							}
						}, this);
						if(!args.par) {
							if(this._data.core.worker_queue.length) {
								this._append_json_data.apply(this, this._data.core.worker_queue.shift());
							}
							else {
								this._data.core.working = false;
							}
						}
						else {
							w.postMessage(args);
						}
					}
					else {
						this._data.core.worker_queue.push([dom, data, cb, true]);
					}
				}
				catch(e) {
					rslt.call(this, func(args), false);
					if(this._data.core.worker_queue.length) {
						this._append_json_data.apply(this, this._data.core.worker_queue.shift());
					}
					else {
						this._data.core.working = false;
					}
				}
			}
			else {
				rslt.call(this, func(args), false);
			}
		},
		/**
		 * parses a node from a jQuery object and appends them to the in memory tree model. Used internally.
		 * @private
		 * @name _parse_model_from_html(d [, p, ps])
		 * @param  {jQuery} d the jQuery object to parse
		 * @param  {String} p the parent ID
		 * @param  {Array} ps list of all parents
		 * @return {String} the ID of the object added to the model
		 */
		_parse_model_from_html : function (d, p, ps) {
			if(!ps) { ps = []; }
			else { ps = [].concat(ps); }
			if(p) { ps.unshift(p); }
			var c, e, m = this._model.data,
				data = {
					id			: false,
					text		: false,
					icon		: true,
					parent		: p,
					parents		: ps,
					children	: [],
					children_d	: [],
					data		: null,
					state		: { },
					li_attr		: { id : false },
					a_attr		: { href : '#' },
					original	: false
				}, i, tmp, tid;
			for(i in this._model.default_state) {
				if(this._model.default_state.hasOwnProperty(i)) {
					data.state[i] = this._model.default_state[i];
				}
			}
			tmp = $.vakata.attributes(d, true);
			$.each(tmp, function (i, v) {
				v = $.trim(v);
				if(!v.length) { return true; }
				data.li_attr[i] = v;
				if(i === 'id') {
					data.id = v.toString();
				}
			});
			tmp = d.children('a').first();
			if(tmp.length) {
				tmp = $.vakata.attributes(tmp, true);
				$.each(tmp, function (i, v) {
					v = $.trim(v);
					if(v.length) {
						data.a_attr[i] = v;
					}
				});
			}
			tmp = d.children("a").first().length ? d.children("a").first().clone() : d.clone();
			tmp.children("ins, i, ul").remove();
			tmp = tmp.html();
			tmp = $('<div />').html(tmp);
			data.text = this.settings.core.force_text ? tmp.text() : tmp.html();
			tmp = d.data();
			data.data = tmp ? $.extend(true, {}, tmp) : null;
			data.state.opened = d.hasClass('jstree-open');
			data.state.selected = d.children('a').hasClass('jstree-clicked');
			data.state.disabled = d.children('a').hasClass('jstree-disabled');
			if(data.data && data.data.jstree) {
				for(i in data.data.jstree) {
					if(data.data.jstree.hasOwnProperty(i)) {
						data.state[i] = data.data.jstree[i];
					}
				}
			}
			tmp = d.children("a").children(".jstree-themeicon");
			if(tmp.length) {
				data.icon = tmp.hasClass('jstree-themeicon-hidden') ? false : tmp.attr('rel');
			}
			if(data.state.icon) {
				data.icon = data.state.icon;
			}
			tmp = d.children("ul").children("li");
			do {
				tid = 'j' + this._id + '_' + (++this._cnt);
			} while(m[tid]);
			data.id = data.li_attr.id ? data.li_attr.id.toString() : tid;
			if(tmp.length) {
				tmp.each($.proxy(function (i, v) {
					c = this._parse_model_from_html($(v), data.id, ps);
					e = this._model.data[c];
					data.children.push(c);
					if(e.children_d.length) {
						data.children_d = data.children_d.concat(e.children_d);
					}
				}, this));
				data.children_d = data.children_d.concat(data.children);
			}
			else {
				if(d.hasClass('jstree-closed')) {
					data.state.loaded = false;
				}
			}
			if(data.li_attr['class']) {
				data.li_attr['class'] = data.li_attr['class'].replace('jstree-closed','').replace('jstree-open','');
			}
			if(data.a_attr['class']) {
				data.a_attr['class'] = data.a_attr['class'].replace('jstree-clicked','').replace('jstree-disabled','');
			}
			m[data.id] = data;
			if(data.state.selected) {
				this._data.core.selected.push(data.id);
			}
			return data.id;
		},
		/**
		 * parses a node from a JSON object (used when dealing with flat data, which has no nesting of children, but has id and parent properties) and appends it to the in memory tree model. Used internally.
		 * @private
		 * @name _parse_model_from_flat_json(d [, p, ps])
		 * @param  {Object} d the JSON object to parse
		 * @param  {String} p the parent ID
		 * @param  {Array} ps list of all parents
		 * @return {String} the ID of the object added to the model
		 */
		_parse_model_from_flat_json : function (d, p, ps) {
			if(!ps) { ps = []; }
			else { ps = ps.concat(); }
			if(p) { ps.unshift(p); }
			var tid = d.id.toString(),
				m = this._model.data,
				df = this._model.default_state,
				i, j, c, e,
				tmp = {
					id			: tid,
					text		: d.text || '',
					icon		: d.icon !== undefined ? d.icon : true,
					parent		: p,
					parents		: ps,
					children	: d.children || [],
					children_d	: d.children_d || [],
					data		: d.data,
					state		: { },
					li_attr		: { id : false },
					a_attr		: { href : '#' },
					original	: false
				};
			for(i in df) {
				if(df.hasOwnProperty(i)) {
					tmp.state[i] = df[i];
				}
			}
			if(d && d.data && d.data.jstree && d.data.jstree.icon) {
				tmp.icon = d.data.jstree.icon;
			}
			if(d && d.data) {
				tmp.data = d.data;
				if(d.data.jstree) {
					for(i in d.data.jstree) {
						if(d.data.jstree.hasOwnProperty(i)) {
							tmp.state[i] = d.data.jstree[i];
						}
					}
				}
			}
			if(d && typeof d.state === 'object') {
				for (i in d.state) {
					if(d.state.hasOwnProperty(i)) {
						tmp.state[i] = d.state[i];
					}
				}
			}
			if(d && typeof d.li_attr === 'object') {
				for (i in d.li_attr) {
					if(d.li_attr.hasOwnProperty(i)) {
						tmp.li_attr[i] = d.li_attr[i];
					}
				}
			}
			if(!tmp.li_attr.id) {
				tmp.li_attr.id = tid;
			}
			if(d && typeof d.a_attr === 'object') {
				for (i in d.a_attr) {
					if(d.a_attr.hasOwnProperty(i)) {
						tmp.a_attr[i] = d.a_attr[i];
					}
				}
			}
			if(d && d.children && d.children === true) {
				tmp.state.loaded = false;
				tmp.children = [];
				tmp.children_d = [];
			}
			m[tmp.id] = tmp;
			for(i = 0, j = tmp.children.length; i < j; i++) {
				c = this._parse_model_from_flat_json(m[tmp.children[i]], tmp.id, ps);
				e = m[c];
				tmp.children_d.push(c);
				if(e.children_d.length) {
					tmp.children_d = tmp.children_d.concat(e.children_d);
				}
			}
			delete d.data;
			delete d.children;
			m[tmp.id].original = d;
			if(tmp.state.selected) {
				this._data.core.selected.push(tmp.id);
			}
			return tmp.id;
		},
		/**
		 * parses a node from a JSON object and appends it to the in memory tree model. Used internally.
		 * @private
		 * @name _parse_model_from_json(d [, p, ps])
		 * @param  {Object} d the JSON object to parse
		 * @param  {String} p the parent ID
		 * @param  {Array} ps list of all parents
		 * @return {String} the ID of the object added to the model
		 */
		_parse_model_from_json : function (d, p, ps) {
			if(!ps) { ps = []; }
			else { ps = ps.concat(); }
			if(p) { ps.unshift(p); }
			var tid = false, i, j, c, e, m = this._model.data, df = this._model.default_state, tmp;
			do {
				tid = 'j' + this._id + '_' + (++this._cnt);
			} while(m[tid]);

			tmp = {
				id			: false,
				text		: typeof d === 'string' ? d : '',
				icon		: typeof d === 'object' && d.icon !== undefined ? d.icon : true,
				parent		: p,
				parents		: ps,
				children	: [],
				children_d	: [],
				data		: null,
				state		: { },
				li_attr		: { id : false },
				a_attr		: { href : '#' },
				original	: false
			};
			for(i in df) {
				if(df.hasOwnProperty(i)) {
					tmp.state[i] = df[i];
				}
			}
			if(d && d.id) { tmp.id = d.id.toString(); }
			if(d && d.text) { tmp.text = d.text; }
			if(d && d.data && d.data.jstree && d.data.jstree.icon) {
				tmp.icon = d.data.jstree.icon;
			}
			if(d && d.data) {
				tmp.data = d.data;
				if(d.data.jstree) {
					for(i in d.data.jstree) {
						if(d.data.jstree.hasOwnProperty(i)) {
							tmp.state[i] = d.data.jstree[i];
						}
					}
				}
			}
			if(d && typeof d.state === 'object') {
				for (i in d.state) {
					if(d.state.hasOwnProperty(i)) {
						tmp.state[i] = d.state[i];
					}
				}
			}
			if(d && typeof d.li_attr === 'object') {
				for (i in d.li_attr) {
					if(d.li_attr.hasOwnProperty(i)) {
						tmp.li_attr[i] = d.li_attr[i];
					}
				}
			}
			if(tmp.li_attr.id && !tmp.id) {
				tmp.id = tmp.li_attr.id.toString();
			}
			if(!tmp.id) {
				tmp.id = tid;
			}
			if(!tmp.li_attr.id) {
				tmp.li_attr.id = tmp.id;
			}
			if(d && typeof d.a_attr === 'object') {
				for (i in d.a_attr) {
					if(d.a_attr.hasOwnProperty(i)) {
						tmp.a_attr[i] = d.a_attr[i];
					}
				}
			}
			if(d && d.children && d.children.length) {
				for(i = 0, j = d.children.length; i < j; i++) {
					c = this._parse_model_from_json(d.children[i], tmp.id, ps);
					e = m[c];
					tmp.children.push(c);
					if(e.children_d.length) {
						tmp.children_d = tmp.children_d.concat(e.children_d);
					}
				}
				tmp.children_d = tmp.children_d.concat(tmp.children);
			}
			if(d && d.children && d.children === true) {
				tmp.state.loaded = false;
				tmp.children = [];
				tmp.children_d = [];
			}
			delete d.data;
			delete d.children;
			tmp.original = d;
			m[tmp.id] = tmp;
			if(tmp.state.selected) {
				this._data.core.selected.push(tmp.id);
			}
			return tmp.id;
		},
		/**
		 * redraws all nodes that need to be redrawn. Used internally.
		 * @private
		 * @name _redraw()
		 * @trigger redraw.jstree
		 */
		_redraw : function () {
			var nodes = this._model.force_full_redraw ? this._model.data['#'].children.concat([]) : this._model.changed.concat([]),
				f = document.createElement('UL'), tmp, i, j, fe = this._data.core.focused;
			for(i = 0, j = nodes.length; i < j; i++) {
				tmp = this.redraw_node(nodes[i], true, this._model.force_full_redraw);
				if(tmp && this._model.force_full_redraw) {
					f.appendChild(tmp);
				}
			}
			if(this._model.force_full_redraw) {
				f.className = this.get_container_ul()[0].className;
				f.setAttribute('role','group');
				this.element.empty().append(f);
				//this.get_container_ul()[0].appendChild(f);
			}
			if(fe !== null) {
				tmp = this.get_node(fe, true);
				if(tmp && tmp.length && tmp.children('.jstree-anchor')[0] !== document.activeElement) {
					tmp.children('.jstree-anchor').focus();
				}
				else {
					this._data.core.focused = null;
				}
			}
			this._model.force_full_redraw = false;
			this._model.changed = [];
			/**
			 * triggered after nodes are redrawn
			 * @event
			 * @name redraw.jstree
			 * @param {array} nodes the redrawn nodes
			 */
			this.trigger('redraw', { "nodes" : nodes });
		},
		/**
		 * redraws all nodes that need to be redrawn or optionally - the whole tree
		 * @name redraw([full])
		 * @param {Boolean} full if set to `true` all nodes are redrawn.
		 */
		redraw : function (full) {
			if(full) {
				this._model.force_full_redraw = true;
			}
			//if(this._model.redraw_timeout) {
			//	clearTimeout(this._model.redraw_timeout);
			//}
			//this._model.redraw_timeout = setTimeout($.proxy(this._redraw, this),0);
			this._redraw();
		},
		/**
		 * redraws a single node's children. Used internally.
		 * @private
		 * @name draw_children(node)
		 * @param {mixed} node the node whose children will be redrawn
		 */
		draw_children : function (node) {
			var obj = this.get_node(node),
				i = false,
				j = false,
				k = false,
				d = document;
			if(!obj) { return false; }
			if(obj.id === '#') { return this.redraw(true); }
			node = this.get_node(node, true);
			if(!node || !node.length) { return false; } // TODO: quick toggle

			node.children('.jstree-children').remove();
			node = node[0];
			if(obj.children.length && obj.state.loaded) {
				k = d.createElement('UL');
				k.setAttribute('role', 'group');
				k.className = 'jstree-children';
				for(i = 0, j = obj.children.length; i < j; i++) {
					k.appendChild(this.redraw_node(obj.children[i], true, true));
				}
				node.appendChild(k);
			}
		},
		/**
		 * redraws a single node. Used internally.
		 * @private
		 * @name redraw_node(node, deep, is_callback, force_render)
		 * @param {mixed} node the node to redraw
		 * @param {Boolean} deep should child nodes be redrawn too
		 * @param {Boolean} is_callback is this a recursion call
		 * @param {Boolean} force_render should children of closed parents be drawn anyway
		 */
		redraw_node : function (node, deep, is_callback, force_render) {
			var obj = this.get_node(node),
				par = false,
				ind = false,
				old = false,
				i = false,
				j = false,
				k = false,
				c = '',
				d = document,
				m = this._model.data,
				f = false,
				s = false,
				tmp = null,
				t = 0,
				l = 0;
			if(!obj) { return false; }
			if(obj.id === '#') {  return this.redraw(true); }
			deep = deep || obj.children.length === 0;
			node = !document.querySelector ? document.getElementById(obj.id) : this.element[0].querySelector('#' + ("0123456789".indexOf(obj.id[0]) !== -1 ? '\\3' + obj.id[0] + ' ' + obj.id.substr(1).replace($.jstree.idregex,'\\$&') : obj.id.replace($.jstree.idregex,'\\$&')) ); //, this.element);
			if(!node) {
				deep = true;
				//node = d.createElement('LI');
				if(!is_callback) {
					par = obj.parent !== '#' ? $('#' + obj.parent.replace($.jstree.idregex,'\\$&'), this.element)[0] : null;
					if(par !== null && (!par || !m[obj.parent].state.opened)) {
						return false;
					}
					ind = $.inArray(obj.id, par === null ? m['#'].children : m[obj.parent].children);
				}
			}
			else {
				node = $(node);
				if(!is_callback) {
					par = node.parent().parent()[0];
					if(par === this.element[0]) {
						par = null;
					}
					ind = node.index();
				}
				// m[obj.id].data = node.data(); // use only node's data, no need to touch jquery storage
				if(!deep && obj.children.length && !node.children('.jstree-children').length) {
					deep = true;
				}
				if(!deep) {
					old = node.children('.jstree-children')[0];
				}
				f = node.children('.jstree-anchor')[0] === document.activeElement;
				node.remove();
				//node = d.createElement('LI');
				//node = node[0];
			}
			node = _node.cloneNode(true);
			// node is DOM, deep is boolean

			c = 'jstree-node ';
			for(i in obj.li_attr) {
				if(obj.li_attr.hasOwnProperty(i)) {
					if(i === 'id') { continue; }
					if(i !== 'class') {
						node.setAttribute(i, obj.li_attr[i]);
					}
					else {
						c += obj.li_attr[i];
					}
				}
			}
			if(!obj.a_attr.id) {
				obj.a_attr.id = obj.id + '_anchor';
			}
			node.setAttribute('aria-selected', !!obj.state.selected);
			node.setAttribute('aria-level', obj.parents.length);
			node.setAttribute('aria-labelledby', obj.a_attr.id);
			if(obj.state.disabled) {
				node.setAttribute('aria-disabled', true);
			}

			if(obj.state.loaded && !obj.children.length) {
				c += ' jstree-leaf';
			}
			else {
				c += obj.state.opened && obj.state.loaded ? ' jstree-open' : ' jstree-closed';
				node.setAttribute('aria-expanded', (obj.state.opened && obj.state.loaded) );
			}
			if(obj.parent !== null && m[obj.parent].children[m[obj.parent].children.length - 1] === obj.id) {
				c += ' jstree-last';
			}
			node.id = obj.id;
			node.className = c;
			c = ( obj.state.selected ? ' jstree-clicked' : '') + ( obj.state.disabled ? ' jstree-disabled' : '');
			for(j in obj.a_attr) {
				if(obj.a_attr.hasOwnProperty(j)) {
					if(j === 'href' && obj.a_attr[j] === '#') { continue; }
					if(j !== 'class') {
						node.childNodes[1].setAttribute(j, obj.a_attr[j]);
					}
					else {
						c += ' ' + obj.a_attr[j];
					}
				}
			}
			if(c.length) {
				node.childNodes[1].className = 'jstree-anchor ' + c;
			}
			if((obj.icon && obj.icon !== true) || obj.icon === false) {
				if(obj.icon === false) {
					node.childNodes[1].childNodes[0].className += ' jstree-themeicon-hidden';
				}
				else if(obj.icon.indexOf('/') === -1 && obj.icon.indexOf('.') === -1) {
					node.childNodes[1].childNodes[0].className += ' ' + obj.icon + ' jstree-themeicon-custom';
				}
				else {
					node.childNodes[1].childNodes[0].style.backgroundImage = 'url('+obj.icon+')';
					node.childNodes[1].childNodes[0].style.backgroundPosition = 'center center';
					node.childNodes[1].childNodes[0].style.backgroundSize = 'auto';
					node.childNodes[1].childNodes[0].className += ' jstree-themeicon-custom';
				}
			}

			if(this.settings.core.force_text) {
				node.childNodes[1].appendChild(d.createTextNode(obj.text));
			}
			else {
				node.childNodes[1].innerHTML += obj.text;
			}


			if(deep && obj.children.length && (obj.state.opened || force_render) && obj.state.loaded) {
				k = d.createElement('UL');
				k.setAttribute('role', 'group');
				k.className = 'jstree-children';
				for(i = 0, j = obj.children.length; i < j; i++) {
					k.appendChild(this.redraw_node(obj.children[i], deep, true));
				}
				node.appendChild(k);
			}
			if(old) {
				node.appendChild(old);
			}
			if(!is_callback) {
				// append back using par / ind
				if(!par) {
					par = this.element[0];
				}
				for(i = 0, j = par.childNodes.length; i < j; i++) {
					if(par.childNodes[i] && par.childNodes[i].className && par.childNodes[i].className.indexOf('jstree-children') !== -1) {
						tmp = par.childNodes[i];
						break;
					}
				}
				if(!tmp) {
					tmp = d.createElement('UL');
					tmp.setAttribute('role', 'group');
					tmp.className = 'jstree-children';
					par.appendChild(tmp);
				}
				par = tmp;

				if(ind < par.childNodes.length) {
					par.insertBefore(node, par.childNodes[ind]);
				}
				else {
					par.appendChild(node);
				}
				if(f) {
					t = this.element[0].scrollTop;
					l = this.element[0].scrollLeft;
					node.childNodes[1].focus();
					this.element[0].scrollTop = t;
					this.element[0].scrollLeft = l;
				}
			}
			if(obj.state.opened && !obj.state.loaded) {
				obj.state.opened = false;
				setTimeout($.proxy(function () {
					this.open_node(obj.id, false, 0);
				}, this), 0);
			}
			return node;
		},
		/**
		 * opens a node, revaling its children. If the node is not loaded it will be loaded and opened once ready.
		 * @name open_node(obj [, callback, animation])
		 * @param {mixed} obj the node to open
		 * @param {Function} callback a function to execute once the node is opened
		 * @param {Number} animation the animation duration in milliseconds when opening the node (overrides the `core.animation` setting). Use `false` for no animation.
		 * @trigger open_node.jstree, after_open.jstree, before_open.jstree
		 */
		open_node : function (obj, callback, animation) {
			var t1, t2, d, t;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.open_node(obj[t1], callback, animation);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			animation = animation === undefined ? this.settings.core.animation : animation;
			if(!this.is_closed(obj)) {
				if(callback) {
					callback.call(this, obj, false);
				}
				return false;
			}
			if(!this.is_loaded(obj)) {
				if(this.is_loading(obj)) {
					return setTimeout($.proxy(function () {
						this.open_node(obj, callback, animation);
					}, this), 500);
				}
				this.load_node(obj, function (o, ok) {
					return ok ? this.open_node(o, callback, animation) : (callback ? callback.call(this, o, false) : false);
				});
			}
			else {
				d = this.get_node(obj, true);
				t = this;
				if(d.length) {
					if(animation && d.children(".jstree-children").length) {
						d.children(".jstree-children").stop(true, true);
					}
					if(obj.children.length && !this._firstChild(d.children('.jstree-children')[0])) {
						this.draw_children(obj);
						//d = this.get_node(obj, true);
					}
					if(!animation) {
						this.trigger('before_open', { "node" : obj });
						d[0].className = d[0].className.replace('jstree-closed', 'jstree-open');
						d[0].setAttribute("aria-expanded", true);
					}
					else {
						this.trigger('before_open', { "node" : obj });
						d
							.children(".jstree-children").css("display","none").end()
							.removeClass("jstree-closed").addClass("jstree-open").attr("aria-expanded", true)
							.children(".jstree-children").stop(true, true)
								.slideDown(animation, function () {
									this.style.display = "";
									t.trigger("after_open", { "node" : obj });
								});
					}
				}
				obj.state.opened = true;
				if(callback) {
					callback.call(this, obj, true);
				}
				if(!d.length) {
					/**
					 * triggered when a node is about to be opened (if the node is supposed to be in the DOM, it will be, but it won't be visible yet)
					 * @event
					 * @name before_open.jstree
					 * @param {Object} node the opened node
					 */
					this.trigger('before_open', { "node" : obj });
				}
				/**
				 * triggered when a node is opened (if there is an animation it will not be completed yet)
				 * @event
				 * @name open_node.jstree
				 * @param {Object} node the opened node
				 */
				this.trigger('open_node', { "node" : obj });
				if(!animation || !d.length) {
					/**
					 * triggered when a node is opened and the animation is complete
					 * @event
					 * @name after_open.jstree
					 * @param {Object} node the opened node
					 */
					this.trigger("after_open", { "node" : obj });
				}
			}
		},
		/**
		 * opens every parent of a node (node should be loaded)
		 * @name _open_to(obj)
		 * @param {mixed} obj the node to reveal
		 * @private
		 */
		_open_to : function (obj) {
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			var i, j, p = obj.parents;
			for(i = 0, j = p.length; i < j; i+=1) {
				if(i !== '#') {
					this.open_node(p[i], false, 0);
				}
			}
			return $('#' + obj.id.replace($.jstree.idregex,'\\$&'), this.element);
		},
		/**
		 * closes a node, hiding its children
		 * @name close_node(obj [, animation])
		 * @param {mixed} obj the node to close
		 * @param {Number} animation the animation duration in milliseconds when closing the node (overrides the `core.animation` setting). Use `false` for no animation.
		 * @trigger close_node.jstree, after_close.jstree
		 */
		close_node : function (obj, animation) {
			var t1, t2, t, d;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.close_node(obj[t1], animation);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			if(this.is_closed(obj)) {
				return false;
			}
			animation = animation === undefined ? this.settings.core.animation : animation;
			t = this;
			d = this.get_node(obj, true);
			if(d.length) {
				if(!animation) {
					d[0].className = d[0].className.replace('jstree-open', 'jstree-closed');
					d.attr("aria-expanded", false).children('.jstree-children').remove();
				}
				else {
					d
						.children(".jstree-children").attr("style","display:block !important").end()
						.removeClass("jstree-open").addClass("jstree-closed").attr("aria-expanded", false)
						.children(".jstree-children").stop(true, true).slideUp(animation, function () {
							this.style.display = "";
							d.children('.jstree-children').remove();
							t.trigger("after_close", { "node" : obj });
						});
				}
			}
			obj.state.opened = false;
			/**
			 * triggered when a node is closed (if there is an animation it will not be complete yet)
			 * @event
			 * @name close_node.jstree
			 * @param {Object} node the closed node
			 */
			this.trigger('close_node',{ "node" : obj });
			if(!animation || !d.length) {
				/**
				 * triggered when a node is closed and the animation is complete
				 * @event
				 * @name after_close.jstree
				 * @param {Object} node the closed node
				 */
				this.trigger("after_close", { "node" : obj });
			}
		},
		/**
		 * toggles a node - closing it if it is open, opening it if it is closed
		 * @name toggle_node(obj)
		 * @param {mixed} obj the node to toggle
		 */
		toggle_node : function (obj) {
			var t1, t2;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.toggle_node(obj[t1]);
				}
				return true;
			}
			if(this.is_closed(obj)) {
				return this.open_node(obj);
			}
			if(this.is_open(obj)) {
				return this.close_node(obj);
			}
		},
		/**
		 * opens all nodes within a node (or the tree), revaling their children. If the node is not loaded it will be loaded and opened once ready.
		 * @name open_all([obj, animation, original_obj])
		 * @param {mixed} obj the node to open recursively, omit to open all nodes in the tree
		 * @param {Number} animation the animation duration in milliseconds when opening the nodes, the default is no animation
		 * @param {jQuery} reference to the node that started the process (internal use)
		 * @trigger open_all.jstree
		 */
		open_all : function (obj, animation, original_obj) {
			if(!obj) { obj = '#'; }
			obj = this.get_node(obj);
			if(!obj) { return false; }
			var dom = obj.id === '#' ? this.get_container_ul() : this.get_node(obj, true), i, j, _this;
			if(!dom.length) {
				for(i = 0, j = obj.children_d.length; i < j; i++) {
					if(this.is_closed(this._model.data[obj.children_d[i]])) {
						this._model.data[obj.children_d[i]].state.opened = true;
					}
				}
				return this.trigger('open_all', { "node" : obj });
			}
			original_obj = original_obj || dom;
			_this = this;
			dom = this.is_closed(obj) ? dom.find('.jstree-closed').addBack() : dom.find('.jstree-closed');
			dom.each(function () {
				_this.open_node(
					this,
					function(node, status) { if(status && this.is_parent(node)) { this.open_all(node, animation, original_obj); } },
					animation || 0
				);
			});
			if(original_obj.find('.jstree-closed').length === 0) {
				/**
				 * triggered when an `open_all` call completes
				 * @event
				 * @name open_all.jstree
				 * @param {Object} node the opened node
				 */
				this.trigger('open_all', { "node" : this.get_node(original_obj) });
			}
		},
		/**
		 * closes all nodes within a node (or the tree), revaling their children
		 * @name close_all([obj, animation])
		 * @param {mixed} obj the node to close recursively, omit to close all nodes in the tree
		 * @param {Number} animation the animation duration in milliseconds when closing the nodes, the default is no animation
		 * @trigger close_all.jstree
		 */
		close_all : function (obj, animation) {
			if(!obj) { obj = '#'; }
			obj = this.get_node(obj);
			if(!obj) { return false; }
			var dom = obj.id === '#' ? this.get_container_ul() : this.get_node(obj, true),
				_this = this, i, j;
			if(!dom.length) {
				for(i = 0, j = obj.children_d.length; i < j; i++) {
					this._model.data[obj.children_d[i]].state.opened = false;
				}
				return this.trigger('close_all', { "node" : obj });
			}
			dom = this.is_open(obj) ? dom.find('.jstree-open').addBack() : dom.find('.jstree-open');
			$(dom.get().reverse()).each(function () { _this.close_node(this, animation || 0); });
			/**
			 * triggered when an `close_all` call completes
			 * @event
			 * @name close_all.jstree
			 * @param {Object} node the closed node
			 */
			this.trigger('close_all', { "node" : obj });
		},
		/**
		 * checks if a node is disabled (not selectable)
		 * @name is_disabled(obj)
		 * @param  {mixed} obj
		 * @return {Boolean}
		 */
		is_disabled : function (obj) {
			obj = this.get_node(obj);
			return obj && obj.state && obj.state.disabled;
		},
		/**
		 * enables a node - so that it can be selected
		 * @name enable_node(obj)
		 * @param {mixed} obj the node to enable
		 * @trigger enable_node.jstree
		 */
		enable_node : function (obj) {
			var t1, t2;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.enable_node(obj[t1]);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			obj.state.disabled = false;
			this.get_node(obj,true).children('.jstree-anchor').removeClass('jstree-disabled').attr('aria-disabled', false);
			/**
			 * triggered when an node is enabled
			 * @event
			 * @name enable_node.jstree
			 * @param {Object} node the enabled node
			 */
			this.trigger('enable_node', { 'node' : obj });
		},
		/**
		 * disables a node - so that it can not be selected
		 * @name disable_node(obj)
		 * @param {mixed} obj the node to disable
		 * @trigger disable_node.jstree
		 */
		disable_node : function (obj) {
			var t1, t2;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.disable_node(obj[t1]);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			obj.state.disabled = true;
			this.get_node(obj,true).children('.jstree-anchor').addClass('jstree-disabled').attr('aria-disabled', true);
			/**
			 * triggered when an node is disabled
			 * @event
			 * @name disable_node.jstree
			 * @param {Object} node the disabled node
			 */
			this.trigger('disable_node', { 'node' : obj });
		},
		/**
		 * called when a node is selected by the user. Used internally.
		 * @private
		 * @name activate_node(obj, e)
		 * @param {mixed} obj the node
		 * @param {Object} e the related event
		 * @trigger activate_node.jstree, changed.jstree
		 */
		activate_node : function (obj, e) {
			if(this.is_disabled(obj)) {
				return false;
			}

			// ensure last_clicked is still in the DOM, make it fresh (maybe it was moved?) and make sure it is still selected, if not - make last_clicked the last selected node
			this._data.core.last_clicked = this._data.core.last_clicked && this._data.core.last_clicked.id !== undefined ? this.get_node(this._data.core.last_clicked.id) : null;
			if(this._data.core.last_clicked && !this._data.core.last_clicked.state.selected) { this._data.core.last_clicked = null; }
			if(!this._data.core.last_clicked && this._data.core.selected.length) { this._data.core.last_clicked = this.get_node(this._data.core.selected[this._data.core.selected.length - 1]); }

			if(!this.settings.core.multiple || (!e.metaKey && !e.ctrlKey && !e.shiftKey) || (e.shiftKey && (!this._data.core.last_clicked || !this.get_parent(obj) || this.get_parent(obj) !== this._data.core.last_clicked.parent ) )) {
				if(!this.settings.core.multiple && (e.metaKey || e.ctrlKey || e.shiftKey) && this.is_selected(obj)) {
					this.deselect_node(obj, false, e);
				}
				else {
					this.deselect_all(true);
					this.select_node(obj, false, false, e);
					this._data.core.last_clicked = this.get_node(obj);
				}
			}
			else {
				if(e.shiftKey) {
					var o = this.get_node(obj).id,
						l = this._data.core.last_clicked.id,
						p = this.get_node(this._data.core.last_clicked.parent).children,
						c = false,
						i, j;
					for(i = 0, j = p.length; i < j; i += 1) {
						// separate IFs work whem o and l are the same
						if(p[i] === o) {
							c = !c;
						}
						if(p[i] === l) {
							c = !c;
						}
						if(c || p[i] === o || p[i] === l) {
							this.select_node(p[i], true, false, e);
						}
						else {
							this.deselect_node(p[i], true, e);
						}
					}
					this.trigger('changed', { 'action' : 'select_node', 'node' : this.get_node(obj), 'selected' : this._data.core.selected, 'event' : e });
				}
				else {
					if(!this.is_selected(obj)) {
						this.select_node(obj, false, false, e);
					}
					else {
						this.deselect_node(obj, false, e);
					}
				}
			}
			/**
			 * triggered when an node is clicked or intercated with by the user
			 * @event
			 * @name activate_node.jstree
			 * @param {Object} node
			 */
			this.trigger('activate_node', { 'node' : this.get_node(obj) });
		},
		/**
		 * applies the hover state on a node, called when a node is hovered by the user. Used internally.
		 * @private
		 * @name hover_node(obj)
		 * @param {mixed} obj
		 * @trigger hover_node.jstree
		 */
		hover_node : function (obj) {
			obj = this.get_node(obj, true);
			if(!obj || !obj.length || obj.children('.jstree-hovered').length) {
				return false;
			}
			var o = this.element.find('.jstree-hovered'), t = this.element;
			if(o && o.length) { this.dehover_node(o); }

			obj.children('.jstree-anchor').addClass('jstree-hovered');
			/**
			 * triggered when an node is hovered
			 * @event
			 * @name hover_node.jstree
			 * @param {Object} node
			 */
			this.trigger('hover_node', { 'node' : this.get_node(obj) });
			setTimeout(function () { t.attr('aria-activedescendant', obj[0].id); }, 0);
		},
		/**
		 * removes the hover state from a nodecalled when a node is no longer hovered by the user. Used internally.
		 * @private
		 * @name dehover_node(obj)
		 * @param {mixed} obj
		 * @trigger dehover_node.jstree
		 */
		dehover_node : function (obj) {
			obj = this.get_node(obj, true);
			if(!obj || !obj.length || !obj.children('.jstree-hovered').length) {
				return false;
			}
			obj.children('.jstree-anchor').removeClass('jstree-hovered');
			/**
			 * triggered when an node is no longer hovered
			 * @event
			 * @name dehover_node.jstree
			 * @param {Object} node
			 */
			this.trigger('dehover_node', { 'node' : this.get_node(obj) });
		},
		/**
		 * select a node
		 * @name select_node(obj [, supress_event, prevent_open])
		 * @param {mixed} obj an array can be used to select multiple nodes
		 * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered
		 * @param {Boolean} prevent_open if set to `true` parents of the selected node won't be opened
		 * @trigger select_node.jstree, changed.jstree
		 */
		select_node : function (obj, supress_event, prevent_open, e) {
			var dom, t1, t2, th;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.select_node(obj[t1], supress_event, prevent_open, e);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			dom = this.get_node(obj, true);
			if(!obj.state.selected) {
				obj.state.selected = true;
				this._data.core.selected.push(obj.id);
				if(!prevent_open) {
					dom = this._open_to(obj);
				}
				if(dom && dom.length) {
					dom.attr('aria-selected', true).children('.jstree-anchor').addClass('jstree-clicked');
				}
				/**
				 * triggered when an node is selected
				 * @event
				 * @name select_node.jstree
				 * @param {Object} node
				 * @param {Array} selected the current selection
				 * @param {Object} event the event (if any) that triggered this select_node
				 */
				this.trigger('select_node', { 'node' : obj, 'selected' : this._data.core.selected, 'event' : e });
				if(!supress_event) {
					/**
					 * triggered when selection changes
					 * @event
					 * @name changed.jstree
					 * @param {Object} node
					 * @param {Object} action the action that caused the selection to change
					 * @param {Array} selected the current selection
					 * @param {Object} event the event (if any) that triggered this changed event
					 */
					this.trigger('changed', { 'action' : 'select_node', 'node' : obj, 'selected' : this._data.core.selected, 'event' : e });
				}
			}
		},
		/**
		 * deselect a node
		 * @name deselect_node(obj [, supress_event])
		 * @param {mixed} obj an array can be used to deselect multiple nodes
		 * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered
		 * @trigger deselect_node.jstree, changed.jstree
		 */
		deselect_node : function (obj, supress_event, e) {
			var t1, t2, dom;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.deselect_node(obj[t1], supress_event, e);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			dom = this.get_node(obj, true);
			if(obj.state.selected) {
				obj.state.selected = false;
				this._data.core.selected = $.vakata.array_remove_item(this._data.core.selected, obj.id);
				if(dom.length) {
					dom.attr('aria-selected', false).children('.jstree-anchor').removeClass('jstree-clicked');
				}
				/**
				 * triggered when an node is deselected
				 * @event
				 * @name deselect_node.jstree
				 * @param {Object} node
				 * @param {Array} selected the current selection
				 * @param {Object} event the event (if any) that triggered this deselect_node
				 */
				this.trigger('deselect_node', { 'node' : obj, 'selected' : this._data.core.selected, 'event' : e });
				if(!supress_event) {
					this.trigger('changed', { 'action' : 'deselect_node', 'node' : obj, 'selected' : this._data.core.selected, 'event' : e });
				}
			}
		},
		/**
		 * select all nodes in the tree
		 * @name select_all([supress_event])
		 * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered
		 * @trigger select_all.jstree, changed.jstree
		 */
		select_all : function (supress_event) {
			var tmp = this._data.core.selected.concat([]), i, j;
			this._data.core.selected = this._model.data['#'].children_d.concat();
			for(i = 0, j = this._data.core.selected.length; i < j; i++) {
				if(this._model.data[this._data.core.selected[i]]) {
					this._model.data[this._data.core.selected[i]].state.selected = true;
				}
			}
			this.redraw(true);
			/**
			 * triggered when all nodes are selected
			 * @event
			 * @name select_all.jstree
			 * @param {Array} selected the current selection
			 */
			this.trigger('select_all', { 'selected' : this._data.core.selected });
			if(!supress_event) {
				this.trigger('changed', { 'action' : 'select_all', 'selected' : this._data.core.selected, 'old_selection' : tmp });
			}
		},
		/**
		 * deselect all selected nodes
		 * @name deselect_all([supress_event])
		 * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered
		 * @trigger deselect_all.jstree, changed.jstree
		 */
		deselect_all : function (supress_event) {
			var tmp = this._data.core.selected.concat([]), i, j;
			for(i = 0, j = this._data.core.selected.length; i < j; i++) {
				if(this._model.data[this._data.core.selected[i]]) {
					this._model.data[this._data.core.selected[i]].state.selected = false;
				}
			}
			this._data.core.selected = [];
			this.element.find('.jstree-clicked').removeClass('jstree-clicked').parent().attr('aria-selected', false);
			/**
			 * triggered when all nodes are deselected
			 * @event
			 * @name deselect_all.jstree
			 * @param {Object} node the previous selection
			 * @param {Array} selected the current selection
			 */
			this.trigger('deselect_all', { 'selected' : this._data.core.selected, 'node' : tmp });
			if(!supress_event) {
				this.trigger('changed', { 'action' : 'deselect_all', 'selected' : this._data.core.selected, 'old_selection' : tmp });
			}
		},
		/**
		 * checks if a node is selected
		 * @name is_selected(obj)
		 * @param  {mixed}  obj
		 * @return {Boolean}
		 */
		is_selected : function (obj) {
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			return obj.state.selected;
		},
		/**
		 * get an array of all selected nodes
		 * @name get_selected([full])
		 * @param  {mixed}  full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
		 * @return {Array}
		 */
		get_selected : function (full) {
			return full ? $.map(this._data.core.selected, $.proxy(function (i) { return this.get_node(i); }, this)) : this._data.core.selected.slice();
		},
		/**
		 * get an array of all top level selected nodes (ignoring children of selected nodes)
		 * @name get_top_selected([full])
		 * @param  {mixed}  full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
		 * @return {Array}
		 */
		get_top_selected : function (full) {
			var tmp = this.get_selected(true),
				obj = {}, i, j, k, l;
			for(i = 0, j = tmp.length; i < j; i++) {
				obj[tmp[i].id] = tmp[i];
			}
			for(i = 0, j = tmp.length; i < j; i++) {
				for(k = 0, l = tmp[i].children_d.length; k < l; k++) {
					if(obj[tmp[i].children_d[k]]) {
						delete obj[tmp[i].children_d[k]];
					}
				}
			}
			tmp = [];
			for(i in obj) {
				if(obj.hasOwnProperty(i)) {
					tmp.push(i);
				}
			}
			return full ? $.map(tmp, $.proxy(function (i) { return this.get_node(i); }, this)) : tmp;
		},
		/**
		 * get an array of all bottom level selected nodes (ignoring selected parents)
		 * @name get_bottom_selected([full])
		 * @param  {mixed}  full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
		 * @return {Array}
		 */
		get_bottom_selected : function (full) {
			var tmp = this.get_selected(true),
				obj = [], i, j;
			for(i = 0, j = tmp.length; i < j; i++) {
				if(!tmp[i].children.length) {
					obj.push(tmp[i].id);
				}
			}
			return full ? $.map(obj, $.proxy(function (i) { return this.get_node(i); }, this)) : obj;
		},
		/**
		 * gets the current state of the tree so that it can be restored later with `set_state(state)`. Used internally.
		 * @name get_state()
		 * @private
		 * @return {Object}
		 */
		get_state : function () {
			var state	= {
				'core' : {
					'open' : [],
					'scroll' : {
						'left' : this.element.scrollLeft(),
						'top' : this.element.scrollTop()
					},
					/*!
					'themes' : {
						'name' : this.get_theme(),
						'icons' : this._data.core.themes.icons,
						'dots' : this._data.core.themes.dots
					},
					*/
					'selected' : []
				}
			}, i;
			for(i in this._model.data) {
				if(this._model.data.hasOwnProperty(i)) {
					if(i !== '#') {
						if(this._model.data[i].state.opened) {
							state.core.open.push(i);
						}
						if(this._model.data[i].state.selected) {
							state.core.selected.push(i);
						}
					}
				}
			}
			return state;
		},
		/**
		 * sets the state of the tree. Used internally.
		 * @name set_state(state [, callback])
		 * @private
		 * @param {Object} state the state to restore
		 * @param {Function} callback an optional function to execute once the state is restored.
		 * @trigger set_state.jstree
		 */
		set_state : function (state, callback) {
			if(state) {
				if(state.core) {
					var res, n, t, _this;
					if(state.core.open) {
						if(!$.isArray(state.core.open)) {
							delete state.core.open;
							this.set_state(state, callback);
							return false;
						}
						res = true;
						n = false;
						t = this;
						$.each(state.core.open.concat([]), function (i, v) {
							n = t.get_node(v);
							if(n) {
								if(t.is_loaded(v)) {
									if(t.is_closed(v)) {
										t.open_node(v, false, 0);
									}
									if(state && state.core && state.core.open) {
										$.vakata.array_remove_item(state.core.open, v);
									}
								}
								else {
									if(!t.is_loading(v)) {
										t.open_node(v, $.proxy(function (o, s) {
											if(!s && state && state.core && state.core.open) {
												$.vakata.array_remove_item(state.core.open, o.id);
											}
											this.set_state(state, callback);
										}, t), 0);
									}
									// there will be some async activity - so wait for it
									res = false;
								}
							}
						});
						if(res) {
							delete state.core.open;
							this.set_state(state, callback);
						}
						return false;
					}
					if(state.core.scroll) {
						if(state.core.scroll && state.core.scroll.left !== undefined) {
							this.element.scrollLeft(state.core.scroll.left);
						}
						if(state.core.scroll && state.core.scroll.top !== undefined) {
							this.element.scrollTop(state.core.scroll.top);
						}
						delete state.core.scroll;
						this.set_state(state, callback);
						return false;
					}
					/*!
					if(state.core.themes) {
						if(state.core.themes.name) {
							this.set_theme(state.core.themes.name);
						}
						if(typeof state.core.themes.dots !== 'undefined') {
							this[ state.core.themes.dots ? "show_dots" : "hide_dots" ]();
						}
						if(typeof state.core.themes.icons !== 'undefined') {
							this[ state.core.themes.icons ? "show_icons" : "hide_icons" ]();
						}
						delete state.core.themes;
						delete state.core.open;
						this.set_state(state, callback);
						return false;
					}
					*/
					if(state.core.selected) {
						_this = this;
						this.deselect_all();
						$.each(state.core.selected, function (i, v) {
							_this.select_node(v);
						});
						delete state.core.selected;
						this.set_state(state, callback);
						return false;
					}
					if($.isEmptyObject(state.core)) {
						delete state.core;
						this.set_state(state, callback);
						return false;
					}
				}
				if($.isEmptyObject(state)) {
					state = null;
					if(callback) { callback.call(this); }
					/**
					 * triggered when a `set_state` call completes
					 * @event
					 * @name set_state.jstree
					 */
					this.trigger('set_state');
					return false;
				}
				return true;
			}
			return false;
		},
		/**
		 * refreshes the tree - all nodes are reloaded with calls to `load_node`.
		 * @name refresh()
		 * @param {Boolean} skip_loading an option to skip showing the loading indicator
		 * @param {Mixed} forget_state if set to `true` state will not be reapplied, if set to a function (receiving the current state as argument) the result of that function will be used as state
		 * @trigger refresh.jstree
		 */
		refresh : function (skip_loading, forget_state) {
			this._data.core.state = forget_state === true ? {} : this.get_state();
			if(forget_state && $.isFunction(forget_state)) { this._data.core.state = forget_state.call(this, this._data.core.state); }
			this._cnt = 0;
			this._model.data = {
				'#' : {
					id : '#',
					parent : null,
					parents : [],
					children : [],
					children_d : [],
					state : { loaded : false }
				}
			};
			var c = this.get_container_ul()[0].className;
			if(!skip_loading) {
				this.element.html("<"+"ul class='"+c+"' role='group'><"+"li class='jstree-initial-node jstree-loading jstree-leaf jstree-last' role='treeitem' id='j"+this._id+"_loading'><i class='jstree-icon jstree-ocl'></i><"+"a class='jstree-anchor' href='#'><i class='jstree-icon jstree-themeicon-hidden'></i>" + this.get_string("Loading ...") + "</a></li></ul>");
				this.element.attr('aria-activedescendant','j'+this._id+'_loading');
			}
			this.load_node('#', function (o, s) {
				if(s) {
					this.get_container_ul()[0].className = c;
					if(this._firstChild(this.get_container_ul()[0])) {
						this.element.attr('aria-activedescendant',this._firstChild(this.get_container_ul()[0]).id);
					}
					this.set_state($.extend(true, {}, this._data.core.state), function () {
						/**
						 * triggered when a `refresh` call completes
						 * @event
						 * @name refresh.jstree
						 */
						this.trigger('refresh');
					});
				}
				this._data.core.state = null;
			});
		},
		/**
		 * refreshes a node in the tree (reload its children) all opened nodes inside that node are reloaded with calls to `load_node`.
		 * @name refresh_node(obj)
		 * @param  {mixed} obj the node
		 * @trigger refresh_node.jstree
		 */
		refresh_node : function (obj) {
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			var opened = [], to_load = [], s = this._data.core.selected.concat([]);
			to_load.push(obj.id);
			if(obj.state.opened === true) { opened.push(obj.id); }
			this.get_node(obj, true).find('.jstree-open').each(function() { opened.push(this.id); });
			this._load_nodes(to_load, $.proxy(function (nodes) {
				this.open_node(opened, false, 0);
				this.select_node(this._data.core.selected);
				/**
				 * triggered when a node is refreshed
				 * @event
				 * @name refresh_node.jstree
				 * @param {Object} node - the refreshed node
				 * @param {Array} nodes - an array of the IDs of the nodes that were reloaded
				 */
				this.trigger('refresh_node', { 'node' : obj, 'nodes' : nodes });
			}, this));
		},
		/**
		 * set (change) the ID of a node
		 * @name set_id(obj, id)
		 * @param  {mixed} obj the node
		 * @param  {String} id the new ID
		 * @return {Boolean}
		 */
		set_id : function (obj, id) {
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			var i, j, m = this._model.data;
			id = id.toString();
			// update parents (replace current ID with new one in children and children_d)
			m[obj.parent].children[$.inArray(obj.id, m[obj.parent].children)] = id;
			for(i = 0, j = obj.parents.length; i < j; i++) {
				m[obj.parents[i]].children_d[$.inArray(obj.id, m[obj.parents[i]].children_d)] = id;
			}
			// update children (replace current ID with new one in parent and parents)
			for(i = 0, j = obj.children.length; i < j; i++) {
				m[obj.children[i]].parent = id;
			}
			for(i = 0, j = obj.children_d.length; i < j; i++) {
				m[obj.children_d[i]].parents[$.inArray(obj.id, m[obj.children_d[i]].parents)] = id;
			}
			i = $.inArray(obj.id, this._data.core.selected);
			if(i !== -1) { this._data.core.selected[i] = id; }
			// update model and obj itself (obj.id, this._model.data[KEY])
			i = this.get_node(obj.id, true);
			if(i) {
				i.attr('id', id);
			}
			delete m[obj.id];
			obj.id = id;
			m[id] = obj;
			return true;
		},
		/**
		 * get the text value of a node
		 * @name get_text(obj)
		 * @param  {mixed} obj the node
		 * @return {String}
		 */
		get_text : function (obj) {
			obj = this.get_node(obj);
			return (!obj || obj.id === '#') ? false : obj.text;
		},
		/**
		 * set the text value of a node. Used internally, please use `rename_node(obj, val)`.
		 * @private
		 * @name set_text(obj, val)
		 * @param  {mixed} obj the node, you can pass an array to set the text on multiple nodes
		 * @param  {String} val the new text value
		 * @return {Boolean}
		 * @trigger set_text.jstree
		 */
		set_text : function (obj, val) {
			var t1, t2;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.set_text(obj[t1], val);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			obj.text = val;
			if(this.get_node(obj, true).length) {
				this.redraw_node(obj.id);
			}
			/**
			 * triggered when a node text value is changed
			 * @event
			 * @name set_text.jstree
			 * @param {Object} obj
			 * @param {String} text the new value
			 */
			this.trigger('set_text',{ "obj" : obj, "text" : val });
			return true;
		},
		/**
		 * gets a JSON representation of a node (or the whole tree)
		 * @name get_json([obj, options])
		 * @param  {mixed} obj
		 * @param  {Object} options
		 * @param  {Boolean} options.no_state do not return state information
		 * @param  {Boolean} options.no_id do not return ID
		 * @param  {Boolean} options.no_children do not include children
		 * @param  {Boolean} options.no_data do not include node data
		 * @param  {Boolean} options.flat return flat JSON instead of nested
		 * @return {Object}
		 */
		get_json : function (obj, options, flat) {
			obj = this.get_node(obj || '#');
			if(!obj) { return false; }
			if(options && options.flat && !flat) { flat = []; }
			var tmp = {
				'id' : obj.id,
				'text' : obj.text,
				'icon' : this.get_icon(obj),
				'li_attr' : $.extend(true, {}, obj.li_attr),
				'a_attr' : $.extend(true, {}, obj.a_attr),
				'state' : {},
				'data' : options && options.no_data ? false : $.extend(true, {}, obj.data)
				//( this.get_node(obj, true).length ? this.get_node(obj, true).data() : obj.data ),
			}, i, j;
			if(options && options.flat) {
				tmp.parent = obj.parent;
			}
			else {
				tmp.children = [];
			}
			if(!options || !options.no_state) {
				for(i in obj.state) {
					if(obj.state.hasOwnProperty(i)) {
						tmp.state[i] = obj.state[i];
					}
				}
			}
			if(options && options.no_id) {
				delete tmp.id;
				if(tmp.li_attr && tmp.li_attr.id) {
					delete tmp.li_attr.id;
				}
				if(tmp.a_attr && tmp.a_attr.id) {
					delete tmp.a_attr.id;
				}
			}
			if(options && options.flat && obj.id !== '#') {
				flat.push(tmp);
			}
			if(!options || !options.no_children) {
				for(i = 0, j = obj.children.length; i < j; i++) {
					if(options && options.flat) {
						this.get_json(obj.children[i], options, flat);
					}
					else {
						tmp.children.push(this.get_json(obj.children[i], options));
					}
				}
			}
			return options && options.flat ? flat : (obj.id === '#' ? tmp.children : tmp);
		},
		/**
		 * create a new node (do not confuse with load_node)
		 * @name create_node([obj, node, pos, callback, is_loaded])
		 * @param  {mixed}   par       the parent node (to create a root node use either "#" (string) or `null`)
		 * @param  {mixed}   node      the data for the new node (a valid JSON object, or a simple string with the name)
		 * @param  {mixed}   pos       the index at which to insert the node, "first" and "last" are also supported, default is "last"
		 * @param  {Function} callback a function to be called once the node is created
		 * @param  {Boolean} is_loaded internal argument indicating if the parent node was succesfully loaded
		 * @return {String}            the ID of the newly create node
		 * @trigger model.jstree, create_node.jstree
		 */
		create_node : function (par, node, pos, callback, is_loaded) {
			if(par === null) { par = "#"; }
			par = this.get_node(par);
			if(!par) { return false; }
			pos = pos === undefined ? "last" : pos;
			if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {
				return this.load_node(par, function () { this.create_node(par, node, pos, callback, true); });
			}
			if(!node) { node = { "text" : this.get_string('New node') }; }
			if(typeof node === "string") { node = { "text" : node }; }
			if(node.text === undefined) { node.text = this.get_string('New node'); }
			var tmp, dpc, i, j;

			if(par.id === '#') {
				if(pos === "before") { pos = "first"; }
				if(pos === "after") { pos = "last"; }
			}
			switch(pos) {
				case "before":
					tmp = this.get_node(par.parent);
					pos = $.inArray(par.id, tmp.children);
					par = tmp;
					break;
				case "after" :
					tmp = this.get_node(par.parent);
					pos = $.inArray(par.id, tmp.children) + 1;
					par = tmp;
					break;
				case "inside":
				case "first":
					pos = 0;
					break;
				case "last":
					pos = par.children.length;
					break;
				default:
					if(!pos) { pos = 0; }
					break;
			}
			if(pos > par.children.length) { pos = par.children.length; }
			if(!node.id) { node.id = true; }
			if(!this.check("create_node", node, par, pos)) {
				this.settings.core.error.call(this, this._data.core.last_error);
				return false;
			}
			if(node.id === true) { delete node.id; }
			node = this._parse_model_from_json(node, par.id, par.parents.concat());
			if(!node) { return false; }
			tmp = this.get_node(node);
			dpc = [];
			dpc.push(node);
			dpc = dpc.concat(tmp.children_d);
			this.trigger('model', { "nodes" : dpc, "parent" : par.id });

			par.children_d = par.children_d.concat(dpc);
			for(i = 0, j = par.parents.length; i < j; i++) {
				this._model.data[par.parents[i]].children_d = this._model.data[par.parents[i]].children_d.concat(dpc);
			}
			node = tmp;
			tmp = [];
			for(i = 0, j = par.children.length; i < j; i++) {
				tmp[i >= pos ? i+1 : i] = par.children[i];
			}
			tmp[pos] = node.id;
			par.children = tmp;

			this.redraw_node(par, true);
			if(callback) { callback.call(this, this.get_node(node)); }
			/**
			 * triggered when a node is created
			 * @event
			 * @name create_node.jstree
			 * @param {Object} node
			 * @param {String} parent the parent's ID
			 * @param {Number} position the position of the new node among the parent's children
			 */
			this.trigger('create_node', { "node" : this.get_node(node), "parent" : par.id, "position" : pos });
			return node.id;
		},
		/**
		 * set the text value of a node
		 * @name rename_node(obj, val)
		 * @param  {mixed} obj the node, you can pass an array to rename multiple nodes to the same name
		 * @param  {String} val the new text value
		 * @return {Boolean}
		 * @trigger rename_node.jstree
		 */
		rename_node : function (obj, val) {
			var t1, t2, old;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.rename_node(obj[t1], val);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			old = obj.text;
			if(!this.check("rename_node", obj, this.get_parent(obj), val)) {
				this.settings.core.error.call(this, this._data.core.last_error);
				return false;
			}
			this.set_text(obj, val); // .apply(this, Array.prototype.slice.call(arguments))
			/**
			 * triggered when a node is renamed
			 * @event
			 * @name rename_node.jstree
			 * @param {Object} node
			 * @param {String} text the new value
			 * @param {String} old the old value
			 */
			this.trigger('rename_node', { "node" : obj, "text" : val, "old" : old });
			return true;
		},
		/**
		 * remove a node
		 * @name delete_node(obj)
		 * @param  {mixed} obj the node, you can pass an array to delete multiple nodes
		 * @return {Boolean}
		 * @trigger delete_node.jstree, changed.jstree
		 */
		delete_node : function (obj) {
			var t1, t2, par, pos, tmp, i, j, k, l, c;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.delete_node(obj[t1]);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			par = this.get_node(obj.parent);
			pos = $.inArray(obj.id, par.children);
			c = false;
			if(!this.check("delete_node", obj, par, pos)) {
				this.settings.core.error.call(this, this._data.core.last_error);
				return false;
			}
			if(pos !== -1) {
				par.children = $.vakata.array_remove(par.children, pos);
			}
			tmp = obj.children_d.concat([]);
			tmp.push(obj.id);
			for(k = 0, l = tmp.length; k < l; k++) {
				for(i = 0, j = obj.parents.length; i < j; i++) {
					pos = $.inArray(tmp[k], this._model.data[obj.parents[i]].children_d);
					if(pos !== -1) {
						this._model.data[obj.parents[i]].children_d = $.vakata.array_remove(this._model.data[obj.parents[i]].children_d, pos);
					}
				}
				if(this._model.data[tmp[k]].state.selected) {
					c = true;
					pos = $.inArray(tmp[k], this._data.core.selected);
					if(pos !== -1) {
						this._data.core.selected = $.vakata.array_remove(this._data.core.selected, pos);
					}
				}
			}
			/**
			 * triggered when a node is deleted
			 * @event
			 * @name delete_node.jstree
			 * @param {Object} node
			 * @param {String} parent the parent's ID
			 */
			this.trigger('delete_node', { "node" : obj, "parent" : par.id });
			if(c) {
				this.trigger('changed', { 'action' : 'delete_node', 'node' : obj, 'selected' : this._data.core.selected, 'parent' : par.id });
			}
			for(k = 0, l = tmp.length; k < l; k++) {
				delete this._model.data[tmp[k]];
			}
			this.redraw_node(par, true);
			return true;
		},
		/**
		 * check if an operation is premitted on the tree. Used internally.
		 * @private
		 * @name check(chk, obj, par, pos)
		 * @param  {String} chk the operation to check, can be "create_node", "rename_node", "delete_node", "copy_node" or "move_node"
		 * @param  {mixed} obj the node
		 * @param  {mixed} par the parent
		 * @param  {mixed} pos the position to insert at, or if "rename_node" - the new name
		 * @param  {mixed} more some various additional information, for example if a "move_node" operations is triggered by DND this will be the hovered node
		 * @return {Boolean}
		 */
		check : function (chk, obj, par, pos, more) {
			obj = obj && obj.id ? obj : this.get_node(obj);
			par = par && par.id ? par : this.get_node(par);
			var tmp = chk.match(/^move_node|copy_node|create_node$/i) ? par : obj,
				chc = this.settings.core.check_callback;
			if(chk === "move_node" || chk === "copy_node") {
				if((!more || !more.is_multi) && (obj.id === par.id || $.inArray(obj.id, par.children) === pos || $.inArray(par.id, obj.children_d) !== -1)) {
					this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_01', 'reason' : 'Moving parent inside child', 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
					return false;
				}
			}
			if(tmp && tmp.data) { tmp = tmp.data; }
			if(tmp && tmp.functions && (tmp.functions[chk] === false || tmp.functions[chk] === true)) {
				if(tmp.functions[chk] === false) {
					this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_02', 'reason' : 'Node data prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
				}
				return tmp.functions[chk];
			}
			if(chc === false || ($.isFunction(chc) && chc.call(this, chk, obj, par, pos, more) === false) || (chc && chc[chk] === false)) {
				this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_03', 'reason' : 'User config for core.check_callback prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
				return false;
			}
			return true;
		},
		/**
		 * get the last error
		 * @name last_error()
		 * @return {Object}
		 */
		last_error : function () {
			return this._data.core.last_error;
		},
		/**
		 * move a node to a new parent
		 * @name move_node(obj, par [, pos, callback, is_loaded])
		 * @param  {mixed} obj the node to move, pass an array to move multiple nodes
		 * @param  {mixed} par the new parent
		 * @param  {mixed} pos the position to insert at (besides integer values, "first" and "last" are supported, as well as "before" and "after"), defaults to integer `0`
		 * @param  {function} callback a function to call once the move is completed, receives 3 arguments - the node, the new parent and the position
		 * @param  {Boolean} internal parameter indicating if the parent node has been loaded
		 * @param  {Boolean} internal parameter indicating if the tree should be redrawn
		 * @trigger move_node.jstree
		 */
		move_node : function (obj, par, pos, callback, is_loaded, skip_redraw) {
			var t1, t2, old_par, old_pos, new_par, old_ins, is_multi, dpc, tmp, i, j, k, l, p;

			par = this.get_node(par);
			pos = pos === undefined ? 0 : pos;
			if(!par) { return false; }
			if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {
				return this.load_node(par, function () { this.move_node(obj, par, pos, callback, true); });
			}

			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					if(this.move_node(obj[t1], par, pos, callback, is_loaded, true)) {
						par = obj[t1];
						pos = "after";
					}
				}
				this.redraw();
				return true;
			}
			obj = obj && obj.id ? obj : this.get_node(obj);

			if(!obj || obj.id === '#') { return false; }

			old_par = (obj.parent || '#').toString();
			new_par = (!pos.toString().match(/^(before|after)$/) || par.id === '#') ? par : this.get_node(par.parent);
			old_ins = obj.instance ? obj.instance : (this._model.data[obj.id] ? this : $.jstree.reference(obj.id));
			is_multi = !old_ins || !old_ins._id || (this._id !== old_ins._id);
			old_pos = old_ins && old_ins._id && old_par && old_ins._model.data[old_par] && old_ins._model.data[old_par].children ? $.inArray(obj.id, old_ins._model.data[old_par].children) : -1;
			if(is_multi) {
				if(this.copy_node(obj, par, pos, callback, is_loaded)) {
					if(old_ins) { old_ins.delete_node(obj); }
					return true;
				}
				return false;
			}
			//var m = this._model.data;
			if(par.id === '#') {
				if(pos === "before") { pos = "first"; }
				if(pos === "after") { pos = "last"; }
			}
			switch(pos) {
				case "before":
					pos = $.inArray(par.id, new_par.children);
					break;
				case "after" :
					pos = $.inArray(par.id, new_par.children) + 1;
					break;
				case "inside":
				case "first":
					pos = 0;
					break;
				case "last":
					pos = new_par.children.length;
					break;
				default:
					if(!pos) { pos = 0; }
					break;
			}
			if(pos > new_par.children.length) { pos = new_par.children.length; }
			if(!this.check("move_node", obj, new_par, pos, { 'core' : true, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id) })) {
				this.settings.core.error.call(this, this._data.core.last_error);
				return false;
			}
			if(obj.parent === new_par.id) {
				dpc = new_par.children.concat();
				tmp = $.inArray(obj.id, dpc);
				if(tmp !== -1) {
					dpc = $.vakata.array_remove(dpc, tmp);
					if(pos > tmp) { pos--; }
				}
				tmp = [];
				for(i = 0, j = dpc.length; i < j; i++) {
					tmp[i >= pos ? i+1 : i] = dpc[i];
				}
				tmp[pos] = obj.id;
				new_par.children = tmp;
				this._node_changed(new_par.id);
				this.redraw(new_par.id === '#');
			}
			else {
				// clean old parent and up
				tmp = obj.children_d.concat();
				tmp.push(obj.id);
				for(i = 0, j = obj.parents.length; i < j; i++) {
					dpc = [];
					p = old_ins._model.data[obj.parents[i]].children_d;
					for(k = 0, l = p.length; k < l; k++) {
						if($.inArray(p[k], tmp) === -1) {
							dpc.push(p[k]);
						}
					}
					old_ins._model.data[obj.parents[i]].children_d = dpc;
				}
				old_ins._model.data[old_par].children = $.vakata.array_remove_item(old_ins._model.data[old_par].children, obj.id);

				// insert into new parent and up
				for(i = 0, j = new_par.parents.length; i < j; i++) {
					this._model.data[new_par.parents[i]].children_d = this._model.data[new_par.parents[i]].children_d.concat(tmp);
				}
				dpc = [];
				for(i = 0, j = new_par.children.length; i < j; i++) {
					dpc[i >= pos ? i+1 : i] = new_par.children[i];
				}
				dpc[pos] = obj.id;
				new_par.children = dpc;
				new_par.children_d.push(obj.id);
				new_par.children_d = new_par.children_d.concat(obj.children_d);

				// update object
				obj.parent = new_par.id;
				tmp = new_par.parents.concat();
				tmp.unshift(new_par.id);
				p = obj.parents.length;
				obj.parents = tmp;

				// update object children
				tmp = tmp.concat();
				for(i = 0, j = obj.children_d.length; i < j; i++) {
					this._model.data[obj.children_d[i]].parents = this._model.data[obj.children_d[i]].parents.slice(0,p*-1);
					Array.prototype.push.apply(this._model.data[obj.children_d[i]].parents, tmp);
				}

				if(old_par === '#' || new_par.id === '#') {
					this._model.force_full_redraw = true;
				}
				if(!this._model.force_full_redraw) {
					this._node_changed(old_par);
					this._node_changed(new_par.id);
				}
				if(!skip_redraw) {
					this.redraw();
				}
			}
			if(callback) { callback.call(this, obj, new_par, pos); }
			/**
			 * triggered when a node is moved
			 * @event
			 * @name move_node.jstree
			 * @param {Object} node
			 * @param {String} parent the parent's ID
			 * @param {Number} position the position of the node among the parent's children
			 * @param {String} old_parent the old parent of the node
			 * @param {Number} old_position the old position of the node
			 * @param {Boolean} is_multi do the node and new parent belong to different instances
			 * @param {jsTree} old_instance the instance the node came from
			 * @param {jsTree} new_instance the instance of the new parent
			 */
			this.trigger('move_node', { "node" : obj, "parent" : new_par.id, "position" : pos, "old_parent" : old_par, "old_position" : old_pos, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id), 'old_instance' : old_ins, 'new_instance' : this });
			return true;
		},
		/**
		 * copy a node to a new parent
		 * @name copy_node(obj, par [, pos, callback, is_loaded])
		 * @param  {mixed} obj the node to copy, pass an array to copy multiple nodes
		 * @param  {mixed} par the new parent
		 * @param  {mixed} pos the position to insert at (besides integer values, "first" and "last" are supported, as well as "before" and "after"), defaults to integer `0`
		 * @param  {function} callback a function to call once the move is completed, receives 3 arguments - the node, the new parent and the position
		 * @param  {Boolean} internal parameter indicating if the parent node has been loaded
		 * @param  {Boolean} internal parameter indicating if the tree should be redrawn
		 * @trigger model.jstree copy_node.jstree
		 */
		copy_node : function (obj, par, pos, callback, is_loaded, skip_redraw) {
			var t1, t2, dpc, tmp, i, j, node, old_par, new_par, old_ins, is_multi;

			par = this.get_node(par);
			pos = pos === undefined ? 0 : pos;
			if(!par) { return false; }
			if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {
				return this.load_node(par, function () { this.copy_node(obj, par, pos, callback, true); });
			}

			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					tmp = this.copy_node(obj[t1], par, pos, callback, is_loaded, true);
					if(tmp) {
						par = tmp;
						pos = "after";
					}
				}
				this.redraw();
				return true;
			}
			obj = obj && obj.id ? obj : this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }

			old_par = (obj.parent || '#').toString();
			new_par = (!pos.toString().match(/^(before|after)$/) || par.id === '#') ? par : this.get_node(par.parent);
			old_ins = obj.instance ? obj.instance : (this._model.data[obj.id] ? this : $.jstree.reference(obj.id));
			is_multi = !old_ins || !old_ins._id || (this._id !== old_ins._id);
			if(par.id === '#') {
				if(pos === "before") { pos = "first"; }
				if(pos === "after") { pos = "last"; }
			}
			switch(pos) {
				case "before":
					pos = $.inArray(par.id, new_par.children);
					break;
				case "after" :
					pos = $.inArray(par.id, new_par.children) + 1;
					break;
				case "inside":
				case "first":
					pos = 0;
					break;
				case "last":
					pos = new_par.children.length;
					break;
				default:
					if(!pos) { pos = 0; }
					break;
			}
			if(pos > new_par.children.length) { pos = new_par.children.length; }
			if(!this.check("copy_node", obj, new_par, pos, { 'core' : true, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id) })) {
				this.settings.core.error.call(this, this._data.core.last_error);
				return false;
			}
			node = old_ins ? old_ins.get_json(obj, { no_id : true, no_data : true, no_state : true }) : obj;
			if(!node) { return false; }
			if(node.id === true) { delete node.id; }
			node = this._parse_model_from_json(node, new_par.id, new_par.parents.concat());
			if(!node) { return false; }
			tmp = this.get_node(node);
			if(obj && obj.state && obj.state.loaded === false) { tmp.state.loaded = false; }
			dpc = [];
			dpc.push(node);
			dpc = dpc.concat(tmp.children_d);
			this.trigger('model', { "nodes" : dpc, "parent" : new_par.id });

			// insert into new parent and up
			for(i = 0, j = new_par.parents.length; i < j; i++) {
				this._model.data[new_par.parents[i]].children_d = this._model.data[new_par.parents[i]].children_d.concat(dpc);
			}
			dpc = [];
			for(i = 0, j = new_par.children.length; i < j; i++) {
				dpc[i >= pos ? i+1 : i] = new_par.children[i];
			}
			dpc[pos] = tmp.id;
			new_par.children = dpc;
			new_par.children_d.push(tmp.id);
			new_par.children_d = new_par.children_d.concat(tmp.children_d);

			if(new_par.id === '#') {
				this._model.force_full_redraw = true;
			}
			if(!this._model.force_full_redraw) {
				this._node_changed(new_par.id);
			}
			if(!skip_redraw) {
				this.redraw(new_par.id === '#');
			}
			if(callback) { callback.call(this, tmp, new_par, pos); }
			/**
			 * triggered when a node is copied
			 * @event
			 * @name copy_node.jstree
			 * @param {Object} node the copied node
			 * @param {Object} original the original node
			 * @param {String} parent the parent's ID
			 * @param {Number} position the position of the node among the parent's children
			 * @param {String} old_parent the old parent of the node
			 * @param {Number} old_position the position of the original node
			 * @param {Boolean} is_multi do the node and new parent belong to different instances
			 * @param {jsTree} old_instance the instance the node came from
			 * @param {jsTree} new_instance the instance of the new parent
			 */
			this.trigger('copy_node', { "node" : tmp, "original" : obj, "parent" : new_par.id, "position" : pos, "old_parent" : old_par, "old_position" : old_ins && old_ins._id && old_par && old_ins._model.data[old_par] && old_ins._model.data[old_par].children ? $.inArray(obj.id, old_ins._model.data[old_par].children) : -1,'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id), 'old_instance' : old_ins, 'new_instance' : this });
			return tmp.id;
		},
		/**
		 * cut a node (a later call to `paste(obj)` would move the node)
		 * @name cut(obj)
		 * @param  {mixed} obj multiple objects can be passed using an array
		 * @trigger cut.jstree
		 */
		cut : function (obj) {
			if(!obj) { obj = this._data.core.selected.concat(); }
			if(!$.isArray(obj)) { obj = [obj]; }
			if(!obj.length) { return false; }
			var tmp = [], o, t1, t2;
			for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
				o = this.get_node(obj[t1]);
				if(o && o.id && o.id !== '#') { tmp.push(o); }
			}
			if(!tmp.length) { return false; }
			ccp_node = tmp;
			ccp_inst = this;
			ccp_mode = 'move_node';
			/**
			 * triggered when nodes are added to the buffer for moving
			 * @event
			 * @name cut.jstree
			 * @param {Array} node
			 */
			this.trigger('cut', { "node" : obj });
		},
		/**
		 * copy a node (a later call to `paste(obj)` would copy the node)
		 * @name copy(obj)
		 * @param  {mixed} obj multiple objects can be passed using an array
		 * @trigger copy.jstre
		 */
		copy : function (obj) {
			if(!obj) { obj = this._data.core.selected.concat(); }
			if(!$.isArray(obj)) { obj = [obj]; }
			if(!obj.length) { return false; }
			var tmp = [], o, t1, t2;
			for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
				o = this.get_node(obj[t1]);
				if(o && o.id && o.id !== '#') { tmp.push(o); }
			}
			if(!tmp.length) { return false; }
			ccp_node = tmp;
			ccp_inst = this;
			ccp_mode = 'copy_node';
			/**
			 * triggered when nodes are added to the buffer for copying
			 * @event
			 * @name copy.jstree
			 * @param {Array} node
			 */
			this.trigger('copy', { "node" : obj });
		},
		/**
		 * get the current buffer (any nodes that are waiting for a paste operation)
		 * @name get_buffer()
		 * @return {Object} an object consisting of `mode` ("copy_node" or "move_node"), `node` (an array of objects) and `inst` (the instance)
		 */
		get_buffer : function () {
			return { 'mode' : ccp_mode, 'node' : ccp_node, 'inst' : ccp_inst };
		},
		/**
		 * check if there is something in the buffer to paste
		 * @name can_paste()
		 * @return {Boolean}
		 */
		can_paste : function () {
			return ccp_mode !== false && ccp_node !== false; // && ccp_inst._model.data[ccp_node];
		},
		/**
		 * copy or move the previously cut or copied nodes to a new parent
		 * @name paste(obj [, pos])
		 * @param  {mixed} obj the new parent
		 * @param  {mixed} pos the position to insert at (besides integer, "first" and "last" are supported), defaults to integer `0`
		 * @trigger paste.jstree
		 */
		paste : function (obj, pos) {
			obj = this.get_node(obj);
			if(!obj || !ccp_mode || !ccp_mode.match(/^(copy_node|move_node)$/) || !ccp_node) { return false; }
			if(this[ccp_mode](ccp_node, obj, pos)) {
				/**
				 * triggered when paste is invoked
				 * @event
				 * @name paste.jstree
				 * @param {String} parent the ID of the receiving node
				 * @param {Array} node the nodes in the buffer
				 * @param {String} mode the performed operation - "copy_node" or "move_node"
				 */
				this.trigger('paste', { "parent" : obj.id, "node" : ccp_node, "mode" : ccp_mode });
			}
			ccp_node = false;
			ccp_mode = false;
			ccp_inst = false;
		},
		/**
		 * clear the buffer of previously copied or cut nodes
		 * @name clear_buffer()
		 * @trigger clear_buffer.jstree
		 */
		clear_buffer : function () {
			ccp_node = false;
			ccp_mode = false;
			ccp_inst = false;
			/**
			 * triggered when the copy / cut buffer is cleared
			 * @event
			 * @name clear_buffer.jstree
			 */
			this.trigger('clear_buffer');
		},
		/**
		 * put a node in edit mode (input field to rename the node)
		 * @name edit(obj [, default_text])
		 * @param  {mixed} obj
		 * @param  {String} default_text the text to populate the input with (if omitted the node text value is used)
		 */
		edit : function (obj, default_text) {
			obj = this.get_node(obj);
			if(!obj) { return false; }
			if(this.settings.core.check_callback === false) {
				this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_07', 'reason' : 'Could not edit node because of check_callback' };
				this.settings.core.error.call(this, this._data.core.last_error);
				return false;
			}
			default_text = typeof default_text === 'string' ? default_text : obj.text;
			this.set_text(obj, "");
			obj = this._open_to(obj);

			var rtl = this._data.core.rtl,
				w  = this.element.width(),
				a  = obj.children('.jstree-anchor'),
				s  = $('<span>'),
				/*!
				oi = obj.children("i:visible"),
				ai = a.children("i:visible"),
				w1 = oi.width() * oi.length,
				w2 = ai.width() * ai.length,
				*/
				t  = default_text,
				h1 = $("<"+"div />", { css : { "position" : "absolute", "top" : "-200px", "left" : (rtl ? "0px" : "-1000px"), "visibility" : "hidden" } }).appendTo("body"),
				h2 = $("<"+"input />", {
						"value" : t,
						"class" : "jstree-rename-input",
						// "size" : t.length,
						"css" : {
							"padding" : "0",
							"border" : "1px solid silver",
							"box-sizing" : "border-box",
							"display" : "inline-block",
							"height" : (this._data.core.li_height) + "px",
							"lineHeight" : (this._data.core.li_height) + "px",
							"width" : "150px" // will be set a bit further down
						},
						"blur" : $.proxy(function () {
							var i = s.children(".jstree-rename-input"),
								v = i.val();
							if(v === "") { v = t; }
							h1.remove();
							s.replaceWith(a);
							s.remove();
							this.set_text(obj, t);
							if(this.rename_node(obj, $('<div></div>').text(v)[this.settings.core.force_text ? 'text' : 'html']()) === false) {
								this.set_text(obj, t); // move this up? and fix #483
							}
						}, this),
						"keydown" : function (event) {
							var key = event.which;
							if(key === 27) {
								this.value = t;
							}
							if(key === 27 || key === 13 || key === 37 || key === 38 || key === 39 || key === 40 || key === 32) {
								event.stopImmediatePropagation();
							}
							if(key === 27 || key === 13) {
								event.preventDefault();
								this.blur();
							}
						},
						"click" : function (e) { e.stopImmediatePropagation(); },
						"mousedown" : function (e) { e.stopImmediatePropagation(); },
						"keyup" : function (event) {
							h2.width(Math.min(h1.text("pW" + this.value).width(),w));
						},
						"keypress" : function(event) {
							if(event.which === 13) { return false; }
						}
					}),
				fn = {
						fontFamily		: a.css('fontFamily')		|| '',
						fontSize		: a.css('fontSize')			|| '',
						fontWeight		: a.css('fontWeight')		|| '',
						fontStyle		: a.css('fontStyle')		|| '',
						fontStretch		: a.css('fontStretch')		|| '',
						fontVariant		: a.css('fontVariant')		|| '',
						letterSpacing	: a.css('letterSpacing')	|| '',
						wordSpacing		: a.css('wordSpacing')		|| ''
				};
			s.attr('class', a.attr('class')).append(a.contents().clone()).append(h2);
			a.replaceWith(s);
			h1.css(fn);
			h2.css(fn).width(Math.min(h1.text("pW" + h2[0].value).width(),w))[0].select();
		},


		/**
		 * changes the theme
		 * @name set_theme(theme_name [, theme_url])
		 * @param {String} theme_name the name of the new theme to apply
		 * @param {mixed} theme_url  the location of the CSS file for this theme. Omit or set to `false` if you manually included the file. Set to `true` to autoload from the `core.themes.dir` directory.
		 * @trigger set_theme.jstree
		 */
		set_theme : function (theme_name, theme_url) {
			if(!theme_name) { return false; }
			if(theme_url === true) {
				var dir = this.settings.core.themes.dir;
				if(!dir) { dir = $.jstree.path + '/themes'; }
				theme_url = dir + '/' + theme_name + '/style.css';
			}
			if(theme_url && $.inArray(theme_url, themes_loaded) === -1) {
				$('head').append('<'+'link rel="stylesheet" href="' + theme_url + '" type="text/css" />');
				themes_loaded.push(theme_url);
			}
			if(this._data.core.themes.name) {
				this.element.removeClass('jstree-' + this._data.core.themes.name);
			}
			this._data.core.themes.name = theme_name;
			this.element.addClass('jstree-' + theme_name);
			this.element[this.settings.core.themes.responsive ? 'addClass' : 'removeClass' ]('jstree-' + theme_name + '-responsive');
			/**
			 * triggered when a theme is set
			 * @event
			 * @name set_theme.jstree
			 * @param {String} theme the new theme
			 */
			this.trigger('set_theme', { 'theme' : theme_name });
		},
		/**
		 * gets the name of the currently applied theme name
		 * @name get_theme()
		 * @return {String}
		 */
		get_theme : function () { return this._data.core.themes.name; },
		/**
		 * changes the theme variant (if the theme has variants)
		 * @name set_theme_variant(variant_name)
		 * @param {String|Boolean} variant_name the variant to apply (if `false` is used the current variant is removed)
		 */
		set_theme_variant : function (variant_name) {
			if(this._data.core.themes.variant) {
				this.element.removeClass('jstree-' + this._data.core.themes.name + '-' + this._data.core.themes.variant);
			}
			this._data.core.themes.variant = variant_name;
			if(variant_name) {
				this.element.addClass('jstree-' + this._data.core.themes.name + '-' + this._data.core.themes.variant);
			}
		},
		/**
		 * gets the name of the currently applied theme variant
		 * @name get_theme()
		 * @return {String}
		 */
		get_theme_variant : function () { return this._data.core.themes.variant; },
		/**
		 * shows a striped background on the container (if the theme supports it)
		 * @name show_stripes()
		 */
		show_stripes : function () { this._data.core.themes.stripes = true; this.get_container_ul().addClass("jstree-striped"); },
		/**
		 * hides the striped background on the container
		 * @name hide_stripes()
		 */
		hide_stripes : function () { this._data.core.themes.stripes = false; this.get_container_ul().removeClass("jstree-striped"); },
		/**
		 * toggles the striped background on the container
		 * @name toggle_stripes()
		 */
		toggle_stripes : function () { if(this._data.core.themes.stripes) { this.hide_stripes(); } else { this.show_stripes(); } },
		/**
		 * shows the connecting dots (if the theme supports it)
		 * @name show_dots()
		 */
		show_dots : function () { this._data.core.themes.dots = true; this.get_container_ul().removeClass("jstree-no-dots"); },
		/**
		 * hides the connecting dots
		 * @name hide_dots()
		 */
		hide_dots : function () { this._data.core.themes.dots = false; this.get_container_ul().addClass("jstree-no-dots"); },
		/**
		 * toggles the connecting dots
		 * @name toggle_dots()
		 */
		toggle_dots : function () { if(this._data.core.themes.dots) { this.hide_dots(); } else { this.show_dots(); } },
		/**
		 * show the node icons
		 * @name show_icons()
		 */
		show_icons : function () { this._data.core.themes.icons = true; this.get_container_ul().removeClass("jstree-no-icons"); },
		/**
		 * hide the node icons
		 * @name hide_icons()
		 */
		hide_icons : function () { this._data.core.themes.icons = false; this.get_container_ul().addClass("jstree-no-icons"); },
		/**
		 * toggle the node icons
		 * @name toggle_icons()
		 */
		toggle_icons : function () { if(this._data.core.themes.icons) { this.hide_icons(); } else { this.show_icons(); } },
		/**
		 * set the node icon for a node
		 * @name set_icon(obj, icon)
		 * @param {mixed} obj
		 * @param {String} icon the new icon - can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class
		 */
		set_icon : function (obj, icon) {
			var t1, t2, dom, old;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.set_icon(obj[t1], icon);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			old = obj.icon;
			obj.icon = icon;
			dom = this.get_node(obj, true).children(".jstree-anchor").children(".jstree-themeicon");
			if(icon === false) {
				this.hide_icon(obj);
			}
			else if(icon === true) {
				dom.removeClass('jstree-themeicon-custom ' + old).css("background","").removeAttr("rel");
				if(old === false) { this.show_icon(obj); }
			}
			else if(icon.indexOf("/") === -1 && icon.indexOf(".") === -1) {
				dom.removeClass(old).css("background","");
				dom.addClass(icon + ' jstree-themeicon-custom').attr("rel",icon);
				if(old === false) { this.show_icon(obj); }
			}
			else {
				dom.removeClass(old).css("background","");
				dom.addClass('jstree-themeicon-custom').css("background", "url('" + icon + "') center center no-repeat").attr("rel",icon);
				if(old === false) { this.show_icon(obj); }
			}
			return true;
		},
		/**
		 * get the node icon for a node
		 * @name get_icon(obj)
		 * @param {mixed} obj
		 * @return {String}
		 */
		get_icon : function (obj) {
			obj = this.get_node(obj);
			return (!obj || obj.id === '#') ? false : obj.icon;
		},
		/**
		 * hide the icon on an individual node
		 * @name hide_icon(obj)
		 * @param {mixed} obj
		 */
		hide_icon : function (obj) {
			var t1, t2;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.hide_icon(obj[t1]);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj === '#') { return false; }
			obj.icon = false;
			this.get_node(obj, true).children(".jstree-anchor").children(".jstree-themeicon").addClass('jstree-themeicon-hidden');
			return true;
		},
		/**
		 * show the icon on an individual node
		 * @name show_icon(obj)
		 * @param {mixed} obj
		 */
		show_icon : function (obj) {
			var t1, t2, dom;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.show_icon(obj[t1]);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj === '#') { return false; }
			dom = this.get_node(obj, true);
			obj.icon = dom.length ? dom.children(".jstree-anchor").children(".jstree-themeicon").attr('rel') : true;
			if(!obj.icon) { obj.icon = true; }
			dom.children(".jstree-anchor").children(".jstree-themeicon").removeClass('jstree-themeicon-hidden');
			return true;
		}
	};

	// helpers
	$.vakata = {};
	// collect attributes
	$.vakata.attributes = function(node, with_values) {
		node = $(node)[0];
		var attr = with_values ? {} : [];
		if(node && node.attributes) {
			$.each(node.attributes, function (i, v) {
				if($.inArray(v.name.toLowerCase(),['style','contenteditable','hasfocus','tabindex']) !== -1) { return; }
				if(v.value !== null && $.trim(v.value) !== '') {
					if(with_values) { attr[v.name] = v.value; }
					else { attr.push(v.name); }
				}
			});
		}
		return attr;
	};
	$.vakata.array_unique = function(array) {
		var a = [], i, j, l;
		for(i = 0, l = array.length; i < l; i++) {
			for(j = 0; j <= i; j++) {
				if(array[i] === array[j]) {
					break;
				}
			}
			if(j === i) { a.push(array[i]); }
		}
		return a;
	};
	// remove item from array
	$.vakata.array_remove = function(array, from, to) {
		var rest = array.slice((to || from) + 1 || array.length);
		array.length = from < 0 ? array.length + from : from;
		array.push.apply(array, rest);
		return array;
	};
	// remove item from array
	$.vakata.array_remove_item = function(array, item) {
		var tmp = $.inArray(item, array);
		return tmp !== -1 ? $.vakata.array_remove(array, tmp) : array;
	};


/**
 * ### Checkbox plugin
 *
 * This plugin renders checkbox icons in front of each node, making multiple selection much easier. 
 * It also supports tri-state behavior, meaning that if a node has a few of its children checked it will be rendered as undetermined, and state will be propagated up.
 */

	var _i = document.createElement('I');
	_i.className = 'jstree-icon jstree-checkbox';
	_i.setAttribute('role', 'presentation');
	/**
	 * stores all defaults for the checkbox plugin
	 * @name $.jstree.defaults.checkbox
	 * @plugin checkbox
	 */
	$.jstree.defaults.checkbox = {
		/**
		 * a boolean indicating if checkboxes should be visible (can be changed at a later time using `show_checkboxes()` and `hide_checkboxes`). Defaults to `true`.
		 * @name $.jstree.defaults.checkbox.visible
		 * @plugin checkbox
		 */
		visible				: true,
		/**
		 * a boolean indicating if checkboxes should cascade down and have an undetermined state. Defaults to `true`.
		 * @name $.jstree.defaults.checkbox.three_state
		 * @plugin checkbox
		 */
		three_state			: true,
		/**
		 * a boolean indicating if clicking anywhere on the node should act as clicking on the checkbox. Defaults to `true`.
		 * @name $.jstree.defaults.checkbox.whole_node
		 * @plugin checkbox
		 */
		whole_node			: true,
		/**
		 * a boolean indicating if the selected style of a node should be kept, or removed. Defaults to `true`.
		 * @name $.jstree.defaults.checkbox.keep_selected_style
		 * @plugin checkbox
		 */
		keep_selected_style	: true,
		/**
		 * This setting controls how cascading and undetermined nodes are applied. 
		 * If 'up' is in the string - cascading up is enabled, if 'down' is in the string - cascading down is enabled, if 'undetermined' is in the string - undetermined nodes will be used. 
		 * If `three_state` is set to `true` this setting is automatically set to 'up+down+undetermined'. Defaults to ''.
		 * @name $.jstree.defaults.checkbox.cascade
		 * @plugin checkbox
		 */
		cascade				: '',
		/**
		 * This setting controls if checkbox are bound to the general tree selection or to an internal array maintained by the checkbox plugin. Defaults to `true`, only set to `false` if you know exactly what you are doing. 
		 * @name $.jstree.defaults.checkbox.tie_selection
		 * @plugin checkbox
		 */
		tie_selection		: true
	};
	$.jstree.plugins.checkbox = function (options, parent) {
		this.bind = function () {
			parent.bind.call(this);
			this._data.checkbox.uto = false;
			this._data.checkbox.selected = [];
			if(this.settings.checkbox.three_state) {
				this.settings.checkbox.cascade = 'up+down+undetermined';
			}
			this.element
				.on("init.jstree", $.proxy(function () {
						this._data.checkbox.visible = this.settings.checkbox.visible;
						if(!this.settings.checkbox.keep_selected_style) {
							this.element.addClass('jstree-checkbox-no-clicked');
						}
						if(this.settings.checkbox.tie_selection) {
							this.element.addClass('jstree-checkbox-selection');
						}
					}, this))
				.on("loading.jstree", $.proxy(function () {
						this[ this._data.checkbox.visible ? 'show_checkboxes' : 'hide_checkboxes' ]();
					}, this));
			if(this.settings.checkbox.cascade.indexOf('undetermined') !== -1) {
				this.element
					.on('changed.jstree uncheck_node.jstree check_node.jstree uncheck_all.jstree check_all.jstree move_node.jstree copy_node.jstree redraw.jstree open_node.jstree', $.proxy(function () {
							// only if undetermined is in setting
							if(this._data.checkbox.uto) { clearTimeout(this._data.checkbox.uto); }
							this._data.checkbox.uto = setTimeout($.proxy(this._undetermined, this), 50);
						}, this));
			}
			if(!this.settings.checkbox.tie_selection) {
				this.element
					.on('model.jstree', $.proxy(function (e, data) {
						var m = this._model.data,
							p = m[data.parent],
							dpc = data.nodes,
							i, j;
						for(i = 0, j = dpc.length; i < j; i++) {
							m[dpc[i]].state.checked = (m[dpc[i]].original && m[dpc[i]].original.state && m[dpc[i]].original.state.checked);
							if(m[dpc[i]].state.checked) {
								this._data.checkbox.selected.push(dpc[i]);
							}
						}
					}, this));
			}
			if(this.settings.checkbox.cascade.indexOf('up') !== -1 || this.settings.checkbox.cascade.indexOf('down') !== -1) {
				this.element
					.on('model.jstree', $.proxy(function (e, data) {
							var m = this._model.data,
								p = m[data.parent],
								dpc = data.nodes,
								chd = [],
								c, i, j, k, l, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection;

							if(s.indexOf('down') !== -1) {
								// apply down
								if(p.state[ t ? 'selected' : 'checked' ]) {
									for(i = 0, j = dpc.length; i < j; i++) {
										m[dpc[i]].state[ t ? 'selected' : 'checked' ] = true;
									}
									this._data[ t ? 'core' : 'checkbox' ].selected = this._data[ t ? 'core' : 'checkbox' ].selected.concat(dpc);
								}
								else {
									for(i = 0, j = dpc.length; i < j; i++) {
										if(m[dpc[i]].state[ t ? 'selected' : 'checked' ]) {
											for(k = 0, l = m[dpc[i]].children_d.length; k < l; k++) {
												m[m[dpc[i]].children_d[k]].state[ t ? 'selected' : 'checked' ] = true;
											}
											this._data[ t ? 'core' : 'checkbox' ].selected = this._data[ t ? 'core' : 'checkbox' ].selected.concat(m[dpc[i]].children_d);
										}
									}
								}
							}

							if(s.indexOf('up') !== -1) {
								// apply up
								for(i = 0, j = p.children_d.length; i < j; i++) {
									if(!m[p.children_d[i]].children.length) {
										chd.push(m[p.children_d[i]].parent);
									}
								}
								chd = $.vakata.array_unique(chd);
								for(k = 0, l = chd.length; k < l; k++) {
									p = m[chd[k]];
									while(p && p.id !== '#') {
										c = 0;
										for(i = 0, j = p.children.length; i < j; i++) {
											c += m[p.children[i]].state[ t ? 'selected' : 'checked' ];
										}
										if(c === j) {
											p.state[ t ? 'selected' : 'checked' ] = true;
											this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id);
											tmp = this.get_node(p, true);
											if(tmp && tmp.length) {
												tmp.attr('aria-selected', true).children('.jstree-anchor').addClass( t ? 'jstree-clicked' : 'jstree-checked');
											}
										}
										else {
											break;
										}
										p = this.get_node(p.parent);
									}
								}
							}

							this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(this._data[ t ? 'core' : 'checkbox' ].selected);
						}, this))
					.on(this.settings.checkbox.tie_selection ? 'select_node.jstree' : 'check_node.jstree', $.proxy(function (e, data) {
							var obj = data.node,
								m = this._model.data,
								par = this.get_node(obj.parent),
								dom = this.get_node(obj, true),
								i, j, c, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection;

							// apply down
							if(s.indexOf('down') !== -1) {
								this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(this._data[ t ? 'core' : 'checkbox' ].selected.concat(obj.children_d));
								for(i = 0, j = obj.children_d.length; i < j; i++) {
									tmp = m[obj.children_d[i]];
									tmp.state[ t ? 'selected' : 'checked' ] = true;
									if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) {
										tmp.original.state.undetermined = false;
									}
								}
							}

							// apply up
							if(s.indexOf('up') !== -1) {
								while(par && par.id !== '#') {
									c = 0;
									for(i = 0, j = par.children.length; i < j; i++) {
										c += m[par.children[i]].state[ t ? 'selected' : 'checked' ];
									}
									if(c === j) {
										par.state[ t ? 'selected' : 'checked' ] = true;
										this._data[ t ? 'core' : 'checkbox' ].selected.push(par.id);
										tmp = this.get_node(par, true);
										if(tmp && tmp.length) {
											tmp.attr('aria-selected', true).children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked');
										}
									}
									else {
										break;
									}
									par = this.get_node(par.parent);
								}
							}

							// apply down (process .children separately?)
							if(s.indexOf('down') !== -1 && dom.length) {
								dom.find('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked').parent().attr('aria-selected', true);
							}
						}, this))
					.on(this.settings.checkbox.tie_selection ? 'deselect_all.jstree' : 'uncheck_all.jstree', $.proxy(function (e, data) {
							var obj = this.get_node('#'),
								m = this._model.data,
								i, j, tmp;
							for(i = 0, j = obj.children_d.length; i < j; i++) {
								tmp = m[obj.children_d[i]];
								if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) {
									tmp.original.state.undetermined = false;
								}
							}
						}, this))
					.on(this.settings.checkbox.tie_selection ? 'deselect_node.jstree' : 'uncheck_node.jstree', $.proxy(function (e, data) {
							var obj = data.node,
								dom = this.get_node(obj, true),
								i, j, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection;
							if(obj && obj.original && obj.original.state && obj.original.state.undetermined) {
								obj.original.state.undetermined = false;
							}

							// apply down
							if(s.indexOf('down') !== -1) {
								for(i = 0, j = obj.children_d.length; i < j; i++) {
									tmp = this._model.data[obj.children_d[i]];
									tmp.state[ t ? 'selected' : 'checked' ] = false;
									if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) {
										tmp.original.state.undetermined = false;
									}
								}
							}

							// apply up
							if(s.indexOf('up') !== -1) {
								for(i = 0, j = obj.parents.length; i < j; i++) {
									tmp = this._model.data[obj.parents[i]];
									tmp.state[ t ? 'selected' : 'checked' ] = false;
									if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) {
										tmp.original.state.undetermined = false;
									}
									tmp = this.get_node(obj.parents[i], true);
									if(tmp && tmp.length) {
										tmp.attr('aria-selected', false).children('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked');
									}
								}
							}
							tmp = [];
							for(i = 0, j = this._data[ t ? 'core' : 'checkbox' ].selected.length; i < j; i++) {
								// apply down + apply up
								if(
									(s.indexOf('down') === -1 || $.inArray(this._data[ t ? 'core' : 'checkbox' ].selected[i], obj.children_d) === -1) &&
									(s.indexOf('up') === -1 || $.inArray(this._data[ t ? 'core' : 'checkbox' ].selected[i], obj.parents) === -1)
								) {
									tmp.push(this._data[ t ? 'core' : 'checkbox' ].selected[i]);
								}
							}
							this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(tmp);

							// apply down (process .children separately?)
							if(s.indexOf('down') !== -1 && dom.length) {
								dom.find('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked').parent().attr('aria-selected', false);
							}
						}, this));
			}
			if(this.settings.checkbox.cascade.indexOf('up') !== -1) {
				this.element
					.on('delete_node.jstree', $.proxy(function (e, data) {
							// apply up (whole handler)
							var p = this.get_node(data.parent),
								m = this._model.data,
								i, j, c, tmp, t = this.settings.checkbox.tie_selection;
							while(p && p.id !== '#') {
								c = 0;
								for(i = 0, j = p.children.length; i < j; i++) {
									c += m[p.children[i]].state[ t ? 'selected' : 'checked' ];
								}
								if(c === j) {
									p.state[ t ? 'selected' : 'checked' ] = true;
									this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id);
									tmp = this.get_node(p, true);
									if(tmp && tmp.length) {
										tmp.attr('aria-selected', true).children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked');
									}
								}
								else {
									break;
								}
								p = this.get_node(p.parent);
							}
						}, this))
					.on('move_node.jstree', $.proxy(function (e, data) {
							// apply up (whole handler)
							var is_multi = data.is_multi,
								old_par = data.old_parent,
								new_par = this.get_node(data.parent),
								m = this._model.data,
								p, c, i, j, tmp, t = this.settings.checkbox.tie_selection;
							if(!is_multi) {
								p = this.get_node(old_par);
								while(p && p.id !== '#') {
									c = 0;
									for(i = 0, j = p.children.length; i < j; i++) {
										c += m[p.children[i]].state[ t ? 'selected' : 'checked' ];
									}
									if(c === j) {
										p.state[ t ? 'selected' : 'checked' ] = true;
										this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id);
										tmp = this.get_node(p, true);
										if(tmp && tmp.length) {
											tmp.attr('aria-selected', true).children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked');
										}
									}
									else {
										break;
									}
									p = this.get_node(p.parent);
								}
							}
							p = new_par;
							while(p && p.id !== '#') {
								c = 0;
								for(i = 0, j = p.children.length; i < j; i++) {
									c += m[p.children[i]].state[ t ? 'selected' : 'checked' ];
								}
								if(c === j) {
									if(!p.state[ t ? 'selected' : 'checked' ]) {
										p.state[ t ? 'selected' : 'checked' ] = true;
										this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id);
										tmp = this.get_node(p, true);
										if(tmp && tmp.length) {
											tmp.attr('aria-selected', true).children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked');
										}
									}
								}
								else {
									if(p.state[ t ? 'selected' : 'checked' ]) {
										p.state[ t ? 'selected' : 'checked' ] = false;
										this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_remove_item(this._data[ t ? 'core' : 'checkbox' ].selected, p.id);
										tmp = this.get_node(p, true);
										if(tmp && tmp.length) {
											tmp.attr('aria-selected', false).children('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked');
										}
									}
									else {
										break;
									}
								}
								p = this.get_node(p.parent);
							}
						}, this));
			}
		};
		/**
		 * set the undetermined state where and if necessary. Used internally.
		 * @private
		 * @name _undetermined()
		 * @plugin checkbox
		 */
		this._undetermined = function () {
			var i, j, m = this._model.data, t = this.settings.checkbox.tie_selection, s = this._data[ t ? 'core' : 'checkbox' ].selected, p = [], tt = this;
			for(i = 0, j = s.length; i < j; i++) {
				if(m[s[i]] && m[s[i]].parents) {
					p = p.concat(m[s[i]].parents);
				}
			}
			// attempt for server side undetermined state
			this.element.find('.jstree-closed').not(':has(.jstree-children)')
				.each(function () {
					var tmp = tt.get_node(this), tmp2;
					if(!tmp.state.loaded) {
						if(tmp.original && tmp.original.state && tmp.original.state.undetermined && tmp.original.state.undetermined === true) {
							p.push(tmp.id);
							p = p.concat(tmp.parents);
						}
					}
					else {
						for(i = 0, j = tmp.children_d.length; i < j; i++) {
							tmp2 = m[tmp.children_d[i]];
							if(!tmp2.state.loaded && tmp2.original && tmp2.original.state && tmp2.original.state.undetermined && tmp2.original.state.undetermined === true) {
								p.push(tmp2.id);
								p = p.concat(tmp2.parents);
							}
						}
					}
				});
			p = $.vakata.array_unique(p);
			p = $.vakata.array_remove_item(p,'#');

			this.element.find('.jstree-undetermined').removeClass('jstree-undetermined');
			for(i = 0, j = p.length; i < j; i++) {
				if(!m[p[i]].state[ t ? 'selected' : 'checked' ]) {
					s = this.get_node(p[i], true);
					if(s && s.length) {
						s.children('.jstree-anchor').children('.jstree-checkbox').addClass('jstree-undetermined');
					}
				}
			}
		};
		this.redraw_node = function(obj, deep, is_callback, force_render) {
			obj = parent.redraw_node.apply(this, arguments);
			if(obj) {
				var i, j, tmp = null;
				for(i = 0, j = obj.childNodes.length; i < j; i++) {
					if(obj.childNodes[i] && obj.childNodes[i].className && obj.childNodes[i].className.indexOf("jstree-anchor") !== -1) {
						tmp = obj.childNodes[i];
						break;
					}
				}
				if(tmp) {
					if(!this.settings.checkbox.tie_selection && this._model.data[obj.id].state.checked) { tmp.className += ' jstree-checked'; }
					tmp.insertBefore(_i.cloneNode(false), tmp.childNodes[0]);
				}
			}
			if(!is_callback && this.settings.checkbox.cascade.indexOf('undetermined') !== -1) {
				if(this._data.checkbox.uto) { clearTimeout(this._data.checkbox.uto); }
				this._data.checkbox.uto = setTimeout($.proxy(this._undetermined, this), 50);
			}
			return obj;
		};
		/**
		 * show the node checkbox icons
		 * @name show_checkboxes()
		 * @plugin checkbox
		 */
		this.show_checkboxes = function () { this._data.core.themes.checkboxes = true; this.get_container_ul().removeClass("jstree-no-checkboxes"); };
		/**
		 * hide the node checkbox icons
		 * @name hide_checkboxes()
		 * @plugin checkbox
		 */
		this.hide_checkboxes = function () { this._data.core.themes.checkboxes = false; this.get_container_ul().addClass("jstree-no-checkboxes"); };
		/**
		 * toggle the node icons
		 * @name toggle_checkboxes()
		 * @plugin checkbox
		 */
		this.toggle_checkboxes = function () { if(this._data.core.themes.checkboxes) { this.hide_checkboxes(); } else { this.show_checkboxes(); } };
		/**
		 * checks if a node is in an undetermined state
		 * @name is_undetermined(obj)
		 * @param  {mixed} obj
		 * @return {Boolean}
		 */
		this.is_undetermined = function (obj) {
			obj = this.get_node(obj);
			var s = this.settings.checkbox.cascade, i, j, t = this.settings.checkbox.tie_selection, d = this._data[ t ? 'core' : 'checkbox' ].selected, m = this._model.data;
			if(!obj || obj.state[ t ? 'selected' : 'checked' ] === true || s.indexOf('undetermined') === -1 || (s.indexOf('down') === -1 && s.indexOf('up') === -1)) {
				return false;
			}
			if(!obj.state.loaded && obj.original.state.undetermined === true) {
				return true;
			}
			for(i = 0, j = obj.children_d.length; i < j; i++) {
				if($.inArray(obj.children_d[i], d) !== -1 || (!m[obj.children_d[i]].state.loaded && m[obj.children_d[i]].original.state.undetermined)) {
					return true;
				}
			}
			return false;
		};

		this.activate_node = function (obj, e) {
			if(this.settings.checkbox.tie_selection && (this.settings.checkbox.whole_node || $(e.target).hasClass('jstree-checkbox'))) {
				e.ctrlKey = true;
			}
			if(this.settings.checkbox.tie_selection || (!this.settings.checkbox.whole_node && !$(e.target).hasClass('jstree-checkbox'))) {
				return parent.activate_node.call(this, obj, e);
			}
			if(this.is_disabled(obj)) {
				return false;
			}
			if(this.is_checked(obj)) {
				this.uncheck_node(obj, e);
			}
			else {
				this.check_node(obj, e);
			}
			this.trigger('activate_node', { 'node' : this.get_node(obj) });
		};

		/**
		 * check a node (only if tie_selection in checkbox settings is false, otherwise select_node will be called internally)
		 * @name check_node(obj)
		 * @param {mixed} obj an array can be used to check multiple nodes
		 * @trigger check_node.jstree
		 * @plugin checkbox
		 */
		this.check_node = function (obj, e) {
			if(this.settings.checkbox.tie_selection) { return this.select_node(obj, false, true, e); }
			var dom, t1, t2, th;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.check_node(obj[t1], e);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			dom = this.get_node(obj, true);
			if(!obj.state.checked) {
				obj.state.checked = true;
				this._data.checkbox.selected.push(obj.id);
				if(dom && dom.length) {
					dom.children('.jstree-anchor').addClass('jstree-checked');
				}
				/**
				 * triggered when an node is checked (only if tie_selection in checkbox settings is false)
				 * @event
				 * @name check_node.jstree
				 * @param {Object} node
				 * @param {Array} selected the current selection
				 * @param {Object} event the event (if any) that triggered this check_node
				 * @plugin checkbox
				 */
				this.trigger('check_node', { 'node' : obj, 'selected' : this._data.checkbox.selected, 'event' : e });
			}
		};
		/**
		 * uncheck a node (only if tie_selection in checkbox settings is false, otherwise deselect_node will be called internally)
		 * @name deselect_node(obj)
		 * @param {mixed} obj an array can be used to deselect multiple nodes
		 * @trigger uncheck_node.jstree
		 * @plugin checkbox
		 */
		this.uncheck_node = function (obj, e) {
			if(this.settings.checkbox.tie_selection) { return this.deselect_node(obj, false, e); }
			var t1, t2, dom;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.uncheck_node(obj[t1], e);
				}
				return true;
			}
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') {
				return false;
			}
			dom = this.get_node(obj, true);
			if(obj.state.checked) {
				obj.state.checked = false;
				this._data.checkbox.selected = $.vakata.array_remove_item(this._data.checkbox.selected, obj.id);
				if(dom.length) {
					dom.children('.jstree-anchor').removeClass('jstree-checked');
				}
				/**
				 * triggered when an node is unchecked (only if tie_selection in checkbox settings is false)
				 * @event
				 * @name uncheck_node.jstree
				 * @param {Object} node
				 * @param {Array} selected the current selection
				 * @param {Object} event the event (if any) that triggered this uncheck_node
				 * @plugin checkbox
				 */
				this.trigger('uncheck_node', { 'node' : obj, 'selected' : this._data.checkbox.selected, 'event' : e });
			}
		};
		/**
		 * checks all nodes in the tree (only if tie_selection in checkbox settings is false, otherwise select_all will be called internally)
		 * @name check_all()
		 * @trigger check_all.jstree, changed.jstree
		 * @plugin checkbox
		 */
		this.check_all = function () {
			if(this.settings.checkbox.tie_selection) { return this.select_all(); }
			var tmp = this._data.checkbox.selected.concat([]), i, j;
			this._data.checkbox.selected = this._model.data['#'].children_d.concat();
			for(i = 0, j = this._data.checkbox.selected.length; i < j; i++) {
				if(this._model.data[this._data.checkbox.selected[i]]) {
					this._model.data[this._data.checkbox.selected[i]].state.checked = true;
				}
			}
			this.redraw(true);
			/**
			 * triggered when all nodes are checked (only if tie_selection in checkbox settings is false)
			 * @event
			 * @name check_all.jstree
			 * @param {Array} selected the current selection
			 * @plugin checkbox
			 */
			this.trigger('check_all', { 'selected' : this._data.checkbox.selected });
		};
		/**
		 * uncheck all checked nodes (only if tie_selection in checkbox settings is false, otherwise deselect_all will be called internally)
		 * @name uncheck_all()
		 * @trigger uncheck_all.jstree
		 * @plugin checkbox
		 */
		this.uncheck_all = function () {
			if(this.settings.checkbox.tie_selection) { return this.deselect_all(); }
			var tmp = this._data.checkbox.selected.concat([]), i, j;
			for(i = 0, j = this._data.checkbox.selected.length; i < j; i++) {
				if(this._model.data[this._data.checkbox.selected[i]]) {
					this._model.data[this._data.checkbox.selected[i]].state.checked = false;
				}
			}
			this._data.checkbox.selected = [];
			this.element.find('.jstree-checked').removeClass('jstree-checked');
			/**
			 * triggered when all nodes are unchecked (only if tie_selection in checkbox settings is false)
			 * @event
			 * @name uncheck_all.jstree
			 * @param {Object} node the previous selection
			 * @param {Array} selected the current selection
			 * @plugin checkbox
			 */
			this.trigger('uncheck_all', { 'selected' : this._data.checkbox.selected, 'node' : tmp });
		};
		/**
		 * checks if a node is checked (if tie_selection is on in the settings this function will return the same as is_selected)
		 * @name is_checked(obj)
		 * @param  {mixed}  obj
		 * @return {Boolean}
		 * @plugin checkbox
		 */
		this.is_checked = function (obj) {
			if(this.settings.checkbox.tie_selection) { return this.is_selected(obj); }
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			return obj.state.checked;
		};
		/**
		 * get an array of all checked nodes (if tie_selection is on in the settings this function will return the same as get_selected)
		 * @name get_checked([full])
		 * @param  {mixed}  full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
		 * @return {Array}
		 * @plugin checkbox
		 */
		this.get_checked = function (full) {
			if(this.settings.checkbox.tie_selection) { return this.get_selected(full); }
			return full ? $.map(this._data.checkbox.selected, $.proxy(function (i) { return this.get_node(i); }, this)) : this._data.checkbox.selected;
		};
		/**
		 * get an array of all top level checked nodes (ignoring children of checked nodes) (if tie_selection is on in the settings this function will return the same as get_top_selected)
		 * @name get_top_checked([full])
		 * @param  {mixed}  full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
		 * @return {Array}
		 * @plugin checkbox
		 */
		this.get_top_checked = function (full) {
			if(this.settings.checkbox.tie_selection) { return this.get_top_selected(full); }
			var tmp = this.get_checked(true),
				obj = {}, i, j, k, l;
			for(i = 0, j = tmp.length; i < j; i++) {
				obj[tmp[i].id] = tmp[i];
			}
			for(i = 0, j = tmp.length; i < j; i++) {
				for(k = 0, l = tmp[i].children_d.length; k < l; k++) {
					if(obj[tmp[i].children_d[k]]) {
						delete obj[tmp[i].children_d[k]];
					}
				}
			}
			tmp = [];
			for(i in obj) {
				if(obj.hasOwnProperty(i)) {
					tmp.push(i);
				}
			}
			return full ? $.map(tmp, $.proxy(function (i) { return this.get_node(i); }, this)) : tmp;
		};
		/**
		 * get an array of all bottom level checked nodes (ignoring selected parents) (if tie_selection is on in the settings this function will return the same as get_bottom_selected)
		 * @name get_bottom_checked([full])
		 * @param  {mixed}  full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
		 * @return {Array}
		 * @plugin checkbox
		 */
		this.get_bottom_checked = function (full) {
			if(this.settings.checkbox.tie_selection) { return this.get_bottom_selected(full); }
			var tmp = this.get_checked(true),
				obj = [], i, j;
			for(i = 0, j = tmp.length; i < j; i++) {
				if(!tmp[i].children.length) {
					obj.push(tmp[i].id);
				}
			}
			return full ? $.map(obj, $.proxy(function (i) { return this.get_node(i); }, this)) : obj;
		};
		this.load_node = function (obj, callback) {
			var k, l, i, j, c, tmp;
			if(!$.isArray(obj) && !this.settings.checkbox.tie_selection) {
				tmp = this.get_node(obj);
				if(tmp && tmp.state.loaded) {
					for(k = 0, l = tmp.children_d.length; k < l; k++) {
						if(this._model.data[tmp.children_d[k]].state.checked) {
							c = true;
							this._data.checkbox.selected = $.vakata.array_remove_item(this._data.checkbox.selected, tmp.children_d[k]);
						}
					}
				}
			}
			return parent.load_node.apply(this, arguments);
		};
		this.get_state = function () {
			var state = parent.get_state.apply(this, arguments);
			if(this.settings.checkbox.tie_selection) { return state; }
			state.checkbox = this._data.checkbox.selected.slice();
			return state;
		};
		this.set_state = function (state, callback) {
			var res = parent.set_state.apply(this, arguments);
			if(res && state.checkbox) {
				if(!this.settings.checkbox.tie_selection) {
					this.uncheck_all();
					var _this = this;
					$.each(state.checkbox, function (i, v) {
						_this.check_node(v);
					});
				}
				delete state.checkbox;
				return false;
			}
			return res;
		};
	};

	// include the checkbox plugin by default
	// $.jstree.defaults.plugins.push("checkbox");

/**
 * ### Contextmenu plugin
 *
 * Shows a context menu when a node is right-clicked.
 */

	var cto = null, ex, ey;

	/**
	 * stores all defaults for the contextmenu plugin
	 * @name $.jstree.defaults.contextmenu
	 * @plugin contextmenu
	 */
	$.jstree.defaults.contextmenu = {
		/**
		 * a boolean indicating if the node should be selected when the context menu is invoked on it. Defaults to `true`.
		 * @name $.jstree.defaults.contextmenu.select_node
		 * @plugin contextmenu
		 */
		select_node : true,
		/**
		 * a boolean indicating if the menu should be shown aligned with the node. Defaults to `true`, otherwise the mouse coordinates are used.
		 * @name $.jstree.defaults.contextmenu.show_at_node
		 * @plugin contextmenu
		 */
		show_at_node : true,
		/**
		 * an object of actions, or a function that accepts a node and a callback function and calls the callback function with an object of actions available for that node (you can also return the items too).
		 * 
		 * Each action consists of a key (a unique name) and a value which is an object with the following properties (only label and action are required):
		 * 
		 * * `separator_before` - a boolean indicating if there should be a separator before this item
		 * * `separator_after` - a boolean indicating if there should be a separator after this item
		 * * `_disabled` - a boolean indicating if this action should be disabled
		 * * `label` - a string - the name of the action (could be a function returning a string)
		 * * `action` - a function to be executed if this item is chosen
		 * * `icon` - a string, can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class
		 * * `shortcut` - keyCode which will trigger the action if the menu is open (for example `113` for rename, which equals F2)
		 * * `shortcut_label` - shortcut label (like for example `F2` for rename)
		 * 
		 * @name $.jstree.defaults.contextmenu.items
		 * @plugin contextmenu
		 */
		items : function (o, cb) { // Could be an object directly
			return {
				"create" : {
					"separator_before"	: false,
					"separator_after"	: true,
					"_disabled"			: false, //(this.check("create_node", data.reference, {}, "last")),
					"label"				: "Create",
					"action"			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						inst.create_node(obj, {}, "last", function (new_node) {
							setTimeout(function () { inst.edit(new_node); },0);
						});
					}
				},
				"rename" : {
					"separator_before"	: false,
					"separator_after"	: false,
					"_disabled"			: false, //(this.check("rename_node", data.reference, this.get_parent(data.reference), "")),
					"label"				: "Rename",
					/*
					"shortcut"			: 113,
					"shortcut_label"	: 'F2',
					"icon"				: "glyphicon glyphicon-leaf",
					*/
					"action"			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						inst.edit(obj);
					}
				},
				"remove" : {
					"separator_before"	: false,
					"icon"				: false,
					"separator_after"	: false,
					"_disabled"			: false, //(this.check("delete_node", data.reference, this.get_parent(data.reference), "")),
					"label"				: "Delete",
					"action"			: function (data) {
						var inst = $.jstree.reference(data.reference),
							obj = inst.get_node(data.reference);
						if(inst.is_selected(obj)) {
							inst.delete_node(inst.get_selected());
						}
						else {
							inst.delete_node(obj);
						}
					}
				},
				"ccp" : {
					"separator_before"	: true,
					"icon"				: false,
					"separator_after"	: false,
					"label"				: "Edit",
					"action"			: false,
					"submenu" : {
						"cut" : {
							"separator_before"	: false,
							"separator_after"	: false,
							"label"				: "Cut",
							"action"			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.cut(inst.get_selected());
								}
								else {
									inst.cut(obj);
								}
							}
						},
						"copy" : {
							"separator_before"	: false,
							"icon"				: false,
							"separator_after"	: false,
							"label"				: "Copy",
							"action"			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								if(inst.is_selected(obj)) {
									inst.copy(inst.get_selected());
								}
								else {
									inst.copy(obj);
								}
							}
						},
						"paste" : {
							"separator_before"	: false,
							"icon"				: false,
							"_disabled"			: function (data) {
								return !$.jstree.reference(data.reference).can_paste();
							},
							"separator_after"	: false,
							"label"				: "Paste",
							"action"			: function (data) {
								var inst = $.jstree.reference(data.reference),
									obj = inst.get_node(data.reference);
								inst.paste(obj);
							}
						}
					}
				}
			};
		}
	};

	$.jstree.plugins.contextmenu = function (options, parent) {
		this.bind = function () {
			parent.bind.call(this);

			var last_ts = 0;
			this.element
				.on("contextmenu.jstree", ".jstree-anchor", $.proxy(function (e, data) {
						e.preventDefault();
						last_ts = e.ctrlKey ? +new Date() : 0;
						if(data || cto) {
							last_ts = (+new Date()) + 10000;
						}
						if(cto) {
							clearTimeout(cto);
						}
						if(!this.is_loading(e.currentTarget)) {
							this.show_contextmenu(e.currentTarget, e.pageX, e.pageY, e);
						}
					}, this))
				.on("click.jstree", ".jstree-anchor", $.proxy(function (e) {
						if(this._data.contextmenu.visible && (!last_ts || (+new Date()) - last_ts > 250)) { // work around safari & macOS ctrl+click
							$.vakata.context.hide();
						}
						last_ts = 0;
					}, this))
				.on("touchstart.jstree", ".jstree-anchor", function (e) {
						if(!e.originalEvent || !e.originalEvent.changedTouches || !e.originalEvent.changedTouches[0]) {
							return;
						}
						ex = e.pageX;
						ey = e.pageY;
						cto = setTimeout(function () {
							$(e.currentTarget).trigger('contextmenu', true);
						}, 750);
					});
			/*
			if(!('oncontextmenu' in document.body) && ('ontouchstart' in document.body)) {
				var el = null, tm = null;
				this.element
					.on("touchstart", ".jstree-anchor", function (e) {
						el = e.currentTarget;
						tm = +new Date();
						$(document).one("touchend", function (e) {
							e.target = document.elementFromPoint(e.originalEvent.targetTouches[0].pageX - window.pageXOffset, e.originalEvent.targetTouches[0].pageY - window.pageYOffset);
							e.currentTarget = e.target;
							tm = ((+(new Date())) - tm);
							if(e.target === el && tm > 600 && tm < 1000) {
								e.preventDefault();
								$(el).trigger('contextmenu', e);
							}
							el = null;
							tm = null;
						});
					});
			}
			*/
			$(document).on("context_hide.vakata.jstree", $.proxy(function () { this._data.contextmenu.visible = false; }, this));
		};
		this.teardown = function () {
			if(this._data.contextmenu.visible) {
				$.vakata.context.hide();
			}
			parent.teardown.call(this);
		};

		/**
		 * prepare and show the context menu for a node
		 * @name show_contextmenu(obj [, x, y])
		 * @param {mixed} obj the node
		 * @param {Number} x the x-coordinate relative to the document to show the menu at
		 * @param {Number} y the y-coordinate relative to the document to show the menu at
		 * @param {Object} e the event if available that triggered the contextmenu
		 * @plugin contextmenu
		 * @trigger show_contextmenu.jstree
		 */
		this.show_contextmenu = function (obj, x, y, e) {
			obj = this.get_node(obj);
			if(!obj || obj.id === '#') { return false; }
			var s = this.settings.contextmenu,
				d = this.get_node(obj, true),
				a = d.children(".jstree-anchor"),
				o = false,
				i = false;
			if(s.show_at_node || x === undefined || y === undefined) {
				o = a.offset();
				x = o.left;
				y = o.top + this._data.core.li_height;
			}
			if(this.settings.contextmenu.select_node && !this.is_selected(obj)) {
				this.activate_node(obj, e);
			}

			i = s.items;
			if($.isFunction(i)) {
				i = i.call(this, obj, $.proxy(function (i) {
					this._show_contextmenu(obj, x, y, i);
				}, this));
			}
			if($.isPlainObject(i)) {
				this._show_contextmenu(obj, x, y, i);
			}
		};
		/**
		 * show the prepared context menu for a node
		 * @name _show_contextmenu(obj, x, y, i)
		 * @param {mixed} obj the node
		 * @param {Number} x the x-coordinate relative to the document to show the menu at
		 * @param {Number} y the y-coordinate relative to the document to show the menu at
		 * @param {Number} i the object of items to show
		 * @plugin contextmenu
		 * @trigger show_contextmenu.jstree
		 * @private
		 */
		this._show_contextmenu = function (obj, x, y, i) {
			var d = this.get_node(obj, true),
				a = d.children(".jstree-anchor");
			$(document).one("context_show.vakata.jstree", $.proxy(function (e, data) {
				var cls = 'jstree-contextmenu jstree-' + this.get_theme() + '-contextmenu';
				$(data.element).addClass(cls);
			}, this));
			this._data.contextmenu.visible = true;
			$.vakata.context.show(a, { 'x' : x, 'y' : y }, i);
			/**
			 * triggered when the contextmenu is shown for a node
			 * @event
			 * @name show_contextmenu.jstree
			 * @param {Object} node the node
			 * @param {Number} x the x-coordinate of the menu relative to the document
			 * @param {Number} y the y-coordinate of the menu relative to the document
			 * @plugin contextmenu
			 */
			this.trigger('show_contextmenu', { "node" : obj, "x" : x, "y" : y });
		};
	};

	$(function () {
		$(document)
			.on('touchmove.vakata.jstree', function (e) {
				if(cto && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0] && (Math.abs(ex - e.pageX) > 50 || Math.abs(ey - e.pageY) > 50)) {
					clearTimeout(cto);
				}
			})
			.on('touchend.vakata.jstree', function (e) {
				if(cto) {
					clearTimeout(cto);
				}
			});
	});

	// contextmenu helper
	(function ($) {
		var right_to_left = false,
			vakata_context = {
				element		: false,
				reference	: false,
				position_x	: 0,
				position_y	: 0,
				items		: [],
				html		: "",
				is_visible	: false
			};

		$.vakata.context = {
			settings : {
				hide_onmouseleave	: 0,
				icons				: true
			},
			_trigger : function (event_name) {
				$(document).triggerHandler("context_" + event_name + ".vakata", {
					"reference"	: vakata_context.reference,
					"element"	: vakata_context.element,
					"position"	: {
						"x" : vakata_context.position_x,
						"y" : vakata_context.position_y
					}
				});
			},
			_execute : function (i) {
				i = vakata_context.items[i];
				return i && (!i._disabled || ($.isFunction(i._disabled) && !i._disabled({ "item" : i, "reference" : vakata_context.reference, "element" : vakata_context.element }))) && i.action ? i.action.call(null, {
							"item"		: i,
							"reference"	: vakata_context.reference,
							"element"	: vakata_context.element,
							"position"	: {
								"x" : vakata_context.position_x,
								"y" : vakata_context.position_y
							}
						}) : false;
			},
			_parse : function (o, is_callback) {
				if(!o) { return false; }
				if(!is_callback) {
					vakata_context.html		= "";
					vakata_context.items	= [];
				}
				var str = "",
					sep = false,
					tmp;

				if(is_callback) { str += "<"+"ul>"; }
				$.each(o, function (i, val) {
					if(!val) { return true; }
					vakata_context.items.push(val);
					if(!sep && val.separator_before) {
						str += "<"+"li class='vakata-context-separator'><"+"a href='#' " + ($.vakata.context.settings.icons ? '' : 'style="margin-left:0px;"') + ">&#160;<"+"/a><"+"/li>";
					}
					sep = false;
					str += "<"+"li class='" + (val._class || "") + (val._disabled === true || ($.isFunction(val._disabled) && val._disabled({ "item" : val, "reference" : vakata_context.reference, "element" : vakata_context.element })) ? " vakata-contextmenu-disabled " : "") + "' "+(val.shortcut?" data-shortcut='"+val.shortcut+"' ":'')+">";
					str += "<"+"a href='#' rel='" + (vakata_context.items.length - 1) + "'>";
					if($.vakata.context.settings.icons) {
						str += "<"+"i ";
						if(val.icon) {
							if(val.icon.indexOf("/") !== -1 || val.icon.indexOf(".") !== -1) { str += " style='background:url(\"" + val.icon + "\") center center no-repeat' "; }
							else { str += " class='" + val.icon + "' "; }
						}
						str += "><"+"/i><"+"span class='vakata-contextmenu-sep'>&#160;<"+"/span>";
					}
					str += ($.isFunction(val.label) ? val.label({ "item" : i, "reference" : vakata_context.reference, "element" : vakata_context.element }) : val.label) + (val.shortcut?' <span class="vakata-contextmenu-shortcut vakata-contextmenu-shortcut-'+val.shortcut+'">'+ (val.shortcut_label || '') +'</span>':'') + "<"+"/a>";
					if(val.submenu) {
						tmp = $.vakata.context._parse(val.submenu, true);
						if(tmp) { str += tmp; }
					}
					str += "<"+"/li>";
					if(val.separator_after) {
						str += "<"+"li class='vakata-context-separator'><"+"a href='#' " + ($.vakata.context.settings.icons ? '' : 'style="margin-left:0px;"') + ">&#160;<"+"/a><"+"/li>";
						sep = true;
					}
				});
				str  = str.replace(/<li class\='vakata-context-separator'\><\/li\>$/,"");
				if(is_callback) { str += "</ul>"; }
				/**
				 * triggered on the document when the contextmenu is parsed (HTML is built)
				 * @event
				 * @plugin contextmenu
				 * @name context_parse.vakata
				 * @param {jQuery} reference the element that was right clicked
				 * @param {jQuery} element the DOM element of the menu itself
				 * @param {Object} position the x & y coordinates of the menu
				 */
				if(!is_callback) { vakata_context.html = str; $.vakata.context._trigger("parse"); }
				return str.length > 10 ? str : false;
			},
			_show_submenu : function (o) {
				o = $(o);
				if(!o.length || !o.children("ul").length) { return; }
				var e = o.children("ul"),
					x = o.offset().left + o.outerWidth(),
					y = o.offset().top,
					w = e.width(),
					h = e.height(),
					dw = $(window).width() + $(window).scrollLeft(),
					dh = $(window).height() + $(window).scrollTop();
				// може да се спести е една проверка - дали няма някой от класовете вече нагоре
				if(right_to_left) {
					o[x - (w + 10 + o.outerWidth()) < 0 ? "addClass" : "removeClass"]("vakata-context-left");
				}
				else {
					o[x + w + 10 > dw ? "addClass" : "removeClass"]("vakata-context-right");
				}
				if(y + h + 10 > dh) {
					e.css("bottom","-1px");
				}
				e.show();
			},
			show : function (reference, position, data) {
				var o, e, x, y, w, h, dw, dh, cond = true;
				if(vakata_context.element && vakata_context.element.length) {
					vakata_context.element.width('');
				}
				switch(cond) {
					case (!position && !reference):
						return false;
					case (!!position && !!reference):
						vakata_context.reference	= reference;
						vakata_context.position_x	= position.x;
						vakata_context.position_y	= position.y;
						break;
					case (!position && !!reference):
						vakata_context.reference	= reference;
						o = reference.offset();
						vakata_context.position_x	= o.left + reference.outerHeight();
						vakata_context.position_y	= o.top;
						break;
					case (!!position && !reference):
						vakata_context.position_x	= position.x;
						vakata_context.position_y	= position.y;
						break;
				}
				if(!!reference && !data && $(reference).data('vakata_contextmenu')) {
					data = $(reference).data('vakata_contextmenu');
				}
				if($.vakata.context._parse(data)) {
					vakata_context.element.html(vakata_context.html);
				}
				if(vakata_context.items.length) {
					vakata_context.element.appendTo("body");
					e = vakata_context.element;
					x = vakata_context.position_x;
					y = vakata_context.position_y;
					w = e.width();
					h = e.height();
					dw = $(window).width() + $(window).scrollLeft();
					dh = $(window).height() + $(window).scrollTop();
					if(right_to_left) {
						x -= (e.outerWidth() - $(reference).outerWidth());
						if(x < $(window).scrollLeft() + 20) {
							x = $(window).scrollLeft() + 20;
						}
					}
					if(x + w + 20 > dw) {
						x = dw - (w + 20);
					}
					if(y + h + 20 > dh) {
						y = dh - (h + 20);
					}

					vakata_context.element
						.css({ "left" : x, "top" : y })
						.show()
						.find('a').first().focus().parent().addClass("vakata-context-hover");
					vakata_context.is_visible = true;
					/**
					 * triggered on the document when the contextmenu is shown
					 * @event
					 * @plugin contextmenu
					 * @name context_show.vakata
					 * @param {jQuery} reference the element that was right clicked
					 * @param {jQuery} element the DOM element of the menu itself
					 * @param {Object} position the x & y coordinates of the menu
					 */
					$.vakata.context._trigger("show");
				}
			},
			hide : function () {
				if(vakata_context.is_visible) {
					vakata_context.element.hide().find("ul").hide().end().find(':focus').blur().end().detach();
					vakata_context.is_visible = false;
					/**
					 * triggered on the document when the contextmenu is hidden
					 * @event
					 * @plugin contextmenu
					 * @name context_hide.vakata
					 * @param {jQuery} reference the element that was right clicked
					 * @param {jQuery} element the DOM element of the menu itself
					 * @param {Object} position the x & y coordinates of the menu
					 */
					$.vakata.context._trigger("hide");
				}
			}
		};
		$(function () {
			right_to_left = $("body").css("direction") === "rtl";
			var to = false;

			vakata_context.element = $("<ul class='vakata-context'></ul>");
			vakata_context.element
				.on("mouseenter", "li", function (e) {
					e.stopImmediatePropagation();

					if($.contains(this, e.relatedTarget)) {
						// премахнато заради delegate mouseleave по-долу
						// $(this).find(".vakata-context-hover").removeClass("vakata-context-hover");
						return;
					}

					if(to) { clearTimeout(to); }
					vakata_context.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end();

					$(this)
						.siblings().find("ul").hide().end().end()
						.parentsUntil(".vakata-context", "li").addBack().addClass("vakata-context-hover");
					$.vakata.context._show_submenu(this);
				})
				// тестово - дали не натоварва?
				.on("mouseleave", "li", function (e) {
					if($.contains(this, e.relatedTarget)) { return; }
					$(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover");
				})
				.on("mouseleave", function (e) {
					$(this).find(".vakata-context-hover").removeClass("vakata-context-hover");
					if($.vakata.context.settings.hide_onmouseleave) {
						to = setTimeout(
							(function (t) {
								return function () { $.vakata.context.hide(); };
							}(this)), $.vakata.context.settings.hide_onmouseleave);
					}
				})
				.on("click", "a", function (e) {
					e.preventDefault();
				//})
				//.on("mouseup", "a", function (e) {
					if(!$(this).blur().parent().hasClass("vakata-context-disabled") && $.vakata.context._execute($(this).attr("rel")) !== false) {
						$.vakata.context.hide();
					}
				})
				.on('keydown', 'a', function (e) {
						var o = null;
						switch(e.which) {
							case 13:
							case 32:
								e.type = "mouseup";
								e.preventDefault();
								$(e.currentTarget).trigger(e);
								break;
							case 37:
								if(vakata_context.is_visible) {
									vakata_context.element.find(".vakata-context-hover").last().closest("li").first().find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children('a').focus();
									e.stopImmediatePropagation();
									e.preventDefault();
								}
								break;
							case 38:
								if(vakata_context.is_visible) {
									o = vakata_context.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").prevAll("li:not(.vakata-context-separator)").first();
									if(!o.length) { o = vakata_context.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").last(); }
									o.addClass("vakata-context-hover").children('a').focus();
									e.stopImmediatePropagation();
									e.preventDefault();
								}
								break;
							case 39:
								if(vakata_context.is_visible) {
									vakata_context.element.find(".vakata-context-hover").last().children("ul").show().children("li:not(.vakata-context-separator)").removeClass("vakata-context-hover").first().addClass("vakata-context-hover").children('a').focus();
									e.stopImmediatePropagation();
									e.preventDefault();
								}
								break;
							case 40:
								if(vakata_context.is_visible) {
									o = vakata_context.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").nextAll("li:not(.vakata-context-separator)").first();
									if(!o.length) { o = vakata_context.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").first(); }
									o.addClass("vakata-context-hover").children('a').focus();
									e.stopImmediatePropagation();
									e.preventDefault();
								}
								break;
							case 27:
								$.vakata.context.hide();
								e.preventDefault();
								break;
							default:
								//console.log(e.which);
								break;
						}
					})
				.on('keydown', function (e) {
					e.preventDefault();
					var a = vakata_context.element.find('.vakata-contextmenu-shortcut-' + e.which).parent();
					if(a.parent().not('.vakata-context-disabled')) {
						a.click();
					}
				});

			$(document)
				.on("mousedown.vakata.jstree", function (e) {
					if(vakata_context.is_visible && !$.contains(vakata_context.element[0], e.target)) {
						$.vakata.context.hide();
					}
				})
				.on("context_show.vakata.jstree", function (e, data) {
					vakata_context.element.find("li:has(ul)").children("a").addClass("vakata-context-parent");
					if(right_to_left) {
						vakata_context.element.addClass("vakata-context-rtl").css("direction", "rtl");
					}
					// also apply a RTL class?
					vakata_context.element.find("ul").hide().end();
				});
		});
	}($));
	// $.jstree.defaults.plugins.push("contextmenu");

/**
 * ### Drag'n'drop plugin
 *
 * Enables dragging and dropping of nodes in the tree, resulting in a move or copy operations.
 */

	/**
	 * stores all defaults for the drag'n'drop plugin
	 * @name $.jstree.defaults.dnd
	 * @plugin dnd
	 */
	$.jstree.defaults.dnd = {
		/**
		 * a boolean indicating if a copy should be possible while dragging (by pressint the meta key or Ctrl). Defaults to `true`.
		 * @name $.jstree.defaults.dnd.copy
		 * @plugin dnd
		 */
		copy : true,
		/**
		 * a number indicating how long a node should remain hovered while dragging to be opened. Defaults to `500`.
		 * @name $.jstree.defaults.dnd.open_timeout
		 * @plugin dnd
		 */
		open_timeout : 500,
		/**
		 * a function invoked each time a node is about to be dragged, invoked in the tree's scope and receives the nodes about to be dragged as an argument (array) - return `false` to prevent dragging
		 * @name $.jstree.defaults.dnd.is_draggable
		 * @plugin dnd
		 */
		is_draggable : true,
		/**
		 * a boolean indicating if checks should constantly be made while the user is dragging the node (as opposed to checking only on drop), default is `true`
		 * @name $.jstree.defaults.dnd.check_while_dragging
		 * @plugin dnd
		 */
		check_while_dragging : true,
		/**
		 * a boolean indicating if nodes from this tree should only be copied with dnd (as opposed to moved), default is `false`
		 * @name $.jstree.defaults.dnd.always_copy
		 * @plugin dnd
		 */
		always_copy : false,
		/**
		 * when dropping a node "inside", this setting indicates the position the node should go to - it can be an integer or a string: "first" (same as 0) or "last", default is `0`
		 * @name $.jstree.defaults.dnd.inside_pos
		 * @plugin dnd
		 */
		inside_pos : 0,
		/**
		 * when starting the drag on a node that is selected this setting controls if all selected nodes are dragged or only the single node, default is `true`, which means all selected nodes are dragged when the drag is started on a selected node
		 * @name $.jstree.defaults.dnd.drag_selection
		 * @plugin dnd
		 */
		drag_selection : true,
		/**
		 * controls whether dnd works on touch devices. If left as boolean true dnd will work the same as in desktop browsers, which in some cases may impair scrolling. If set to boolean false dnd will not work on touch devices. There is a special third option - string "selected" which means only selected nodes can be dragged on touch devices.
		 * @name $.jstree.defaults.dnd.touch
		 * @plugin dnd
		 */
		touch : true
	};
	// TODO: now check works by checking for each node individually, how about max_children, unique, etc?
	$.jstree.plugins.dnd = function (options, parent) {
		this.bind = function () {
			parent.bind.call(this);

			this.element
				.on('mousedown.jstree touchstart.jstree', '.jstree-anchor', $.proxy(function (e) {
					if(e.type === "touchstart" && (!this.settings.dnd.touch || (this.settings.dnd.touch === 'selected' && !$(e.currentTarget).hasClass('jstree-clicked')))) {
						return true;
					}
					var obj = this.get_node(e.target),
						mlt = this.is_selected(obj) && this.settings.drag_selection ? this.get_selected().length : 1,
						txt = (mlt > 1 ? mlt + ' ' + this.get_string('nodes') : this.get_text(e.currentTarget));
					if(this.settings.core.force_text) {
						txt = $('<div />').text(txt).html();
					}
					if(obj && obj.id && obj.id !== "#" && (e.which === 1 || e.type === "touchstart") &&
						(this.settings.dnd.is_draggable === true || ($.isFunction(this.settings.dnd.is_draggable) && this.settings.dnd.is_draggable.call(this, (mlt > 1 ? this.get_selected(true) : [obj]))))
					) {
						this.element.trigger('mousedown.jstree');
						return $.vakata.dnd.start(e, { 'jstree' : true, 'origin' : this, 'obj' : this.get_node(obj,true), 'nodes' : mlt > 1 ? this.get_selected() : [obj.id] }, '<div id="jstree-dnd" class="jstree-' + this.get_theme() + ' jstree-' + this.get_theme() + '-' + this.get_theme_variant() + ' ' + ( this.settings.core.themes.responsive ? ' jstree-dnd-responsive' : '' ) + '"><i class="jstree-icon jstree-er"></i>' + txt + '<ins class="jstree-copy" style="display:none;">+</ins></div>');
					}
				}, this));
		};
	};

	$(function() {
		// bind only once for all instances
		var lastmv = false,
			laster = false,
			opento = false,
			marker = $('<div id="jstree-marker">&#160;</div>').hide(); //.appendTo('body');

		$(document)
			.on('dnd_start.vakata.jstree', function (e, data) {
				lastmv = false;
				if(!data || !data.data || !data.data.jstree) { return; }
				marker.appendTo('body'); //.show();
			})
			.on('dnd_move.vakata.jstree', function (e, data) {
				if(opento) { clearTimeout(opento); }
				if(!data || !data.data || !data.data.jstree) { return; }

				// if we are hovering the marker image do nothing (can happen on "inside" drags)
				if(data.event.target.id && data.event.target.id === 'jstree-marker') {
					return;
				}

				var ins = $.jstree.reference(data.event.target),
					ref = false,
					off = false,
					rel = false,
					l, t, h, p, i, o, ok, t1, t2, op, ps, pr, ip, tm;
				// if we are over an instance
				if(ins && ins._data && ins._data.dnd) {
					marker.attr('class', 'jstree-' + ins.get_theme() + ( ins.settings.core.themes.responsive ? ' jstree-dnd-responsive' : '' ));
					data.helper
						.children().attr('class', 'jstree-' + ins.get_theme() + ' jstree-' + ins.get_theme() + '-' + ins.get_theme_variant() + ' ' + ( ins.settings.core.themes.responsive ? ' jstree-dnd-responsive' : '' ))
						.find('.jstree-copy').first()[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? 'show' : 'hide' ]();


					// if are hovering the container itself add a new root node
					if( (data.event.target === ins.element[0] || data.event.target === ins.get_container_ul()[0]) && ins.get_container_ul().children().length === 0) {
						ok = true;
						for(t1 = 0, t2 = data.data.nodes.length; t1 < t2; t1++) {
							ok = ok && ins.check( (data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey)) ) ? "copy_node" : "move_node"), (data.data.origin && data.data.origin !== ins ? data.data.origin.get_node(data.data.nodes[t1]) : data.data.nodes[t1]), '#', 'last', { 'dnd' : true, 'ref' : ins.get_node('#'), 'pos' : 'i', 'is_multi' : (data.data.origin && data.data.origin !== ins), 'is_foreign' : (!data.data.origin) });
							if(!ok) { break; }
						}
						if(ok) {
							lastmv = { 'ins' : ins, 'par' : '#', 'pos' : 'last' };
							marker.hide();
							data.helper.find('.jstree-icon').first().removeClass('jstree-er').addClass('jstree-ok');
							return;
						}
					}
					else {
						// if we are hovering a tree node
						ref = $(data.event.target).closest('.jstree-anchor');
						if(ref && ref.length && ref.parent().is('.jstree-closed, .jstree-open, .jstree-leaf')) {
							off = ref.offset();
							rel = data.event.pageY - off.top;
							h = ref.height();
							if(rel < h / 3) {
								o = ['b', 'i', 'a'];
							}
							else if(rel > h - h / 3) {
								o = ['a', 'i', 'b'];
							}
							else {
								o = rel > h / 2 ? ['i', 'a', 'b'] : ['i', 'b', 'a'];
							}
							$.each(o, function (j, v) {
								switch(v) {
									case 'b':
										l = off.left - 6;
										t = off.top;
										p = ins.get_parent(ref);
										i = ref.parent().index();
										break;
									case 'i':
										ip = ins.settings.dnd.inside_pos;
										tm = ins.get_node(ref.parent());
										l = off.left - 2;
										t = off.top + h / 2 + 1;
										p = tm.id;
										i = ip === 'first' ? 0 : (ip === 'last' ? tm.children.length : Math.min(ip, tm.children.length));
										break;
									case 'a':
										l = off.left - 6;
										t = off.top + h;
										p = ins.get_parent(ref);
										i = ref.parent().index() + 1;
										break;
								}
								ok = true;
								for(t1 = 0, t2 = data.data.nodes.length; t1 < t2; t1++) {
									op = data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? "copy_node" : "move_node";
									ps = i;
									if(op === "move_node" && v === 'a' && (data.data.origin && data.data.origin === ins) && p === ins.get_parent(data.data.nodes[t1])) {
										pr = ins.get_node(p);
										if(ps > $.inArray(data.data.nodes[t1], pr.children)) {
											ps -= 1;
										}
									}
									ok = ok && ( (ins && ins.settings && ins.settings.dnd && ins.settings.dnd.check_while_dragging === false) || ins.check(op, (data.data.origin && data.data.origin !== ins ? data.data.origin.get_node(data.data.nodes[t1]) : data.data.nodes[t1]), p, ps, { 'dnd' : true, 'ref' : ins.get_node(ref.parent()), 'pos' : v, 'is_multi' : (data.data.origin && data.data.origin !== ins), 'is_foreign' : (!data.data.origin) }) );
									if(!ok) {
										if(ins && ins.last_error) { laster = ins.last_error(); }
										break;
									}
								}
								if(v === 'i' && ref.parent().is('.jstree-closed') && ins.settings.dnd.open_timeout) {
									opento = setTimeout((function (x, z) { return function () { x.open_node(z); }; }(ins, ref)), ins.settings.dnd.open_timeout);
								}
								if(ok) {
									lastmv = { 'ins' : ins, 'par' : p, 'pos' : v === 'i' && ip === 'last' && i === 0 && !ins.is_loaded(tm) ? 'last' : i };
									marker.css({ 'left' : l + 'px', 'top' : t + 'px' }).show();
									data.helper.find('.jstree-icon').first().removeClass('jstree-er').addClass('jstree-ok');
									laster = {};
									o = true;
									return false;
								}
							});
							if(o === true) { return; }
						}
					}
				}
				lastmv = false;
				data.helper.find('.jstree-icon').removeClass('jstree-ok').addClass('jstree-er');
				marker.hide();
			})
			.on('dnd_scroll.vakata.jstree', function (e, data) {
				if(!data || !data.data || !data.data.jstree) { return; }
				marker.hide();
				lastmv = false;
				data.helper.find('.jstree-icon').first().removeClass('jstree-ok').addClass('jstree-er');
			})
			.on('dnd_stop.vakata.jstree', function (e, data) {
				if(opento) { clearTimeout(opento); }
				if(!data || !data.data || !data.data.jstree) { return; }
				marker.hide().detach();
				var i, j, nodes = [];
				if(lastmv) {
					for(i = 0, j = data.data.nodes.length; i < j; i++) {
						nodes[i] = data.data.origin ? data.data.origin.get_node(data.data.nodes[i]) : data.data.nodes[i];
						if(data.data.origin) {
							nodes[i].instance = data.data.origin;
						}
					}
					lastmv.ins[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? 'copy_node' : 'move_node' ](nodes, lastmv.par, lastmv.pos);
					for(i = 0, j = nodes.length; i < j; i++) {
						if(nodes[i].instance) {
							nodes[i].instance = null;
						}
					}
				}
				else {
					i = $(data.event.target).closest('.jstree');
					if(i.length && laster && laster.error && laster.error === 'check') {
						i = i.jstree(true);
						if(i) {
							i.settings.core.error.call(this, laster);
						}
					}
				}
			})
			.on('keyup.jstree keydown.jstree', function (e, data) {
				data = $.vakata.dnd._get();
				if(data && data.data && data.data.jstree) {
					data.helper.find('.jstree-copy').first()[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (e.metaKey || e.ctrlKey))) ? 'show' : 'hide' ]();
				}
			});
	});

	// helpers
	(function ($) {
		// private variable
		var vakata_dnd = {
			element	: false,
			target	: false,
			is_down	: false,
			is_drag	: false,
			helper	: false,
			helper_w: 0,
			data	: false,
			init_x	: 0,
			init_y	: 0,
			scroll_l: 0,
			scroll_t: 0,
			scroll_e: false,
			scroll_i: false,
			is_touch: false
		};
		$.vakata.dnd = {
			settings : {
				scroll_speed		: 10,
				scroll_proximity	: 20,
				helper_left			: 5,
				helper_top			: 10,
				threshold			: 5,
				threshold_touch		: 50
			},
			_trigger : function (event_name, e) {
				var data = $.vakata.dnd._get();
				data.event = e;
				$(document).triggerHandler("dnd_" + event_name + ".vakata", data);
			},
			_get : function () {
				return {
					"data"		: vakata_dnd.data,
					"element"	: vakata_dnd.element,
					"helper"	: vakata_dnd.helper
				};
			},
			_clean : function () {
				if(vakata_dnd.helper) { vakata_dnd.helper.remove(); }
				if(vakata_dnd.scroll_i) { clearInterval(vakata_dnd.scroll_i); vakata_dnd.scroll_i = false; }
				vakata_dnd = {
					element	: false,
					target	: false,
					is_down	: false,
					is_drag	: false,
					helper	: false,
					helper_w: 0,
					data	: false,
					init_x	: 0,
					init_y	: 0,
					scroll_l: 0,
					scroll_t: 0,
					scroll_e: false,
					scroll_i: false,
					is_touch: false
				};
				$(document).off("mousemove.vakata.jstree touchmove.vakata.jstree", $.vakata.dnd.drag);
				$(document).off("mouseup.vakata.jstree touchend.vakata.jstree", $.vakata.dnd.stop);
			},
			_scroll : function (init_only) {
				if(!vakata_dnd.scroll_e || (!vakata_dnd.scroll_l && !vakata_dnd.scroll_t)) {
					if(vakata_dnd.scroll_i) { clearInterval(vakata_dnd.scroll_i); vakata_dnd.scroll_i = false; }
					return false;
				}
				if(!vakata_dnd.scroll_i) {
					vakata_dnd.scroll_i = setInterval($.vakata.dnd._scroll, 100);
					return false;
				}
				if(init_only === true) { return false; }

				var i = vakata_dnd.scroll_e.scrollTop(),
					j = vakata_dnd.scroll_e.scrollLeft();
				vakata_dnd.scroll_e.scrollTop(i + vakata_dnd.scroll_t * $.vakata.dnd.settings.scroll_speed);
				vakata_dnd.scroll_e.scrollLeft(j + vakata_dnd.scroll_l * $.vakata.dnd.settings.scroll_speed);
				if(i !== vakata_dnd.scroll_e.scrollTop() || j !== vakata_dnd.scroll_e.scrollLeft()) {
					/**
					 * triggered on the document when a drag causes an element to scroll
					 * @event
					 * @plugin dnd
					 * @name dnd_scroll.vakata
					 * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start
					 * @param {DOM} element the DOM element being dragged
					 * @param {jQuery} helper the helper shown next to the mouse
					 * @param {jQuery} event the element that is scrolling
					 */
					$.vakata.dnd._trigger("scroll", vakata_dnd.scroll_e);
				}
			},
			start : function (e, data, html) {
				if(e.type === "touchstart" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) {
					e.pageX = e.originalEvent.changedTouches[0].pageX;
					e.pageY = e.originalEvent.changedTouches[0].pageY;
					e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset);
				}
				if(vakata_dnd.is_drag) { $.vakata.dnd.stop({}); }
				try {
					e.currentTarget.unselectable = "on";
					e.currentTarget.onselectstart = function() { return false; };
					if(e.currentTarget.style) { e.currentTarget.style.MozUserSelect = "none"; }
				} catch(ignore) { }
				vakata_dnd.init_x	= e.pageX;
				vakata_dnd.init_y	= e.pageY;
				vakata_dnd.data		= data;
				vakata_dnd.is_down	= true;
				vakata_dnd.element	= e.currentTarget;
				vakata_dnd.target	= e.target;
				vakata_dnd.is_touch	= e.type === "touchstart";
				if(html !== false) {
					vakata_dnd.helper = $("<div id='vakata-dnd'></div>").html(html).css({
						"display"		: "block",
						"margin"		: "0",
						"padding"		: "0",
						"position"		: "absolute",
						"top"			: "-2000px",
						"lineHeight"	: "16px",
						"zIndex"		: "10000"
					});
				}
				$(document).on("mousemove.vakata.jstree touchmove.vakata.jstree", $.vakata.dnd.drag);
				$(document).on("mouseup.vakata.jstree touchend.vakata.jstree", $.vakata.dnd.stop);
				return false;
			},
			drag : function (e) {
				if(e.type === "touchmove" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) {
					e.pageX = e.originalEvent.changedTouches[0].pageX;
					e.pageY = e.originalEvent.changedTouches[0].pageY;
					e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset);
				}
				if(!vakata_dnd.is_down) { return; }
				if(!vakata_dnd.is_drag) {
					if(
						Math.abs(e.pageX - vakata_dnd.init_x) > (vakata_dnd.is_touch ? $.vakata.dnd.settings.threshold_touch : $.vakata.dnd.settings.threshold) ||
						Math.abs(e.pageY - vakata_dnd.init_y) > (vakata_dnd.is_touch ? $.vakata.dnd.settings.threshold_touch : $.vakata.dnd.settings.threshold)
					) {
						if(vakata_dnd.helper) {
							vakata_dnd.helper.appendTo("body");
							vakata_dnd.helper_w = vakata_dnd.helper.outerWidth();
						}
						vakata_dnd.is_drag = true;
						/**
						 * triggered on the document when a drag starts
						 * @event
						 * @plugin dnd
						 * @name dnd_start.vakata
						 * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start
						 * @param {DOM} element the DOM element being dragged
						 * @param {jQuery} helper the helper shown next to the mouse
						 * @param {Object} event the event that caused the start (probably mousemove)
						 */
						$.vakata.dnd._trigger("start", e);
					}
					else { return; }
				}

				var d  = false, w  = false,
					dh = false, wh = false,
					dw = false, ww = false,
					dt = false, dl = false,
					ht = false, hl = false;

				vakata_dnd.scroll_t = 0;
				vakata_dnd.scroll_l = 0;
				vakata_dnd.scroll_e = false;
				$($(e.target).parentsUntil("body").addBack().get().reverse())
					.filter(function () {
						return	(/^auto|scroll$/).test($(this).css("overflow")) &&
								(this.scrollHeight > this.offsetHeight || this.scrollWidth > this.offsetWidth);
					})
					.each(function () {
						var t = $(this), o = t.offset();
						if(this.scrollHeight > this.offsetHeight) {
							if(o.top + t.height() - e.pageY < $.vakata.dnd.settings.scroll_proximity)	{ vakata_dnd.scroll_t = 1; }
							if(e.pageY - o.top < $.vakata.dnd.settings.scroll_proximity)				{ vakata_dnd.scroll_t = -1; }
						}
						if(this.scrollWidth > this.offsetWidth) {
							if(o.left + t.width() - e.pageX < $.vakata.dnd.settings.scroll_proximity)	{ vakata_dnd.scroll_l = 1; }
							if(e.pageX - o.left < $.vakata.dnd.settings.scroll_proximity)				{ vakata_dnd.scroll_l = -1; }
						}
						if(vakata_dnd.scroll_t || vakata_dnd.scroll_l) {
							vakata_dnd.scroll_e = $(this);
							return false;
						}
					});

				if(!vakata_dnd.scroll_e) {
					d  = $(document); w = $(window);
					dh = d.height(); wh = w.height();
					dw = d.width(); ww = w.width();
					dt = d.scrollTop(); dl = d.scrollLeft();
					if(dh > wh && e.pageY - dt < $.vakata.dnd.settings.scroll_proximity)		{ vakata_dnd.scroll_t = -1;  }
					if(dh > wh && wh - (e.pageY - dt) < $.vakata.dnd.settings.scroll_proximity)	{ vakata_dnd.scroll_t = 1; }
					if(dw > ww && e.pageX - dl < $.vakata.dnd.settings.scroll_proximity)		{ vakata_dnd.scroll_l = -1; }
					if(dw > ww && ww - (e.pageX - dl) < $.vakata.dnd.settings.scroll_proximity)	{ vakata_dnd.scroll_l = 1; }
					if(vakata_dnd.scroll_t || vakata_dnd.scroll_l) {
						vakata_dnd.scroll_e = d;
					}
				}
				if(vakata_dnd.scroll_e) { $.vakata.dnd._scroll(true); }

				if(vakata_dnd.helper) {
					ht = parseInt(e.pageY + $.vakata.dnd.settings.helper_top, 10);
					hl = parseInt(e.pageX + $.vakata.dnd.settings.helper_left, 10);
					if(dh && ht + 25 > dh) { ht = dh - 50; }
					if(dw && hl + vakata_dnd.helper_w > dw) { hl = dw - (vakata_dnd.helper_w + 2); }
					vakata_dnd.helper.css({
						left	: hl + "px",
						top		: ht + "px"
					});
				}
				/**
				 * triggered on the document when a drag is in progress
				 * @event
				 * @plugin dnd
				 * @name dnd_move.vakata
				 * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start
				 * @param {DOM} element the DOM element being dragged
				 * @param {jQuery} helper the helper shown next to the mouse
				 * @param {Object} event the event that caused this to trigger (most likely mousemove)
				 */
				$.vakata.dnd._trigger("move", e);
				return false;
			},
			stop : function (e) {
				if(e.type === "touchend" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) {
					e.pageX = e.originalEvent.changedTouches[0].pageX;
					e.pageY = e.originalEvent.changedTouches[0].pageY;
					e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset);
				}
				if(vakata_dnd.is_drag) {
					/**
					 * triggered on the document when a drag stops (the dragged element is dropped)
					 * @event
					 * @plugin dnd
					 * @name dnd_stop.vakata
					 * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start
					 * @param {DOM} element the DOM element being dragged
					 * @param {jQuery} helper the helper shown next to the mouse
					 * @param {Object} event the event that caused the stop
					 */
					$.vakata.dnd._trigger("stop", e);
				}
				else {
					if(e.type === "touchend" && e.target === vakata_dnd.target) {
						var to = setTimeout(function () { $(e.target).click(); }, 100);
						$(e.target).one('click', function() { if(to) { clearTimeout(to); } });
					}
				}
				$.vakata.dnd._clean();
				return false;
			}
		};
	}($));

	// include the dnd plugin by default
	// $.jstree.defaults.plugins.push("dnd");


/**
 * ### Search plugin
 *
 * Adds search functionality to jsTree.
 */

	/**
	 * stores all defaults for the search plugin
	 * @name $.jstree.defaults.search
	 * @plugin search
	 */
	$.jstree.defaults.search = {
		/**
		 * a jQuery-like AJAX config, which jstree uses if a server should be queried for results. 
		 * 
		 * A `str` (which is the search string) parameter will be added with the request. The expected result is a JSON array with nodes that need to be opened so that matching nodes will be revealed.
		 * Leave this setting as `false` to not query the server. You can also set this to a function, which will be invoked in the instance's scope and receive 2 parameters - the search string and the callback to call with the array of nodes to load.
		 * @name $.jstree.defaults.search.ajax
		 * @plugin search
		 */
		ajax : false,
		/**
		 * Indicates if the search should be fuzzy or not (should `chnd3` match `child node 3`). Default is `false`.
		 * @name $.jstree.defaults.search.fuzzy
		 * @plugin search
		 */
		fuzzy : false,
		/**
		 * Indicates if the search should be case sensitive. Default is `false`.
		 * @name $.jstree.defaults.search.case_sensitive
		 * @plugin search
		 */
		case_sensitive : false,
		/**
		 * Indicates if the tree should be filtered (by default) to show only matching nodes (keep in mind this can be a heavy on large trees in old browsers). 
		 * This setting can be changed at runtime when calling the search method. Default is `false`.
		 * @name $.jstree.defaults.search.show_only_matches
		 * @plugin search
		 */
		show_only_matches : false,
		/**
		 * Indicates if all nodes opened to reveal the search result, should be closed when the search is cleared or a new search is performed. Default is `true`.
		 * @name $.jstree.defaults.search.close_opened_onclear
		 * @plugin search
		 */
		close_opened_onclear : true,
		/**
		 * Indicates if only leaf nodes should be included in search results. Default is `false`.
		 * @name $.jstree.defaults.search.search_leaves_only
		 * @plugin search
		 */
		search_leaves_only : false,
		/**
		 * If set to a function it wil be called in the instance's scope with two arguments - search string and node (where node will be every node in the structure, so use with caution).
		 * If the function returns a truthy value the node will be considered a match (it might not be displayed if search_only_leaves is set to true and the node is not a leaf). Default is `false`.
		 * @name $.jstree.defaults.search.search_callback
		 * @plugin search
		 */
		search_callback : false
	};

	$.jstree.plugins.search = function (options, parent) {
		this.bind = function () {
			parent.bind.call(this);

			this._data.search.str = "";
			this._data.search.dom = $();
			this._data.search.res = [];
			this._data.search.opn = [];
			this._data.search.som = false;

			this.element
				.on('before_open.jstree', $.proxy(function (e, data) {
						var i, j, f, r = this._data.search.res, s = [], o = $();
						if(r && r.length) {
							this._data.search.dom = $(this.element[0].querySelectorAll('#' + $.map(r, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #')));
							this._data.search.dom.children(".jstree-anchor").addClass('jstree-search');
							if(this._data.search.som && this._data.search.res.length) {
								for(i = 0, j = r.length; i < j; i++) {
									s = s.concat(this.get_node(r[i]).parents);
								}
								s = $.vakata.array_remove_item($.vakata.array_unique(s),'#');
								o = s.length ? $(this.element[0].querySelectorAll('#' + $.map(s, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #'))) : $();

								this.element.find(".jstree-node").hide().filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last');
								o = o.add(this._data.search.dom);
								o.parentsUntil(".jstree").addBack().show()
									.filter(".jstree-children").each(function () { $(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last"); });
							}
						}
					}, this))
				.on("search.jstree", $.proxy(function (e, data) {
						if(this._data.search.som) {
							if(data.nodes.length) {
								this.element.find(".jstree-node").hide().filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last');
								data.nodes.parentsUntil(".jstree").addBack().show()
									.filter(".jstree-children").each(function () { $(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last"); });
							}
						}
					}, this))
				.on("clear_search.jstree", $.proxy(function (e, data) {
						if(this._data.search.som && data.nodes.length) {
							this.element.find(".jstree-node").css("display","").filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last');
						}
					}, this));
		};
		/**
		 * used to search the tree nodes for a given string
		 * @name search(str [, skip_async])
		 * @param {String} str the search string
		 * @param {Boolean} skip_async if set to true server will not be queried even if configured
		 * @param {Boolean} show_only_matches if set to true only matching nodes will be shown (keep in mind this can be very slow on large trees or old browsers)
		 * @plugin search
		 * @trigger search.jstree
		 */
		this.search = function (str, skip_async, show_only_matches) {
			if(str === false || $.trim(str.toString()) === "") {
				return this.clear_search();
			}
			str = str.toString();
			var s = this.settings.search,
				a = s.ajax ? s.ajax : false,
				f = null,
				r = [],
				p = [], i, j;
			if(this._data.search.res.length) {
				this.clear_search();
			}
			if(show_only_matches === undefined) {
				show_only_matches = s.show_only_matches;
			}
			if(!skip_async && a !== false) {
				if($.isFunction(a)) {
					return a.call(this, str, $.proxy(function (d) {
							if(d && d.d) { d = d.d; }
							this._load_nodes(!$.isArray(d) ? [] : $.vakata.array_unique(d), function () {
								this.search(str, true, show_only_matches);
							}, true);
						}, this));
				}
				else {
					a = $.extend({}, a);
					if(!a.data) { a.data = {}; }
					a.data.str = str;
					return $.ajax(a)
						.fail($.proxy(function () {
							this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'search', 'id' : 'search_01', 'reason' : 'Could not load search parents', 'data' : JSON.stringify(a) };
							this.settings.core.error.call(this, this._data.core.last_error);
						}, this))
						.done($.proxy(function (d) {
							if(d && d.d) { d = d.d; }
							this._load_nodes(!$.isArray(d) ? [] : $.vakata.array_unique(d), function () {
								this.search(str, true, show_only_matches);
							}, true);
						}, this));
				}
			}
			this._data.search.str = str;
			this._data.search.dom = $();
			this._data.search.res = [];
			this._data.search.opn = [];
			this._data.search.som = show_only_matches;

			f = new $.vakata.search(str, true, { caseSensitive : s.case_sensitive, fuzzy : s.fuzzy });

			$.each(this._model.data, function (i, v) {
				if(v.text && ( (s.search_callback && s.search_callback.call(this, str, v)) || (!s.search_callback && f.search(v.text).isMatch) ) && (!s.search_leaves_only || (v.state.loaded && v.children.length === 0)) ) {
					r.push(i);
					p = p.concat(v.parents);
				}
			});
			if(r.length) {
				p = $.vakata.array_unique(p);
				this._search_open(p);
				this._data.search.dom = $(this.element[0].querySelectorAll('#' + $.map(r, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #')));
				this._data.search.res = r;
				this._data.search.dom.children(".jstree-anchor").addClass('jstree-search');
			}
			/**
			 * triggered after search is complete
			 * @event
			 * @name search.jstree
			 * @param {jQuery} nodes a jQuery collection of matching nodes
			 * @param {String} str the search string
			 * @param {Array} res a collection of objects represeing the matching nodes
			 * @plugin search
			 */
			this.trigger('search', { nodes : this._data.search.dom, str : str, res : this._data.search.res, show_only_matches : show_only_matches });
		};
		/**
		 * used to clear the last search (removes classes and shows all nodes if filtering is on)
		 * @name clear_search()
		 * @plugin search
		 * @trigger clear_search.jstree
		 */
		this.clear_search = function () {
			this._data.search.dom.children(".jstree-anchor").removeClass("jstree-search");
			if(this.settings.search.close_opened_onclear) {
				this.close_node(this._data.search.opn, 0);
			}
			/**
			 * triggered after search is complete
			 * @event
			 * @name clear_search.jstree
			 * @param {jQuery} nodes a jQuery collection of matching nodes (the result from the last search)
			 * @param {String} str the search string (the last search string)
			 * @param {Array} res a collection of objects represeing the matching nodes (the result from the last search)
			 * @plugin search
			 */
			this.trigger('clear_search', { 'nodes' : this._data.search.dom, str : this._data.search.str, res : this._data.search.res });
			this._data.search.str = "";
			this._data.search.res = [];
			this._data.search.opn = [];
			this._data.search.dom = $();
		};
		/**
		 * opens nodes that need to be opened to reveal the search results. Used only internally.
		 * @private
		 * @name _search_open(d)
		 * @param {Array} d an array of node IDs
		 * @plugin search
		 */
		this._search_open = function (d) {
			var t = this;
			$.each(d.concat([]), function (i, v) {
				if(v === "#") { return true; }
				try { v = $('#' + v.replace($.jstree.idregex,'\\$&'), t.element); } catch(ignore) { }
				if(v && v.length) {
					if(t.is_closed(v)) {
						t._data.search.opn.push(v[0].id);
						t.open_node(v, function () { t._search_open(d); }, 0);
					}
				}
			});
		};
	};

	// helpers
	(function ($) {
		// from http://kiro.me/projects/fuse.html
		$.vakata.search = function(pattern, txt, options) {
			options = options || {};
			if(options.fuzzy !== false) {
				options.fuzzy = true;
			}
			pattern = options.caseSensitive ? pattern : pattern.toLowerCase();
			var MATCH_LOCATION	= options.location || 0,
				MATCH_DISTANCE	= options.distance || 100,
				MATCH_THRESHOLD	= options.threshold || 0.6,
				patternLen = pattern.length,
				matchmask, pattern_alphabet, match_bitapScore, search;
			if(patternLen > 32) {
				options.fuzzy = false;
			}
			if(options.fuzzy) {
				matchmask = 1 << (patternLen - 1);
				pattern_alphabet = (function () {
					var mask = {},
						i = 0;
					for (i = 0; i < patternLen; i++) {
						mask[pattern.charAt(i)] = 0;
					}
					for (i = 0; i < patternLen; i++) {
						mask[pattern.charAt(i)] |= 1 << (patternLen - i - 1);
					}
					return mask;
				}());
				match_bitapScore = function (e, x) {
					var accuracy = e / patternLen,
						proximity = Math.abs(MATCH_LOCATION - x);
					if(!MATCH_DISTANCE) {
						return proximity ? 1.0 : accuracy;
					}
					return accuracy + (proximity / MATCH_DISTANCE);
				};
			}
			search = function (text) {
				text = options.caseSensitive ? text : text.toLowerCase();
				if(pattern === text || text.indexOf(pattern) !== -1) {
					return {
						isMatch: true,
						score: 0
					};
				}
				if(!options.fuzzy) {
					return {
						isMatch: false,
						score: 1
					};
				}
				var i, j,
					textLen = text.length,
					scoreThreshold = MATCH_THRESHOLD,
					bestLoc = text.indexOf(pattern, MATCH_LOCATION),
					binMin, binMid,
					binMax = patternLen + textLen,
					lastRd, start, finish, rd, charMatch,
					score = 1,
					locations = [];
				if (bestLoc !== -1) {
					scoreThreshold = Math.min(match_bitapScore(0, bestLoc), scoreThreshold);
					bestLoc = text.lastIndexOf(pattern, MATCH_LOCATION + patternLen);
					if (bestLoc !== -1) {
						scoreThreshold = Math.min(match_bitapScore(0, bestLoc), scoreThreshold);
					}
				}
				bestLoc = -1;
				for (i = 0; i < patternLen; i++) {
					binMin = 0;
					binMid = binMax;
					while (binMin < binMid) {
						if (match_bitapScore(i, MATCH_LOCATION + binMid) <= scoreThreshold) {
							binMin = binMid;
						} else {
							binMax = binMid;
						}
						binMid = Math.floor((binMax - binMin) / 2 + binMin);
					}
					binMax = binMid;
					start = Math.max(1, MATCH_LOCATION - binMid + 1);
					finish = Math.min(MATCH_LOCATION + binMid, textLen) + patternLen;
					rd = new Array(finish + 2);
					rd[finish + 1] = (1 << i) - 1;
					for (j = finish; j >= start; j--) {
						charMatch = pattern_alphabet[text.charAt(j - 1)];
						if (i === 0) {
							rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;
						} else {
							rd[j] = ((rd[j + 1] << 1) | 1) & charMatch | (((lastRd[j + 1] | lastRd[j]) << 1) | 1) | lastRd[j + 1];
						}
						if (rd[j] & matchmask) {
							score = match_bitapScore(i, j - 1);
							if (score <= scoreThreshold) {
								scoreThreshold = score;
								bestLoc = j - 1;
								locations.push(bestLoc);
								if (bestLoc > MATCH_LOCATION) {
									start = Math.max(1, 2 * MATCH_LOCATION - bestLoc);
								} else {
									break;
								}
							}
						}
					}
					if (match_bitapScore(i + 1, MATCH_LOCATION) > scoreThreshold) {
						break;
					}
					lastRd = rd;
				}
				return {
					isMatch: bestLoc >= 0,
					score: score
				};
			};
			return txt === true ? { 'search' : search } : search(txt);
		};
	}($));

	// include the search plugin by default
	// $.jstree.defaults.plugins.push("search");

/**
 * ### Sort plugin
 *
 * Automatically sorts all siblings in the tree according to a sorting function.
 */

	/**
	 * the settings function used to sort the nodes.
	 * It is executed in the tree's context, accepts two nodes as arguments and should return `1` or `-1`.
	 * @name $.jstree.defaults.sort
	 * @plugin sort
	 */
	$.jstree.defaults.sort = function (a, b) {
		//return this.get_type(a) === this.get_type(b) ? (this.get_text(a) > this.get_text(b) ? 1 : -1) : this.get_type(a) >= this.get_type(b);
		return this.get_text(a) > this.get_text(b) ? 1 : -1;
	};
	$.jstree.plugins.sort = function (options, parent) {
		this.bind = function () {
			parent.bind.call(this);
			this.element
				.on("model.jstree", $.proxy(function (e, data) {
						this.sort(data.parent, true);
					}, this))
				.on("rename_node.jstree create_node.jstree", $.proxy(function (e, data) {
						this.sort(data.parent || data.node.parent, false);
						this.redraw_node(data.parent || data.node.parent, true);
					}, this))
				.on("move_node.jstree copy_node.jstree", $.proxy(function (e, data) {
						this.sort(data.parent, false);
						this.redraw_node(data.parent, true);
					}, this));
		};
		/**
		 * used to sort a node's children
		 * @private
		 * @name sort(obj [, deep])
		 * @param  {mixed} obj the node
		 * @param {Boolean} deep if set to `true` nodes are sorted recursively.
		 * @plugin sort
		 * @trigger search.jstree
		 */
		this.sort = function (obj, deep) {
			var i, j;
			obj = this.get_node(obj);
			if(obj && obj.children && obj.children.length) {
				obj.children.sort($.proxy(this.settings.sort, this));
				if(deep) {
					for(i = 0, j = obj.children_d.length; i < j; i++) {
						this.sort(obj.children_d[i], false);
					}
				}
			}
		};
	};

	// include the sort plugin by default
	// $.jstree.defaults.plugins.push("sort");

/**
 * ### State plugin
 *
 * Saves the state of the tree (selected nodes, opened nodes) on the user's computer using available options (localStorage, cookies, etc)
 */

	var to = false;
	/**
	 * stores all defaults for the state plugin
	 * @name $.jstree.defaults.state
	 * @plugin state
	 */
	$.jstree.defaults.state = {
		/**
		 * A string for the key to use when saving the current tree (change if using multiple trees in your project). Defaults to `jstree`.
		 * @name $.jstree.defaults.state.key
		 * @plugin state
		 */
		key		: 'jstree',
		/**
		 * A space separated list of events that trigger a state save. Defaults to `changed.jstree open_node.jstree close_node.jstree`.
		 * @name $.jstree.defaults.state.events
		 * @plugin state
		 */
		events	: 'changed.jstree open_node.jstree close_node.jstree check_node.jstree uncheck_node.jstree',
		/**
		 * Time in milliseconds after which the state will expire. Defaults to 'false' meaning - no expire.
		 * @name $.jstree.defaults.state.ttl
		 * @plugin state
		 */
		ttl		: false,
		/**
		 * A function that will be executed prior to restoring state with one argument - the state object. Can be used to clear unwanted parts of the state.
		 * @name $.jstree.defaults.state.filter
		 * @plugin state
		 */
		filter	: false
	};
	$.jstree.plugins.state = function (options, parent) {
		this.bind = function () {
			parent.bind.call(this);
			var bind = $.proxy(function () {
				this.element.on(this.settings.state.events, $.proxy(function () {
					if(to) { clearTimeout(to); }
					to = setTimeout($.proxy(function () { this.save_state(); }, this), 100);
				}, this));
				/**
				 * triggered when the state plugin is finished restoring the state (and immediately after ready if there is no state to restore).
				 * @event
				 * @name state_ready.jstree
				 * @plugin state
				 */
				this.trigger('state_ready');
			}, this);
			this.element
				.on("ready.jstree", $.proxy(function (e, data) {
						this.element.one("restore_state.jstree", bind);
						if(!this.restore_state()) { bind(); }
					}, this));
		};
		/**
		 * save the state
		 * @name save_state()
		 * @plugin state
		 */
		this.save_state = function () {
			var st = { 'state' : this.get_state(), 'ttl' : this.settings.state.ttl, 'sec' : +(new Date()) };
			$.vakata.storage.set(this.settings.state.key, JSON.stringify(st));
		};
		/**
		 * restore the state from the user's computer
		 * @name restore_state()
		 * @plugin state
		 */
		this.restore_state = function () {
			var k = $.vakata.storage.get(this.settings.state.key);
			if(!!k) { try { k = JSON.parse(k); } catch(ex) { return false; } }
			if(!!k && k.ttl && k.sec && +(new Date()) - k.sec > k.ttl) { return false; }
			if(!!k && k.state) { k = k.state; }
			if(!!k && $.isFunction(this.settings.state.filter)) { k = this.settings.state.filter.call(this, k); }
			if(!!k) {
				this.element.one("set_state.jstree", function (e, data) { data.instance.trigger('restore_state', { 'state' : $.extend(true, {}, k) }); });
				this.set_state(k);
				return true;
			}
			return false;
		};
		/**
		 * clear the state on the user's computer
		 * @name clear_state()
		 * @plugin state
		 */
		this.clear_state = function () {
			return $.vakata.storage.del(this.settings.state.key);
		};
	};

	(function ($, undefined) {
		$.vakata.storage = {
			// simply specifying the functions in FF throws an error
			set : function (key, val) { return window.localStorage.setItem(key, val); },
			get : function (key) { return window.localStorage.getItem(key); },
			del : function (key) { return window.localStorage.removeItem(key); }
		};
	}($));

	// include the state plugin by default
	// $.jstree.defaults.plugins.push("state");

/**
 * ### Types plugin
 *
 * Makes it possible to add predefined types for groups of nodes, which make it possible to easily control nesting rules and icon for each group.
 */

	/**
	 * An object storing all types as key value pairs, where the key is the type name and the value is an object that could contain following keys (all optional).
	 * 
	 * * `max_children` the maximum number of immediate children this node type can have. Do not specify or set to `-1` for unlimited.
	 * * `max_depth` the maximum number of nesting this node type can have. A value of `1` would mean that the node can have children, but no grandchildren. Do not specify or set to `-1` for unlimited.
	 * * `valid_children` an array of node type strings, that nodes of this type can have as children. Do not specify or set to `-1` for no limits.
	 * * `icon` a string - can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class. Omit to use the default icon from your theme.
	 *
	 * There are two predefined types:
	 * 
	 * * `#` represents the root of the tree, for example `max_children` would control the maximum number of root nodes.
	 * * `default` represents the default node - any settings here will be applied to all nodes that do not have a type specified.
	 * 
	 * @name $.jstree.defaults.types
	 * @plugin types
	 */
	$.jstree.defaults.types = {
		'#' : {},
		'default' : {}
	};

	$.jstree.plugins.types = function (options, parent) {
		this.init = function (el, options) {
			var i, j;
			if(options && options.types && options.types['default']) {
				for(i in options.types) {
					if(i !== "default" && i !== "#" && options.types.hasOwnProperty(i)) {
						for(j in options.types['default']) {
							if(options.types['default'].hasOwnProperty(j) && options.types[i][j] === undefined) {
								options.types[i][j] = options.types['default'][j];
							}
						}
					}
				}
			}
			parent.init.call(this, el, options);
			this._model.data['#'].type = '#';
		};
		this.refresh = function (skip_loading, forget_state) {
			parent.refresh.call(this, skip_loading, forget_state);
			this._model.data['#'].type = '#';
		};
		this.bind = function () {
			this.element
				.on('model.jstree', $.proxy(function (e, data) {
						var m = this._model.data,
							dpc = data.nodes,
							t = this.settings.types,
							i, j, c = 'default';
						for(i = 0, j = dpc.length; i < j; i++) {
							c = 'default';
							if(m[dpc[i]].original && m[dpc[i]].original.type && t[m[dpc[i]].original.type]) {
								c = m[dpc[i]].original.type;
							}
							if(m[dpc[i]].data && m[dpc[i]].data.jstree && m[dpc[i]].data.jstree.type && t[m[dpc[i]].data.jstree.type]) {
								c = m[dpc[i]].data.jstree.type;
							}
							m[dpc[i]].type = c;
							if(m[dpc[i]].icon === true && t[c].icon !== undefined) {
								m[dpc[i]].icon = t[c].icon;
							}
						}
						m['#'].type = '#';
					}, this));
			parent.bind.call(this);
		};
		this.get_json = function (obj, options, flat) {
			var i, j,
				m = this._model.data,
				opt = options ? $.extend(true, {}, options, {no_id:false}) : {},
				tmp = parent.get_json.call(this, obj, opt, flat);
			if(tmp === false) { return false; }
			if($.isArray(tmp)) {
				for(i = 0, j = tmp.length; i < j; i++) {
					tmp[i].type = tmp[i].id && m[tmp[i].id] && m[tmp[i].id].type ? m[tmp[i].id].type : "default";
					if(options && options.no_id) {
						delete tmp[i].id;
						if(tmp[i].li_attr && tmp[i].li_attr.id) {
							delete tmp[i].li_attr.id;
						}
						if(tmp[i].a_attr && tmp[i].a_attr.id) {
							delete tmp[i].a_attr.id;
						}
					}
				}
			}
			else {
				tmp.type = tmp.id && m[tmp.id] && m[tmp.id].type ? m[tmp.id].type : "default";
				if(options && options.no_id) {
					tmp = this._delete_ids(tmp);
				}
			}
			return tmp;
		};
		this._delete_ids = function (tmp) {
			if($.isArray(tmp)) {
				for(var i = 0, j = tmp.length; i < j; i++) {
					tmp[i] = this._delete_ids(tmp[i]);
				}
				return tmp;
			}
			delete tmp.id;
			if(tmp.li_attr && tmp.li_attr.id) {
				delete tmp.li_attr.id;
			}
			if(tmp.a_attr && tmp.a_attr.id) {
				delete tmp.a_attr.id;
			}
			if(tmp.children && $.isArray(tmp.children)) {
				tmp.children = this._delete_ids(tmp.children);
			}
			return tmp;
		};
		this.check = function (chk, obj, par, pos, more) {
			if(parent.check.call(this, chk, obj, par, pos, more) === false) { return false; }
			obj = obj && obj.id ? obj : this.get_node(obj);
			par = par && par.id ? par : this.get_node(par);
			var m = obj && obj.id ? $.jstree.reference(obj.id) : null, tmp, d, i, j;
			m = m && m._model && m._model.data ? m._model.data : null;
			switch(chk) {
				case "create_node":
				case "move_node":
				case "copy_node":
					if(chk !== 'move_node' || $.inArray(obj.id, par.children) === -1) {
						tmp = this.get_rules(par);
						if(tmp.max_children !== undefined && tmp.max_children !== -1 && tmp.max_children === par.children.length) {
							this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_01', 'reason' : 'max_children prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
							return false;
						}
						if(tmp.valid_children !== undefined && tmp.valid_children !== -1 && $.inArray((obj.type || 'default'), tmp.valid_children) === -1) {
							this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_02', 'reason' : 'valid_children prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
							return false;
						}
						if(m && obj.children_d && obj.parents) {
							d = 0;
							for(i = 0, j = obj.children_d.length; i < j; i++) {
								d = Math.max(d, m[obj.children_d[i]].parents.length);
							}
							d = d - obj.parents.length + 1;
						}
						if(d <= 0 || d === undefined) { d = 1; }
						do {
							if(tmp.max_depth !== undefined && tmp.max_depth !== -1 && tmp.max_depth < d) {
								this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_03', 'reason' : 'max_depth prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
								return false;
							}
							par = this.get_node(par.parent);
							tmp = this.get_rules(par);
							d++;
						} while(par);
					}
					break;
			}
			return true;
		};
		/**
		 * used to retrieve the type settings object for a node
		 * @name get_rules(obj)
		 * @param {mixed} obj the node to find the rules for
		 * @return {Object}
		 * @plugin types
		 */
		this.get_rules = function (obj) {
			obj = this.get_node(obj);
			if(!obj) { return false; }
			var tmp = this.get_type(obj, true);
			if(tmp.max_depth === undefined) { tmp.max_depth = -1; }
			if(tmp.max_children === undefined) { tmp.max_children = -1; }
			if(tmp.valid_children === undefined) { tmp.valid_children = -1; }
			return tmp;
		};
		/**
		 * used to retrieve the type string or settings object for a node
		 * @name get_type(obj [, rules])
		 * @param {mixed} obj the node to find the rules for
		 * @param {Boolean} rules if set to `true` instead of a string the settings object will be returned
		 * @return {String|Object}
		 * @plugin types
		 */
		this.get_type = function (obj, rules) {
			obj = this.get_node(obj);
			return (!obj) ? false : ( rules ? $.extend({ 'type' : obj.type }, this.settings.types[obj.type]) : obj.type);
		};
		/**
		 * used to change a node's type
		 * @name set_type(obj, type)
		 * @param {mixed} obj the node to change
		 * @param {String} type the new type
		 * @plugin types
		 */
		this.set_type = function (obj, type) {
			var t, t1, t2, old_type, old_icon;
			if($.isArray(obj)) {
				obj = obj.slice();
				for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
					this.set_type(obj[t1], type);
				}
				return true;
			}
			t = this.settings.types;
			obj = this.get_node(obj);
			if(!t[type] || !obj) { return false; }
			old_type = obj.type;
			old_icon = this.get_icon(obj);
			obj.type = type;
			if(old_icon === true || (t[old_type] && t[old_type].icon !== undefined && old_icon === t[old_type].icon)) {
				this.set_icon(obj, t[type].icon !== undefined ? t[type].icon : true);
			}
			return true;
		};
	};
	// include the types plugin by default
	// $.jstree.defaults.plugins.push("types");

/**
 * ### Unique plugin
 *
 * Enforces that no nodes with the same name can coexist as siblings.
 */

	/**
	 * stores all defaults for the unique plugin
	 * @name $.jstree.defaults.unique
	 * @plugin unique
	 */
	$.jstree.defaults.unique = {
		/**
		 * Indicates if the comparison should be case sensitive. Default is `false`.
		 * @name $.jstree.defaults.unique.case_sensitive
		 * @plugin unique
		 */
		case_sensitive : false,
		/**
		 * A callback executed in the instance's scope when a new node is created and the name is already taken, the two arguments are the conflicting name and the counter. The default will produce results like `New node (2)`.
		 * @name $.jstree.defaults.unique.duplicate
		 * @plugin unique
		 */
		duplicate : function (name, counter) {
			return name + ' (' + counter + ')';
		}
	};

	$.jstree.plugins.unique = function (options, parent) {
		this.check = function (chk, obj, par, pos, more) {
			if(parent.check.call(this, chk, obj, par, pos, more) === false) { return false; }
			obj = obj && obj.id ? obj : this.get_node(obj);
			par = par && par.id ? par : this.get_node(par);
			if(!par || !par.children) { return true; }
			var n = chk === "rename_node" ? pos : obj.text,
				c = [],
				s = this.settings.unique.case_sensitive,
				m = this._model.data, i, j;
			for(i = 0, j = par.children.length; i < j; i++) {
				c.push(s ? m[par.children[i]].text : m[par.children[i]].text.toLowerCase());
			}
			if(!s) { n = n.toLowerCase(); }
			switch(chk) {
				case "delete_node":
					return true;
				case "rename_node":
					i = ($.inArray(n, c) === -1 || (obj.text && obj.text[ s ? 'toString' : 'toLowerCase']() === n));
					if(!i) {
						this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_01', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
					}
					return i;
				case "create_node":
					i = ($.inArray(n, c) === -1);
					if(!i) {
						this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_04', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
					}
					return i;
				case "copy_node":
					i = ($.inArray(n, c) === -1);
					if(!i) {
						this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_02', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
					}
					return i;
				case "move_node":
					i = (obj.parent === par.id || $.inArray(n, c) === -1);
					if(!i) {
						this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_03', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
					}
					return i;
			}
			return true;
		};
		this.create_node = function (par, node, pos, callback, is_loaded) {
			if(!node || node.text === undefined) {
				if(par === null) {
					par = "#";
				}
				par = this.get_node(par);
				if(!par) {
					return parent.create_node.call(this, par, node, pos, callback, is_loaded);
				}
				pos = pos === undefined ? "last" : pos;
				if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {
					return parent.create_node.call(this, par, node, pos, callback, is_loaded);
				}
				if(!node) { node = {}; }
				var tmp, n, dpc, i, j, m = this._model.data, s = this.settings.unique.case_sensitive, cb = this.settings.unique.duplicate;
				n = tmp = this.get_string('New node');
				dpc = [];
				for(i = 0, j = par.children.length; i < j; i++) {
					dpc.push(s ? m[par.children[i]].text : m[par.children[i]].text.toLowerCase());
				}
				i = 1;
				while($.inArray(s ? n : n.toLowerCase(), dpc) !== -1) {
					n = cb.call(this, tmp, (++i)).toString();
				}
				node.text = n;
			}
			return parent.create_node.call(this, par, node, pos, callback, is_loaded);
		};
	};

	// include the unique plugin by default
	// $.jstree.defaults.plugins.push("unique");


/**
 * ### Wholerow plugin
 *
 * Makes each node appear block level. Making selection easier. May cause slow down for large trees in old browsers.
 */

	var div = document.createElement('DIV');
	div.setAttribute('unselectable','on');
	div.setAttribute('role','presentation');
	div.className = 'jstree-wholerow';
	div.innerHTML = '&#160;';
	$.jstree.plugins.wholerow = function (options, parent) {
		this.bind = function () {
			parent.bind.call(this);

			this.element
				.on('ready.jstree set_state.jstree', $.proxy(function () {
						this.hide_dots();
					}, this))
				.on("init.jstree loading.jstree ready.jstree", $.proxy(function () {
						//div.style.height = this._data.core.li_height + 'px';
						this.get_container_ul().addClass('jstree-wholerow-ul');
					}, this))
				.on("deselect_all.jstree", $.proxy(function (e, data) {
						this.element.find('.jstree-wholerow-clicked').removeClass('jstree-wholerow-clicked');
					}, this))
				.on("changed.jstree", $.proxy(function (e, data) {
						this.element.find('.jstree-wholerow-clicked').removeClass('jstree-wholerow-clicked');
						var tmp = false, i, j;
						for(i = 0, j = data.selected.length; i < j; i++) {
							tmp = this.get_node(data.selected[i], true);
							if(tmp && tmp.length) {
								tmp.children('.jstree-wholerow').addClass('jstree-wholerow-clicked');
							}
						}
					}, this))
				.on("open_node.jstree", $.proxy(function (e, data) {
						this.get_node(data.node, true).find('.jstree-clicked').parent().children('.jstree-wholerow').addClass('jstree-wholerow-clicked');
					}, this))
				.on("hover_node.jstree dehover_node.jstree", $.proxy(function (e, data) {
						if(e.type === "hover_node" && this.is_disabled(data.node)) { return; }
						this.get_node(data.node, true).children('.jstree-wholerow')[e.type === "hover_node"?"addClass":"removeClass"]('jstree-wholerow-hovered');
					}, this))
				.on("contextmenu.jstree", ".jstree-wholerow", $.proxy(function (e) {
						e.preventDefault();
						var tmp = $.Event('contextmenu', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey, pageX : e.pageX, pageY : e.pageY });
						$(e.currentTarget).closest(".jstree-node").children(".jstree-anchor").first().trigger(tmp);
					}, this))
				.on("click.jstree", ".jstree-wholerow", function (e) {
						e.stopImmediatePropagation();
						var tmp = $.Event('click', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey });
						$(e.currentTarget).closest(".jstree-node").children(".jstree-anchor").first().trigger(tmp).focus();
					})
				.on("click.jstree", ".jstree-leaf > .jstree-ocl", $.proxy(function (e) {
						e.stopImmediatePropagation();
						var tmp = $.Event('click', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey });
						$(e.currentTarget).closest(".jstree-node").children(".jstree-anchor").first().trigger(tmp).focus();
					}, this))
				.on("mouseover.jstree", ".jstree-wholerow, .jstree-icon", $.proxy(function (e) {
						e.stopImmediatePropagation();
						if(!this.is_disabled(e.currentTarget)) {
							this.hover_node(e.currentTarget);
						}
						return false;
					}, this))
				.on("mouseleave.jstree", ".jstree-node", $.proxy(function (e) {
						this.dehover_node(e.currentTarget);
					}, this));
		};
		this.teardown = function () {
			if(this.settings.wholerow) {
				this.element.find(".jstree-wholerow").remove();
			}
			parent.teardown.call(this);
		};
		this.redraw_node = function(obj, deep, callback, force_render) {
			obj = parent.redraw_node.apply(this, arguments);
			if(obj) {
				var tmp = div.cloneNode(true);
				//tmp.style.height = this._data.core.li_height + 'px';
				if($.inArray(obj.id, this._data.core.selected) !== -1) { tmp.className += ' jstree-wholerow-clicked'; }
				if(this._data.core.focused && this._data.core.focused === obj.id) { tmp.className += ' jstree-wholerow-hovered'; }
				obj.insertBefore(tmp, obj.childNodes[0]);
			}
			return obj;
		};
	};
	// include the wholerow plugin by default
	// $.jstree.defaults.plugins.push("wholerow");


(function ($) {
	if(document.registerElement && Object && Object.create) {
		var proto = Object.create(HTMLElement.prototype);
		proto.createdCallback = function () {
			var c = { core : {}, plugins : [] }, i;
			for(i in $.jstree.plugins) {
				if($.jstree.plugins.hasOwnProperty(i) && this.attributes[i]) {
					c.plugins.push(i);
					if(this.getAttribute(i) && JSON.parse(this.getAttribute(i))) {
						c[i] = JSON.parse(this.getAttribute(i));
					}
				}
			}
      $.jstree.THEMES_DIR = '/assets/javascripts/jstree/themes/';
			for(i in $.jstree.defaults.core) {
				if($.jstree.defaults.core.hasOwnProperty(i) && this.attributes[i]) {
					c.core[i] = JSON.parse(this.getAttribute(i)) || this.getAttribute(i);
				}
			}
			jQuery(this).jstree(c);
		};
		// proto.attributeChangedCallback = function (name, previous, value) { };
		try {
			document.registerElement("vakata-jstree", { prototype: proto });
		} catch(ignore) { }
	}
}(jQuery));
}));
var $j = jQuery.noConflict();
/*!
 * jQuery Cookie Plugin v1.3
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */

(function ($, document, undefined) {

	var pluses = /\+/g;

	function raw(s) {
		return s;
	}

	function decoded(s) {
		return decodeURIComponent(s.replace(pluses, ' '));
	}

	var config = $.cookie = function (key, value, options) {

		// write
		if (value !== undefined) {
			options = $.extend({}, config.defaults, options);

			if (value === null) {
				options.expires = -1;
			}

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			value = config.json ? JSON.stringify(value) : String(value);

			return (document.cookie = [
				encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// read
		var decode = config.raw ? raw : decoded;
		var cookies = document.cookie.split('; ');
		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			if (decode(parts.shift()) === key) {
				var cookie = decode(parts.join('='));
				return config.json ? JSON.parse(cookie) : cookie;
			}
		}

		return null;
	};

	config.defaults = {};

	$.removeCookie = function (key, options) {
		if ($.cookie(key) !== null) {
			$.cookie(key, null, options);
			return true;
		}
		return false;
	};

})(jQuery, document);
/*!
 * jquery-timepicker v1.11.10 - A jQuery timepicker plugin inspired by Google Calendar. It supports both mouse and keyboard navigation.
 * Copyright (c) 2015 Jon Thornton - http://jonthornton.github.com/jquery-timepicker/
 * License: MIT
 */



(function (factory) {
    if (typeof exports === "object" && exports &&
        typeof module === "object" && module && module.exports === exports) {
        // Browserify. Attach to jQuery module.
        factory(require("jquery"));
    } else if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(['jquery'], factory);
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {
	var _ONE_DAY = 86400;
	var _lang = {
		am: 'am',
		pm: 'pm',
		AM: 'AM',
		PM: 'PM',
		decimal: '.',
		mins: 'mins',
		hr: 'hr',
		hrs: 'hrs'
	};

	var _DEFAULTS = {
		appendTo: 'body',
		className: null,
		closeOnWindowScroll: false,
		disableTextInput: false,
		disableTimeRanges: [],
		disableTouchKeyboard: false,
		durationTime: null,
		forceRoundTime: false,
		maxTime: null,
		minTime: null,
		noneOption: false,
		orientation: 'l',
		roundingFunction: function(seconds, settings) {
			if (seconds === null) {
				return null;
			} else if (typeof settings.step !== "number") {
				// TODO: nearest fit irregular steps
				return seconds;
			} else {
				var offset = seconds % (settings.step*60); // step is in minutes

				var start = settings.minTime || 0;

                // adjust offset by start mod step so that the offset is aligned not to 00:00 but to the start
                offset -= start % (settings.step * 60);

				if (offset >= settings.step*30) {
					// if offset is larger than a half step, round up
					seconds += (settings.step*60) - offset;
				} else {
					// round down
					seconds -= offset;
				}

				return _moduloSeconds(seconds, settings);
			}
		},
		scrollDefault: null,
		selectOnBlur: false,
		show2400: false,
		showDuration: false,
		showOn: ['click', 'focus'],
		showOnFocus: true,
		step: 30,
		stopScrollPropagation: false,
		timeFormat: 'g:ia',
		typeaheadHighlight: true,
		useSelect: false,
		wrapHours: true
	};

	var methods = {
		init: function(options)
		{
			return this.each(function()
			{
				var self = $(this);

				// pick up settings from data attributes
				var attributeOptions = [];
				for (var key in _DEFAULTS) {
					if (self.data(key))  {
						attributeOptions[key] = self.data(key);
					}
				}

				var settings = $.extend({}, _DEFAULTS, options, attributeOptions);

				if (settings.lang) {
					_lang = $.extend(_lang, settings.lang);
				}

				settings = _parseSettings(settings);
				self.data('timepicker-settings', settings);
				self.addClass('ui-timepicker-input');

				if (settings.useSelect) {
					_render(self);
				} else {
					self.prop('autocomplete', 'off');
					if (settings.showOn) {
						for (var i in settings.showOn) {
							self.on(settings.showOn[i]+'.timepicker', methods.show);
						}
					}
					self.on('change.timepicker', _formatValue);
					self.on('keydown.timepicker', _keydownhandler);
					self.on('keyup.timepicker', _keyuphandler);
					if (settings.disableTextInput) {
						self.on('keydown.timepicker', _disableTextInputHandler);
					}

					_formatValue.call(self.get(0), null, 'initial');
				}
			});
		},

		show: function(e)
		{
			var self = $(this);
			var settings = self.data('timepicker-settings');

			if (e) {
				e.preventDefault();
			}

			if (settings.useSelect) {
				self.data('timepicker-list').focus();
				return;
			}

			if (_hideKeyboard(self)) {
				// block the keyboard on mobile devices
				self.blur();
			}

			var list = self.data('timepicker-list');

			// check if input is readonly
			if (self.prop('readonly')) {
				return;
			}

			// check if list needs to be rendered
			if (!list || list.length === 0 || typeof settings.durationTime === 'function') {
				_render(self);
				list = self.data('timepicker-list');
			}

			if (_isVisible(list)) {
				return;
			}

			self.data('ui-timepicker-value', self.val());
			_setSelected(self, list);

			// make sure other pickers are hidden
			methods.hide();

			// position the dropdown relative to the input
			list.show();
			var listOffset = {};

			if (settings.orientation.match(/r/)) {
				// right-align the dropdown
				listOffset.left = self.offset().left + self.outerWidth() - list.outerWidth() + parseInt(list.css('marginLeft').replace('px', ''), 10);
			} else {
				// left-align the dropdown
				listOffset.left = self.offset().left + parseInt(list.css('marginLeft').replace('px', ''), 10);
			}

			var verticalOrientation;
			if (settings.orientation.match(/t/)) {
				verticalOrientation = 't';
			} else if (settings.orientation.match(/b/)) {
				verticalOrientation = 'b';
			} else if ((self.offset().top + self.outerHeight(true) + list.outerHeight()) > $(window).height() + $(window).scrollTop()) {
				verticalOrientation = 't';
			} else {
				verticalOrientation = 'b';
			}

			if (verticalOrientation == 't') {
				// position the dropdown on top
				list.addClass('ui-timepicker-positioned-top');
				listOffset.top = self.offset().top - list.outerHeight() + parseInt(list.css('marginTop').replace('px', ''), 10);
			} else {
				// put it under the input
				list.removeClass('ui-timepicker-positioned-top');
				listOffset.top = self.offset().top + self.outerHeight() + parseInt(list.css('marginTop').replace('px', ''), 10);
			}

			list.offset(listOffset);

			// position scrolling
			var selected = list.find('.ui-timepicker-selected');

			if (!selected.length) {
				var timeInt = _time2int(_getTimeValue(self));
				if (timeInt !== null) {
					selected = _findRow(self, list, timeInt);
				} else if (settings.scrollDefault) {
					selected = _findRow(self, list, settings.scrollDefault());
				}
			}

			if (selected && selected.length) {
				var topOffset = list.scrollTop() + selected.position().top - selected.outerHeight();
				list.scrollTop(topOffset);
			} else {
				list.scrollTop(0);
			}

			// prevent scroll propagation
			if(settings.stopScrollPropagation) {
				$(document).on('wheel.ui-timepicker', '.ui-timepicker-wrapper', function(e){
					e.preventDefault();
					var currentScroll = $(this).scrollTop();
					$(this).scrollTop(currentScroll + e.originalEvent.deltaY);
				});
			}

			// attach close handlers
			$(document).on('touchstart.ui-timepicker mousedown.ui-timepicker', _closeHandler);
			$(window).on('resize.ui-timepicker', _closeHandler);
			if (settings.closeOnWindowScroll) {
				$(document).on('scroll.ui-timepicker', _closeHandler);
			}

			self.trigger('showTimepicker');

			return this;
		},

		hide: function(e)
		{
			var self = $(this);
			var settings = self.data('timepicker-settings');

			if (settings && settings.useSelect) {
				self.blur();
			}

			$('.ui-timepicker-wrapper').each(function() {
				var list = $(this);
				if (!_isVisible(list)) {
					return;
				}

				var self = list.data('timepicker-input');
				var settings = self.data('timepicker-settings');

				if (settings && settings.selectOnBlur) {
					_selectValue(self);
				}

				list.hide();
				self.trigger('hideTimepicker');
			});

			return this;
		},

		option: function(key, value)
		{
			if (typeof key == 'string' && typeof value == 'undefined') {
				return $(this).data('timepicker-settings')[key];
			}

			return this.each(function(){
				var self = $(this);
				var settings = self.data('timepicker-settings');
				var list = self.data('timepicker-list');

				if (typeof key == 'object') {
					settings = $.extend(settings, key);
				} else if (typeof key == 'string') {
					settings[key] = value;
				}

				settings = _parseSettings(settings);

				self.data('timepicker-settings', settings);

				_formatValue.call(self.get(0), {'type':'change'}, 'initial');

				if (list) {
					list.remove();
					self.data('timepicker-list', false);
				}

				if (settings.useSelect) {
					_render(self);
				}
			});
		},

		getSecondsFromMidnight: function()
		{
			return _time2int(_getTimeValue(this));
		},

		getTime: function(relative_date)
		{
			var self = this;

			var time_string = _getTimeValue(self);
			if (!time_string) {
				return null;
			}

			var offset = _time2int(time_string);
			if (offset === null) {
				return null;
			}

			if (!relative_date) {
				relative_date = new Date();
			}

			// construct a Date from relative date, and offset's time
			var time = new Date(relative_date);
			time.setHours(offset / 3600);
			time.setMinutes(offset % 3600 / 60);
			time.setSeconds(offset % 60);
			time.setMilliseconds(0);

			return time;
		},

		isVisible: function() {
			var self = this;
			var list = self.data('timepicker-list');
			return !!(list && _isVisible(list));
		},

		setTime: function(value)
		{
			var self = this;
			var settings = self.data('timepicker-settings');

			if (settings.forceRoundTime) {
				var prettyTime = _roundAndFormatTime(_time2int(value), settings)
			} else {
				var prettyTime = _int2time(_time2int(value), settings);
			}

			if (value && prettyTime === null && settings.noneOption) {
				prettyTime = value;
			}

			_setTimeValue(self, prettyTime);
			if (self.data('timepicker-list')) {
				_setSelected(self, self.data('timepicker-list'));
			}

			return this;
		},

		remove: function()
		{
			var self = this;

			// check if this element is a timepicker
			if (!self.hasClass('ui-timepicker-input')) {
				return;
			}

			var settings = self.data('timepicker-settings');
			self.removeAttr('autocomplete', 'off');
			self.removeClass('ui-timepicker-input');
			self.removeData('timepicker-settings');
			self.off('.timepicker');

			// timepicker-list won't be present unless the user has interacted with this timepicker
			if (self.data('timepicker-list')) {
				self.data('timepicker-list').remove();
			}

			if (settings.useSelect) {
				self.show();
			}

			self.removeData('timepicker-list');

			return this;
		}
	};

	// private methods

	function _isVisible(elem)
	{
		var el = elem[0];
		return el.offsetWidth > 0 && el.offsetHeight > 0;
	}

	function _parseSettings(settings)
	{
		if (settings.minTime) {
			settings.minTime = _time2int(settings.minTime);
		}

		if (settings.maxTime) {
			settings.maxTime = _time2int(settings.maxTime);
		}

		if (settings.durationTime && typeof settings.durationTime !== 'function') {
			settings.durationTime = _time2int(settings.durationTime);
		}

		if (settings.scrollDefault == 'now') {
			settings.scrollDefault = function() {
				return settings.roundingFunction(_time2int(new Date()), settings);
			}
		} else if (settings.scrollDefault && typeof settings.scrollDefault != 'function') {
			var val = settings.scrollDefault;
			settings.scrollDefault = function() {
				return settings.roundingFunction(_time2int(val), settings);
			}
		} else if (settings.minTime) {
			settings.scrollDefault = function() {
				return settings.roundingFunction(settings.minTime, settings);
			}
		}

		if ($.type(settings.timeFormat) === "string" && settings.timeFormat.match(/[gh]/)) {
			settings._twelveHourTime = true;
		}

		if (settings.showOnFocus === false && settings.showOn.indexOf('focus') != -1) {
			settings.showOn.splice(settings.showOn.indexOf('focus'), 1);
		}

		if (settings.disableTimeRanges.length > 0) {
			// convert string times to integers
			for (var i in settings.disableTimeRanges) {
				settings.disableTimeRanges[i] = [
					_time2int(settings.disableTimeRanges[i][0]),
					_time2int(settings.disableTimeRanges[i][1])
				];
			}

			// sort by starting time
			settings.disableTimeRanges = settings.disableTimeRanges.sort(function(a, b){
				return a[0] - b[0];
			});

			// merge any overlapping ranges
			for (var i = settings.disableTimeRanges.length-1; i > 0; i--) {
				if (settings.disableTimeRanges[i][0] <= settings.disableTimeRanges[i-1][1]) {
					settings.disableTimeRanges[i-1] = [
						Math.min(settings.disableTimeRanges[i][0], settings.disableTimeRanges[i-1][0]),
						Math.max(settings.disableTimeRanges[i][1], settings.disableTimeRanges[i-1][1])
					];
					settings.disableTimeRanges.splice(i, 1);
				}
			}
		}

		return settings;
	}

	function _render(self)
	{
		var settings = self.data('timepicker-settings');
		var list = self.data('timepicker-list');

		if (list && list.length) {
			list.remove();
			self.data('timepicker-list', false);
		}

		if (settings.useSelect) {
			list = $('<select />', { 'class': 'ui-timepicker-select' });
			var wrapped_list = list;
		} else {
			list = $('<ul />', { 'class': 'ui-timepicker-list' });

			var wrapped_list = $('<div />', { 'class': 'ui-timepicker-wrapper', 'tabindex': -1 });
			wrapped_list.css({'display':'none', 'position': 'absolute' }).append(list);
		}

		if (settings.noneOption) {
			if (settings.noneOption === true) {
				settings.noneOption = (settings.useSelect) ? 'Time...' : 'None';
			}

			if ($.isArray(settings.noneOption)) {
				for (var i in settings.noneOption) {
					if (parseInt(i, 10) == i){
						var noneElement = _generateNoneElement(settings.noneOption[i], settings.useSelect);
						list.append(noneElement);
					}
				}
			} else {
				var noneElement = _generateNoneElement(settings.noneOption, settings.useSelect);
				list.append(noneElement);
			}
		}

		if (settings.className) {
			wrapped_list.addClass(settings.className);
		}

		if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) {
			var stepval = typeof settings.step == 'function' ? 'function' : settings.step;
			wrapped_list.addClass('ui-timepicker-with-duration');
			wrapped_list.addClass('ui-timepicker-step-'+settings.step);
		}

		var durStart = settings.minTime;
		if (typeof settings.durationTime === 'function') {
			durStart = _time2int(settings.durationTime());
		} else if (settings.durationTime !== null) {
			durStart = settings.durationTime;
		}
		var start = (settings.minTime !== null) ? settings.minTime : 0;
		var end = (settings.maxTime !== null) ? settings.maxTime : (start + _ONE_DAY - 1);

		if (end < start) {
			// make sure the end time is greater than start time, otherwise there will be no list to show
			end += _ONE_DAY;
		}

		if (end === _ONE_DAY-1 && $.type(settings.timeFormat) === "string" && settings.show2400) {
			// show a 24:00 option when using military time
			end = _ONE_DAY;
		}

		var dr = settings.disableTimeRanges;
		var drCur = 0;
		var drLen = dr.length;

		var stepFunc = settings.step;
		if (typeof stepFunc != 'function') {
			stepFunc = function() {
				return settings.step;
			}
		}

		for (var i=start, j=0; i <= end; j++, i += stepFunc(j)*60) {
			var timeInt = i;
			var timeString = _int2time(timeInt, settings);

			if (settings.useSelect) {
				var row = $('<option />', { 'value': timeString });
				row.text(timeString);
			} else {
				var row = $('<li />');
				row.addClass((timeInt % _ONE_DAY) < (_ONE_DAY / 2) ? 'ui-timepicker-am' : 'ui-timepicker-pm');
				row.data('time', _moduloSeconds(timeInt, settings));
				row.text(timeString);
			}

			if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) {
				var durationString = _int2duration(i - durStart, settings.step);
				if (settings.useSelect) {
					row.text(row.text()+' ('+durationString+')');
				} else {
					var duration = $('<span />', { 'class': 'ui-timepicker-duration' });
					duration.text(' ('+durationString+')');
					row.append(duration);
				}
			}

			if (drCur < drLen) {
				if (timeInt >= dr[drCur][1]) {
					drCur += 1;
				}

				if (dr[drCur] && timeInt >= dr[drCur][0] && timeInt < dr[drCur][1]) {
					if (settings.useSelect) {
						row.prop('disabled', true);
					} else {
						row.addClass('ui-timepicker-disabled');
					}
				}
			}

			list.append(row);
		}

		wrapped_list.data('timepicker-input', self);
		self.data('timepicker-list', wrapped_list);

		if (settings.useSelect) {
			if (self.val()) {
				list.val(_roundAndFormatTime(_time2int(self.val()), settings));
			}

			list.on('focus', function(){
				$(this).data('timepicker-input').trigger('showTimepicker');
			});
			list.on('blur', function(){
				$(this).data('timepicker-input').trigger('hideTimepicker');
			});
			list.on('change', function(){
				_setTimeValue(self, $(this).val(), 'select');
			});

			_setTimeValue(self, list.val(), 'initial');
			self.hide().after(list);
		} else {
			var appendTo = settings.appendTo;
			if (typeof appendTo === 'string') {
				appendTo = $(appendTo);
			} else if (typeof appendTo === 'function') {
				appendTo = appendTo(self);
			}
			appendTo.append(wrapped_list);
			_setSelected(self, list);

			list.on('mousedown click', 'li', function(e) {

				// hack: temporarily disable the focus handler
				// to deal with the fact that IE fires 'focus'
				// events asynchronously
				self.off('focus.timepicker');
				self.on('focus.timepicker-ie-hack', function(){
					self.off('focus.timepicker-ie-hack');
					self.on('focus.timepicker', methods.show);
				});

				if (!_hideKeyboard(self)) {
					self[0].focus();
				}

				// make sure only the clicked row is selected
				list.find('li').removeClass('ui-timepicker-selected');
				$(this).addClass('ui-timepicker-selected');

				if (_selectValue(self)) {
					self.trigger('hideTimepicker');

					list.on('mouseup.timepicker click.timepicker', 'li', function(e) {
						list.off('mouseup.timepicker click.timepicker');
						wrapped_list.hide();
					});
				}
			});
		}
	}

	function _generateNoneElement(optionValue, useSelect)
	{
		var label, className, value;

		if (typeof optionValue == 'object') {
			label = optionValue.label;
			className = optionValue.className;
			value = optionValue.value;
		} else if (typeof optionValue == 'string') {
			label = optionValue;
		} else {
			$.error('Invalid noneOption value');
		}

		if (useSelect) {
			return $('<option />', {
					'value': value,
					'class': className,
					'text': label
				});
		} else {
			return $('<li />', {
					'class': className,
					'text': label
				}).data('time', String(value));
		}
	}

	function _roundAndFormatTime(seconds, settings)
	{
		seconds = settings.roundingFunction(seconds, settings);
		if (seconds !== null) {
			return _int2time(seconds, settings);
		}
	}

	// event handler to decide whether to close timepicker
	function _closeHandler(e)
	{
		if (e.target == window) {
			// mobile Chrome fires focus events against window for some reason
			return;
		}

		var target = $(e.target);

		if (target.closest('.ui-timepicker-input').length || target.closest('.ui-timepicker-wrapper').length) {
			// active timepicker was focused. ignore
			return;
		}

		methods.hide();
		$(document).unbind('.ui-timepicker');
		$(window).unbind('.ui-timepicker');
	}

	function _hideKeyboard(self)
	{
		var settings = self.data('timepicker-settings');
		return ((window.navigator.msMaxTouchPoints || 'ontouchstart' in document) && settings.disableTouchKeyboard);
	}

	function _findRow(self, list, value)
	{
		if (!value && value !== 0) {
			return false;
		}

		var settings = self.data('timepicker-settings');
		var out = false;
		var value = settings.roundingFunction(value, settings);

		// loop through the menu items
		list.find('li').each(function(i, obj) {
			var jObj = $(obj);
			if (typeof jObj.data('time') != 'number') {
				return;
			}

			if (jObj.data('time') == value) {
				out = jObj;
				return false;
			}
		});

		return out;
	}

	function _setSelected(self, list)
	{
		list.find('li').removeClass('ui-timepicker-selected');

		var timeValue = _time2int(_getTimeValue(self), self.data('timepicker-settings'));
		if (timeValue === null) {
			return;
		}

		var selected = _findRow(self, list, timeValue);
		if (selected) {

			var topDelta = selected.offset().top - list.offset().top;

			if (topDelta + selected.outerHeight() > list.outerHeight() || topDelta < 0) {
				list.scrollTop(list.scrollTop() + selected.position().top - selected.outerHeight());
			}

			selected.addClass('ui-timepicker-selected');
		}
	}


	function _formatValue(e, origin)
	{
		if (this.value === '' || origin == 'timepicker') {
			return;
		}

		var self = $(this);

		if (self.is(':focus') && (!e || e.type != 'change')) {
			return;
		}

		var settings = self.data('timepicker-settings');
		var seconds = _time2int(this.value, settings);

		if (seconds === null) {
			self.trigger('timeFormatError');
			return;
		}

		var rangeError = false;
		// check that the time in within bounds
		if ((settings.minTime !== null && settings.maxTime !== null)
			&& (seconds < settings.minTime || seconds > settings.maxTime)) {
			rangeError = true;
		}

		// check that time isn't within disabled time ranges
		$.each(settings.disableTimeRanges, function(){
			if (seconds >= this[0] && seconds < this[1]) {
				rangeError = true;
				return false;
			}
		});

		if (settings.forceRoundTime) {
			var roundSeconds = settings.roundingFunction(seconds, settings);
			if (roundSeconds != seconds) {
				seconds = roundSeconds;
				origin = null;
			}
		}

		var prettyTime = _int2time(seconds, settings);

		if (rangeError) {
			if (_setTimeValue(self, prettyTime, 'error') || e && e.type == 'change') {
				self.trigger('timeRangeError');
			}
		} else {
			_setTimeValue(self, prettyTime, origin);
		}
	}

	function _getTimeValue(self)
	{
		if (self.is('input')) {
			return self.val();
		} else {
			// use the element's data attributes to store values
			return self.data('ui-timepicker-value');
		}
	}

	function _setTimeValue(self, value, source)
	{
		if (self.is('input')) {
			self.val(value);

			var settings = self.data('timepicker-settings');
			if (settings.useSelect && source != 'select' && source != 'initial') {
				self.data('timepicker-list').val(_roundAndFormatTime(_time2int(value), settings));
			}
		}

		if (self.data('ui-timepicker-value') != value) {
			self.data('ui-timepicker-value', value);
			if (source == 'select') {
				self.trigger('selectTime').trigger('changeTime').trigger('change', 'timepicker');
			} else if (['error', 'initial'].indexOf(source) == -1) {
				self.trigger('changeTime');
			}

			return true;
		} else {
			self.trigger('selectTime');
			return false;
		}
	}

	/*
	*  Filter freeform input
	*/
	function _disableTextInputHandler(e)
	{
		switch (e.keyCode) {
			case 13: // return
			case 9: //tab
				return;

			default:
				e.preventDefault();
		}
	}

	/*
	*  Keyboard navigation via arrow keys
	*/
	function _keydownhandler(e)
	{
		var self = $(this);
		var list = self.data('timepicker-list');

		if (!list || !_isVisible(list)) {
			if (e.keyCode == 40) {
				// show the list!
				methods.show.call(self.get(0));
				list = self.data('timepicker-list');
				if (!_hideKeyboard(self)) {
					self.focus();
				}
			} else {
				return true;
			}
		}

		switch (e.keyCode) {

			case 13: // return
				if (_selectValue(self)) {
					_formatValue.call(self.get(0), {'type':'change'});
					methods.hide.apply(this);
				}

				e.preventDefault();
				return false;

			case 38: // up
				var selected = list.find('.ui-timepicker-selected');

				if (!selected.length) {
					list.find('li').each(function(i, obj) {
						if ($(obj).position().top > 0) {
							selected = $(obj);
							return false;
						}
					});
					selected.addClass('ui-timepicker-selected');

				} else if (!selected.is(':first-child')) {
					selected.removeClass('ui-timepicker-selected');
					selected.prev().addClass('ui-timepicker-selected');

					if (selected.prev().position().top < selected.outerHeight()) {
						list.scrollTop(list.scrollTop() - selected.outerHeight());
					}
				}

				return false;

			case 40: // down
				selected = list.find('.ui-timepicker-selected');

				if (selected.length === 0) {
					list.find('li').each(function(i, obj) {
						if ($(obj).position().top > 0) {
							selected = $(obj);
							return false;
						}
					});

					selected.addClass('ui-timepicker-selected');
				} else if (!selected.is(':last-child')) {
					selected.removeClass('ui-timepicker-selected');
					selected.next().addClass('ui-timepicker-selected');

					if (selected.next().position().top + 2*selected.outerHeight() > list.outerHeight()) {
						list.scrollTop(list.scrollTop() + selected.outerHeight());
					}
				}

				return false;

			case 27: // escape
				list.find('li').removeClass('ui-timepicker-selected');
				methods.hide();
				break;

			case 9: //tab
				methods.hide();
				break;

			default:
				return true;
		}
	}

	/*
	*	Time typeahead
	*/
	function _keyuphandler(e)
	{
		var self = $(this);
		var list = self.data('timepicker-list');
		var settings = self.data('timepicker-settings');

		if (!list || !_isVisible(list) || settings.disableTextInput) {
			return true;
		}

		switch (e.keyCode) {

			case 96: // numpad numerals
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
			case 103:
			case 104:
			case 105:
			case 48: // numerals
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
			case 65: // a
			case 77: // m
			case 80: // p
			case 186: // colon
			case 8: // backspace
			case 46: // delete
				if (settings.typeaheadHighlight) {
					_setSelected(self, list);
				} else {
					list.hide();
				}
				break;
		}
	}

	function _selectValue(self)
	{
		var settings = self.data('timepicker-settings');
		var list = self.data('timepicker-list');
		var timeValue = null;

		var cursor = list.find('.ui-timepicker-selected');

		if (cursor.hasClass('ui-timepicker-disabled')) {
			return false;
		}

		if (cursor.length) {
			// selected value found
			timeValue = cursor.data('time');
		}

		if (timeValue !== null) {
			if (typeof timeValue != 'string') {
				timeValue = _int2time(timeValue, settings);
			}

			_setTimeValue(self, timeValue, 'select');
		}

		return true;
	}

	function _int2duration(seconds, step)
	{
		seconds = Math.abs(seconds);
		var minutes = Math.round(seconds/60),
			duration = [],
			hours, mins;

		if (minutes < 60) {
			// Only show (x mins) under 1 hour
			duration = [minutes, _lang.mins];
		} else {
			hours = Math.floor(minutes/60);
			mins = minutes%60;

			// Show decimal notation (eg: 1.5 hrs) for 30 minute steps
			if (step == 30 && mins == 30) {
				hours += _lang.decimal + 5;
			}

			duration.push(hours);
			duration.push(hours == 1 ? _lang.hr : _lang.hrs);

			// Show remainder minutes notation (eg: 1 hr 15 mins) for non-30 minute steps
			// and only if there are remainder minutes to show
			if (step != 30 && mins) {
				duration.push(mins);
				duration.push(_lang.mins);
			}
		}

		return duration.join(' ');
	}

	function _int2time(timeInt, settings)
	{
		if (typeof timeInt != 'number') {
			return null;
		}

		var seconds = parseInt(timeInt%60)
			, minutes = parseInt((timeInt/60)%60)
			, hours = parseInt((timeInt/(60*60))%24);

		var time = new Date(1970, 0, 2, hours, minutes, seconds, 0);

		if (isNaN(time.getTime())) {
			return null;
		}

		if ($.type(settings.timeFormat) === "function") {
			return settings.timeFormat(time);
		}

		var output = '';
		var hour, code;
		for (var i=0; i<settings.timeFormat.length; i++) {

			code = settings.timeFormat.charAt(i);
			switch (code) {

				case 'a':
					output += (time.getHours() > 11) ? _lang.pm : _lang.am;
					break;

				case 'A':
					output += (time.getHours() > 11) ? _lang.PM : _lang.AM;
					break;

				case 'g':
					hour = time.getHours() % 12;
					output += (hour === 0) ? '12' : hour;
					break;

				case 'G':
					hour = time.getHours();
					if (timeInt === _ONE_DAY) hour = settings.show2400 ? 24 : 0;
					output += hour;
					break;

				case 'h':
					hour = time.getHours() % 12;

					if (hour !== 0 && hour < 10) {
						hour = '0'+hour;
					}

					output += (hour === 0) ? '12' : hour;
					break;

				case 'H':
					hour = time.getHours();
					if (timeInt === _ONE_DAY) hour = settings.show2400 ? 24 : 0;
					output += (hour > 9) ? hour : '0'+hour;
					break;

				case 'i':
					var minutes = time.getMinutes();
					output += (minutes > 9) ? minutes : '0'+minutes;
					break;

				case 's':
					seconds = time.getSeconds();
					output += (seconds > 9) ? seconds : '0'+seconds;
					break;

				case '\\':
					// escape character; add the next character and skip ahead
					i++;
					output += settings.timeFormat.charAt(i);
					break;

				default:
					output += code;
			}
		}

		return output;
	}

	function _time2int(timeString, settings)
	{
		if (timeString === '' || timeString === null) return null;
		if (typeof timeString == 'object') {
			return timeString.getHours()*3600 + timeString.getMinutes()*60 + timeString.getSeconds();
		}
		if (typeof timeString != 'string') {
			return timeString;
		}

		timeString = timeString.toLowerCase().replace(/[\s\.]/g, '');

		// if the last character is an "a" or "p", add the "m"
		if (timeString.slice(-1) == 'a' || timeString.slice(-1) == 'p') {
			timeString += 'm';
		}

		var ampmRegex = '(' +
			_lang.am.replace('.', '')+'|' +
			_lang.pm.replace('.', '')+'|' +
			_lang.AM.replace('.', '')+'|' +
			_lang.PM.replace('.', '')+')?';

		// try to parse time input
		var pattern = new RegExp('^'+ampmRegex+'([0-9]?[0-9])\\W?([0-5][0-9])?\\W?([0-5][0-9])?'+ampmRegex+'$');

		var time = timeString.match(pattern);
		if (!time) {
			return null;
		}

		var hour = parseInt(time[2]*1, 10);
		if (hour > 24) {
			if (settings && settings.wrapHours === false) {
				return null;
			} else {
				hour = hour % 24;
			}
		}

		var ampm = time[1] || time[5];
		var hours = hour;

		if (hour <= 12 && ampm) {
			var isPm = (ampm == _lang.pm || ampm == _lang.PM);

			if (hour == 12) {
				hours = isPm ? 12 : 0;
			} else {
				hours = (hour + (isPm ? 12 : 0));
			}
		}

		var minutes = ( time[3]*1 || 0 );
		var seconds = ( time[4]*1 || 0 );
		var timeInt = hours*3600 + minutes*60 + seconds;

		// if no am/pm provided, intelligently guess based on the scrollDefault
		if (hour < 12 && !ampm && settings && settings._twelveHourTime && settings.scrollDefault) {
			var delta = timeInt - settings.scrollDefault();
			if (delta < 0 && delta >= _ONE_DAY / -2) {
				timeInt = (timeInt + (_ONE_DAY / 2)) % _ONE_DAY;
			}
		}

		return timeInt;
	}

	function _pad2(n) {
		return ("0" + n).slice(-2);
	}

	function _moduloSeconds(seconds, settings) {
		if (seconds == _ONE_DAY && settings.show2400) {
			return seconds;
		}

		return seconds%_ONE_DAY;
	}

	// Plugin entry
	$.fn.timepicker = function(method)
	{
		if (!this.length) return this;
		if (methods[method]) {
			// check if this element is a timepicker
			if (!this.hasClass('ui-timepicker-input')) {
				return this;
			}
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		}
		else if(typeof method === "object" || !method) { return methods.init.apply(this, arguments); }
		else { $.error("Method "+ method + " does not exist on jQuery.timepicker"); }
	};
}));
/*!
 * datepair.js v0.4.15 - A javascript plugin for intelligently selecting date and time ranges inspired by Google Calendar.
 * Copyright (c) 2016 Jon Thornton - http://jonthornton.github.com/Datepair.js
 * License: MIT
 */


(function($) {

	if(!$) {
		return;
	}

	////////////
	// Plugin //
	////////////

	$.fn.datepair = function(option) {
		var out;
		this.each(function() {
			var $this = $(this);
			var data = $this.data('datepair');
			var options = typeof option === 'object' && option;

			if (!data) {
				data = new Datepair(this, options);
				$this.data('datepair', data);
			}

			if (option === 'remove') {
				out = data['remove']();
				$this.removeData('datepair', data);
			}

			if (typeof option === 'string') {
				out = data[option]();
			}
		});

		return out || this;
	};

	//////////////
	// Data API //
	//////////////

	$('[data-datepair]').each(function() {
		var $this = $(this);
		$this.datepair($this.data());
	});

}(window.Zepto || window.jQuery));
/*!
 * datepair.js v0.4.15 - A javascript plugin for intelligently selecting date and time ranges inspired by Google Calendar.
 * Copyright (c) 2016 Jon Thornton - http://jonthornton.github.com/Datepair.js
 * License: MIT
 */


(function(window, document) {

	'use strict';

	var _ONE_DAY = 86400000;
	var jq = window.Zepto || window.jQuery;
	
	function simpleExtend(obj1, obj2) {
		var out = obj2 || {};
	
		for (var i in obj1) {
			if (!(i in out)) {
				out[i] = obj1[i];
			}
		}
	
		return out;
	}
	
	// IE's custom event support is totally borked.
	// Use jQuery if possible
	function triggerSimpleCustomEvent(el, eventName) {
		if (jq) {
			jq(el).trigger(eventName);
		} else {
			var event = document.createEvent('CustomEvent');
			event.initCustomEvent(eventName, true, true, {});
			el.dispatchEvent(event);
		}
	}
	
	// el.classList not supported by < IE10
	// use jQuery if available
	function hasClass(el, className) {
		if (jq) {
			return jq(el).hasClass(className);
		} else {
			return el.classList.contains(className);
		}
	}
	
	function Datepair(container, options) {
		this.dateDelta = null;
		this.timeDelta = null;
		this._defaults =	{
			startClass: 'start',
			endClass: 'end',
			timeClass: 'time',
			dateClass: 'date',
			defaultDateDelta: 0,
			defaultTimeDelta: 3600000,
			anchor: 'start',
	
			// defaults for jquery-timepicker; override when using other input widgets
			parseTime: function(input){
				return jq(input).timepicker('getTime');
			},
			updateTime: function(input, dateObj){
				jq(input).timepicker('setTime', dateObj);
			},
			setMinTime: function(input, dateObj){
				jq(input).timepicker('option', 'minTime', dateObj);
			},
	
			// defaults for bootstrap datepicker; override when using other input widgets
			parseDate: function(input){
				return input.value && jq(input).datepicker('getDate');
			},
			updateDate: function(input, dateObj){
				jq(input).datepicker('update', dateObj);
			}
		};
	
		this.container = container;
		this.settings = simpleExtend(this._defaults, options);
	
		this.startDateInput = this.container.querySelector('.'+this.settings.startClass+'.'+this.settings.dateClass);
		this.endDateInput = this.container.querySelector('.'+this.settings.endClass+'.'+this.settings.dateClass);
		this.startTimeInput = this.container.querySelector('.'+this.settings.startClass+'.'+this.settings.timeClass);
		this.endTimeInput = this.container.querySelector('.'+this.settings.endClass+'.'+this.settings.timeClass);
	
		// initialize date and time deltas
		this.refresh();
	
		// init starts here
		this._bindChangeHandler();
	}
	
	Datepair.prototype = {
		constructor: Datepair,
	
		option: function(key, value)
		{
			if (typeof key == 'object') {
				this.settings = simpleExtend(this.settings, key);
	
			} else if (typeof key == 'string' && typeof value != 'undefined') {
				this.settings[key] = value;
	
			} else if (typeof key == 'string') {
				return this.settings[key];
			}
	
			this._updateEndMintime();
		},
	
		getTimeDiff: function()
		{
			// due to the fact that times can wrap around, timeDiff for any
			// time-only pair will always be >= 0
			var delta = this.dateDelta + this.timeDelta;
			if (delta < 0 && (!this.startDateInput || !this.endDateInput) ) {
				delta += _ONE_DAY;
			}
	
			return delta;
		},
	
		refresh: function()
		{
			if (this.startDateInput && this.startDateInput.value && this.endDateInput && this.endDateInput.value) {
				var startDate = this.settings.parseDate(this.startDateInput);
				var endDate = this.settings.parseDate(this.endDateInput);
				if (startDate && endDate) {
					this.dateDelta = endDate.getTime() - startDate.getTime();
				}
			}
			if (this.startTimeInput && this.startTimeInput.value && this.endTimeInput && this.endTimeInput.value) {
				var startTime = this.settings.parseTime(this.startTimeInput);
				var endTime = this.settings.parseTime(this.endTimeInput);
				if (startTime && endTime) {
					this.timeDelta = endTime.getTime() - startTime.getTime();
					this._updateEndMintime();
				}
			}
		},
	
		remove: function()
		{
			this._unbindChangeHandler();
		},
	
		_bindChangeHandler: function(){
			// addEventListener doesn't work with synthetic "change" events
			// fired by jQuery's trigger() functioin. If jQuery is present,
			// use that for event binding
			if (jq) {
				jq(this.container).on('change.datepair', jq.proxy(this.handleEvent, this));
			} else {
				this.container.addEventListener('change', this, false);
			}
		},
	
		_unbindChangeHandler: function(){
			if (jq) {
				jq(this.container).off('change.datepair');
			} else {
				this.container.removeEventListener('change', this, false);
			}
		},
	
		// This function will be called when passing 'this' to addEventListener
		handleEvent: function(e){
			// temporarily unbind the change handler to prevent triggering this
			// if we update other inputs
			this._unbindChangeHandler();
	
			if (hasClass(e.target, this.settings.dateClass)) {
				if (e.target.value != '') {
					this._dateChanged(e.target);
					this._timeChanged(e.target);
				} else {
					this.dateDelta = null;
				}
	
			} else if (hasClass(e.target, this.settings.timeClass)) {
				if (e.target.value != '') {
					this._timeChanged(e.target);
				} else {
					this.timeDelta = null;
				}
			}
	
			this._validateRanges();
			this._updateEndMintime();
			this._bindChangeHandler();
		},
	
		_dateChanged: function(target){
			if (!this.startDateInput || !this.endDateInput) {
				return;
			}
	
			var startDate = this.settings.parseDate(this.startDateInput);
			var endDate = this.settings.parseDate(this.endDateInput);
	
			if (!startDate || !endDate) {
				if (this.settings.defaultDateDelta !== null) {
					if (startDate) {
						var newEnd = new Date(startDate.getTime() + this.settings.defaultDateDelta * _ONE_DAY);
						this.settings.updateDate(this.endDateInput, newEnd);
	
					} else if (endDate) {
						var newStart = new Date(endDate.getTime() - this.settings.defaultDateDelta * _ONE_DAY);
						this.settings.updateDate(this.startDateInput, newStart);
					}
	
					this.dateDelta = this.settings.defaultDateDelta * _ONE_DAY;
				} else {
					this.dateDelta = null;
				}
	
				return;
			}
	
			if (this.settings.anchor == 'start' && hasClass(target, this.settings.startClass)) {
				var newDate = new Date(startDate.getTime() + this.dateDelta);
				this.settings.updateDate(this.endDateInput, newDate);
			} else if (this.settings.anchor == 'end' && hasClass(target, this.settings.endClass)) {
				var newDate = new Date(endDate.getTime() - this.dateDelta);
				this.settings.updateDate(this.startDateInput, newDate);
			} else {
				if (endDate < startDate) {
					var otherInput = hasClass(target, this.settings.startClass) ? this.endDateInput : this.startDateInput;
					var selectedDate = this.settings.parseDate(target);
					this.dateDelta = 0;
					this.settings.updateDate(otherInput, selectedDate);
				} else {
					this.dateDelta = endDate.getTime() - startDate.getTime();
				}
			}
		},
	
		_timeChanged: function(target){
			if (!this.startTimeInput || !this.endTimeInput) {
				return;
			}
	
			var startTime = this.settings.parseTime(this.startTimeInput);
			var endTime = this.settings.parseTime(this.endTimeInput);
	
			if (!startTime || !endTime) {
				if (this.settings.defaultTimeDelta !== null) {
					if (startTime) {
						var newEnd = new Date(startTime.getTime() + this.settings.defaultTimeDelta);
						this.settings.updateTime(this.endTimeInput, newEnd);
					} else if (endTime) {
						var newStart = new Date(endTime.getTime() - this.settings.defaultTimeDelta);
						this.settings.updateTime(this.startTimeInput, newStart);
					}
	
					this.timeDelta = this.settings.defaultTimeDelta;
				} else {
					this.timeDelta = null;
				}
	
				return;
			}
	
			if (this.settings.anchor == 'start' && hasClass(target, this.settings.startClass)) {
				var newTime = new Date(startTime.getTime() + this.timeDelta);
				this.settings.updateTime(this.endTimeInput, newTime);
				endTime = this.settings.parseTime(this.endTimeInput);
	
				this._doMidnightRollover(startTime, endTime);
			} else if (this.settings.anchor == 'end' && hasClass(target, this.settings.endClass)) {
				var newTime = new Date(endTime.getTime() - this.timeDelta);
				this.settings.updateTime(this.startTimeInput, newTime);
				startTime = this.settings.parseTime(this.startTimeInput);
	
				this._doMidnightRollover(startTime, endTime);
			} else {
				this._doMidnightRollover(startTime, endTime);
	
				var startDate, endDate;
				if (this.startDateInput && this.endDateInput) {
					startDate = this.settings.parseDate(this.startDateInput);
					endDate = this.settings.parseDate(this.endDateInput);
				}
	
				if ((+startDate == +endDate) && (endTime < startTime)) {
					var thisInput  = hasClass(target, this.settings.endClass) ? this.endTimeInput : this.startTimeInput;
					var otherInput = hasClass(target, this.settings.startClass) ? this.endTimeInput : this.startTimeInput;
					var selectedTime = this.settings.parseTime(thisInput);
					this.timeDelta = 0;
					this.settings.updateTime(otherInput, selectedTime);
				} else {
					this.timeDelta = endTime.getTime() - startTime.getTime();
				}
			}
	
	
		},
	
		_doMidnightRollover: function(startTime, endTime) {
			if (!this.startDateInput || !this.endDateInput) {
				return;
			}
	
			var endDate = this.settings.parseDate(this.endDateInput);
			var startDate = this.settings.parseDate(this.startDateInput);
			var newDelta = endTime.getTime() - startTime.getTime();
			var offset = (endTime < startTime) ? _ONE_DAY : -1 * _ONE_DAY;
	
			if (this.dateDelta !== null
					&& this.dateDelta + this.timeDelta <= _ONE_DAY
					&& this.dateDelta + newDelta != 0
					&& (offset > 0 || this.dateDelta != 0)
					&& ((newDelta >= 0 && this.timeDelta < 0) || (newDelta < 0 && this.timeDelta >= 0))) {
	
				if (this.settings.anchor == 'start') {
					this.settings.updateDate(this.endDateInput, new Date(endDate.getTime() + offset));
					this._dateChanged(this.endDateInput);
				} else if (this.settings.anchor == 'end') {
					this.settings.updateDate(this.startDateInput, new Date(startDate.getTime() - offset));
					this._dateChanged(this.startDateInput);
				}
			}
			this.timeDelta = newDelta;
		},
	
		_updateEndMintime: function(){
			if (typeof this.settings.setMinTime != 'function') return;
	
			var baseTime = null;
			if (this.settings.anchor == 'start' && (!this.dateDelta || this.dateDelta < _ONE_DAY || (this.timeDelta && this.dateDelta + this.timeDelta < _ONE_DAY))) {
				baseTime = this.settings.parseTime(this.startTimeInput);
			}
	
			this.settings.setMinTime(this.endTimeInput, baseTime);
		},
	
		_validateRanges: function(){
			if (this.startTimeInput && this.endTimeInput && this.timeDelta === null) {
				triggerSimpleCustomEvent(this.container, 'rangeIncomplete');
				return;
			}
	
			if (this.startDateInput && this.endDateInput && this.dateDelta === null) {
				triggerSimpleCustomEvent(this.container, 'rangeIncomplete');
				return;
			}
	
			// due to the fact that times can wrap around, any time-only pair will be considered valid
			if (!this.startDateInput || !this.endDateInput || this.dateDelta + this.timeDelta >= 0) {
				triggerSimpleCustomEvent(this.container, 'rangeSelected');
			} else {
				triggerSimpleCustomEvent(this.container, 'rangeError');
			}
		}
	};

	window.Datepair = Datepair;

}(window, document));
/*
Copyright 2012 Igor Vaynberg

Version: 3.5.4 Timestamp: Sun Aug 30 13:30:32 EDT 2015

This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
General Public License version 2 (the "GPL License"). You may choose either license to govern your
use of this software only upon the condition that you accept all of the terms of either the Apache
License or the GPL License.

You may obtain a copy of the Apache License and the GPL License at:

    http://www.apache.org/licenses/LICENSE-2.0
    http://www.gnu.org/licenses/gpl-2.0.html

Unless required by applicable law or agreed to in writing, software distributed under the
Apache License or the GPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for
the specific language governing permissions and limitations under the Apache License and the GPL License.
*/

(function ($) {
    if(typeof $.fn.each2 == "undefined") {
        $.extend($.fn, {
            /*
            * 4-10 times faster .each replacement
            * use it carefully, as it overrides jQuery context of element on each iteration
            */
            each2 : function (c) {
                var j = $([0]), i = -1, l = this.length;
                while (
                    ++i < l
                    && (j.context = j[0] = this[i])
                    && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
                );
                return this;
            }
        });
    }
})(jQuery);

(function ($, undefined) {
    "use strict";
    /*global document, window, jQuery, console */

    if (window.Select2 !== undefined) {
        return;
    }

    var AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
        lastMousePosition={x:0,y:0}, $document, scrollBarDimensions,

    KEY = {
        TAB: 9,
        ENTER: 13,
        ESC: 27,
        SPACE: 32,
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        DOWN: 40,
        SHIFT: 16,
        CTRL: 17,
        ALT: 18,
        PAGE_UP: 33,
        PAGE_DOWN: 34,
        HOME: 36,
        END: 35,
        BACKSPACE: 8,
        DELETE: 46,
        isArrow: function (k) {
            k = k.which ? k.which : k;
            switch (k) {
            case KEY.LEFT:
            case KEY.RIGHT:
            case KEY.UP:
            case KEY.DOWN:
                return true;
            }
            return false;
        },
        isControl: function (e) {
            var k = e.which;
            switch (k) {
            case KEY.SHIFT:
            case KEY.CTRL:
            case KEY.ALT:
                return true;
            }

            if (e.metaKey) return true;

            return false;
        },
        isFunctionKey: function (k) {
            k = k.which ? k.which : k;
            return k >= 112 && k <= 123;
        }
    },
    MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>",

    DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z","\u0386":"\u0391","\u0388":"\u0395","\u0389":"\u0397","\u038A":"\u0399","\u03AA":"\u0399","\u038C":"\u039F","\u038E":"\u03A5","\u03AB":"\u03A5","\u038F":"\u03A9","\u03AC":"\u03B1","\u03AD":"\u03B5","\u03AE":"\u03B7","\u03AF":"\u03B9","\u03CA":"\u03B9","\u0390":"\u03B9","\u03CC":"\u03BF","\u03CD":"\u03C5","\u03CB":"\u03C5","\u03B0":"\u03C5","\u03C9":"\u03C9","\u03C2":"\u03C3"};

    $document = $(document);

    nextUid=(function() { var counter=1; return function() { return counter++; }; }());


    function reinsertElement(element) {
        var placeholder = $(document.createTextNode(''));

        element.before(placeholder);
        placeholder.before(element);
        placeholder.remove();
    }

    function stripDiacritics(str) {
        // Used 'uni range + named function' from http://jsperf.com/diacritics/18
        function match(a) {
            return DIACRITICS[a] || a;
        }

        return str.replace(/[^\u0000-\u007E]/g, match);
    }

    function indexOf(value, array) {
        var i = 0, l = array.length;
        for (; i < l; i = i + 1) {
            if (equal(value, array[i])) return i;
        }
        return -1;
    }

    function measureScrollbar () {
        var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
        $template.appendTo(document.body);

        var dim = {
            width: $template.width() - $template[0].clientWidth,
            height: $template.height() - $template[0].clientHeight
        };
        $template.remove();

        return dim;
    }

    /**
     * Compares equality of a and b
     * @param a
     * @param b
     */
    function equal(a, b) {
        if (a === b) return true;
        if (a === undefined || b === undefined) return false;
        if (a === null || b === null) return false;
        // Check whether 'a' or 'b' is a string (primitive or object).
        // The concatenation of an empty string (+'') converts its argument to a string's primitive.
        if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
        if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
        return false;
    }

    /**
     * Splits the string into an array of values, transforming each value. An empty array is returned for nulls or empty
     * strings
     * @param string
     * @param separator
     */
    function splitVal(string, separator, transform) {
        var val, i, l;
        if (string === null || string.length < 1) return [];
        val = string.split(separator);
        for (i = 0, l = val.length; i < l; i = i + 1) val[i] = transform(val[i]);
        return val;
    }

    function getSideBorderPadding(element) {
        return element.outerWidth(false) - element.width();
    }

    function installKeyUpChangeEvent(element) {
        var key="keyup-change-value";
        element.on("keydown", function () {
            if ($.data(element, key) === undefined) {
                $.data(element, key, element.val());
            }
        });
        element.on("keyup", function () {
            var val= $.data(element, key);
            if (val !== undefined && element.val() !== val) {
                $.removeData(element, key);
                element.trigger("keyup-change");
            }
        });
    }


    /**
     * filters mouse events so an event is fired only if the mouse moved.
     *
     * filters out mouse events that occur when mouse is stationary but
     * the elements under the pointer are scrolled.
     */
    function installFilteredMouseMove(element) {
        element.on("mousemove", function (e) {
            var lastpos = lastMousePosition;
            if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
                $(e.target).trigger("mousemove-filtered", e);
            }
        });
    }

    /**
     * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
     * within the last quietMillis milliseconds.
     *
     * @param quietMillis number of milliseconds to wait before invoking fn
     * @param fn function to be debounced
     * @param ctx object to be used as this reference within fn
     * @return debounced version of fn
     */
    function debounce(quietMillis, fn, ctx) {
        ctx = ctx || undefined;
        var timeout;
        return function () {
            var args = arguments;
            window.clearTimeout(timeout);
            timeout = window.setTimeout(function() {
                fn.apply(ctx, args);
            }, quietMillis);
        };
    }

    function installDebouncedScroll(threshold, element) {
        var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
        element.on("scroll", function (e) {
            if (indexOf(e.target, element.get()) >= 0) notify(e);
        });
    }

    function focus($el) {
        if ($el[0] === document.activeElement) return;

        /* set the focus in a 0 timeout - that way the focus is set after the processing
            of the current event has finished - which seems like the only reliable way
            to set focus */
        window.setTimeout(function() {
            var el=$el[0], pos=$el.val().length, range;

            $el.focus();

            /* make sure el received focus so we do not error out when trying to manipulate the caret.
                sometimes modals or others listeners may steal it after its set */
            var isVisible = (el.offsetWidth > 0 || el.offsetHeight > 0);
            if (isVisible && el === document.activeElement) {

                /* after the focus is set move the caret to the end, necessary when we val()
                    just before setting focus */
                if(el.setSelectionRange)
                {
                    el.setSelectionRange(pos, pos);
                }
                else if (el.createTextRange) {
                    range = el.createTextRange();
                    range.collapse(false);
                    range.select();
                }
            }
        }, 0);
    }

    function getCursorInfo(el) {
        el = $(el)[0];
        var offset = 0;
        var length = 0;
        if ('selectionStart' in el) {
            offset = el.selectionStart;
            length = el.selectionEnd - offset;
        } else if ('selection' in document) {
            el.focus();
            var sel = document.selection.createRange();
            length = document.selection.createRange().text.length;
            sel.moveStart('character', -el.value.length);
            offset = sel.text.length - length;
        }
        return { offset: offset, length: length };
    }

    function killEvent(event) {
        event.preventDefault();
        event.stopPropagation();
    }
    function killEventImmediately(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
    }

    function measureTextWidth(e) {
        if (!sizer){
            var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
            sizer = $(document.createElement("div")).css({
                position: "absolute",
                left: "-10000px",
                top: "-10000px",
                display: "none",
                fontSize: style.fontSize,
                fontFamily: style.fontFamily,
                fontStyle: style.fontStyle,
                fontWeight: style.fontWeight,
                letterSpacing: style.letterSpacing,
                textTransform: style.textTransform,
                whiteSpace: "nowrap"
            });
            sizer.attr("class","select2-sizer");
            $(document.body).append(sizer);
        }
        sizer.text(e.val());
        return sizer.width();
    }

    function syncCssClasses(dest, src, adapter) {
        var classes, replacements = [], adapted;

        classes = $.trim(dest.attr("class"));

        if (classes) {
            classes = '' + classes; // for IE which returns object

            $(classes.split(/\s+/)).each2(function() {
                if (this.indexOf("select2-") === 0) {
                    replacements.push(this);
                }
            });
        }

        classes = $.trim(src.attr("class"));

        if (classes) {
            classes = '' + classes; // for IE which returns object

            $(classes.split(/\s+/)).each2(function() {
                if (this.indexOf("select2-") !== 0) {
                    adapted = adapter(this);

                    if (adapted) {
                        replacements.push(adapted);
                    }
                }
            });
        }

        dest.attr("class", replacements.join(" "));
    }


    function markMatch(text, term, markup, escapeMarkup) {
        var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
            tl=term.length;

        if (match<0) {
            markup.push(escapeMarkup(text));
            return;
        }

        markup.push(escapeMarkup(text.substring(0, match)));
        markup.push("<span class='select2-match'>");
        markup.push(escapeMarkup(text.substring(match, match + tl)));
        markup.push("</span>");
        markup.push(escapeMarkup(text.substring(match + tl, text.length)));
    }

    function defaultEscapeMarkup(markup) {
        var replace_map = {
            '\\': '&#92;',
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;',
            "/": '&#47;'
        };

        return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
            return replace_map[match];
        });
    }

    /**
     * Produces an ajax-based query function
     *
     * @param options object containing configuration parameters
     * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
     * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
     * @param options.url url for the data
     * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
     * @param options.dataType request data type: ajax, jsonp, other datatypes supported by jQuery's $.ajax function or the transport function if specified
     * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
     * @param options.results a function(remoteData, pageNumber, query) that converts data returned form the remote request to the format expected by Select2.
     *      The expected format is an object containing the following keys:
     *      results array of objects that will be used as choices
     *      more (optional) boolean indicating whether there are more results available
     *      Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
     */
    function ajax(options) {
        var timeout, // current scheduled but not yet executed request
            handler = null,
            quietMillis = options.quietMillis || 100,
            ajaxUrl = options.url,
            self = this;

        return function (query) {
            window.clearTimeout(timeout);
            timeout = window.setTimeout(function () {
                var data = options.data, // ajax data function
                    url = ajaxUrl, // ajax url string or function
                    transport = options.transport || $.fn.select2.ajaxDefaults.transport,
                    // deprecated - to be removed in 4.0  - use params instead
                    deprecated = {
                        type: options.type || 'GET', // set type of request (GET or POST)
                        cache: options.cache || false,
                        jsonpCallback: options.jsonpCallback||undefined,
                        dataType: options.dataType||"json"
                    },
                    params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);

                data = data ? data.call(self, query.term, query.page, query.context) : null;
                url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;

                if (handler && typeof handler.abort === "function") { handler.abort(); }

                if (options.params) {
                    if ($.isFunction(options.params)) {
                        $.extend(params, options.params.call(self));
                    } else {
                        $.extend(params, options.params);
                    }
                }

                $.extend(params, {
                    url: url,
                    dataType: options.dataType,
                    data: data,
                    success: function (data) {
                        // TODO - replace query.page with query so users have access to term, page, etc.
                        // added query as third paramter to keep backwards compatibility
                        var results = options.results(data, query.page, query);
                        query.callback(results);
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        var results = {
                            hasError: true,
                            jqXHR: jqXHR,
                            textStatus: textStatus,
                            errorThrown: errorThrown
                        };

                        query.callback(results);
                    }
                });
                handler = transport.call(self, params);
            }, quietMillis);
        };
    }

    /**
     * Produces a query function that works with a local array
     *
     * @param options object containing configuration parameters. The options parameter can either be an array or an
     * object.
     *
     * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
     *
     * If the object form is used it is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
     * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
     * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
     * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
     * the text.
     */
    function local(options) {
        var data = options, // data elements
            dataText,
            tmp,
            text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search

         if ($.isArray(data)) {
            tmp = data;
            data = { results: tmp };
        }

         if ($.isFunction(data) === false) {
            tmp = data;
            data = function() { return tmp; };
        }

        var dataItem = data();
        if (dataItem.text) {
            text = dataItem.text;
            // if text is not a function we assume it to be a key name
            if (!$.isFunction(text)) {
                dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
                text = function (item) { return item[dataText]; };
            }
        }

        return function (query) {
            var t = query.term, filtered = { results: [] }, process;
            if (t === "") {
                query.callback(data());
                return;
            }

            process = function(datum, collection) {
                var group, attr;
                datum = datum[0];
                if (datum.children) {
                    group = {};
                    for (attr in datum) {
                        if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
                    }
                    group.children=[];
                    $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
                    if (group.children.length || query.matcher(t, text(group), datum)) {
                        collection.push(group);
                    }
                } else {
                    if (query.matcher(t, text(datum), datum)) {
                        collection.push(datum);
                    }
                }
            };

            $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
            query.callback(filtered);
        };
    }

    // TODO javadoc
    function tags(data) {
        var isFunc = $.isFunction(data);
        return function (query) {
            var t = query.term, filtered = {results: []};
            var result = isFunc ? data(query) : data;
            if ($.isArray(result)) {
                $(result).each(function () {
                    var isObject = this.text !== undefined,
                        text = isObject ? this.text : this;
                    if (t === "" || query.matcher(t, text)) {
                        filtered.results.push(isObject ? this : {id: this, text: this});
                    }
                });
                query.callback(filtered);
            }
        };
    }

    /**
     * Checks if the formatter function should be used.
     *
     * Throws an error if it is not a function. Returns true if it should be used,
     * false if no formatting should be performed.
     *
     * @param formatter
     */
    function checkFormatter(formatter, formatterName) {
        if ($.isFunction(formatter)) return true;
        if (!formatter) return false;
        if (typeof(formatter) === 'string') return true;
        throw new Error(formatterName +" must be a string, function, or falsy value");
    }

  /**
   * Returns a given value
   * If given a function, returns its output
   *
   * @param val string|function
   * @param context value of "this" to be passed to function
   * @returns {*}
   */
    function evaluate(val, context) {
        if ($.isFunction(val)) {
            var args = Array.prototype.slice.call(arguments, 2);
            return val.apply(context, args);
        }
        return val;
    }

    function countResults(results) {
        var count = 0;
        $.each(results, function(i, item) {
            if (item.children) {
                count += countResults(item.children);
            } else {
                count++;
            }
        });
        return count;
    }

    /**
     * Default tokenizer. This function uses breaks the input on substring match of any string from the
     * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
     * two options have to be defined in order for the tokenizer to work.
     *
     * @param input text user has typed so far or pasted into the search field
     * @param selection currently selected choices
     * @param selectCallback function(choice) callback tho add the choice to selection
     * @param opts select2's opts
     * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
     */
    function defaultTokenizer(input, selection, selectCallback, opts) {
        var original = input, // store the original so we can compare and know if we need to tell the search to update its text
            dupe = false, // check for whether a token we extracted represents a duplicate selected choice
            token, // token
            index, // position at which the separator was found
            i, l, // looping variables
            separator; // the matched separator

        if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;

        while (true) {
            index = -1;

            for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
                separator = opts.tokenSeparators[i];
                index = input.indexOf(separator);
                if (index >= 0) break;
            }

            if (index < 0) break; // did not find any token separator in the input string, bail

            token = input.substring(0, index);
            input = input.substring(index + separator.length);

            if (token.length > 0) {
                token = opts.createSearchChoice.call(this, token, selection);
                if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
                    dupe = false;
                    for (i = 0, l = selection.length; i < l; i++) {
                        if (equal(opts.id(token), opts.id(selection[i]))) {
                            dupe = true; break;
                        }
                    }

                    if (!dupe) selectCallback(token);
                }
            }
        }

        if (original!==input) return input;
    }

    function cleanupJQueryElements() {
        var self = this;

        $.each(arguments, function (i, element) {
            self[element].remove();
            self[element] = null;
        });
    }

    /**
     * Creates a new class
     *
     * @param superClass
     * @param methods
     */
    function clazz(SuperClass, methods) {
        var constructor = function () {};
        constructor.prototype = new SuperClass;
        constructor.prototype.constructor = constructor;
        constructor.prototype.parent = SuperClass.prototype;
        constructor.prototype = $.extend(constructor.prototype, methods);
        return constructor;
    }

    AbstractSelect2 = clazz(Object, {

        // abstract
        bind: function (func) {
            var self = this;
            return function () {
                func.apply(self, arguments);
            };
        },

        // abstract
        init: function (opts) {
            var results, search, resultsSelector = ".select2-results";

            // prepare options
            this.opts = opts = this.prepareOpts(opts);

            this.id=opts.id;

            // destroy if called on an existing component
            if (opts.element.data("select2") !== undefined &&
                opts.element.data("select2") !== null) {
                opts.element.data("select2").destroy();
            }

            this.container = this.createContainer();

            this.liveRegion = $('.select2-hidden-accessible');
            if (this.liveRegion.length == 0) {
                this.liveRegion = $("<span>", {
                        role: "status",
                        "aria-live": "polite"
                    })
                    .addClass("select2-hidden-accessible")
                    .appendTo(document.body);
            }

            this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
            this.containerEventName= this.containerId
                .replace(/([.])/g, '_')
                .replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
            this.container.attr("id", this.containerId);

            this.container.attr("title", opts.element.attr("title"));

            this.body = $(document.body);

            syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);

            this.container.attr("style", opts.element.attr("style"));
            this.container.css(evaluate(opts.containerCss, this.opts.element));
            this.container.addClass(evaluate(opts.containerCssClass, this.opts.element));

            this.elementTabIndex = this.opts.element.attr("tabindex");

            // swap container for the element
            this.opts.element
                .data("select2", this)
                .attr("tabindex", "-1")
                .before(this.container)
                .on("click.select2", killEvent); // do not leak click events

            this.container.data("select2", this);

            this.dropdown = this.container.find(".select2-drop");

            syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);

            this.dropdown.addClass(evaluate(opts.dropdownCssClass, this.opts.element));
            this.dropdown.data("select2", this);
            this.dropdown.on("click", killEvent);

            this.results = results = this.container.find(resultsSelector);
            this.search = search = this.container.find("input.select2-input");

            this.queryCount = 0;
            this.resultsPage = 0;
            this.context = null;

            // initialize the container
            this.initContainer();

            this.container.on("click", killEvent);

            installFilteredMouseMove(this.results);

            this.dropdown.on("mousemove-filtered", resultsSelector, this.bind(this.highlightUnderEvent));
            this.dropdown.on("touchstart touchmove touchend", resultsSelector, this.bind(function (event) {
                this._touchEvent = true;
                this.highlightUnderEvent(event);
            }));
            this.dropdown.on("touchmove", resultsSelector, this.bind(this.touchMoved));
            this.dropdown.on("touchstart touchend", resultsSelector, this.bind(this.clearTouchMoved));

            // Waiting for a click event on touch devices to select option and hide dropdown
            // otherwise click will be triggered on an underlying element
            this.dropdown.on('click', this.bind(function (event) {
                if (this._touchEvent) {
                    this._touchEvent = false;
                    this.selectHighlighted();
                }
            }));

            installDebouncedScroll(80, this.results);
            this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));

            // do not propagate change event from the search field out of the component
            $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
            $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});

            // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
            if ($.fn.mousewheel) {
                results.mousewheel(function (e, delta, deltaX, deltaY) {
                    var top = results.scrollTop();
                    if (deltaY > 0 && top - deltaY <= 0) {
                        results.scrollTop(0);
                        killEvent(e);
                    } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
                        results.scrollTop(results.get(0).scrollHeight - results.height());
                        killEvent(e);
                    }
                });
            }

            installKeyUpChangeEvent(search);
            search.on("keyup-change input paste", this.bind(this.updateResults));
            search.on("focus", function () { search.addClass("select2-focused"); });
            search.on("blur", function () { search.removeClass("select2-focused");});

            this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
                if ($(e.target).closest(".select2-result-selectable").length > 0) {
                    this.highlightUnderEvent(e);
                    this.selectHighlighted(e);
                }
            }));

            // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
            // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
            // dom it will trigger the popup close, which is not what we want
            // focusin can cause focus wars between modals and select2 since the dropdown is outside the modal.
            this.dropdown.on("click mouseup mousedown touchstart touchend focusin", function (e) { e.stopPropagation(); });

            this.lastSearchTerm = undefined;

            if ($.isFunction(this.opts.initSelection)) {
                // initialize selection based on the current value of the source element
                this.initSelection();

                // if the user has provided a function that can set selection based on the value of the source element
                // we monitor the change event on the element and trigger it, allowing for two way synchronization
                this.monitorSource();
            }

            if (opts.maximumInputLength !== null) {
                this.search.attr("maxlength", opts.maximumInputLength);
            }

            var disabled = opts.element.prop("disabled");
            if (disabled === undefined) disabled = false;
            this.enable(!disabled);

            var readonly = opts.element.prop("readonly");
            if (readonly === undefined) readonly = false;
            this.readonly(readonly);

            // Calculate size of scrollbar
            scrollBarDimensions = scrollBarDimensions || measureScrollbar();

            this.autofocus = opts.element.prop("autofocus");
            opts.element.prop("autofocus", false);
            if (this.autofocus) this.focus();

            this.search.attr("placeholder", opts.searchInputPlaceholder);
        },

        // abstract
        destroy: function () {
            var element=this.opts.element, select2 = element.data("select2"), self = this;

            this.close();

            if (element.length && element[0].detachEvent && self._sync) {
                element.each(function () {
                    if (self._sync) {
                        this.detachEvent("onpropertychange", self._sync);
                    }
                });
            }
            if (this.propertyObserver) {
                this.propertyObserver.disconnect();
                this.propertyObserver = null;
            }
            this._sync = null;

            if (select2 !== undefined) {
                select2.container.remove();
                select2.liveRegion.remove();
                select2.dropdown.remove();
                element.removeData("select2")
                    .off(".select2");
                if (!element.is("input[type='hidden']")) {
                    element
                        .show()
                        .prop("autofocus", this.autofocus || false);
                    if (this.elementTabIndex) {
                        element.attr({tabindex: this.elementTabIndex});
                    } else {
                        element.removeAttr("tabindex");
                    }
                    element.show();
                } else {
                    element.css("display", "");
                }
            }

            cleanupJQueryElements.call(this,
                "container",
                "liveRegion",
                "dropdown",
                "results",
                "search"
            );
        },

        // abstract
        optionToData: function(element) {
            if (element.is("option")) {
                return {
                    id:element.prop("value"),
                    text:element.text(),
                    element: element.get(),
                    css: element.attr("class"),
                    disabled: element.prop("disabled"),
                    locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
                };
            } else if (element.is("optgroup")) {
                return {
                    text:element.attr("label"),
                    children:[],
                    element: element.get(),
                    css: element.attr("class")
                };
            }
        },

        // abstract
        prepareOpts: function (opts) {
            var element, select, idKey, ajaxUrl, self = this;

            element = opts.element;

            if (element.get(0).tagName.toLowerCase() === "select") {
                this.select = select = opts.element;
            }

            if (select) {
                // these options are not allowed when attached to a select because they are picked up off the element itself
                $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
                    if (this in opts) {
                        throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
                    }
                });
            }

            opts.debug = opts.debug || $.fn.select2.defaults.debug;

            // Warnings for options renamed/removed in Select2 4.0.0
            // Only when it's enabled through debug mode
            if (opts.debug && console && console.warn) {
                // id was removed
                if (opts.id != null) {
                    console.warn(
                        'Select2: The `id` option has been removed in Select2 4.0.0, ' +
                        'consider renaming your `id` property or mapping the property before your data makes it to Select2. ' +
                        'You can read more at https://select2.github.io/announcements-4.0.html#changed-id'
                    );
                }

                // text was removed
                if (opts.text != null) {
                    console.warn(
                        'Select2: The `text` option has been removed in Select2 4.0.0, ' +
                        'consider renaming your `text` property or mapping the property before your data makes it to Select2. ' +
                        'You can read more at https://select2.github.io/announcements-4.0.html#changed-id'
                    );
                }

                // sortResults was renamed to results
                if (opts.sortResults != null) {
                    console.warn(
                        'Select2: the `sortResults` option has been renamed to `sorter` in Select2 4.0.0. '
                    );
                }

                // selectOnBlur was renamed to selectOnClose
                if (opts.selectOnBlur != null) {
                    console.warn(
                        'Select2: The `selectOnBlur` option has been renamed to `selectOnClose` in Select2 4.0.0.'
                    );
                }

                // ajax.results was renamed to ajax.processResults
                if (opts.ajax != null && opts.ajax.results != null) {
                    console.warn(
                        'Select2: The `ajax.results` option has been renamed to `ajax.processResults` in Select2 4.0.0.'
                    );
                }

                // format* options were renamed to language.*
                if (opts.formatNoResults != null) {
                    console.warn(
                        'Select2: The `formatNoResults` option has been renamed to `language.noResults` in Select2 4.0.0.'
                    );
                }
                if (opts.formatSearching != null) {
                    console.warn(
                        'Select2: The `formatSearching` option has been renamed to `language.searching` in Select2 4.0.0.'
                    );
                }
                if (opts.formatInputTooShort != null) {
                    console.warn(
                        'Select2: The `formatInputTooShort` option has been renamed to `language.inputTooShort` in Select2 4.0.0.'
                    );
                }
                if (opts.formatInputTooLong != null) {
                    console.warn(
                        'Select2: The `formatInputTooLong` option has been renamed to `language.inputTooLong` in Select2 4.0.0.'
                    );
                }
                if (opts.formatLoading != null) {
                    console.warn(
                        'Select2: The `formatLoading` option has been renamed to `language.loadingMore` in Select2 4.0.0.'
                    );
                }
                if (opts.formatSelectionTooBig != null) {
                    console.warn(
                        'Select2: The `formatSelectionTooBig` option has been renamed to `language.maximumSelected` in Select2 4.0.0.'
                    );
                }

                if (opts.element.data('select2Tags')) {
                    console.warn(
                        'Select2: The `data-select2-tags` attribute has been renamed to `data-tags` in Select2 4.0.0.'
                    );
                }
            }

            // Aliasing options renamed in Select2 4.0.0

            // data-select2-tags -> data-tags
            if (opts.element.data('tags') != null) {
                var elemTags = opts.element.data('tags');

                // data-tags should actually be a boolean
                if (!$.isArray(elemTags)) {
                    elemTags = [];
                }

                opts.element.data('select2Tags', elemTags);
            }

            // sortResults -> sorter
            if (opts.sorter != null) {
                opts.sortResults = opts.sorter;
            }

            // selectOnBlur -> selectOnClose
            if (opts.selectOnClose != null) {
                opts.selectOnBlur = opts.selectOnClose;
            }

            // ajax.results -> ajax.processResults
            if (opts.ajax != null) {
                if ($.isFunction(opts.ajax.processResults)) {
                    opts.ajax.results = opts.ajax.processResults;
                }
            }

            // Formatters/language options
            if (opts.language != null) {
                var lang = opts.language;

                // formatNoMatches -> language.noMatches
                if ($.isFunction(lang.noMatches)) {
                    opts.formatNoMatches = lang.noMatches;
                }

                // formatSearching -> language.searching
                if ($.isFunction(lang.searching)) {
                    opts.formatSearching = lang.searching;
                }

                // formatInputTooShort -> language.inputTooShort
                if ($.isFunction(lang.inputTooShort)) {
                    opts.formatInputTooShort = lang.inputTooShort;
                }

                // formatInputTooLong -> language.inputTooLong
                if ($.isFunction(lang.inputTooLong)) {
                    opts.formatInputTooLong = lang.inputTooLong;
                }

                // formatLoading -> language.loadingMore
                if ($.isFunction(lang.loadingMore)) {
                    opts.formatLoading = lang.loadingMore;
                }

                // formatSelectionTooBig -> language.maximumSelected
                if ($.isFunction(lang.maximumSelected)) {
                    opts.formatSelectionTooBig = lang.maximumSelected;
                }
            }

            opts = $.extend({}, {
                populateResults: function(container, results, query) {
                    var populate, id=this.opts.id, liveRegion=this.liveRegion;

                    populate=function(results, container, depth) {

                        var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;

                        results = opts.sortResults(results, container, query);

                        // collect the created nodes for bulk append
                        var nodes = [];
                        for (i = 0, l = results.length; i < l; i = i + 1) {

                            result=results[i];

                            disabled = (result.disabled === true);
                            selectable = (!disabled) && (id(result) !== undefined);

                            compound=result.children && result.children.length > 0;

                            node=$("<li></li>");
                            node.addClass("select2-results-dept-"+depth);
                            node.addClass("select2-result");
                            node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
                            if (disabled) { node.addClass("select2-disabled"); }
                            if (compound) { node.addClass("select2-result-with-children"); }
                            node.addClass(self.opts.formatResultCssClass(result));
                            node.attr("role", "presentation");

                            label=$(document.createElement("div"));
                            label.addClass("select2-result-label");
                            label.attr("id", "select2-result-label-" + nextUid());
                            label.attr("role", "option");

                            formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
                            if (formatted!==undefined) {
                                label.html(formatted);
                                node.append(label);
                            }


                            if (compound) {
                                innerContainer=$("<ul></ul>");
                                innerContainer.addClass("select2-result-sub");
                                populate(result.children, innerContainer, depth+1);
                                node.append(innerContainer);
                            }

                            node.data("select2-data", result);
                            nodes.push(node[0]);
                        }

                        // bulk append the created nodes
                        container.append(nodes);
                        liveRegion.text(opts.formatMatches(results.length));
                    };

                    populate(results, container, 0);
                }
            }, $.fn.select2.defaults, opts);

            if (typeof(opts.id) !== "function") {
                idKey = opts.id;
                opts.id = function (e) { return e[idKey]; };
            }

            if ($.isArray(opts.element.data("select2Tags"))) {
                if ("tags" in opts) {
                    throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
                }
                opts.tags=opts.element.data("select2Tags");
            }

            if (select) {
                opts.query = this.bind(function (query) {
                    var data = { results: [], more: false },
                        term = query.term,
                        children, placeholderOption, process;

                    process=function(element, collection) {
                        var group;
                        if (element.is("option")) {
                            if (query.matcher(term, element.text(), element)) {
                                collection.push(self.optionToData(element));
                            }
                        } else if (element.is("optgroup")) {
                            group=self.optionToData(element);
                            element.children().each2(function(i, elm) { process(elm, group.children); });
                            if (group.children.length>0) {
                                collection.push(group);
                            }
                        }
                    };

                    children=element.children();

                    // ignore the placeholder option if there is one
                    if (this.getPlaceholder() !== undefined && children.length > 0) {
                        placeholderOption = this.getPlaceholderOption();
                        if (placeholderOption) {
                            children=children.not(placeholderOption);
                        }
                    }

                    children.each2(function(i, elm) { process(elm, data.results); });

                    query.callback(data);
                });
                // this is needed because inside val() we construct choices from options and their id is hardcoded
                opts.id=function(e) { return e.id; };
            } else {
                if (!("query" in opts)) {
                    if ("ajax" in opts) {
                        ajaxUrl = opts.element.data("ajax-url");
                        if (ajaxUrl && ajaxUrl.length > 0) {
                            opts.ajax.url = ajaxUrl;
                        }
                        opts.query = ajax.call(opts.element, opts.ajax);
                    } else if ("data" in opts) {
                        opts.query = local(opts.data);
                    } else if ("tags" in opts) {
                        opts.query = tags(opts.tags);
                        if (opts.createSearchChoice === undefined) {
                            opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
                        }
                        if (opts.initSelection === undefined) {
                            opts.initSelection = function (element, callback) {
                                var data = [];
                                $(splitVal(element.val(), opts.separator, opts.transformVal)).each(function () {
                                    var obj = { id: this, text: this },
                                        tags = opts.tags;
                                    if ($.isFunction(tags)) tags=tags();
                                    $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
                                    data.push(obj);
                                });

                                callback(data);
                            };
                        }
                    }
                }
            }
            if (typeof(opts.query) !== "function") {
                throw "query function not defined for Select2 " + opts.element.attr("id");
            }

            if (opts.createSearchChoicePosition === 'top') {
                opts.createSearchChoicePosition = function(list, item) { list.unshift(item); };
            }
            else if (opts.createSearchChoicePosition === 'bottom') {
                opts.createSearchChoicePosition = function(list, item) { list.push(item); };
            }
            else if (typeof(opts.createSearchChoicePosition) !== "function")  {
                throw "invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function";
            }

            return opts;
        },

        /**
         * Monitor the original element for changes and update select2 accordingly
         */
        // abstract
        monitorSource: function () {
            var el = this.opts.element, observer, self = this;

            el.on("change.select2", this.bind(function (e) {
                if (this.opts.element.data("select2-change-triggered") !== true) {
                    this.initSelection();
                }
            }));

            this._sync = this.bind(function () {

                // sync enabled state
                var disabled = el.prop("disabled");
                if (disabled === undefined) disabled = false;
                this.enable(!disabled);

                var readonly = el.prop("readonly");
                if (readonly === undefined) readonly = false;
                this.readonly(readonly);

                if (this.container) {
                    syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
                    this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element));
                }

                if (this.dropdown) {
                    syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
                    this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element));
                }

            });

            // IE8-10 (IE9/10 won't fire propertyChange via attachEventListener)
            if (el.length && el[0].attachEvent) {
                el.each(function() {
                    this.attachEvent("onpropertychange", self._sync);
                });
            }

            // safari, chrome, firefox, IE11
            observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
            if (observer !== undefined) {
                if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
                this.propertyObserver = new observer(function (mutations) {
                    $.each(mutations, self._sync);
                });
                this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
            }
        },

        // abstract
        triggerSelect: function(data) {
            var evt = $.Event("select2-selecting", { val: this.id(data), object: data, choice: data });
            this.opts.element.trigger(evt);
            return !evt.isDefaultPrevented();
        },

        /**
         * Triggers the change event on the source element
         */
        // abstract
        triggerChange: function (details) {

            details = details || {};
            details= $.extend({}, details, { type: "change", val: this.val() });
            // prevents recursive triggering
            this.opts.element.data("select2-change-triggered", true);
            this.opts.element.trigger(details);
            this.opts.element.data("select2-change-triggered", false);

            // some validation frameworks ignore the change event and listen instead to keyup, click for selects
            // so here we trigger the click event manually
            this.opts.element.click();

            // ValidationEngine ignores the change event and listens instead to blur
            // so here we trigger the blur event manually if so desired
            if (this.opts.blurOnChange)
                this.opts.element.blur();
        },

        //abstract
        isInterfaceEnabled: function()
        {
            return this.enabledInterface === true;
        },

        // abstract
        enableInterface: function() {
            var enabled = this._enabled && !this._readonly,
                disabled = !enabled;

            if (enabled === this.enabledInterface) return false;

            this.container.toggleClass("select2-container-disabled", disabled);
            this.close();
            this.enabledInterface = enabled;

            return true;
        },

        // abstract
        enable: function(enabled) {
            if (enabled === undefined) enabled = true;
            if (this._enabled === enabled) return;
            this._enabled = enabled;

            this.opts.element.prop("disabled", !enabled);
            this.enableInterface();
        },

        // abstract
        disable: function() {
            this.enable(false);
        },

        // abstract
        readonly: function(enabled) {
            if (enabled === undefined) enabled = false;
            if (this._readonly === enabled) return;
            this._readonly = enabled;

            this.opts.element.prop("readonly", enabled);
            this.enableInterface();
        },

        // abstract
        opened: function () {
            return (this.container) ? this.container.hasClass("select2-dropdown-open") : false;
        },

        // abstract
        positionDropdown: function() {
            var $dropdown = this.dropdown,
                container = this.container,
                offset = container.offset(),
                height = container.outerHeight(false),
                width = container.outerWidth(false),
                dropHeight = $dropdown.outerHeight(false),
                $window = $(window),
                windowWidth = $window.width(),
                windowHeight = $window.height(),
                viewPortRight = $window.scrollLeft() + windowWidth,
                viewportBottom = $window.scrollTop() + windowHeight,
                dropTop = offset.top + height,
                dropLeft = offset.left,
                enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
                enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(),
                dropWidth = $dropdown.outerWidth(false),
                enoughRoomOnRight = function() {
                    return dropLeft + dropWidth <= viewPortRight;
                },
                enoughRoomOnLeft = function() {
                    return offset.left + viewPortRight + container.outerWidth(false)  > dropWidth;
                },
                aboveNow = $dropdown.hasClass("select2-drop-above"),
                bodyOffset,
                above,
                changeDirection,
                css,
                resultsListNode;

            // always prefer the current above/below alignment, unless there is not enough room
            if (aboveNow) {
                above = true;
                if (!enoughRoomAbove && enoughRoomBelow) {
                    changeDirection = true;
                    above = false;
                }
            } else {
                above = false;
                if (!enoughRoomBelow && enoughRoomAbove) {
                    changeDirection = true;
                    above = true;
                }
            }

            //if we are changing direction we need to get positions when dropdown is hidden;
            if (changeDirection) {
                $dropdown.hide();
                offset = this.container.offset();
                height = this.container.outerHeight(false);
                width = this.container.outerWidth(false);
                dropHeight = $dropdown.outerHeight(false);
                viewPortRight = $window.scrollLeft() + windowWidth;
                viewportBottom = $window.scrollTop() + windowHeight;
                dropTop = offset.top + height;
                dropLeft = offset.left;
                dropWidth = $dropdown.outerWidth(false);
                $dropdown.show();

                // fix so the cursor does not move to the left within the search-textbox in IE
                this.focusSearch();
            }

            if (this.opts.dropdownAutoWidth) {
                resultsListNode = $('.select2-results', $dropdown)[0];
                $dropdown.addClass('select2-drop-auto-width');
                $dropdown.css('width', '');
                // Add scrollbar width to dropdown if vertical scrollbar is present
                dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
                dropWidth > width ? width = dropWidth : dropWidth = width;
                dropHeight = $dropdown.outerHeight(false);
            }
            else {
                this.container.removeClass('select2-drop-auto-width');
            }

            //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
            //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body.scrollTop(), "enough?", enoughRoomAbove);

            // fix positioning when body has an offset and is not position: static
            if (this.body.css('position') !== 'static') {
                bodyOffset = this.body.offset();
                dropTop -= bodyOffset.top;
                dropLeft -= bodyOffset.left;
            }

            if (!enoughRoomOnRight() && enoughRoomOnLeft()) {
                dropLeft = offset.left + this.container.outerWidth(false) - dropWidth;
            }

            css =  {
                left: dropLeft,
                width: width
            };

            if (above) {
                this.container.addClass("select2-drop-above");
                $dropdown.addClass("select2-drop-above");
                dropHeight = $dropdown.outerHeight(false);
                css.top = offset.top - dropHeight;
                css.bottom = 'auto';
            }
            else {
                css.top = dropTop;
                css.bottom = 'auto';
                this.container.removeClass("select2-drop-above");
                $dropdown.removeClass("select2-drop-above");
            }
            css = $.extend(css, evaluate(this.opts.dropdownCss, this.opts.element));

            $dropdown.css(css);
        },

        // abstract
        shouldOpen: function() {
            var event;

            if (this.opened()) return false;

            if (this._enabled === false || this._readonly === true) return false;

            event = $.Event("select2-opening");
            this.opts.element.trigger(event);
            return !event.isDefaultPrevented();
        },

        // abstract
        clearDropdownAlignmentPreference: function() {
            // clear the classes used to figure out the preference of where the dropdown should be opened
            this.container.removeClass("select2-drop-above");
            this.dropdown.removeClass("select2-drop-above");
        },

        /**
         * Opens the dropdown
         *
         * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
         * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
         */
        // abstract
        open: function () {

            if (!this.shouldOpen()) return false;

            this.opening();

            // Only bind the document mousemove when the dropdown is visible
            $document.on("mousemove.select2Event", function (e) {
                lastMousePosition.x = e.pageX;
                lastMousePosition.y = e.pageY;
            });

            return true;
        },

        /**
         * Performs the opening of the dropdown
         */
        // abstract
        opening: function() {
            var cid = this.containerEventName,
                scroll = "scroll." + cid,
                resize = "resize."+cid,
                orient = "orientationchange."+cid,
                mask;

            this.container.addClass("select2-dropdown-open").addClass("select2-container-active");

            this.clearDropdownAlignmentPreference();

            if(this.dropdown[0] !== this.body.children().last()[0]) {
                this.dropdown.detach().appendTo(this.body);
            }

            // create the dropdown mask if doesn't already exist
            mask = $("#select2-drop-mask");
            if (mask.length === 0) {
                mask = $(document.createElement("div"));
                mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
                mask.hide();
                mask.appendTo(this.body);
                mask.on("mousedown touchstart click", function (e) {
                    // Prevent IE from generating a click event on the body
                    reinsertElement(mask);

                    var dropdown = $("#select2-drop"), self;
                    if (dropdown.length > 0) {
                        self=dropdown.data("select2");
                        if (self.opts.selectOnBlur) {
                            self.selectHighlighted({noFocus: true});
                        }
                        self.close();
                        e.preventDefault();
                        e.stopPropagation();
                    }
                });
            }

            // ensure the mask is always right before the dropdown
            if (this.dropdown.prev()[0] !== mask[0]) {
                this.dropdown.before(mask);
            }

            // move the global id to the correct dropdown
            $("#select2-drop").removeAttr("id");
            this.dropdown.attr("id", "select2-drop");

            // show the elements
            mask.show();

            this.positionDropdown();
            this.dropdown.show();
            this.positionDropdown();

            this.dropdown.addClass("select2-drop-active");

            // attach listeners to events that can change the position of the container and thus require
            // the position of the dropdown to be updated as well so it does not come unglued from the container
            var that = this;
            this.container.parents().add(window).each(function () {
                $(this).on(resize+" "+scroll+" "+orient, function (e) {
                    if (that.opened()) that.positionDropdown();
                });
            });


        },

        // abstract
        close: function () {
            if (!this.opened()) return;

            var cid = this.containerEventName,
                scroll = "scroll." + cid,
                resize = "resize."+cid,
                orient = "orientationchange."+cid;

            // unbind event listeners
            this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });

            this.clearDropdownAlignmentPreference();

            $("#select2-drop-mask").hide();
            this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
            this.dropdown.hide();
            this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
            this.results.empty();

            // Now that the dropdown is closed, unbind the global document mousemove event
            $document.off("mousemove.select2Event");

            this.clearSearch();
            this.search.removeClass("select2-active");

            // Remove the aria active descendant for highlighted element
            this.search.removeAttr("aria-activedescendant");
            this.opts.element.trigger($.Event("select2-close"));
        },

        /**
         * Opens control, sets input value, and updates results.
         */
        // abstract
        externalSearch: function (term) {
            this.open();
            this.search.val(term);
            this.updateResults(false);
        },

        // abstract
        clearSearch: function () {

        },

        /**
         * @return {Boolean} Whether or not search value was changed.
         * @private
         */
        prefillNextSearchTerm: function () {
            // initializes search's value with nextSearchTerm (if defined by user)
            // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
            if(this.search.val() !== "") {
                return false;
            }

            var nextSearchTerm = this.opts.nextSearchTerm(this.data(), this.lastSearchTerm);
            if(nextSearchTerm !== undefined){
                this.search.val(nextSearchTerm);
                this.search.select();
                return true;
            }

            return false;
        },

        //abstract
        getMaximumSelectionSize: function() {
            return evaluate(this.opts.maximumSelectionSize, this.opts.element);
        },

        // abstract
        ensureHighlightVisible: function () {
            var results = this.results, children, index, child, hb, rb, y, more, topOffset;

            index = this.highlight();

            if (index < 0) return;

            if (index == 0) {

                // if the first element is highlighted scroll all the way to the top,
                // that way any unselectable headers above it will also be scrolled
                // into view

                results.scrollTop(0);
                return;
            }

            children = this.findHighlightableChoices().find('.select2-result-label');

            child = $(children[index]);

            topOffset = (child.offset() || {}).top || 0;

            hb = topOffset + child.outerHeight(true);

            // if this is the last child lets also make sure select2-more-results is visible
            if (index === children.length - 1) {
                more = results.find("li.select2-more-results");
                if (more.length > 0) {
                    hb = more.offset().top + more.outerHeight(true);
                }
            }

            rb = results.offset().top + results.outerHeight(false);
            if (hb > rb) {
                results.scrollTop(results.scrollTop() + (hb - rb));
            }
            y = topOffset - results.offset().top;

            // make sure the top of the element is visible
            if (y < 0 && child.css('display') != 'none' ) {
                results.scrollTop(results.scrollTop() + y); // y is negative
            }
        },

        // abstract
        findHighlightableChoices: function() {
            return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)");
        },

        // abstract
        moveHighlight: function (delta) {
            var choices = this.findHighlightableChoices(),
                index = this.highlight();

            while (index > -1 && index < choices.length) {
                index += delta;
                var choice = $(choices[index]);
                if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
                    this.highlight(index);
                    break;
                }
            }
        },

        // abstract
        highlight: function (index) {
            var choices = this.findHighlightableChoices(),
                choice,
                data;

            if (arguments.length === 0) {
                return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
            }

            if (index >= choices.length) index = choices.length - 1;
            if (index < 0) index = 0;

            this.removeHighlight();

            choice = $(choices[index]);
            choice.addClass("select2-highlighted");

            // ensure assistive technology can determine the active choice
            this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id"));

            this.ensureHighlightVisible();

            this.liveRegion.text(choice.text());

            data = choice.data("select2-data");
            if (data) {
                this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
            }
        },

        removeHighlight: function() {
            this.results.find(".select2-highlighted").removeClass("select2-highlighted");
        },

        touchMoved: function() {
            this._touchMoved = true;
        },

        clearTouchMoved: function() {
          this._touchMoved = false;
        },

        // abstract
        countSelectableResults: function() {
            return this.findHighlightableChoices().length;
        },

        // abstract
        highlightUnderEvent: function (event) {
            var el = $(event.target).closest(".select2-result-selectable");
            if (el.length > 0 && !el.is(".select2-highlighted")) {
                var choices = this.findHighlightableChoices();
                this.highlight(choices.index(el));
            } else if (el.length == 0) {
                // if we are over an unselectable item remove all highlights
                this.removeHighlight();
            }
        },

        // abstract
        loadMoreIfNeeded: function () {
            var results = this.results,
                more = results.find("li.select2-more-results"),
                below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
                page = this.resultsPage + 1,
                self=this,
                term=this.search.val(),
                context=this.context;

            if (more.length === 0) return;
            below = more.offset().top - results.offset().top - results.height();

            if (below <= this.opts.loadMorePadding) {
                more.addClass("select2-active");
                this.opts.query({
                        element: this.opts.element,
                        term: term,
                        page: page,
                        context: context,
                        matcher: this.opts.matcher,
                        callback: this.bind(function (data) {

                    // ignore a response if the select2 has been closed before it was received
                    if (!self.opened()) return;


                    self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
                    self.postprocessResults(data, false, false);

                    if (data.more===true) {
                        more.detach().appendTo(results).html(self.opts.escapeMarkup(evaluate(self.opts.formatLoadMore, self.opts.element, page+1)));
                        window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
                    } else {
                        more.remove();
                    }
                    self.positionDropdown();
                    self.resultsPage = page;
                    self.context = data.context;
                    this.opts.element.trigger({ type: "select2-loaded", items: data });
                })});
            }
        },

        /**
         * Default tokenizer function which does nothing
         */
        tokenize: function() {

        },

        /**
         * @param initial whether or not this is the call to this method right after the dropdown has been opened
         */
        // abstract
        updateResults: function (initial) {
            var search = this.search,
                results = this.results,
                opts = this.opts,
                data,
                self = this,
                input,
                term = search.val(),
                lastTerm = $.data(this.container, "select2-last-term"),
                // sequence number used to drop out-of-order responses
                queryNumber;

            // prevent duplicate queries against the same term
            if (initial !== true && lastTerm && equal(term, lastTerm)) return;

            $.data(this.container, "select2-last-term", term);

            // if the search is currently hidden we do not alter the results
            if (initial !== true && (this.showSearchInput === false || !this.opened())) {
                return;
            }

            function postRender() {
                search.removeClass("select2-active");
                self.positionDropdown();
                if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) {
                    self.liveRegion.text(results.text());
                }
                else {
                    self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable:not(".select2-selected")').length));
                }
            }

            function render(html) {
                results.html(html);
                postRender();
            }

            queryNumber = ++this.queryCount;

            var maxSelSize = this.getMaximumSelectionSize();
            if (maxSelSize >=1) {
                data = this.data();
                if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
                    render("<li class='select2-selection-limit'>" + evaluate(opts.formatSelectionTooBig, opts.element, maxSelSize) + "</li>");
                    return;
                }
            }

            if (search.val().length < opts.minimumInputLength) {
                if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
                    render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooShort, opts.element, search.val(), opts.minimumInputLength) + "</li>");
                } else {
                    render("");
                }
                if (initial && this.showSearch) this.showSearch(true);
                return;
            }

            if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
                if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
                    render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooLong, opts.element, search.val(), opts.maximumInputLength) + "</li>");
                } else {
                    render("");
                }
                return;
            }

            if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
                render("<li class='select2-searching'>" + evaluate(opts.formatSearching, opts.element) + "</li>");
            }

            search.addClass("select2-active");

            this.removeHighlight();

            // give the tokenizer a chance to pre-process the input
            input = this.tokenize();
            if (input != undefined && input != null) {
                search.val(input);
            }

            this.resultsPage = 1;

            opts.query({
                element: opts.element,
                    term: search.val(),
                    page: this.resultsPage,
                    context: null,
                    matcher: opts.matcher,
                    callback: this.bind(function (data) {
                var def; // default choice

                // ignore old responses
                if (queryNumber != this.queryCount) {
                  return;
                }

                // ignore a response if the select2 has been closed before it was received
                if (!this.opened()) {
                    this.search.removeClass("select2-active");
                    return;
                }

                // handle ajax error
                if(data.hasError !== undefined && checkFormatter(opts.formatAjaxError, "formatAjaxError")) {
                    render("<li class='select2-ajax-error'>" + evaluate(opts.formatAjaxError, opts.element, data.jqXHR, data.textStatus, data.errorThrown) + "</li>");
                    return;
                }

                // save context, if any
                this.context = (data.context===undefined) ? null : data.context;
                // create a default choice and prepend it to the list
                if (this.opts.createSearchChoice && search.val() !== "") {
                    def = this.opts.createSearchChoice.call(self, search.val(), data.results);
                    if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
                        if ($(data.results).filter(
                            function () {
                                return equal(self.id(this), self.id(def));
                            }).length === 0) {
                            this.opts.createSearchChoicePosition(data.results, def);
                        }
                    }
                }

                if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
                    render("<li class='select2-no-results'>" + evaluate(opts.formatNoMatches, opts.element, search.val()) + "</li>");
                    if(this.showSearch){
                        this.showSearch(search.val());
                    }
                    return;
                }

                results.empty();
                self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});

                if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
                    results.append("<li class='select2-more-results'>" + opts.escapeMarkup(evaluate(opts.formatLoadMore, opts.element, this.resultsPage)) + "</li>");
                    window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
                }

                this.postprocessResults(data, initial);

                postRender();

                this.opts.element.trigger({ type: "select2-loaded", items: data });
            })});
        },

        // abstract
        cancel: function () {
            this.close();
        },

        // abstract
        blur: function () {
            // if selectOnBlur == true, select the currently highlighted option
            if (this.opts.selectOnBlur)
                this.selectHighlighted({noFocus: true});

            this.close();
            this.container.removeClass("select2-container-active");
            // synonymous to .is(':focus'), which is available in jquery >= 1.6
            if (this.search[0] === document.activeElement) { this.search.blur(); }
            this.clearSearch();
            this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
        },

        // abstract
        focusSearch: function () {
            focus(this.search);
        },

        // abstract
        selectHighlighted: function (options) {
            if (this._touchMoved) {
              this.clearTouchMoved();
              return;
            }
            var index=this.highlight(),
                highlighted=this.results.find(".select2-highlighted"),
                data = highlighted.closest('.select2-result').data("select2-data");

            if (data) {
                this.highlight(index);
                this.onSelect(data, options);
            } else if (options && options.noFocus) {
                this.close();
            }
        },

        // abstract
        getPlaceholder: function () {
            var placeholderOption;
            return this.opts.element.attr("placeholder") ||
                this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
                this.opts.element.data("placeholder") ||
                this.opts.placeholder ||
                ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
        },

        // abstract
        getPlaceholderOption: function() {
            if (this.select) {
                var firstOption = this.select.children('option').first();
                if (this.opts.placeholderOption !== undefined ) {
                    //Determine the placeholder option based on the specified placeholderOption setting
                    return (this.opts.placeholderOption === "first" && firstOption) ||
                           (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
                } else if ($.trim(firstOption.text()) === "" && firstOption.val() === "") {
                    //No explicit placeholder option specified, use the first if it's blank
                    return firstOption;
                }
            }
        },

        /**
         * Get the desired width for the container element.  This is
         * derived first from option `width` passed to select2, then
         * the inline 'style' on the original element, and finally
         * falls back to the jQuery calculated element width.
         */
        // abstract
        initContainerWidth: function () {
            function resolveContainerWidth() {
                var style, attrs, matches, i, l, attr;

                if (this.opts.width === "off") {
                    return null;
                } else if (this.opts.width === "element"){
                    return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
                } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
                    // check if there is inline style on the element that contains width
                    style = this.opts.element.attr('style');
                    if (typeof(style) === "string") {
                        attrs = style.split(';');
                        for (i = 0, l = attrs.length; i < l; i = i + 1) {
                            attr = attrs[i].replace(/\s/g, '');
                            matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
                            if (matches !== null && matches.length >= 1)
                                return matches[1];
                        }
                    }

                    if (this.opts.width === "resolve") {
                        // next check if css('width') can resolve a width that is percent based, this is sometimes possible
                        // when attached to input type=hidden or elements hidden via css
                        style = this.opts.element.css('width');
                        if (style.indexOf("%") > 0) return style;

                        // finally, fallback on the calculated width of the element
                        return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
                    }

                    return null;
                } else if ($.isFunction(this.opts.width)) {
                    return this.opts.width();
                } else {
                    return this.opts.width;
               }
            };

            var width = resolveContainerWidth.call(this);
            if (width !== null) {
                this.container.css("width", width);
            }
        }
    });

    SingleSelect2 = clazz(AbstractSelect2, {

        // single

        createContainer: function () {
            var container = $(document.createElement("div")).attr({
                "class": "select2-container"
            }).html([
                "<a href='javascript:void(0)' class='select2-choice' tabindex='-1'>",
                "   <span class='select2-chosen'>&#160;</span><abbr class='select2-search-choice-close'></abbr>",
                "   <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>",
                "</a>",
                "<label for='' class='select2-offscreen'></label>",
                "<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />",
                "<div class='select2-drop select2-display-none'>",
                "   <div class='select2-search'>",
                "       <label for='' class='select2-offscreen'></label>",
                "       <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'",
                "       aria-autocomplete='list' />",
                "   </div>",
                "   <ul class='select2-results' role='listbox'>",
                "   </ul>",
                "</div>"].join(""));
            return container;
        },

        // single
        enableInterface: function() {
            if (this.parent.enableInterface.apply(this, arguments)) {
                this.focusser.prop("disabled", !this.isInterfaceEnabled());
            }
        },

        // single
        opening: function () {
            var el, range, len;

            if (this.opts.minimumResultsForSearch >= 0) {
                this.showSearch(true);
            }

            this.parent.opening.apply(this, arguments);

            if (this.showSearchInput !== false) {
                // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
                // all other browsers handle this just fine

                this.search.val(this.focusser.val());
            }
            if (this.opts.shouldFocusInput(this)) {
                this.search.focus();
                // move the cursor to the end after focussing, otherwise it will be at the beginning and
                // new text will appear *before* focusser.val()
                el = this.search.get(0);
                if (el.createTextRange) {
                    range = el.createTextRange();
                    range.collapse(false);
                    range.select();
                } else if (el.setSelectionRange) {
                    len = this.search.val().length;
                    el.setSelectionRange(len, len);
                }
            }

            this.prefillNextSearchTerm();

            this.focusser.prop("disabled", true).val("");
            this.updateResults(true);
            this.opts.element.trigger($.Event("select2-open"));
        },

        // single
        close: function () {
            if (!this.opened()) return;
            this.parent.close.apply(this, arguments);

            this.focusser.prop("disabled", false);

            if (this.opts.shouldFocusInput(this)) {
                this.focusser.focus();
            }
        },

        // single
        focus: function () {
            if (this.opened()) {
                this.close();
            } else {
                this.focusser.prop("disabled", false);
                if (this.opts.shouldFocusInput(this)) {
                    this.focusser.focus();
                }
            }
        },

        // single
        isFocused: function () {
            return this.container.hasClass("select2-container-active");
        },

        // single
        cancel: function () {
            this.parent.cancel.apply(this, arguments);
            this.focusser.prop("disabled", false);

            if (this.opts.shouldFocusInput(this)) {
                this.focusser.focus();
            }
        },

        // single
        destroy: function() {
            $("label[for='" + this.focusser.attr('id') + "']")
                .attr('for', this.opts.element.attr("id"));
            this.parent.destroy.apply(this, arguments);

            cleanupJQueryElements.call(this,
                "selection",
                "focusser"
            );
        },

        // single
        initContainer: function () {

            var selection,
                container = this.container,
                dropdown = this.dropdown,
                idSuffix = nextUid(),
                elementLabel;

            if (this.opts.minimumResultsForSearch < 0) {
                this.showSearch(false);
            } else {
                this.showSearch(true);
            }

            this.selection = selection = container.find(".select2-choice");

            this.focusser = container.find(".select2-focusser");

            // add aria associations
            selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix);
            this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix);
            this.results.attr("id", "select2-results-"+idSuffix);
            this.search.attr("aria-owns", "select2-results-"+idSuffix);

            // rewrite labels from original element to focusser
            this.focusser.attr("id", "s2id_autogen"+idSuffix);

            elementLabel = $("label[for='" + this.opts.element.attr("id") + "']");
            this.opts.element.on('focus.select2', this.bind(function () { this.focus(); }));

            this.focusser.prev()
                .text(elementLabel.text())
                .attr('for', this.focusser.attr('id'));

            // Ensure the original element retains an accessible name
            var originalTitle = this.opts.element.attr("title");
            this.opts.element.attr("title", (originalTitle || elementLabel.text()));

            this.focusser.attr("tabindex", this.elementTabIndex);

            // write label for search field using the label from the focusser element
            this.search.attr("id", this.focusser.attr('id') + '_search');

            this.search.prev()
                .text($("label[for='" + this.focusser.attr('id') + "']").text())
                .attr('for', this.search.attr('id'));

            this.search.on("keydown", this.bind(function (e) {
                if (!this.isInterfaceEnabled()) return;

                // filter 229 keyCodes (input method editor is processing key input)
                if (229 == e.keyCode) return;

                if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
                    // prevent the page from scrolling
                    killEvent(e);
                    return;
                }

                switch (e.which) {
                    case KEY.UP:
                    case KEY.DOWN:
                        this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
                        killEvent(e);
                        return;
                    case KEY.ENTER:
                        this.selectHighlighted();
                        killEvent(e);
                        return;
                    case KEY.TAB:
                        this.selectHighlighted({noFocus: true});
                        return;
                    case KEY.ESC:
                        this.cancel(e);
                        killEvent(e);
                        return;
                }
            }));

            this.search.on("blur", this.bind(function(e) {
                // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
                // without this the search field loses focus which is annoying
                if (document.activeElement === this.body.get(0)) {
                    window.setTimeout(this.bind(function() {
                        if (this.opened() && this.results && this.results.length > 1) {
                            this.search.focus();
                        }
                    }), 0);
                }
            }));

            this.focusser.on("keydown", this.bind(function (e) {
                if (!this.isInterfaceEnabled()) return;

                if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
                    return;
                }

                if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
                    killEvent(e);
                    return;
                }

                if (e.which == KEY.DOWN || e.which == KEY.UP
                    || (e.which == KEY.ENTER && this.opts.openOnEnter)) {

                    if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;

                    this.open();
                    killEvent(e);
                    return;
                }

                if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
                    if (this.opts.allowClear) {
                        this.clear();
                    }
                    killEvent(e);
                    return;
                }
            }));


            installKeyUpChangeEvent(this.focusser);
            this.focusser.on("keyup-change input", this.bind(function(e) {
                if (this.opts.minimumResultsForSearch >= 0) {
                    e.stopPropagation();
                    if (this.opened()) return;
                    this.open();
                }
            }));

            selection.on("mousedown touchstart", "abbr", this.bind(function (e) {
                if (!this.isInterfaceEnabled()) {
                    return;
                }

                this.clear();
                killEventImmediately(e);
                this.close();

                if (this.selection) {
                    this.selection.focus();
                }
            }));

            selection.on("mousedown touchstart", this.bind(function (e) {
                // Prevent IE from generating a click event on the body
                reinsertElement(selection);

                if (!this.container.hasClass("select2-container-active")) {
                    this.opts.element.trigger($.Event("select2-focus"));
                }

                if (this.opened()) {
                    this.close();
                } else if (this.isInterfaceEnabled()) {
                    this.open();
                }

                killEvent(e);
            }));

            dropdown.on("mousedown touchstart", this.bind(function() {
                if (this.opts.shouldFocusInput(this)) {
                    this.search.focus();
                }
            }));

            selection.on("focus", this.bind(function(e) {
                killEvent(e);
            }));

            this.focusser.on("focus", this.bind(function(){
                if (!this.container.hasClass("select2-container-active")) {
                    this.opts.element.trigger($.Event("select2-focus"));
                }
                this.container.addClass("select2-container-active");
            })).on("blur", this.bind(function() {
                if (!this.opened()) {
                    this.container.removeClass("select2-container-active");
                    this.opts.element.trigger($.Event("select2-blur"));
                }
            }));
            this.search.on("focus", this.bind(function(){
                if (!this.container.hasClass("select2-container-active")) {
                    this.opts.element.trigger($.Event("select2-focus"));
                }
                this.container.addClass("select2-container-active");
            }));

            this.initContainerWidth();
            this.opts.element.hide();
            this.setPlaceholder();

        },

        // single
        clear: function(triggerChange) {
            var data=this.selection.data("select2-data");
            if (data) { // guard against queued quick consecutive clicks
                var evt = $.Event("select2-clearing");
                this.opts.element.trigger(evt);
                if (evt.isDefaultPrevented()) {
                    return;
                }
                var placeholderOption = this.getPlaceholderOption();
                this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
                this.selection.find(".select2-chosen").empty();
                this.selection.removeData("select2-data");
                this.setPlaceholder();

                if (triggerChange !== false){
                    this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
                    this.triggerChange({removed:data});
                }
            }
        },

        /**
         * Sets selection based on source element's value
         */
        // single
        initSelection: function () {
            var selected;
            if (this.isPlaceholderOptionSelected()) {
                this.updateSelection(null);
                this.close();
                this.setPlaceholder();
            } else {
                var self = this;
                this.opts.initSelection.call(null, this.opts.element, function(selected){
                    if (selected !== undefined && selected !== null) {
                        self.updateSelection(selected);
                        self.close();
                        self.setPlaceholder();
                        self.lastSearchTerm = self.search.val();
                    }
                });
            }
        },

        isPlaceholderOptionSelected: function() {
            var placeholderOption;
            if (this.getPlaceholder() === undefined) return false; // no placeholder specified so no option should be considered
            return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
                || (this.opts.element.val() === "")
                || (this.opts.element.val() === undefined)
                || (this.opts.element.val() === null);
        },

        // single
        prepareOpts: function () {
            var opts = this.parent.prepareOpts.apply(this, arguments),
                self=this;

            if (opts.element.get(0).tagName.toLowerCase() === "select") {
                // install the selection initializer
                opts.initSelection = function (element, callback) {
                    var selected = element.find("option").filter(function() { return this.selected && !this.disabled });
                    // a single select box always has a value, no need to null check 'selected'
                    callback(self.optionToData(selected));
                };
            } else if ("data" in opts) {
                // install default initSelection when applied to hidden input and data is local
                opts.initSelection = opts.initSelection || function (element, callback) {
                    var id = element.val();
                    //search in data by id, storing the actual matching item
                    var match = null;
                    opts.query({
                        matcher: function(term, text, el){
                            var is_match = equal(id, opts.id(el));
                            if (is_match) {
                                match = el;
                            }
                            return is_match;
                        },
                        callback: !$.isFunction(callback) ? $.noop : function() {
                            callback(match);
                        }
                    });
                };
            }

            return opts;
        },

        // single
        getPlaceholder: function() {
            // if a placeholder is specified on a single select without a valid placeholder option ignore it
            if (this.select) {
                if (this.getPlaceholderOption() === undefined) {
                    return undefined;
                }
            }

            return this.parent.getPlaceholder.apply(this, arguments);
        },

        // single
        setPlaceholder: function () {
            var placeholder = this.getPlaceholder();

            if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {

                // check for a placeholder option if attached to a select
                if (this.select && this.getPlaceholderOption() === undefined) return;

                this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));

                this.selection.addClass("select2-default");

                this.container.removeClass("select2-allowclear");
            }
        },

        // single
        postprocessResults: function (data, initial, noHighlightUpdate) {
            var selected = 0, self = this, showSearchInput = true;

            // find the selected element in the result list

            this.findHighlightableChoices().each2(function (i, elm) {
                if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
                    selected = i;
                    return false;
                }
            });

            // and highlight it
            if (noHighlightUpdate !== false) {
                if (initial === true && selected >= 0) {
                    this.highlight(selected);
                } else {
                    this.highlight(0);
                }
            }

            // hide the search box if this is the first we got the results and there are enough of them for search

            if (initial === true) {
                var min = this.opts.minimumResultsForSearch;
                if (min >= 0) {
                    this.showSearch(countResults(data.results) >= min);
                }
            }
        },

        // single
        showSearch: function(showSearchInput) {
            if (this.showSearchInput === showSearchInput) return;

            this.showSearchInput = showSearchInput;

            this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
            this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
            //add "select2-with-searchbox" to the container if search box is shown
            $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
        },

        // single
        onSelect: function (data, options) {

            if (!this.triggerSelect(data)) { return; }

            var old = this.opts.element.val(),
                oldData = this.data();

            this.opts.element.val(this.id(data));
            this.updateSelection(data);

            this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });

            this.lastSearchTerm = this.search.val();
            this.close();

            if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) {
                this.focusser.focus();
            }

            if (!equal(old, this.id(data))) {
                this.triggerChange({ added: data, removed: oldData });
            }
        },

        // single
        updateSelection: function (data) {

            var container=this.selection.find(".select2-chosen"), formatted, cssClass;

            this.selection.data("select2-data", data);

            container.empty();
            if (data !== null) {
                formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
            }
            if (formatted !== undefined) {
                container.append(formatted);
            }
            cssClass=this.opts.formatSelectionCssClass(data, container);
            if (cssClass !== undefined) {
                container.addClass(cssClass);
            }

            this.selection.removeClass("select2-default");

            if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
                this.container.addClass("select2-allowclear");
            }
        },

        // single
        val: function () {
            var val,
                triggerChange = false,
                data = null,
                self = this,
                oldData = this.data();

            if (arguments.length === 0) {
                return this.opts.element.val();
            }

            val = arguments[0];

            if (arguments.length > 1) {
                triggerChange = arguments[1];

                if (this.opts.debug && console && console.warn) {
                    console.warn(
                        'Select2: The second option to `select2("val")` is not supported in Select2 4.0.0. ' +
                        'The `change` event will always be triggered in 4.0.0.'
                    );
                }
            }

            if (this.select) {
                if (this.opts.debug && console && console.warn) {
                    console.warn(
                        'Select2: Setting the value on a <select> using `select2("val")` is no longer supported in 4.0.0. ' +
                        'You can use the `.val(newValue).trigger("change")` method provided by jQuery instead.'
                    );
                }

                this.select
                    .val(val)
                    .find("option").filter(function() { return this.selected }).each2(function (i, elm) {
                        data = self.optionToData(elm);
                        return false;
                    });
                this.updateSelection(data);
                this.setPlaceholder();
                if (triggerChange) {
                    this.triggerChange({added: data, removed:oldData});
                }
            } else {
                // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
                if (!val && val !== 0) {
                    this.clear(triggerChange);
                    return;
                }
                if (this.opts.initSelection === undefined) {
                    throw new Error("cannot call val() if initSelection() is not defined");
                }
                this.opts.element.val(val);
                this.opts.initSelection(this.opts.element, function(data){
                    self.opts.element.val(!data ? "" : self.id(data));
                    self.updateSelection(data);
                    self.setPlaceholder();
                    if (triggerChange) {
                        self.triggerChange({added: data, removed:oldData});
                    }
                });
            }
        },

        // single
        clearSearch: function () {
            this.search.val("");
            this.focusser.val("");
        },

        // single
        data: function(value) {
            var data,
                triggerChange = false;

            if (arguments.length === 0) {
                data = this.selection.data("select2-data");
                if (data == undefined) data = null;
                return data;
            } else {
                if (this.opts.debug && console && console.warn) {
                    console.warn(
                        'Select2: The `select2("data")` method can no longer set selected values in 4.0.0, ' +
                        'consider using the `.val()` method instead.'
                    );
                }

                if (arguments.length > 1) {
                    triggerChange = arguments[1];
                }
                if (!value) {
                    this.clear(triggerChange);
                } else {
                    data = this.data();
                    this.opts.element.val(!value ? "" : this.id(value));
                    this.updateSelection(value);
                    if (triggerChange) {
                        this.triggerChange({added: value, removed:data});
                    }
                }
            }
        }
    });

    MultiSelect2 = clazz(AbstractSelect2, {

        // multi
        createContainer: function () {
            var container = $(document.createElement("div")).attr({
                "class": "select2-container select2-container-multi"
            }).html([
                "<ul class='select2-choices'>",
                "  <li class='select2-search-field'>",
                "    <label for='' class='select2-offscreen'></label>",
                "    <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>",
                "  </li>",
                "</ul>",
                "<div class='select2-drop select2-drop-multi select2-display-none'>",
                "   <ul class='select2-results'>",
                "   </ul>",
                "</div>"].join(""));
            return container;
        },

        // multi
        prepareOpts: function () {
            var opts = this.parent.prepareOpts.apply(this, arguments),
                self=this;

            // TODO validate placeholder is a string if specified
            if (opts.element.get(0).tagName.toLowerCase() === "select") {
                // install the selection initializer
                opts.initSelection = function (element, callback) {

                    var data = [];

                    element.find("option").filter(function() { return this.selected && !this.disabled }).each2(function (i, elm) {
                        data.push(self.optionToData(elm));
                    });
                    callback(data);
                };
            } else if ("data" in opts) {
                // install default initSelection when applied to hidden input and data is local
                opts.initSelection = opts.initSelection || function (element, callback) {
                    var ids = splitVal(element.val(), opts.separator, opts.transformVal);
                    //search in data by array of ids, storing matching items in a list
                    var matches = [];
                    opts.query({
                        matcher: function(term, text, el){
                            var is_match = $.grep(ids, function(id) {
                                return equal(id, opts.id(el));
                            }).length;
                            if (is_match) {
                                matches.push(el);
                            }
                            return is_match;
                        },
                        callback: !$.isFunction(callback) ? $.noop : function() {
                            // reorder matches based on the order they appear in the ids array because right now
                            // they are in the order in which they appear in data array
                            var ordered = [];
                            for (var i = 0; i < ids.length; i++) {
                                var id = ids[i];
                                for (var j = 0; j < matches.length; j++) {
                                    var match = matches[j];
                                    if (equal(id, opts.id(match))) {
                                        ordered.push(match);
                                        matches.splice(j, 1);
                                        break;
                                    }
                                }
                            }
                            callback(ordered);
                        }
                    });
                };
            }

            return opts;
        },

        // multi
        selectChoice: function (choice) {

            var selected = this.container.find(".select2-search-choice-focus");
            if (selected.length && choice && choice[0] == selected[0]) {

            } else {
                if (selected.length) {
                    this.opts.element.trigger("choice-deselected", selected);
                }
                selected.removeClass("select2-search-choice-focus");
                if (choice && choice.length) {
                    this.close();
                    choice.addClass("select2-search-choice-focus");
                    this.opts.element.trigger("choice-selected", choice);
                }
            }
        },

        // multi
        destroy: function() {
            $("label[for='" + this.search.attr('id') + "']")
                .attr('for', this.opts.element.attr("id"));
            this.parent.destroy.apply(this, arguments);

            cleanupJQueryElements.call(this,
                "searchContainer",
                "selection"
            );
        },

        // multi
        initContainer: function () {

            var selector = ".select2-choices", selection;

            this.searchContainer = this.container.find(".select2-search-field");
            this.selection = selection = this.container.find(selector);

            var _this = this;
            this.selection.on("click", ".select2-container:not(.select2-container-disabled) .select2-search-choice:not(.select2-locked)", function (e) {
                _this.search[0].focus();
                _this.selectChoice($(this));
            });

            // rewrite labels from original element to focusser
            this.search.attr("id", "s2id_autogen"+nextUid());

            this.search.prev()
                .text($("label[for='" + this.opts.element.attr("id") + "']").text())
                .attr('for', this.search.attr('id'));
            this.opts.element.on('focus.select2', this.bind(function () { this.focus(); }));

            this.search.on("input paste", this.bind(function() {
                if (this.search.attr('placeholder') && this.search.val().length == 0) return;
                if (!this.isInterfaceEnabled()) return;
                if (!this.opened()) {
                    this.open();
                }
            }));

            this.search.attr("tabindex", this.elementTabIndex);

            this.keydowns = 0;
            this.search.on("keydown", this.bind(function (e) {
                if (!this.isInterfaceEnabled()) return;

                ++this.keydowns;
                var selected = selection.find(".select2-search-choice-focus");
                var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
                var next = selected.next(".select2-search-choice:not(.select2-locked)");
                var pos = getCursorInfo(this.search);

                if (selected.length &&
                    (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
                    var selectedChoice = selected;
                    if (e.which == KEY.LEFT && prev.length) {
                        selectedChoice = prev;
                    }
                    else if (e.which == KEY.RIGHT) {
                        selectedChoice = next.length ? next : null;
                    }
                    else if (e.which === KEY.BACKSPACE) {
                        if (this.unselect(selected.first())) {
                            this.search.width(10);
                            selectedChoice = prev.length ? prev : next;
                        }
                    } else if (e.which == KEY.DELETE) {
                        if (this.unselect(selected.first())) {
                            this.search.width(10);
                            selectedChoice = next.length ? next : null;
                        }
                    } else if (e.which == KEY.ENTER) {
                        selectedChoice = null;
                    }

                    this.selectChoice(selectedChoice);
                    killEvent(e);
                    if (!selectedChoice || !selectedChoice.length) {
                        this.open();
                    }
                    return;
                } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
                    || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {

                    this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
                    killEvent(e);
                    return;
                } else {
                    this.selectChoice(null);
                }

                if (this.opened()) {
                    switch (e.which) {
                    case KEY.UP:
                    case KEY.DOWN:
                        this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
                        killEvent(e);
                        return;
                    case KEY.ENTER:
                        this.selectHighlighted();
                        killEvent(e);
                        return;
                    case KEY.TAB:
                        this.selectHighlighted({noFocus:true});
                        this.close();
                        return;
                    case KEY.ESC:
                        this.cancel(e);
                        killEvent(e);
                        return;
                    }
                }

                if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
                 || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
                    return;
                }

                if (e.which === KEY.ENTER) {
                    if (this.opts.openOnEnter === false) {
                        return;
                    } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
                        return;
                    }
                }

                this.open();

                if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
                    // prevent the page from scrolling
                    killEvent(e);
                }

                if (e.which === KEY.ENTER) {
                    // prevent form from being submitted
                    killEvent(e);
                }

            }));

            this.search.on("keyup", this.bind(function (e) {
                this.keydowns = 0;
                this.resizeSearch();
            })
            );

            this.search.on("blur", this.bind(function(e) {
                this.container.removeClass("select2-container-active");
                this.search.removeClass("select2-focused");
                this.selectChoice(null);
                if (!this.opened()) this.clearSearch();
                e.stopImmediatePropagation();
                this.opts.element.trigger($.Event("select2-blur"));
            }));

            this.container.on("click", selector, this.bind(function (e) {
                if (!this.isInterfaceEnabled()) return;
                if ($(e.target).closest(".select2-search-choice").length > 0) {
                    // clicked inside a select2 search choice, do not open
                    return;
                }
                this.selectChoice(null);
                this.clearPlaceholder();
                if (!this.container.hasClass("select2-container-active")) {
                    this.opts.element.trigger($.Event("select2-focus"));
                }
                this.open();
                this.focusSearch();
                e.preventDefault();
            }));

            this.container.on("focus", selector, this.bind(function () {
                if (!this.isInterfaceEnabled()) return;
                if (!this.container.hasClass("select2-container-active")) {
                    this.opts.element.trigger($.Event("select2-focus"));
                }
                this.container.addClass("select2-container-active");
                this.dropdown.addClass("select2-drop-active");
                this.clearPlaceholder();
            }));

            this.initContainerWidth();
            this.opts.element.hide();

            // set the placeholder if necessary
            this.clearSearch();
        },

        // multi
        enableInterface: function() {
            if (this.parent.enableInterface.apply(this, arguments)) {
                this.search.prop("disabled", !this.isInterfaceEnabled());
            }
        },

        // multi
        initSelection: function () {
            var data;
            if (this.opts.element.val() === "" && this.opts.element.text() === "") {
                this.updateSelection([]);
                this.close();
                // set the placeholder if necessary
                this.clearSearch();
            }
            if (this.select || this.opts.element.val() !== "") {
                var self = this;
                this.opts.initSelection.call(null, this.opts.element, function(data){
                    if (data !== undefined && data !== null) {
                        self.updateSelection(data);
                        self.close();
                        // set the placeholder if necessary
                        self.clearSearch();
                    }
                });
            }
        },

        // multi
        clearSearch: function () {
            var placeholder = this.getPlaceholder(),
                maxWidth = this.getMaxSearchWidth();

            if (placeholder !== undefined  && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
                this.search.val(placeholder).addClass("select2-default");
                // stretch the search box to full width of the container so as much of the placeholder is visible as possible
                // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
                this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
            } else {
                this.search.val("").width(10);
            }
        },

        // multi
        clearPlaceholder: function () {
            if (this.search.hasClass("select2-default")) {
                this.search.val("").removeClass("select2-default");
            }
        },

        // multi
        opening: function () {
            this.clearPlaceholder(); // should be done before super so placeholder is not used to search
            this.resizeSearch();

            this.parent.opening.apply(this, arguments);

            this.focusSearch();

            this.prefillNextSearchTerm();
            this.updateResults(true);

            if (this.opts.shouldFocusInput(this)) {
                this.search.focus();
            }
            this.opts.element.trigger($.Event("select2-open"));
        },

        // multi
        close: function () {
            if (!this.opened()) return;
            this.parent.close.apply(this, arguments);
        },

        // multi
        focus: function () {
            this.close();
            this.search.focus();
        },

        // multi
        isFocused: function () {
            return this.search.hasClass("select2-focused");
        },

        // multi
        updateSelection: function (data) {
            var ids = {}, filtered = [], self = this;

            // filter out duplicates
            $(data).each(function () {
                if (!(self.id(this) in ids)) {
                    ids[self.id(this)] = 0;
                    filtered.push(this);
                }
            });

            this.selection.find(".select2-search-choice").remove();
            this.addSelectedChoice(filtered);
            self.postprocessResults();
        },

        // multi
        tokenize: function() {
            var input = this.search.val();
            input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
            if (input != null && input != undefined) {
                this.search.val(input);
                if (input.length > 0) {
                    this.open();
                }
            }

        },

        // multi
        onSelect: function (data, options) {

            if (!this.triggerSelect(data) || data.text === "") { return; }

            this.addSelectedChoice(data);

            this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });

            // keep track of the search's value before it gets cleared
            this.lastSearchTerm = this.search.val();

            this.clearSearch();
            this.updateResults();

            if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);

            if (this.opts.closeOnSelect) {
                this.close();
                this.search.width(10);
            } else {
                if (this.countSelectableResults()>0) {
                    this.search.width(10);
                    this.resizeSearch();
                    if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
                        // if we reached max selection size repaint the results so choices
                        // are replaced with the max selection reached message
                        this.updateResults(true);
                    } else {
                        // initializes search's value with nextSearchTerm and update search result
                        if (this.prefillNextSearchTerm()) {
                            this.updateResults();
                        }
                    }
                    this.positionDropdown();
                } else {
                    // if nothing left to select close
                    this.close();
                    this.search.width(10);
                }
            }

            // since its not possible to select an element that has already been
            // added we do not need to check if this is a new element before firing change
            this.triggerChange({ added: data });

            if (!options || !options.noFocus)
                this.focusSearch();
        },

        // multi
        cancel: function () {
            this.close();
            this.focusSearch();
        },

        addSelectedChoice: function (data) {
            var val = this.getVal(), self = this;
            $(data).each(function () {
                val.push(self.createChoice(this));
            });
            this.setVal(val);
        },

        createChoice: function (data) {
            var enableChoice = !data.locked,
                enabledItem = $(
                    "<li class='select2-search-choice'>" +
                    "    <div></div>" +
                    "    <a href='#' class='select2-search-choice-close' tabindex='-1'></a>" +
                    "</li>"),
                disabledItem = $(
                    "<li class='select2-search-choice select2-locked'>" +
                    "<div></div>" +
                    "</li>");
            var choice = enableChoice ? enabledItem : disabledItem,
                id = this.id(data),
                formatted,
                cssClass;

            formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
            if (formatted != undefined) {
                choice.find("div").replaceWith($("<div></div>").html(formatted));
            }
            cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
            if (cssClass != undefined) {
                choice.addClass(cssClass);
            }

            if(enableChoice){
              choice.find(".select2-search-choice-close")
                  .on("mousedown", killEvent)
                  .on("click dblclick", this.bind(function (e) {
                  if (!this.isInterfaceEnabled()) return;

                  this.unselect($(e.target));
                  this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
                  killEvent(e);
                  this.close();
                  this.focusSearch();
              })).on("focus", this.bind(function () {
                  if (!this.isInterfaceEnabled()) return;
                  this.container.addClass("select2-container-active");
                  this.dropdown.addClass("select2-drop-active");
              }));
            }

            choice.data("select2-data", data);
            choice.insertBefore(this.searchContainer);

            return id;
        },

        // multi
        unselect: function (selected) {
            var val = this.getVal(),
                data,
                index;
            selected = selected.closest(".select2-search-choice");

            if (selected.length === 0) {
                throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
            }

            data = selected.data("select2-data");

            if (!data) {
                // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
                // and invoked on an element already removed
                return;
            }

            var evt = $.Event("select2-removing");
            evt.val = this.id(data);
            evt.choice = data;
            this.opts.element.trigger(evt);

            if (evt.isDefaultPrevented()) {
                return false;
            }

            while((index = indexOf(this.id(data), val)) >= 0) {
                val.splice(index, 1);
                this.setVal(val);
                if (this.select) this.postprocessResults();
            }

            selected.remove();

            this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
            this.triggerChange({ removed: data });

            return true;
        },

        // multi
        postprocessResults: function (data, initial, noHighlightUpdate) {
            var val = this.getVal(),
                choices = this.results.find(".select2-result"),
                compound = this.results.find(".select2-result-with-children"),
                self = this;

            choices.each2(function (i, choice) {
                var id = self.id(choice.data("select2-data"));
                if (indexOf(id, val) >= 0) {
                    choice.addClass("select2-selected");
                    // mark all children of the selected parent as selected
                    choice.find(".select2-result-selectable").addClass("select2-selected");
                }
            });

            compound.each2(function(i, choice) {
                // hide an optgroup if it doesn't have any selectable children
                if (!choice.is('.select2-result-selectable')
                    && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
                    choice.addClass("select2-selected");
                }
            });

            if (this.highlight() == -1 && noHighlightUpdate !== false && this.opts.closeOnSelect === true){
                self.highlight(0);
            }

            //If all results are chosen render formatNoMatches
            if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
                if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
                    if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
                        this.results.append("<li class='select2-no-results'>" + evaluate(self.opts.formatNoMatches, self.opts.element, self.search.val()) + "</li>");
                    }
                }
            }

        },

        // multi
        getMaxSearchWidth: function() {
            return this.selection.width() - getSideBorderPadding(this.search);
        },

        // multi
        resizeSearch: function () {
            var minimumWidth, left, maxWidth, containerLeft, searchWidth,
                sideBorderPadding = getSideBorderPadding(this.search);

            minimumWidth = measureTextWidth(this.search) + 10;

            left = this.search.offset().left;

            maxWidth = this.selection.width();
            containerLeft = this.selection.offset().left;

            searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;

            if (searchWidth < minimumWidth) {
                searchWidth = maxWidth - sideBorderPadding;
            }

            if (searchWidth < 40) {
                searchWidth = maxWidth - sideBorderPadding;
            }

            if (searchWidth <= 0) {
              searchWidth = minimumWidth;
            }

            this.search.width(Math.floor(searchWidth));
        },

        // multi
        getVal: function () {
            var val;
            if (this.select) {
                val = this.select.val();
                return val === null ? [] : val;
            } else {
                val = this.opts.element.val();
                return splitVal(val, this.opts.separator, this.opts.transformVal);
            }
        },

        // multi
        setVal: function (val) {
            if (this.select) {
                this.select.val(val);
            } else {
                var unique = [], valMap = {};
                // filter out duplicates
                $(val).each(function () {
                    if (!(this in valMap)) {
                        unique.push(this);
                        valMap[this] = 0;
                    }
                });
                this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
            }
        },

        // multi
        buildChangeDetails: function (old, current) {
            var current = current.slice(0),
                old = old.slice(0);

            // remove intersection from each array
            for (var i = 0; i < current.length; i++) {
                for (var j = 0; j < old.length; j++) {
                    if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
                        current.splice(i, 1);
                        i--;
                        old.splice(j, 1);
                        break;
                    }
                }
            }

            return {added: current, removed: old};
        },


        // multi
        val: function (val, triggerChange) {
            var oldData, self=this;

            if (arguments.length === 0) {
                return this.getVal();
            }

            oldData=this.data();
            if (!oldData.length) oldData=[];

            // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
            if (!val && val !== 0) {
                this.opts.element.val("");
                this.updateSelection([]);
                this.clearSearch();
                if (triggerChange) {
                    this.triggerChange({added: this.data(), removed: oldData});
                }
                return;
            }

            // val is a list of ids
            this.setVal(val);

            if (this.select) {
                this.opts.initSelection(this.select, this.bind(this.updateSelection));
                if (triggerChange) {
                    this.triggerChange(this.buildChangeDetails(oldData, this.data()));
                }
            } else {
                if (this.opts.initSelection === undefined) {
                    throw new Error("val() cannot be called if initSelection() is not defined");
                }

                this.opts.initSelection(this.opts.element, function(data){
                    var ids=$.map(data, self.id);
                    self.setVal(ids);
                    self.updateSelection(data);
                    self.clearSearch();
                    if (triggerChange) {
                        self.triggerChange(self.buildChangeDetails(oldData, self.data()));
                    }
                });
            }
            this.clearSearch();
        },

        // multi
        onSortStart: function() {
            if (this.select) {
                throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
            }

            // collapse search field into 0 width so its container can be collapsed as well
            this.search.width(0);
            // hide the container
            this.searchContainer.hide();
        },

        // multi
        onSortEnd:function() {

            var val=[], self=this;

            // show search and move it to the end of the list
            this.searchContainer.show();
            // make sure the search container is the last item in the list
            this.searchContainer.appendTo(this.searchContainer.parent());
            // since we collapsed the width in dragStarted, we resize it here
            this.resizeSearch();

            // update selection
            this.selection.find(".select2-search-choice").each(function() {
                val.push(self.opts.id($(this).data("select2-data")));
            });
            this.setVal(val);
            this.triggerChange();
        },

        // multi
        data: function(values, triggerChange) {
            var self=this, ids, old;
            if (arguments.length === 0) {
                 return this.selection
                     .children(".select2-search-choice")
                     .map(function() { return $(this).data("select2-data"); })
                     .get();
            } else {
                old = this.data();
                if (!values) { values = []; }
                ids = $.map(values, function(e) { return self.opts.id(e); });
                this.setVal(ids);
                this.updateSelection(values);
                this.clearSearch();
                if (triggerChange) {
                    this.triggerChange(this.buildChangeDetails(old, this.data()));
                }
            }
        }
    });

    $.fn.select2 = function () {

        var args = Array.prototype.slice.call(arguments, 0),
            opts,
            select2,
            method, value, multiple,
            allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
            valueMethods = ["opened", "isFocused", "container", "dropdown"],
            propertyMethods = ["val", "data"],
            methodsMap = { search: "externalSearch" };

        this.each(function () {
            if (args.length === 0 || typeof(args[0]) === "object") {
                opts = args.length === 0 ? {} : $.extend({}, args[0]);
                opts.element = $(this);

                if (opts.element.get(0).tagName.toLowerCase() === "select") {
                    multiple = opts.element.prop("multiple");
                } else {
                    multiple = opts.multiple || false;
                    if ("tags" in opts) {opts.multiple = multiple = true;}
                }

                select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single();
                select2.init(opts);
            } else if (typeof(args[0]) === "string") {

                if (indexOf(args[0], allowedMethods) < 0) {
                    throw "Unknown method: " + args[0];
                }

                value = undefined;
                select2 = $(this).data("select2");
                if (select2 === undefined) return;

                method=args[0];

                if (method === "container") {
                    value = select2.container;
                } else if (method === "dropdown") {
                    value = select2.dropdown;
                } else {
                    if (methodsMap[method]) method = methodsMap[method];

                    value = select2[method].apply(select2, args.slice(1));
                }
                if (indexOf(args[0], valueMethods) >= 0
                    || (indexOf(args[0], propertyMethods) >= 0 && args.length == 1)) {
                    return false; // abort the iteration, ready to return first matched value
                }
            } else {
                throw "Invalid arguments to select2 plugin: " + args;
            }
        });
        return (value === undefined) ? this : value;
    };

    // plugin defaults, accessible to users
    $.fn.select2.defaults = {
        debug: false,
        width: "copy",
        loadMorePadding: 0,
        closeOnSelect: true,
        openOnEnter: true,
        containerCss: {},
        dropdownCss: {},
        containerCssClass: "",
        dropdownCssClass: "",
        formatResult: function(result, container, query, escapeMarkup) {
            var markup=[];
            markMatch(this.text(result), query.term, markup, escapeMarkup);
            return markup.join("");
        },
        transformVal: function(val) {
            return $.trim(val);
        },
        formatSelection: function (data, container, escapeMarkup) {
            return data ? escapeMarkup(this.text(data)) : undefined;
        },
        sortResults: function (results, container, query) {
            return results;
        },
        formatResultCssClass: function(data) {return data.css;},
        formatSelectionCssClass: function(data, container) {return undefined;},
        minimumResultsForSearch: 0,
        minimumInputLength: 0,
        maximumInputLength: null,
        maximumSelectionSize: 0,
        id: function (e) { return e == undefined ? null : e.id; },
        text: function (e) {
          if (e && this.data && this.data.text) {
            if ($.isFunction(this.data.text)) {
              return this.data.text(e);
            } else {
              return e[this.data.text];
            }
          } else {
            return e.text;
          }
        },
        matcher: function(term, text) {
            return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
        },
        separator: ",",
        tokenSeparators: [],
        tokenizer: defaultTokenizer,
        escapeMarkup: defaultEscapeMarkup,
        blurOnChange: false,
        selectOnBlur: false,
        adaptContainerCssClass: function(c) { return c; },
        adaptDropdownCssClass: function(c) { return null; },
        nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; },
        searchInputPlaceholder: '',
        createSearchChoicePosition: 'top',
        shouldFocusInput: function (instance) {
            // Attempt to detect touch devices
            var supportsTouchEvents = (('ontouchstart' in window) ||
                                       (navigator.msMaxTouchPoints > 0));

            // Only devices which support touch events should be special cased
            if (!supportsTouchEvents) {
                return true;
            }

            // Never focus the input if search is disabled
            if (instance.opts.minimumResultsForSearch < 0) {
                return false;
            }

            return true;
        }
    };

    $.fn.select2.locales = [];

    $.fn.select2.locales['en'] = {
         formatMatches: function (matches) { if (matches === 1) { return "One result is available, press enter to select it."; } return matches + " results are available, use up and down arrow keys to navigate."; },
         formatNoMatches: function () { return "No matches found"; },
         formatAjaxError: function (jqXHR, textStatus, errorThrown) { return "Loading failed"; },
         formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1 ? "" : "s"); },
         formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1 ? "" : "s"); },
         formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
         formatLoadMore: function (pageNumber) { return "Loading more results…"; },
         formatSearching: function () { return "Searching…"; }
    };

    $.extend($.fn.select2.defaults, $.fn.select2.locales['en']);

    $.fn.select2.ajaxDefaults = {
        transport: $.ajax,
        params: {
            type: "GET",
            cache: false,
            dataType: "json"
        }
    };

    // exports
    window.Select2 = {
        query: {
            ajax: ajax,
            local: local,
            tags: tags
        }, util: {
            debounce: debounce,
            markMatch: markMatch,
            escapeMarkup: defaultEscapeMarkup,
            stripDiacritics: stripDiacritics
        }, "class": {
            "abstract": AbstractSelect2,
            "single": SingleSelect2,
            "multi": MultiSelect2
        }
    };

}(jQuery));
/*! Magnific Popup - v0.9.9 - 2013-12-27
* http://dimsemenov.com/plugins/magnific-popup/
* Copyright (c) 2013 Dmitry Semenov; */

;(function($) {

/*>>core*/
/**
 * 
 * Magnific Popup Core JS file
 * 
 */


/**
 * Private static constants
 */
var CLOSE_EVENT = 'Close',
	BEFORE_CLOSE_EVENT = 'BeforeClose',
	AFTER_CLOSE_EVENT = 'AfterClose',
	BEFORE_APPEND_EVENT = 'BeforeAppend',
	MARKUP_PARSE_EVENT = 'MarkupParse',
	OPEN_EVENT = 'Open',
	CHANGE_EVENT = 'Change',
	NS = 'mfp',
	EVENT_NS = '.' + NS,
	READY_CLASS = 'mfp-ready',
	REMOVING_CLASS = 'mfp-removing',
	PREVENT_CLOSE_CLASS = 'mfp-prevent-close';


/**
 * Private vars 
 */
var mfp, // As we have only one instance of MagnificPopup object, we define it locally to not to use 'this'
	MagnificPopup = function(){},
	_isJQ = !!(window.jQuery),
	_prevStatus,
	_window = $(window),
	_body,
	_document,
	_prevContentType,
	_wrapClasses,
	_currPopupType;


/**
 * Private functions
 */
var _mfpOn = function(name, f) {
		mfp.ev.on(NS + name + EVENT_NS, f);
	},
	_getEl = function(className, appendTo, html, raw) {
		var el = document.createElement('div');
		el.className = 'mfp-'+className;
		if(html) {
			el.innerHTML = html;
		}
		if(!raw) {
			el = $(el);
			if(appendTo) {
				el.appendTo(appendTo);
			}
		} else if(appendTo) {
			appendTo.appendChild(el);
		}
		return el;
	},
	_mfpTrigger = function(e, data) {
		mfp.ev.triggerHandler(NS + e, data);

		if(mfp.st.callbacks) {
			// converts "mfpEventName" to "eventName" callback and triggers it if it's present
			e = e.charAt(0).toLowerCase() + e.slice(1);
			if(mfp.st.callbacks[e]) {
				mfp.st.callbacks[e].apply(mfp, $.isArray(data) ? data : [data]);
			}
		}
	},
	_getCloseBtn = function(type) {
		if(type !== _currPopupType || !mfp.currTemplate.closeBtn) {
			mfp.currTemplate.closeBtn = $( mfp.st.closeMarkup.replace('%title%', mfp.st.tClose ) );
			_currPopupType = type;
		}
		return mfp.currTemplate.closeBtn;
	},
	// Initialize Magnific Popup only when called at least once
	_checkInstance = function() {
		if(!$.magnificPopup.instance) {
			mfp = new MagnificPopup();
			mfp.init();
			$.magnificPopup.instance = mfp;
		}
	},
	// CSS transition detection, http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
	supportsTransitions = function() {
		var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist
			v = ['ms','O','Moz','Webkit']; // 'v' for vendor

		if( s['transition'] !== undefined ) {
			return true; 
		}
			
		while( v.length ) {
			if( v.pop() + 'Transition' in s ) {
				return true;
			}
		}
				
		return false;
	};



/**
 * Public functions
 */
MagnificPopup.prototype = {

	constructor: MagnificPopup,

	/**
	 * Initializes Magnific Popup plugin. 
	 * This function is triggered only once when $.fn.magnificPopup or $.magnificPopup is executed
	 */
	init: function() {
		var appVersion = navigator.appVersion;
		mfp.isIE7 = appVersion.indexOf("MSIE 7.") !== -1; 
		mfp.isIE8 = appVersion.indexOf("MSIE 8.") !== -1;
		mfp.isLowIE = mfp.isIE7 || mfp.isIE8;
		mfp.isAndroid = (/android/gi).test(appVersion);
		mfp.isIOS = (/iphone|ipad|ipod/gi).test(appVersion);
		mfp.supportsTransition = supportsTransitions();

		// We disable fixed positioned lightbox on devices that don't handle it nicely.
		// If you know a better way of detecting this - let me know.
		mfp.probablyMobile = (mfp.isAndroid || mfp.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent) );
		_document = $(document);

		mfp.popupsCache = {};
	},

	/**
	 * Opens popup
	 * @param  data [description]
	 */
	open: function(data) {

		if(!_body) {
			_body = $(document.body);
		}

		var i;

		if(data.isObj === false) { 
			// convert jQuery collection to array to avoid conflicts later
			mfp.items = data.items.toArray();

			mfp.index = 0;
			var items = data.items,
				item;
			for(i = 0; i < items.length; i++) {
				item = items[i];
				if(item.parsed) {
					item = item.el[0];
				}
				if(item === data.el[0]) {
					mfp.index = i;
					break;
				}
			}
		} else {
			mfp.items = $.isArray(data.items) ? data.items : [data.items];
			mfp.index = data.index || 0;
		}

		// if popup is already opened - we just update the content
		if(mfp.isOpen) {
			mfp.updateItemHTML();
			return;
		}
		
		mfp.types = []; 
		_wrapClasses = '';
		if(data.mainEl && data.mainEl.length) {
			mfp.ev = data.mainEl.eq(0);
		} else {
			mfp.ev = _document;
		}

		if(data.key) {
			if(!mfp.popupsCache[data.key]) {
				mfp.popupsCache[data.key] = {};
			}
			mfp.currTemplate = mfp.popupsCache[data.key];
		} else {
			mfp.currTemplate = {};
		}



		mfp.st = $.extend(true, {}, $.magnificPopup.defaults, data ); 
		mfp.fixedContentPos = mfp.st.fixedContentPos === 'auto' ? !mfp.probablyMobile : mfp.st.fixedContentPos;

		if(mfp.st.modal) {
			mfp.st.closeOnContentClick = false;
			mfp.st.closeOnBgClick = false;
			mfp.st.showCloseBtn = false;
			mfp.st.enableEscapeKey = false;
		}
		

		// Building markup
		// main containers are created only once
		if(!mfp.bgOverlay) {

			// Dark overlay
			mfp.bgOverlay = _getEl('bg').on('click'+EVENT_NS, function() {
				mfp.close();
			});

			mfp.wrap = _getEl('wrap').attr('tabindex', -1).on('click'+EVENT_NS, function(e) {
				if(mfp._checkIfClose(e.target)) {
					mfp.close();
				}
			});

			mfp.container = _getEl('container', mfp.wrap);
		}

		mfp.contentContainer = _getEl('content');
		if(mfp.st.preloader) {
			mfp.preloader = _getEl('preloader', mfp.container, mfp.st.tLoading);
		}


		// Initializing modules
		var modules = $.magnificPopup.modules;
		for(i = 0; i < modules.length; i++) {
			var n = modules[i];
			n = n.charAt(0).toUpperCase() + n.slice(1);
			mfp['init'+n].call(mfp);
		}
		_mfpTrigger('BeforeOpen');


		if(mfp.st.showCloseBtn) {
			// Close button
			if(!mfp.st.closeBtnInside) {
				mfp.wrap.append( _getCloseBtn() );
			} else {
				_mfpOn(MARKUP_PARSE_EVENT, function(e, template, values, item) {
					values.close_replaceWith = _getCloseBtn(item.type);
				});
				_wrapClasses += ' mfp-close-btn-in';
			}
		}

		if(mfp.st.alignTop) {
			_wrapClasses += ' mfp-align-top';
		}

	

		if(mfp.fixedContentPos) {
			mfp.wrap.css({
				overflow: mfp.st.overflowY,
				overflowX: 'hidden',
				overflowY: mfp.st.overflowY
			});
		} else {
			mfp.wrap.css({ 
				top: _window.scrollTop(),
				position: 'absolute'
			});
		}
		if( mfp.st.fixedBgPos === false || (mfp.st.fixedBgPos === 'auto' && !mfp.fixedContentPos) ) {
			mfp.bgOverlay.css({
				height: _document.height(),
				position: 'absolute'
			});
		}

		

		if(mfp.st.enableEscapeKey) {
			// Close on ESC key
			_document.on('keyup' + EVENT_NS, function(e) {
				if(e.keyCode === 27) {
					mfp.close();
				}
			});
		}

		_window.on('resize' + EVENT_NS, function() {
			mfp.updateSize();
		});


		if(!mfp.st.closeOnContentClick) {
			_wrapClasses += ' mfp-auto-cursor';
		}
		
		if(_wrapClasses)
			mfp.wrap.addClass(_wrapClasses);


		// this triggers recalculation of layout, so we get it once to not to trigger twice
		var windowHeight = mfp.wH = _window.height();

		
		var windowStyles = {};

		if( mfp.fixedContentPos ) {
            if(mfp._hasScrollBar(windowHeight)){
                var s = mfp._getScrollbarSize();
                if(s) {
                    windowStyles.marginRight = s;
                }
            }
        }

		if(mfp.fixedContentPos) {
			if(!mfp.isIE7) {
				windowStyles.overflow = 'hidden';
			} else {
				// ie7 double-scroll bug
				$('body, html').css('overflow', 'hidden');
			}
		}

		
		
		var classesToadd = mfp.st.mainClass;
		if(mfp.isIE7) {
			classesToadd += ' mfp-ie7';
		}
		if(classesToadd) {
			mfp._addClassToMFP( classesToadd );
		}

		// add content
		mfp.updateItemHTML();

		_mfpTrigger('BuildControls');

		// remove scrollbar, add margin e.t.c
		$('html').css(windowStyles);
		
		// add everything to DOM
		mfp.bgOverlay.add(mfp.wrap).prependTo( mfp.st.prependTo || _body );

		// Save last focused element
		mfp._lastFocusedEl = document.activeElement;
		
		// Wait for next cycle to allow CSS transition
		setTimeout(function() {
			
			if(mfp.content) {
				mfp._addClassToMFP(READY_CLASS);
				mfp._setFocus();
			} else {
				// if content is not defined (not loaded e.t.c) we add class only for BG
				mfp.bgOverlay.addClass(READY_CLASS);
			}
			
			// Trap the focus in popup
			_document.on('focusin' + EVENT_NS, mfp._onFocusIn);

		}, 16);

		mfp.isOpen = true;
		mfp.updateSize(windowHeight);
		_mfpTrigger(OPEN_EVENT);

		return data;
	},

	/**
	 * Closes the popup
	 */
	close: function() {
		if(!mfp.isOpen) return;
		_mfpTrigger(BEFORE_CLOSE_EVENT);

		mfp.isOpen = false;
		// for CSS3 animation
		if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition )  {
			mfp._addClassToMFP(REMOVING_CLASS);
			setTimeout(function() {
				mfp._close();
			}, mfp.st.removalDelay);
		} else {
			mfp._close();
		}
	},

	/**
	 * Helper for close() function
	 */
	_close: function() {
		_mfpTrigger(CLOSE_EVENT);

		var classesToRemove = REMOVING_CLASS + ' ' + READY_CLASS + ' ';

		mfp.bgOverlay.detach();
		mfp.wrap.detach();
		mfp.container.empty();

		if(mfp.st.mainClass) {
			classesToRemove += mfp.st.mainClass + ' ';
		}

		mfp._removeClassFromMFP(classesToRemove);

		if(mfp.fixedContentPos) {
			var windowStyles = {marginRight: ''};
			if(mfp.isIE7) {
				$('body, html').css('overflow', '');
			} else {
				windowStyles.overflow = '';
			}
			$('html').css(windowStyles);
		}
		
		_document.off('keyup' + EVENT_NS + ' focusin' + EVENT_NS);
		mfp.ev.off(EVENT_NS);

		// clean up DOM elements that aren't removed
		mfp.wrap.attr('class', 'mfp-wrap').removeAttr('style');
		mfp.bgOverlay.attr('class', 'mfp-bg');
		mfp.container.attr('class', 'mfp-container');

		// remove close button from target element
		if(mfp.st.showCloseBtn &&
		(!mfp.st.closeBtnInside || mfp.currTemplate[mfp.currItem.type] === true)) {
			if(mfp.currTemplate.closeBtn)
				mfp.currTemplate.closeBtn.detach();
		}


		if(mfp._lastFocusedEl) {
			$(mfp._lastFocusedEl).focus(); // put tab focus back
		}
		mfp.currItem = null;	
		mfp.content = null;
		mfp.currTemplate = null;
		mfp.prevHeight = 0;

		_mfpTrigger(AFTER_CLOSE_EVENT);
	},
	
	updateSize: function(winHeight) {

		if(mfp.isIOS) {
			// fixes iOS nav bars https://github.com/dimsemenov/Magnific-Popup/issues/2
			var zoomLevel = document.documentElement.clientWidth / window.innerWidth;
			var height = window.innerHeight * zoomLevel;
			mfp.wrap.css('height', height);
			mfp.wH = height;
		} else {
			mfp.wH = winHeight || _window.height();
		}
		// Fixes #84: popup incorrectly positioned with position:relative on body
		if(!mfp.fixedContentPos) {
			mfp.wrap.css('height', mfp.wH);
		}

		_mfpTrigger('Resize');

	},

	/**
	 * Set content of popup based on current index
	 */
	updateItemHTML: function() {
		var item = mfp.items[mfp.index];

		// Detach and perform modifications
		mfp.contentContainer.detach();

		if(mfp.content)
			mfp.content.detach();

		if(!item.parsed) {
			item = mfp.parseEl( mfp.index );
		}

		var type = item.type;	

		_mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]);
		// BeforeChange event works like so:
		// _mfpOn('BeforeChange', function(e, prevType, newType) { });
		
		mfp.currItem = item;

		

		

		if(!mfp.currTemplate[type]) {
			var markup = mfp.st[type] ? mfp.st[type].markup : false;

			// allows to modify markup
			_mfpTrigger('FirstMarkupParse', markup);

			if(markup) {
				mfp.currTemplate[type] = $(markup);
			} else {
				// if there is no markup found we just define that template is parsed
				mfp.currTemplate[type] = true;
			}
		}

		if(_prevContentType && _prevContentType !== item.type) {
			mfp.container.removeClass('mfp-'+_prevContentType+'-holder');
		}
		
		var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]);
		mfp.appendContent(newContent, type);

		item.preloaded = true;

		_mfpTrigger(CHANGE_EVENT, item);
		_prevContentType = item.type;
		
		// Append container back after its content changed
		mfp.container.prepend(mfp.contentContainer);

		_mfpTrigger('AfterChange');
	},


	/**
	 * Set HTML content of popup
	 */
	appendContent: function(newContent, type) {
		mfp.content = newContent;
		
		if(newContent) {
			if(mfp.st.showCloseBtn && mfp.st.closeBtnInside &&
				mfp.currTemplate[type] === true) {
				// if there is no markup, we just append close button element inside
				if(!mfp.content.find('.mfp-close').length) {
					mfp.content.append(_getCloseBtn());
				}
			} else {
				mfp.content = newContent;
			}
		} else {
			mfp.content = '';
		}

		_mfpTrigger(BEFORE_APPEND_EVENT);
		mfp.container.addClass('mfp-'+type+'-holder');

		mfp.contentContainer.append(mfp.content);
	},



	
	/**
	 * Creates Magnific Popup data object based on given data
	 * @param  {int} index Index of item to parse
	 */
	parseEl: function(index) {
		var item = mfp.items[index],
			type;

		if(item.tagName) {
			item = { el: $(item) };
		} else {
			type = item.type;
			item = { data: item, src: item.src };
		}

		if(item.el) {
			var types = mfp.types;

			// check for 'mfp-TYPE' class
			for(var i = 0; i < types.length; i++) {
				if( item.el.hasClass('mfp-'+types[i]) ) {
					type = types[i];
					break;
				}
			}

			item.src = item.el.attr('data-mfp-src');
			if(!item.src) {
				item.src = item.el.attr('href');
			}
		}

		item.type = type || mfp.st.type || 'inline';
		item.index = index;
		item.parsed = true;
		mfp.items[index] = item;
		_mfpTrigger('ElementParse', item);

		return mfp.items[index];
	},


	/**
	 * Initializes single popup or a group of popups
	 */
	addGroup: function(el, options) {
		var eHandler = function(e) {
			e.mfpEl = this;
			mfp._openClick(e, el, options);
		};

		if(!options) {
			options = {};
		} 

		var eName = 'click.magnificPopup';
		options.mainEl = el;
		
		if(options.items) {
			options.isObj = true;
			el.off(eName).on(eName, eHandler);
		} else {
			options.isObj = false;
			if(options.delegate) {
				el.off(eName).on(eName, options.delegate , eHandler);
			} else {
				options.items = el;
				el.off(eName).on(eName, eHandler);
			}
		}
	},
	_openClick: function(e, el, options) {
		var midClick = options.midClick !== undefined ? options.midClick : $.magnificPopup.defaults.midClick;


		if(!midClick && ( e.which === 2 || e.ctrlKey || e.metaKey ) ) {
			return;
		}

		var disableOn = options.disableOn !== undefined ? options.disableOn : $.magnificPopup.defaults.disableOn;

		if(disableOn) {
			if($.isFunction(disableOn)) {
				if( !disableOn.call(mfp) ) {
					return true;
				}
			} else { // else it's number
				if( _window.width() < disableOn ) {
					return true;
				}
			}
		}
		
		if(e.type) {
			e.preventDefault();

			// This will prevent popup from closing if element is inside and popup is already opened
			if(mfp.isOpen) {
				e.stopPropagation();
			}
		}
			

		options.el = $(e.mfpEl);
		if(options.delegate) {
			options.items = el.find(options.delegate);
		}
		mfp.open(options);
	},


	/**
	 * Updates text on preloader
	 */
	updateStatus: function(status, text) {

		if(mfp.preloader) {
			if(_prevStatus !== status) {
				mfp.container.removeClass('mfp-s-'+_prevStatus);
			}

			if(!text && status === 'loading') {
				text = mfp.st.tLoading;
			}

			var data = {
				status: status,
				text: text
			};
			// allows to modify status
			_mfpTrigger('UpdateStatus', data);

			status = data.status;
			text = data.text;

			mfp.preloader.html(text);

			mfp.preloader.find('a').on('click', function(e) {
				e.stopImmediatePropagation();
			});

			mfp.container.addClass('mfp-s-'+status);
			_prevStatus = status;
		}
	},


	/*
		"Private" helpers that aren't private at all
	 */
	// Check to close popup or not
	// "target" is an element that was clicked
	_checkIfClose: function(target) {

		if($(target).hasClass(PREVENT_CLOSE_CLASS)) {
			return;
		}

		var closeOnContent = mfp.st.closeOnContentClick;
		var closeOnBg = mfp.st.closeOnBgClick;

		if(closeOnContent && closeOnBg) {
			return true;
		} else {

			// We close the popup if click is on close button or on preloader. Or if there is no content.
			if(!mfp.content || $(target).hasClass('mfp-close') || (mfp.preloader && target === mfp.preloader[0]) ) {
				return true;
			}

			// if click is outside the content
			if(  (target !== mfp.content[0] && !$.contains(mfp.content[0], target))  ) {
				if(closeOnBg) {
					// last check, if the clicked element is in DOM, (in case it's removed onclick)
					if( $.contains(document, target) ) {
						return true;
					}
				}
			} else if(closeOnContent) {
				return true;
			}

		}
		return false;
	},
	_addClassToMFP: function(cName) {
		mfp.bgOverlay.addClass(cName);
		mfp.wrap.addClass(cName);
	},
	_removeClassFromMFP: function(cName) {
		this.bgOverlay.removeClass(cName);
		mfp.wrap.removeClass(cName);
	},
	_hasScrollBar: function(winHeight) {
		return (  (mfp.isIE7 ? _document.height() : document.body.scrollHeight) > (winHeight || _window.height()) );
	},
	_setFocus: function() {
		(mfp.st.focus ? mfp.content.find(mfp.st.focus).eq(0) : mfp.wrap).focus();
	},
	_onFocusIn: function(e) {
		if( e.target !== mfp.wrap[0] && !$.contains(mfp.wrap[0], e.target) ) {
			mfp._setFocus();
			return false;
		}
	},
	_parseMarkup: function(template, values, item) {
		var arr;
		if(item.data) {
			values = $.extend(item.data, values);
		}
		_mfpTrigger(MARKUP_PARSE_EVENT, [template, values, item] );

		$.each(values, function(key, value) {
			if(value === undefined || value === false) {
				return true;
			}
			arr = key.split('_');
			if(arr.length > 1) {
				var el = template.find(EVENT_NS + '-'+arr[0]);

				if(el.length > 0) {
					var attr = arr[1];
					if(attr === 'replaceWith') {
						if(el[0] !== value[0]) {
							el.replaceWith(value);
						}
					} else if(attr === 'img') {
						if(el.is('img')) {
							el.attr('src', value);
						} else {
							el.replaceWith( '<img src="'+value+'" class="' + el.attr('class') + '" />' );
						}
					} else {
						el.attr(arr[1], value);
					}
				}

			} else {
				template.find(EVENT_NS + '-'+key).html(value);
			}
		});
	},

	_getScrollbarSize: function() {
		// thx David
		if(mfp.scrollbarSize === undefined) {
			var scrollDiv = document.createElement("div");
			scrollDiv.id = "mfp-sbm";
			scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
			document.body.appendChild(scrollDiv);
			mfp.scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;
			document.body.removeChild(scrollDiv);
		}
		return mfp.scrollbarSize;
	}

}; /* MagnificPopup core prototype end */




/**
 * Public static functions
 */
$.magnificPopup = {
	instance: null,
	proto: MagnificPopup.prototype,
	modules: [],

	open: function(options, index) {
		_checkInstance();	

		if(!options) {
			options = {};
		} else {
			options = $.extend(true, {}, options);
		}
			

		options.isObj = true;
		options.index = index || 0;
		return this.instance.open(options);
	},

	close: function() {
		return $.magnificPopup.instance && $.magnificPopup.instance.close();
	},

	registerModule: function(name, module) {
		if(module.options) {
			$.magnificPopup.defaults[name] = module.options;
		}
		$.extend(this.proto, module.proto);			
		this.modules.push(name);
	},

	defaults: {   

		// Info about options is in docs:
		// http://dimsemenov.com/plugins/magnific-popup/documentation.html#options
		
		disableOn: 0,	

		key: null,

		midClick: false,

		mainClass: '',

		preloader: true,

		focus: '', // CSS selector of input to focus after popup is opened
		
		closeOnContentClick: false,

		closeOnBgClick: true,

		closeBtnInside: true, 

		showCloseBtn: true,

		enableEscapeKey: true,

		modal: false,

		alignTop: false,
	
		removalDelay: 0,

		prependTo: null,
		
		fixedContentPos: 'auto', 
	
		fixedBgPos: 'auto',

		overflowY: 'auto',

		closeMarkup: '<button title="%title%" type="button" class="mfp-close"></button>',

		tClose: 'Close (Esc)',

		tLoading: 'Loading...'

	}
};



$.fn.magnificPopup = function(options) {
	_checkInstance();

	var jqEl = $(this);

	// We call some API method of first param is a string
	if (typeof options === "string" ) {

		if(options === 'open') {
			var items,
				itemOpts = _isJQ ? jqEl.data('magnificPopup') : jqEl[0].magnificPopup,
				index = parseInt(arguments[1], 10) || 0;

			if(itemOpts.items) {
				items = itemOpts.items[index];
			} else {
				items = jqEl;
				if(itemOpts.delegate) {
					items = items.find(itemOpts.delegate);
				}
				items = items.eq( index );
			}
			mfp._openClick({mfpEl:items}, jqEl, itemOpts);
		} else {
			if(mfp.isOpen)
				mfp[options].apply(mfp, Array.prototype.slice.call(arguments, 1));
		}

	} else {
		// clone options obj
		options = $.extend(true, {}, options);
		
		/*
		 * As Zepto doesn't support .data() method for objects 
		 * and it works only in normal browsers
		 * we assign "options" object directly to the DOM element. FTW!
		 */
		if(_isJQ) {
			jqEl.data('magnificPopup', options);
		} else {
			jqEl[0].magnificPopup = options;
		}

		mfp.addGroup(jqEl, options);

	}
	return jqEl;
};


//Quick benchmark
/*
var start = performance.now(),
	i,
	rounds = 1000;

for(i = 0; i < rounds; i++) {

}
console.log('Test #1:', performance.now() - start);

start = performance.now();
for(i = 0; i < rounds; i++) {

}
console.log('Test #2:', performance.now() - start);
*/


/*>>core*/

/*>>inline*/

var INLINE_NS = 'inline',
	_hiddenClass,
	_inlinePlaceholder, 
	_lastInlineElement,
	_putInlineElementsBack = function() {
		if(_lastInlineElement) {
			_inlinePlaceholder.after( _lastInlineElement.addClass(_hiddenClass) ).detach();
			_lastInlineElement = null;
		}
	};

$.magnificPopup.registerModule(INLINE_NS, {
	options: {
		hiddenClass: 'hide', // will be appended with `mfp-` prefix
		markup: '',
		tNotFound: 'loading...'
	},
	proto: {

		initInline: function() {
			mfp.types.push(INLINE_NS);

			_mfpOn(CLOSE_EVENT+'.'+INLINE_NS, function() {
				_putInlineElementsBack();
			});
		},

		getInline: function(item, template) {

			_putInlineElementsBack();

			if(item.src) {
				var inlineSt = mfp.st.inline,
					el = $(item.src);

				if(el.length) {

					// If target element has parent - we replace it with placeholder and put it back after popup is closed
					var parent = el[0].parentNode;
					if(parent && parent.tagName) {
						if(!_inlinePlaceholder) {
							_hiddenClass = inlineSt.hiddenClass;
							_inlinePlaceholder = _getEl(_hiddenClass);
							_hiddenClass = 'mfp-'+_hiddenClass;
						}
						// replace target inline element with placeholder
						_lastInlineElement = el.after(_inlinePlaceholder).detach().removeClass(_hiddenClass);
					}

					mfp.updateStatus('ready');
				} else {
					mfp.updateStatus('error', inlineSt.tNotFound);
					el = $('<div>');
				}

				item.inlineElement = el;
				return el;
			}

			mfp.updateStatus('ready');
			mfp._parseMarkup(template, {}, item);
			return template;
		}
	}
});

/*>>inline*/

/*>>ajax*/
var AJAX_NS = 'ajax',
	_ajaxCur,
	_removeAjaxCursor = function() {
		if(_ajaxCur) {
			_body.removeClass(_ajaxCur);
		}
	},
	_destroyAjaxRequest = function() {
		_removeAjaxCursor();
		if(mfp.req) {
			mfp.req.abort();
		}
	};

$.magnificPopup.registerModule(AJAX_NS, {

	options: {
		settings: null,
		cursor: 'mfp-ajax-cur',
		tError: '<a href="%url%">The content</a> could not be loaded.'
	},

	proto: {
		initAjax: function() {
			mfp.types.push(AJAX_NS);
			_ajaxCur = mfp.st.ajax.cursor;

			_mfpOn(CLOSE_EVENT+'.'+AJAX_NS, _destroyAjaxRequest);
			_mfpOn('BeforeChange.' + AJAX_NS, _destroyAjaxRequest);
		},
		getAjax: function(item) {

			if(_ajaxCur)
				_body.addClass(_ajaxCur);

			mfp.updateStatus('loading');

			var opts = $.extend({
				url: item.src,
				success: function(data, textStatus, jqXHR) {
					var temp = {
						data:data,
						xhr:jqXHR
					};

					_mfpTrigger('ParseAjax', temp);

					mfp.appendContent( $(temp.data), AJAX_NS );

					item.finished = true;

					_removeAjaxCursor();

					mfp._setFocus();

					setTimeout(function() {
						mfp.wrap.addClass(READY_CLASS);
					}, 16);

					mfp.updateStatus('ready');

					_mfpTrigger('AjaxContentAdded');
				},
				error: function() {
					_removeAjaxCursor();
					item.finished = item.loadError = true;
					mfp.updateStatus('error', mfp.st.ajax.tError.replace('%url%', item.src));
				}
			}, mfp.st.ajax.settings);

			mfp.req = $.ajax(opts);

			return '';
		}
	}
});





	

/*>>ajax*/

/*>>image*/
var _imgInterval,
	_getTitle = function(item) {
		if(item.data && item.data.title !== undefined) 
			return item.data.title;

		var src = mfp.st.image.titleSrc;

		if(src) {
			if($.isFunction(src)) {
				return src.call(mfp, item);
			} else if(item.el) {
				return item.el.attr(src) || '';
			}
		}
		return '';
	};

$.magnificPopup.registerModule('image', {

	options: {
		markup: '<div class="mfp-figure">'+
					'<div class="mfp-close"></div>'+
					'<figure>'+
						'<div class="mfp-img"></div>'+
						'<figcaption>'+
							'<div class="mfp-bottom-bar">'+
								'<div class="mfp-title"></div>'+
								'<div class="mfp-counter"></div>'+
							'</div>'+
						'</figcaption>'+
					'</figure>'+
				'</div>',
		cursor: 'mfp-zoom-out-cur',
		titleSrc: 'title', 
		verticalFit: true,
		tError: '<a href="%url%">The image</a> could not be loaded.'
	},

	proto: {
		initImage: function() {
			var imgSt = mfp.st.image,
				ns = '.image';

			mfp.types.push('image');

			_mfpOn(OPEN_EVENT+ns, function() {
				if(mfp.currItem.type === 'image' && imgSt.cursor) {
					_body.addClass(imgSt.cursor);
				}
			});

			_mfpOn(CLOSE_EVENT+ns, function() {
				if(imgSt.cursor) {
					_body.removeClass(imgSt.cursor);
				}
				_window.off('resize' + EVENT_NS);
			});

			_mfpOn('Resize'+ns, mfp.resizeImage);
			if(mfp.isLowIE) {
				_mfpOn('AfterChange', mfp.resizeImage);
			}
		},
		resizeImage: function() {
			var item = mfp.currItem;
			if(!item || !item.img) return;

			if(mfp.st.image.verticalFit) {
				var decr = 0;
				// fix box-sizing in ie7/8
				if(mfp.isLowIE) {
					decr = parseInt(item.img.css('padding-top'), 10) + parseInt(item.img.css('padding-bottom'),10);
				}
				item.img.css('max-height', mfp.wH-decr);
			}
		},
		_onImageHasSize: function(item) {
			if(item.img) {
				
				item.hasSize = true;

				if(_imgInterval) {
					clearInterval(_imgInterval);
				}
				
				item.isCheckingImgSize = false;

				_mfpTrigger('ImageHasSize', item);

				if(item.imgHidden) {
					if(mfp.content)
						mfp.content.removeClass('mfp-loading');
					
					item.imgHidden = false;
				}

			}
		},

		/**
		 * Function that loops until the image has size to display elements that rely on it asap
		 */
		findImageSize: function(item) {

			var counter = 0,
				img = item.img[0],
				mfpSetInterval = function(delay) {

					if(_imgInterval) {
						clearInterval(_imgInterval);
					}
					// decelerating interval that checks for size of an image
					_imgInterval = setInterval(function() {
						if(img.naturalWidth > 0) {
							mfp._onImageHasSize(item);
							return;
						}

						if(counter > 200) {
							clearInterval(_imgInterval);
						}

						counter++;
						if(counter === 3) {
							mfpSetInterval(10);
						} else if(counter === 40) {
							mfpSetInterval(50);
						} else if(counter === 100) {
							mfpSetInterval(500);
						}
					}, delay);
				};

			mfpSetInterval(1);
		},

		getImage: function(item, template) {

			var guard = 0,

				// image load complete handler
				onLoadComplete = function() {
					if(item) {
						if (item.img[0].complete) {
							item.img.off('.mfploader');
							
							if(item === mfp.currItem){
								mfp._onImageHasSize(item);

								mfp.updateStatus('ready');
							}

							item.hasSize = true;
							item.loaded = true;

							_mfpTrigger('ImageLoadComplete');
							
						}
						else {
							// if image complete check fails 200 times (20 sec), we assume that there was an error.
							guard++;
							if(guard < 200) {
								setTimeout(onLoadComplete,100);
							} else {
								onLoadError();
							}
						}
					}
				},

				// image error handler
				onLoadError = function() {
					if(item) {
						item.img.off('.mfploader');
						if(item === mfp.currItem){
							mfp._onImageHasSize(item);
							mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src) );
						}

						item.hasSize = true;
						item.loaded = true;
						item.loadError = true;
					}
				},
				imgSt = mfp.st.image;


			var el = template.find('.mfp-img');
			if(el.length) {
				var img = document.createElement('img');
				img.className = 'mfp-img';
				item.img = $(img).on('load.mfploader', onLoadComplete).on('error.mfploader', onLoadError);
				img.src = item.src;

				// without clone() "error" event is not firing when IMG is replaced by new IMG
				// TODO: find a way to avoid such cloning
				if(el.is('img')) {
					item.img = item.img.clone();
				}

				img = item.img[0];
				if(img.naturalWidth > 0) {
					item.hasSize = true;
				} else if(!img.width) {										
					item.hasSize = false;
				}
			}

			mfp._parseMarkup(template, {
				title: _getTitle(item),
				img_replaceWith: item.img
			}, item);

			mfp.resizeImage();

			if(item.hasSize) {
				if(_imgInterval) clearInterval(_imgInterval);

				if(item.loadError) {
					template.addClass('mfp-loading');
					mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src) );
				} else {
					template.removeClass('mfp-loading');
					mfp.updateStatus('ready');
				}
				return template;
			}

			mfp.updateStatus('loading');
			item.loading = true;

			if(!item.hasSize) {
				item.imgHidden = true;
				template.addClass('mfp-loading');
				mfp.findImageSize(item);
			} 

			return template;
		}
	}
});



/*>>image*/

/*>>zoom*/
var hasMozTransform,
	getHasMozTransform = function() {
		if(hasMozTransform === undefined) {
			hasMozTransform = document.createElement('p').style.MozTransform !== undefined;
		}
		return hasMozTransform;		
	};

$.magnificPopup.registerModule('zoom', {

	options: {
		enabled: false,
		easing: 'ease-in-out',
		duration: 300,
		opener: function(element) {
			return element.is('img') ? element : element.find('img');
		}
	},

	proto: {

		initZoom: function() {
			var zoomSt = mfp.st.zoom,
				ns = '.zoom',
				image;
				
			if(!zoomSt.enabled || !mfp.supportsTransition) {
				return;
			}

			var duration = zoomSt.duration,
				getElToAnimate = function(image) {
					var newImg = image.clone().removeAttr('style').removeAttr('class').addClass('mfp-animated-image'),
						transition = 'all '+(zoomSt.duration/1000)+'s ' + zoomSt.easing,
						cssObj = {
							position: 'fixed',
							zIndex: 9999,
							left: 0,
							top: 0,
							'-webkit-backface-visibility': 'hidden'
						},
						t = 'transition';

					cssObj['-webkit-'+t] = cssObj['-moz-'+t] = cssObj['-o-'+t] = cssObj[t] = transition;

					newImg.css(cssObj);
					return newImg;
				},
				showMainContent = function() {
					mfp.content.css('visibility', 'visible');
				},
				openTimeout,
				animatedImg;

			_mfpOn('BuildControls'+ns, function() {
				if(mfp._allowZoom()) {

					clearTimeout(openTimeout);
					mfp.content.css('visibility', 'hidden');

					// Basically, all code below does is clones existing image, puts in on top of the current one and animated it
					
					image = mfp._getItemToZoom();

					if(!image) {
						showMainContent();
						return;
					}

					animatedImg = getElToAnimate(image); 
					
					animatedImg.css( mfp._getOffset() );

					mfp.wrap.append(animatedImg);

					openTimeout = setTimeout(function() {
						animatedImg.css( mfp._getOffset( true ) );
						openTimeout = setTimeout(function() {

							showMainContent();

							setTimeout(function() {
								animatedImg.remove();
								image = animatedImg = null;
								_mfpTrigger('ZoomAnimationEnded');
							}, 16); // avoid blink when switching images 

						}, duration); // this timeout equals animation duration

					}, 16); // by adding this timeout we avoid short glitch at the beginning of animation


					// Lots of timeouts...
				}
			});
			_mfpOn(BEFORE_CLOSE_EVENT+ns, function() {
				if(mfp._allowZoom()) {

					clearTimeout(openTimeout);

					mfp.st.removalDelay = duration;

					if(!image) {
						image = mfp._getItemToZoom();
						if(!image) {
							return;
						}
						animatedImg = getElToAnimate(image);
					}
					
					
					animatedImg.css( mfp._getOffset(true) );
					mfp.wrap.append(animatedImg);
					mfp.content.css('visibility', 'hidden');
					
					setTimeout(function() {
						animatedImg.css( mfp._getOffset() );
					}, 16);
				}

			});

			_mfpOn(CLOSE_EVENT+ns, function() {
				if(mfp._allowZoom()) {
					showMainContent();
					if(animatedImg) {
						animatedImg.remove();
					}
					image = null;
				}	
			});
		},

		_allowZoom: function() {
			return mfp.currItem.type === 'image';
		},

		_getItemToZoom: function() {
			if(mfp.currItem.hasSize) {
				return mfp.currItem.img;
			} else {
				return false;
			}
		},

		// Get element postion relative to viewport
		_getOffset: function(isLarge) {
			var el;
			if(isLarge) {
				el = mfp.currItem.img;
			} else {
				el = mfp.st.zoom.opener(mfp.currItem.el || mfp.currItem);
			}

			var offset = el.offset();
			var paddingTop = parseInt(el.css('padding-top'),10);
			var paddingBottom = parseInt(el.css('padding-bottom'),10);
			offset.top -= ( $(window).scrollTop() - paddingTop );


			/*
			
			Animating left + top + width/height looks glitchy in Firefox, but perfect in Chrome. And vice-versa.

			 */
			var obj = {
				width: el.width(),
				// fix Zepto height+padding issue
				height: (_isJQ ? el.innerHeight() : el[0].offsetHeight) - paddingBottom - paddingTop
			};

			// I hate to do this, but there is no another option
			if( getHasMozTransform() ) {
				obj['-moz-transform'] = obj['transform'] = 'translate(' + offset.left + 'px,' + offset.top + 'px)';
			} else {
				obj.left = offset.left;
				obj.top = offset.top;
			}
			return obj;
		}

	}
});



/*>>zoom*/

/*>>iframe*/

var IFRAME_NS = 'iframe',
	_emptyPage = '//about:blank',
	
	_fixIframeBugs = function(isShowing) {
		if(mfp.currTemplate[IFRAME_NS]) {
			var el = mfp.currTemplate[IFRAME_NS].find('iframe');
			if(el.length) { 
				// reset src after the popup is closed to avoid "video keeps playing after popup is closed" bug
				if(!isShowing) {
					el[0].src = _emptyPage;
				}

				// IE8 black screen bug fix
				if(mfp.isIE8) {
					el.css('display', isShowing ? 'block' : 'none');
				}
			}
		}
	};

$.magnificPopup.registerModule(IFRAME_NS, {

	options: {
		markup: '<div class="mfp-iframe-scaler">'+
					'<div class="mfp-close"></div>'+
					'<iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe>'+
				'</div>',

		srcAction: 'iframe_src',

		// we don't care and support only one default type of URL by default
		patterns: {
			youtube: {
				index: 'youtube.com', 
				id: 'v=', 
				src: '//www.youtube.com/embed/%id%?autoplay=1'
			},
			vimeo: {
				index: 'vimeo.com/',
				id: '/',
				src: '//player.vimeo.com/video/%id%?autoplay=1'
			},
			gmaps: {
				index: '//maps.google.',
				src: '%id%&output=embed'
			}
		}
	},

	proto: {
		initIframe: function() {
			mfp.types.push(IFRAME_NS);

			_mfpOn('BeforeChange', function(e, prevType, newType) {
				if(prevType !== newType) {
					if(prevType === IFRAME_NS) {
						_fixIframeBugs(); // iframe if removed
					} else if(newType === IFRAME_NS) {
						_fixIframeBugs(true); // iframe is showing
					} 
				}// else {
					// iframe source is switched, don't do anything
				//}
			});

			_mfpOn(CLOSE_EVENT + '.' + IFRAME_NS, function() {
				_fixIframeBugs();
			});
		},

		getIframe: function(item, template) {
			var embedSrc = item.src;
			var iframeSt = mfp.st.iframe;
				
			$.each(iframeSt.patterns, function() {
				if(embedSrc.indexOf( this.index ) > -1) {
					if(this.id) {
						if(typeof this.id === 'string') {
							embedSrc = embedSrc.substr(embedSrc.lastIndexOf(this.id)+this.id.length, embedSrc.length);
						} else {
							embedSrc = this.id.call( this, embedSrc );
						}
					}
					embedSrc = this.src.replace('%id%', embedSrc );
					return false; // break;
				}
			});
			
			var dataObj = {};
			if(iframeSt.srcAction) {
				dataObj[iframeSt.srcAction] = embedSrc;
			}
			mfp._parseMarkup(template, dataObj, item);

			mfp.updateStatus('ready');

			return template;
		}
	}
});



/*>>iframe*/

/*>>gallery*/
/**
 * Get looped index depending on number of slides
 */
var _getLoopedId = function(index) {
		var numSlides = mfp.items.length;
		if(index > numSlides - 1) {
			return index - numSlides;
		} else  if(index < 0) {
			return numSlides + index;
		}
		return index;
	},
	_replaceCurrTotal = function(text, curr, total) {
		return text.replace(/%curr%/gi, curr + 1).replace(/%total%/gi, total);
	};

$.magnificPopup.registerModule('gallery', {

	options: {
		enabled: false,
		arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',
		preload: [0,2],
		navigateByImgClick: true,
		arrows: true,

		tPrev: 'Previous (Left arrow key)',
		tNext: 'Next (Right arrow key)',
		tCounter: '%curr% of %total%'
	},

	proto: {
		initGallery: function() {

			var gSt = mfp.st.gallery,
				ns = '.mfp-gallery',
				supportsFastClick = Boolean($.fn.mfpFastClick);

			mfp.direction = true; // true - next, false - prev
			
			if(!gSt || !gSt.enabled ) return false;

			_wrapClasses += ' mfp-gallery';

			_mfpOn(OPEN_EVENT+ns, function() {

				if(gSt.navigateByImgClick) {
					mfp.wrap.on('click'+ns, '.mfp-img', function() {
						if(mfp.items.length > 1) {
							mfp.next();
							return false;
						}
					});
				}

				_document.on('keydown'+ns, function(e) {
					if (e.keyCode === 37) {
						mfp.prev();
					} else if (e.keyCode === 39) {
						mfp.next();
					}
				});
			});

			_mfpOn('UpdateStatus'+ns, function(e, data) {
				if(data.text) {
					data.text = _replaceCurrTotal(data.text, mfp.currItem.index, mfp.items.length);
				}
			});

			_mfpOn(MARKUP_PARSE_EVENT+ns, function(e, element, values, item) {
				var l = mfp.items.length;
				values.counter = l > 1 ? _replaceCurrTotal(gSt.tCounter, item.index, l) : '';
			});

			_mfpOn('BuildControls' + ns, function() {
				if(mfp.items.length > 1 && gSt.arrows && !mfp.arrowLeft) {
					var markup = gSt.arrowMarkup,
						arrowLeft = mfp.arrowLeft = $( markup.replace(/%title%/gi, gSt.tPrev).replace(/%dir%/gi, 'left') ).addClass(PREVENT_CLOSE_CLASS),			
						arrowRight = mfp.arrowRight = $( markup.replace(/%title%/gi, gSt.tNext).replace(/%dir%/gi, 'right') ).addClass(PREVENT_CLOSE_CLASS);

					var eName = supportsFastClick ? 'mfpFastClick' : 'click';
					arrowLeft[eName](function() {
						mfp.prev();
					});			
					arrowRight[eName](function() {
						mfp.next();
					});	

					// Polyfill for :before and :after (adds elements with classes mfp-a and mfp-b)
					if(mfp.isIE7) {
						_getEl('b', arrowLeft[0], false, true);
						_getEl('a', arrowLeft[0], false, true);
						_getEl('b', arrowRight[0], false, true);
						_getEl('a', arrowRight[0], false, true);
					}

					mfp.container.append(arrowLeft.add(arrowRight));
				}
			});

			_mfpOn(CHANGE_EVENT+ns, function() {
				if(mfp._preloadTimeout) clearTimeout(mfp._preloadTimeout);

				mfp._preloadTimeout = setTimeout(function() {
					mfp.preloadNearbyImages();
					mfp._preloadTimeout = null;
				}, 16);		
			});


			_mfpOn(CLOSE_EVENT+ns, function() {
				_document.off(ns);
				mfp.wrap.off('click'+ns);
			
				if(mfp.arrowLeft && supportsFastClick) {
					mfp.arrowLeft.add(mfp.arrowRight).destroyMfpFastClick();
				}
				mfp.arrowRight = mfp.arrowLeft = null;
			});

		}, 
		next: function() {
			mfp.direction = true;
			mfp.index = _getLoopedId(mfp.index + 1);
			mfp.updateItemHTML();
		},
		prev: function() {
			mfp.direction = false;
			mfp.index = _getLoopedId(mfp.index - 1);
			mfp.updateItemHTML();
		},
		goTo: function(newIndex) {
			mfp.direction = (newIndex >= mfp.index);
			mfp.index = newIndex;
			mfp.updateItemHTML();
		},
		preloadNearbyImages: function() {
			var p = mfp.st.gallery.preload,
				preloadBefore = Math.min(p[0], mfp.items.length),
				preloadAfter = Math.min(p[1], mfp.items.length),
				i;

			for(i = 1; i <= (mfp.direction ? preloadAfter : preloadBefore); i++) {
				mfp._preloadItem(mfp.index+i);
			}
			for(i = 1; i <= (mfp.direction ? preloadBefore : preloadAfter); i++) {
				mfp._preloadItem(mfp.index-i);
			}
		},
		_preloadItem: function(index) {
			index = _getLoopedId(index);

			if(mfp.items[index].preloaded) {
				return;
			}

			var item = mfp.items[index];
			if(!item.parsed) {
				item = mfp.parseEl( index );
			}

			_mfpTrigger('LazyLoad', item);

			if(item.type === 'image') {
				item.img = $('<img class="mfp-img" />').on('load.mfploader', function() {
					item.hasSize = true;
				}).on('error.mfploader', function() {
					item.hasSize = true;
					item.loadError = true;
					_mfpTrigger('LazyLoadError', item);
				}).attr('src', item.src);
			}


			item.preloaded = true;
		}
	}
});

/*
Touch Support that might be implemented some day

addSwipeGesture: function() {
	var startX,
		moved,
		multipleTouches;

		return;

	var namespace = '.mfp',
		addEventNames = function(pref, down, move, up, cancel) {
			mfp._tStart = pref + down + namespace;
			mfp._tMove = pref + move + namespace;
			mfp._tEnd = pref + up + namespace;
			mfp._tCancel = pref + cancel + namespace;
		};

	if(window.navigator.msPointerEnabled) {
		addEventNames('MSPointer', 'Down', 'Move', 'Up', 'Cancel');
	} else if('ontouchstart' in window) {
		addEventNames('touch', 'start', 'move', 'end', 'cancel');
	} else {
		return;
	}
	_window.on(mfp._tStart, function(e) {
		var oE = e.originalEvent;
		multipleTouches = moved = false;
		startX = oE.pageX || oE.changedTouches[0].pageX;
	}).on(mfp._tMove, function(e) {
		if(e.originalEvent.touches.length > 1) {
			multipleTouches = e.originalEvent.touches.length;
		} else {
			//e.preventDefault();
			moved = true;
		}
	}).on(mfp._tEnd + ' ' + mfp._tCancel, function(e) {
		if(moved && !multipleTouches) {
			var oE = e.originalEvent,
				diff = startX - (oE.pageX || oE.changedTouches[0].pageX);

			if(diff > 20) {
				mfp.next();
			} else if(diff < -20) {
				mfp.prev();
			}
		}
	});
},
*/


/*>>gallery*/

/*>>retina*/

var RETINA_NS = 'retina';

$.magnificPopup.registerModule(RETINA_NS, {
	options: {
		replaceSrc: function(item) {
			return item.src.replace(/\.\w+$/, function(m) { return '@2x' + m; });
		},
		ratio: 1 // Function or number.  Set to 1 to disable.
	},
	proto: {
		initRetina: function() {
			if(window.devicePixelRatio > 1) {

				var st = mfp.st.retina,
					ratio = st.ratio;

				ratio = !isNaN(ratio) ? ratio : ratio();

				if(ratio > 1) {
					_mfpOn('ImageHasSize' + '.' + RETINA_NS, function(e, item) {
						item.img.css({
							'max-width': item.img[0].naturalWidth / ratio,
							'width': '100%'
						});
					});
					_mfpOn('ElementParse' + '.' + RETINA_NS, function(e, item) {
						item.src = st.replaceSrc(item, ratio);
					});
				}
			}

		}
	}
});

/*>>retina*/

/*>>fastclick*/
/**
 * FastClick event implementation. (removes 300ms delay on touch devices)
 * Based on https://developers.google.com/mobile/articles/fast_buttons
 *
 * You may use it outside the Magnific Popup by calling just:
 *
 * $('.your-el').mfpFastClick(function() {
 *     console.log('Clicked!');
 * });
 *
 * To unbind:
 * $('.your-el').destroyMfpFastClick();
 * 
 * 
 * Note that it's a very basic and simple implementation, it blocks ghost click on the same element where it was bound.
 * If you need something more advanced, use plugin by FT Labs https://github.com/ftlabs/fastclick
 * 
 */

(function() {
	var ghostClickDelay = 1000,
		supportsTouch = 'ontouchstart' in window,
		unbindTouchMove = function() {
			_window.off('touchmove'+ns+' touchend'+ns);
		},
		eName = 'mfpFastClick',
		ns = '.'+eName;


	// As Zepto.js doesn't have an easy way to add custom events (like jQuery), so we implement it in this way
	$.fn.mfpFastClick = function(callback) {

		return $(this).each(function() {

			var elem = $(this),
				lock;

			if( supportsTouch ) {

				var timeout,
					startX,
					startY,
					pointerMoved,
					point,
					numPointers;

				elem.on('touchstart' + ns, function(e) {
					pointerMoved = false;
					numPointers = 1;

					point = e.originalEvent ? e.originalEvent.touches[0] : e.touches[0];
					startX = point.clientX;
					startY = point.clientY;

					_window.on('touchmove'+ns, function(e) {
						point = e.originalEvent ? e.originalEvent.touches : e.touches;
						numPointers = point.length;
						point = point[0];
						if (Math.abs(point.clientX - startX) > 10 ||
							Math.abs(point.clientY - startY) > 10) {
							pointerMoved = true;
							unbindTouchMove();
						}
					}).on('touchend'+ns, function(e) {
						unbindTouchMove();
						if(pointerMoved || numPointers > 1) {
							return;
						}
						lock = true;
						e.preventDefault();
						clearTimeout(timeout);
						timeout = setTimeout(function() {
							lock = false;
						}, ghostClickDelay);
						callback();
					});
				});

			}

			elem.on('click' + ns, function() {
				if(!lock) {
					callback();
				}
			});
		});
	};

	$.fn.destroyMfpFastClick = function() {
		$(this).off('touchstart' + ns + ' click' + ns);
		if(supportsTouch) _window.off('touchmove'+ns+' touchend'+ns);
	};
})();

/*>>fastclick*/
 _checkInstance(); })(window.jQuery || window.Zepto);
/*! Copyright (c) 2011 by Jonas Mosbech - https://github.com/jmosbech/StickyTableHeaders
	MIT license info: https://github.com/jmosbech/StickyTableHeaders/blob/master/license.txt */


;(function ($, window, undefined) {
	'use strict';

	var name = 'stickyTableHeaders',
		id = 0,
		defaults = {
			fixedOffset: 0,
			leftOffset: 0,
			scrollableArea: window
		};

	function Plugin (el, options) {
		// To avoid scope issues, use 'base' instead of 'this'
		// to reference this class from internal events and functions.
		var base = this;

		// Access to jQuery and DOM versions of element
		base.$el = $(el);
		base.el = el;
		base.id = id++;

		// Listen for destroyed, call teardown
		base.$el.bind('destroyed',
			$.proxy(base.teardown, base));

		// Cache DOM refs for performance reasons
		base.$clonedHeader = null;
		base.$originalHeader = null;

		// Keep track of state
		base.isSticky = false;
		base.hasBeenSticky = false;
		base.leftOffset = null;
		base.topOffset = null;

		base.init = function () {
			base.options = $.extend({}, defaults, options);

			base.$el.each(function () {
				var $this = $(this);

				// remove padding on <table> to fix issue #7
				$this.css('padding', 0);

				base.$scrollableArea = $(base.options.scrollableArea);

				base.$originalHeader = $('thead:first', this);
				base.$clonedHeader = base.$originalHeader.clone();
				$this.trigger('clonedHeader.' + name, [base.$clonedHeader]);

				base.$clonedHeader.addClass('tableFloatingHeader');
				base.$clonedHeader.css('display', 'none');

				base.$originalHeader.addClass('tableFloatingHeaderOriginal');

				base.$originalHeader.after(base.$clonedHeader);

				base.$printStyle = $('<style type="text/css" media="print">' +
					'.tableFloatingHeader{display:none !important;}' +
					'.tableFloatingHeaderOriginal{position:static !important;}' +
					'</style>');
				$('head').append(base.$printStyle);
			});

			base.updateWidth();
			base.toggleHeaders();

			base.bind();
		};

		base.destroy = function (){
			base.$el.unbind('destroyed', base.teardown);
			base.teardown();
		};

		base.teardown = function(){
			if (base.isSticky) {
				base.$originalHeader.css('position', 'static');
			}
			$.removeData(base.el, 'plugin_' + name);
			base.unbind();

			base.$clonedHeader.remove();
			base.$originalHeader.removeClass('tableFloatingHeaderOriginal');
			base.$originalHeader.css('visibility', 'visible');
			base.$printStyle.remove();

			base.el = null;
			base.$el = null;
		};

		base.bind = function(){
			base.$scrollableArea.on('scroll.' + name, base.toggleHeaders);
			if (!base.isWindowScrolling()) {
				$(window).on('scroll.' + name + base.id, base.setPositionValues);
				$(window).on('resize.' + name + base.id, base.toggleHeaders);
			}
			base.$scrollableArea.on('resize.' + name, base.toggleHeaders);
			base.$scrollableArea.on('resize.' + name, base.updateWidth);
		};

		base.unbind = function(){
			// unbind window events by specifying handle so we don't remove too much
			base.$scrollableArea.off('.' + name, base.toggleHeaders);
			if (!base.isWindowScrolling()) {
				$(window).off('.' + name + base.id, base.setPositionValues);
				$(window).off('.' + name + base.id, base.toggleHeaders);
			}
			base.$scrollableArea.off('.' + name, base.updateWidth);
			base.$el.off('.' + name);
			base.$el.find('*').off('.' + name);
		};

		base.toggleHeaders = function () {
			if (base.$el) {
				base.$el.each(function () {
					var $this = $(this),
						newLeft,
						newTopOffset = base.isWindowScrolling() ? (
									isNaN(base.options.fixedOffset) ?
									base.options.fixedOffset.outerHeight() :
									base.options.fixedOffset
								) :
								base.$scrollableArea.offset().top + (!isNaN(base.options.fixedOffset) ? base.options.fixedOffset : 0),
						offset = $this.offset(),

						scrollTop = base.$scrollableArea.scrollTop() + newTopOffset,
						scrollLeft = base.$scrollableArea.scrollLeft(),

						scrolledPastTop = base.isWindowScrolling() ?
								scrollTop > offset.top :
								newTopOffset > offset.top,
						notScrolledPastBottom = (base.isWindowScrolling() ? scrollTop : 0) <
								(offset.top + $this.height() - base.$clonedHeader.height() - (base.isWindowScrolling() ? 0 : newTopOffset));

					if (scrolledPastTop && notScrolledPastBottom) {
						newLeft = offset.left - scrollLeft + base.options.leftOffset;
						base.$originalHeader.css({
							'position': 'fixed',
							'margin-top': 0,
							'left': newLeft,
							'z-index': 1 // #18: opacity bug
						});
						base.isSticky = true;
						base.leftOffset = newLeft;
						base.topOffset = newTopOffset;
						base.$clonedHeader.css('display', '');
						base.setPositionValues();
						// make sure the width is correct: the user might have resized the browser while in static mode
						base.updateWidth();
					} else if (base.isSticky) {
						base.$originalHeader.css('position', 'static');
						base.$clonedHeader.css('display', 'none');
						base.isSticky = false;
						base.resetWidth($("td,th", base.$clonedHeader), $("td,th", base.$originalHeader));
					}
				});
			}
		};

		base.isWindowScrolling = function() {
			return base.$scrollableArea[0] === window;
		};

		base.setPositionValues = function () {
			var winScrollTop = $(window).scrollTop(),
				winScrollLeft = $(window).scrollLeft();
			if (!base.isSticky ||
					winScrollTop < 0 || winScrollTop + $(window).height() > $(document).height() ||
					winScrollLeft < 0 || winScrollLeft + $(window).width() > $(document).width()) {
				return;
			}
			base.$originalHeader.css({
				'top': base.topOffset - (base.isWindowScrolling() ? 0 : winScrollTop),
				'left': base.leftOffset - (base.isWindowScrolling() ? 0 : winScrollLeft)
			});
		};

		base.updateWidth = function () {
			if (!base.isSticky) {
				return;
			}
			// Copy cell widths from clone
			if (!base.$originalHeaderCells) {
				base.$originalHeaderCells = $('th,td', base.$originalHeader);
			}
			if (!base.$clonedHeaderCells) {
				base.$clonedHeaderCells = $('th,td', base.$clonedHeader);
			}
			var cellWidths = base.getWidth(base.$clonedHeaderCells);
			base.setWidth(cellWidths, base.$clonedHeaderCells, base.$originalHeaderCells);

			// Copy row width from whole table
			base.$originalHeader.css('width', base.$clonedHeader.width());
		};

		base.getWidth = function ($clonedHeaders) {
			var widths = [];
			$clonedHeaders.each(function (index) {
				var width, $this = $(this);

				if ($this.css('box-sizing') === 'border-box') {
					width = $this.outerWidth(); // #39: border-box bug
				} else {
					width = $this.width();
				}

				widths[index] = width;
			});
			return widths;
		};

		base.setWidth = function (widths, $clonedHeaders, $origHeaders) {
			$clonedHeaders.each(function (index) {
				var width = widths[index];
				$origHeaders.eq(index).css({
					'min-width': width,
					'max-width': width
				});
			});
		};

		base.resetWidth = function ($clonedHeaders, $origHeaders) {
			$clonedHeaders.each(function (index) {
				var $this = $(this);
				$origHeaders.eq(index).css({
					'min-width': $this.css("min-width"),
					'max-width': $this.css("max-width")
				});
			});
		};

		base.updateOptions = function(options) {
			base.options = $.extend({}, defaults, options);
			base.updateWidth();
			base.toggleHeaders();
		};

		// Run initializer
		base.init();
	}

	// A plugin wrapper around the constructor,
	// preventing against multiple instantiations
	$.fn[name] = function ( options ) {
		return this.each(function () {
			var instance = $.data(this, 'plugin_' + name);
			if (instance) {
				if (typeof options === "string") {
					instance[options].apply(instance);
				} else {
					instance.updateOptions(options);
				}
			} else if(options !== 'destroy') {
				$.data(this, 'plugin_' + name, new Plugin( this, options ));
			}
		});
	};

})(jQuery, window);
/*! DataTables 1.10.15
 * ©2008-2017 SpryMedia Ltd - datatables.net/license
 */

/**
 * @summary     DataTables
 * @description Paginate, search and order HTML tables
 * @version     1.10.15
 * @file        jquery.dataTables.js
 * @author      SpryMedia Ltd
 * @contact     www.datatables.net
 * @copyright   Copyright 2008-2017 SpryMedia Ltd.
 *
 * This source file is free software, available under the following license:
 *   MIT license - http://datatables.net/license
 *
 * This source file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
 *
 * For details please refer to: http://www.datatables.net
 */

/*jslint evil: true, undef: true, browser: true */
/*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidate,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/


(function( factory ) {
	"use strict";

	if ( typeof define === 'function' && define.amd ) {
		// AMD
		define( ['jquery'], function ( $ ) {
			return factory( $, window, document );
		} );
	}
	else if ( typeof exports === 'object' ) {
		// CommonJS
		module.exports = function (root, $) {
			if ( ! root ) {
				// CommonJS environments without a window global must pass a
				// root. This will give an error otherwise
				root = window;
			}

			if ( ! $ ) {
				$ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
					require('jquery') :
					require('jquery')( root );
			}

			return factory( $, root, root.document );
		};
	}
	else {
		// Browser
		factory( jQuery, window, document );
	}
}
(function( $, window, document, undefined ) {
	"use strict";

	/**
	 * DataTables is a plug-in for the jQuery Javascript library. It is a highly
	 * flexible tool, based upon the foundations of progressive enhancement,
	 * which will add advanced interaction controls to any HTML table. For a
	 * full list of features please refer to
	 * [DataTables.net](href="http://datatables.net).
	 *
	 * Note that the `DataTable` object is not a global variable but is aliased
	 * to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may
	 * be  accessed.
	 *
	 *  @class
	 *  @param {object} [init={}] Configuration object for DataTables. Options
	 *    are defined by {@link DataTable.defaults}
	 *  @requires jQuery 1.7+
	 *
	 *  @example
	 *    // Basic initialisation
	 *    $(document).ready( function {
	 *      $('#example').dataTable();
	 *    } );
	 *
	 *  @example
	 *    // Initialisation with configuration options - in this case, disable
	 *    // pagination and sorting.
	 *    $(document).ready( function {
	 *      $('#example').dataTable( {
	 *        "paginate": false,
	 *        "sort": false
	 *      } );
	 *    } );
	 */
	var DataTable = function ( options )
	{
		/**
		 * Perform a jQuery selector action on the table's TR elements (from the tbody) and
		 * return the resulting jQuery object.
		 *  @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
		 *  @param {object} [oOpts] Optional parameters for modifying the rows to be included
		 *  @param {string} [oOpts.filter=none] Select TR elements that meet the current filter
		 *    criterion ("applied") or all TR elements (i.e. no filter).
		 *  @param {string} [oOpts.order=current] Order of the TR elements in the processed array.
		 *    Can be either 'current', whereby the current sorting of the table is used, or
		 *    'original' whereby the original order the data was read into the table is used.
		 *  @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
		 *    ("current") or not ("all"). If 'current' is given, then order is assumed to be
		 *    'current' and filter is 'applied', regardless of what they might be given as.
		 *  @returns {object} jQuery object, filtered by the given selector.
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Highlight every second row
		 *      oTable.$('tr:odd').css('backgroundColor', 'blue');
		 *    } );
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Filter to rows with 'Webkit' in them, add a background colour and then
		 *      // remove the filter, thus highlighting the 'Webkit' rows only.
		 *      oTable.fnFilter('Webkit');
		 *      oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue');
		 *      oTable.fnFilter('');
		 *    } );
		 */
		this.$ = function ( sSelector, oOpts )
		{
			return this.api(true).$( sSelector, oOpts );
		};
		
		
		/**
		 * Almost identical to $ in operation, but in this case returns the data for the matched
		 * rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
		 * rather than any descendants, so the data can be obtained for the row/cell. If matching
		 * rows are found, the data returned is the original data array/object that was used to
		 * create the row (or a generated array if from a DOM source).
		 *
		 * This method is often useful in-combination with $ where both functions are given the
		 * same parameters and the array indexes will match identically.
		 *  @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
		 *  @param {object} [oOpts] Optional parameters for modifying the rows to be included
		 *  @param {string} [oOpts.filter=none] Select elements that meet the current filter
		 *    criterion ("applied") or all elements (i.e. no filter).
		 *  @param {string} [oOpts.order=current] Order of the data in the processed array.
		 *    Can be either 'current', whereby the current sorting of the table is used, or
		 *    'original' whereby the original order the data was read into the table is used.
		 *  @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
		 *    ("current") or not ("all"). If 'current' is given, then order is assumed to be
		 *    'current' and filter is 'applied', regardless of what they might be given as.
		 *  @returns {array} Data for the matched elements. If any elements, as a result of the
		 *    selector, were not TR, TD or TH elements in the DataTable, they will have a null
		 *    entry in the array.
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Get the data from the first row in the table
		 *      var data = oTable._('tr:first');
		 *
		 *      // Do something useful with the data
		 *      alert( "First cell is: "+data[0] );
		 *    } );
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Filter to 'Webkit' and get all data for
		 *      oTable.fnFilter('Webkit');
		 *      var data = oTable._('tr', {"search": "applied"});
		 *
		 *      // Do something with the data
		 *      alert( data.length+" rows matched the search" );
		 *    } );
		 */
		this._ = function ( sSelector, oOpts )
		{
			return this.api(true).rows( sSelector, oOpts ).data();
		};
		
		
		/**
		 * Create a DataTables Api instance, with the currently selected tables for
		 * the Api's context.
		 * @param {boolean} [traditional=false] Set the API instance's context to be
		 *   only the table referred to by the `DataTable.ext.iApiIndex` option, as was
		 *   used in the API presented by DataTables 1.9- (i.e. the traditional mode),
		 *   or if all tables captured in the jQuery object should be used.
		 * @return {DataTables.Api}
		 */
		this.api = function ( traditional )
		{
			return traditional ?
				new _Api(
					_fnSettingsFromNode( this[ _ext.iApiIndex ] )
				) :
				new _Api( this );
		};
		
		
		/**
		 * Add a single new row or multiple rows of data to the table. Please note
		 * that this is suitable for client-side processing only - if you are using
		 * server-side processing (i.e. "bServerSide": true), then to add data, you
		 * must add it to the data source, i.e. the server-side, through an Ajax call.
		 *  @param {array|object} data The data to be added to the table. This can be:
		 *    <ul>
		 *      <li>1D array of data - add a single row with the data provided</li>
		 *      <li>2D array of arrays - add multiple rows in a single call</li>
		 *      <li>object - data object when using <i>mData</i></li>
		 *      <li>array of objects - multiple data objects when using <i>mData</i></li>
		 *    </ul>
		 *  @param {bool} [redraw=true] redraw the table or not
		 *  @returns {array} An array of integers, representing the list of indexes in
		 *    <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
		 *    the table.
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    // Global var for counter
		 *    var giCount = 2;
		 *
		 *    $(document).ready(function() {
		 *      $('#example').dataTable();
		 *    } );
		 *
		 *    function fnClickAddRow() {
		 *      $('#example').dataTable().fnAddData( [
		 *        giCount+".1",
		 *        giCount+".2",
		 *        giCount+".3",
		 *        giCount+".4" ]
		 *      );
		 *
		 *      giCount++;
		 *    }
		 */
		this.fnAddData = function( data, redraw )
		{
			var api = this.api( true );
		
			/* Check if we want to add multiple rows or not */
			var rows = $.isArray(data) && ( $.isArray(data[0]) || $.isPlainObject(data[0]) ) ?
				api.rows.add( data ) :
				api.row.add( data );
		
			if ( redraw === undefined || redraw ) {
				api.draw();
			}
		
			return rows.flatten().toArray();
		};
		
		
		/**
		 * This function will make DataTables recalculate the column sizes, based on the data
		 * contained in the table and the sizes applied to the columns (in the DOM, CSS or
		 * through the sWidth parameter). This can be useful when the width of the table's
		 * parent element changes (for example a window resize).
		 *  @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable( {
		 *        "sScrollY": "200px",
		 *        "bPaginate": false
		 *      } );
		 *
		 *      $(window).on('resize', function () {
		 *        oTable.fnAdjustColumnSizing();
		 *      } );
		 *    } );
		 */
		this.fnAdjustColumnSizing = function ( bRedraw )
		{
			var api = this.api( true ).columns.adjust();
			var settings = api.settings()[0];
			var scroll = settings.oScroll;
		
			if ( bRedraw === undefined || bRedraw ) {
				api.draw( false );
			}
			else if ( scroll.sX !== "" || scroll.sY !== "" ) {
				/* If not redrawing, but scrolling, we want to apply the new column sizes anyway */
				_fnScrollDraw( settings );
			}
		};
		
		
		/**
		 * Quickly and simply clear a table
		 *  @param {bool} [bRedraw=true] redraw the table or not
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...)
		 *      oTable.fnClearTable();
		 *    } );
		 */
		this.fnClearTable = function( bRedraw )
		{
			var api = this.api( true ).clear();
		
			if ( bRedraw === undefined || bRedraw ) {
				api.draw();
			}
		};
		
		
		/**
		 * The exact opposite of 'opening' a row, this function will close any rows which
		 * are currently 'open'.
		 *  @param {node} nTr the table row to 'close'
		 *  @returns {int} 0 on success, or 1 if failed (can't find the row)
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable;
		 *
		 *      // 'open' an information row when a row is clicked on
		 *      $('#example tbody tr').click( function () {
		 *        if ( oTable.fnIsOpen(this) ) {
		 *          oTable.fnClose( this );
		 *        } else {
		 *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
		 *        }
		 *      } );
		 *
		 *      oTable = $('#example').dataTable();
		 *    } );
		 */
		this.fnClose = function( nTr )
		{
			this.api( true ).row( nTr ).child.hide();
		};
		
		
		/**
		 * Remove a row for the table
		 *  @param {mixed} target The index of the row from aoData to be deleted, or
		 *    the TR element you want to delete
		 *  @param {function|null} [callBack] Callback function
		 *  @param {bool} [redraw=true] Redraw the table or not
		 *  @returns {array} The row that was deleted
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Immediately remove the first row
		 *      oTable.fnDeleteRow( 0 );
		 *    } );
		 */
		this.fnDeleteRow = function( target, callback, redraw )
		{
			var api = this.api( true );
			var rows = api.rows( target );
			var settings = rows.settings()[0];
			var data = settings.aoData[ rows[0][0] ];
		
			rows.remove();
		
			if ( callback ) {
				callback.call( this, settings, data );
			}
		
			if ( redraw === undefined || redraw ) {
				api.draw();
			}
		
			return data;
		};
		
		
		/**
		 * Restore the table to it's original state in the DOM by removing all of DataTables
		 * enhancements, alterations to the DOM structure of the table and event listeners.
		 *  @param {boolean} [remove=false] Completely remove the table from the DOM
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      // This example is fairly pointless in reality, but shows how fnDestroy can be used
		 *      var oTable = $('#example').dataTable();
		 *      oTable.fnDestroy();
		 *    } );
		 */
		this.fnDestroy = function ( remove )
		{
			this.api( true ).destroy( remove );
		};
		
		
		/**
		 * Redraw the table
		 *  @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw.
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Re-draw the table - you wouldn't want to do it here, but it's an example :-)
		 *      oTable.fnDraw();
		 *    } );
		 */
		this.fnDraw = function( complete )
		{
			// Note that this isn't an exact match to the old call to _fnDraw - it takes
			// into account the new data, but can hold position.
			this.api( true ).draw( complete );
		};
		
		
		/**
		 * Filter the input based on data
		 *  @param {string} sInput String to filter the table on
		 *  @param {int|null} [iColumn] Column to limit filtering to
		 *  @param {bool} [bRegex=false] Treat as regular expression or not
		 *  @param {bool} [bSmart=true] Perform smart filtering or not
		 *  @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es)
		 *  @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false)
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Sometime later - filter...
		 *      oTable.fnFilter( 'test string' );
		 *    } );
		 */
		this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive )
		{
			var api = this.api( true );
		
			if ( iColumn === null || iColumn === undefined ) {
				api.search( sInput, bRegex, bSmart, bCaseInsensitive );
			}
			else {
				api.column( iColumn ).search( sInput, bRegex, bSmart, bCaseInsensitive );
			}
		
			api.draw();
		};
		
		
		/**
		 * Get the data for the whole table, an individual row or an individual cell based on the
		 * provided parameters.
		 *  @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as
		 *    a TR node then the data source for the whole row will be returned. If given as a
		 *    TD/TH cell node then iCol will be automatically calculated and the data for the
		 *    cell returned. If given as an integer, then this is treated as the aoData internal
		 *    data index for the row (see fnGetPosition) and the data for that row used.
		 *  @param {int} [col] Optional column index that you want the data of.
		 *  @returns {array|object|string} If mRow is undefined, then the data for all rows is
		 *    returned. If mRow is defined, just data for that row, and is iCol is
		 *    defined, only data for the designated cell is returned.
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    // Row data
		 *    $(document).ready(function() {
		 *      oTable = $('#example').dataTable();
		 *
		 *      oTable.$('tr').click( function () {
		 *        var data = oTable.fnGetData( this );
		 *        // ... do something with the array / object of data for the row
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Individual cell data
		 *    $(document).ready(function() {
		 *      oTable = $('#example').dataTable();
		 *
		 *      oTable.$('td').click( function () {
		 *        var sData = oTable.fnGetData( this );
		 *        alert( 'The cell clicked on had the value of '+sData );
		 *      } );
		 *    } );
		 */
		this.fnGetData = function( src, col )
		{
			var api = this.api( true );
		
			if ( src !== undefined ) {
				var type = src.nodeName ? src.nodeName.toLowerCase() : '';
		
				return col !== undefined || type == 'td' || type == 'th' ?
					api.cell( src, col ).data() :
					api.row( src ).data() || null;
			}
		
			return api.data().toArray();
		};
		
		
		/**
		 * Get an array of the TR nodes that are used in the table's body. Note that you will
		 * typically want to use the '$' API method in preference to this as it is more
		 * flexible.
		 *  @param {int} [iRow] Optional row index for the TR element you want
		 *  @returns {array|node} If iRow is undefined, returns an array of all TR elements
		 *    in the table's body, or iRow is defined, just the TR element requested.
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Get the nodes from the table
		 *      var nNodes = oTable.fnGetNodes( );
		 *    } );
		 */
		this.fnGetNodes = function( iRow )
		{
			var api = this.api( true );
		
			return iRow !== undefined ?
				api.row( iRow ).node() :
				api.rows().nodes().flatten().toArray();
		};
		
		
		/**
		 * Get the array indexes of a particular cell from it's DOM element
		 * and column index including hidden columns
		 *  @param {node} node this can either be a TR, TD or TH in the table's body
		 *  @returns {int} If nNode is given as a TR, then a single index is returned, or
		 *    if given as a cell, an array of [row index, column index (visible),
		 *    column index (all)] is given.
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      $('#example tbody td').click( function () {
		 *        // Get the position of the current data from the node
		 *        var aPos = oTable.fnGetPosition( this );
		 *
		 *        // Get the data array for this row
		 *        var aData = oTable.fnGetData( aPos[0] );
		 *
		 *        // Update the data array and return the value
		 *        aData[ aPos[1] ] = 'clicked';
		 *        this.innerHTML = 'clicked';
		 *      } );
		 *
		 *      // Init DataTables
		 *      oTable = $('#example').dataTable();
		 *    } );
		 */
		this.fnGetPosition = function( node )
		{
			var api = this.api( true );
			var nodeName = node.nodeName.toUpperCase();
		
			if ( nodeName == 'TR' ) {
				return api.row( node ).index();
			}
			else if ( nodeName == 'TD' || nodeName == 'TH' ) {
				var cell = api.cell( node ).index();
		
				return [
					cell.row,
					cell.columnVisible,
					cell.column
				];
			}
			return null;
		};
		
		
		/**
		 * Check to see if a row is 'open' or not.
		 *  @param {node} nTr the table row to check
		 *  @returns {boolean} true if the row is currently open, false otherwise
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable;
		 *
		 *      // 'open' an information row when a row is clicked on
		 *      $('#example tbody tr').click( function () {
		 *        if ( oTable.fnIsOpen(this) ) {
		 *          oTable.fnClose( this );
		 *        } else {
		 *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
		 *        }
		 *      } );
		 *
		 *      oTable = $('#example').dataTable();
		 *    } );
		 */
		this.fnIsOpen = function( nTr )
		{
			return this.api( true ).row( nTr ).child.isShown();
		};
		
		
		/**
		 * This function will place a new row directly after a row which is currently
		 * on display on the page, with the HTML contents that is passed into the
		 * function. This can be used, for example, to ask for confirmation that a
		 * particular record should be deleted.
		 *  @param {node} nTr The table row to 'open'
		 *  @param {string|node|jQuery} mHtml The HTML to put into the row
		 *  @param {string} sClass Class to give the new TD cell
		 *  @returns {node} The row opened. Note that if the table row passed in as the
		 *    first parameter, is not found in the table, this method will silently
		 *    return.
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable;
		 *
		 *      // 'open' an information row when a row is clicked on
		 *      $('#example tbody tr').click( function () {
		 *        if ( oTable.fnIsOpen(this) ) {
		 *          oTable.fnClose( this );
		 *        } else {
		 *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
		 *        }
		 *      } );
		 *
		 *      oTable = $('#example').dataTable();
		 *    } );
		 */
		this.fnOpen = function( nTr, mHtml, sClass )
		{
			return this.api( true )
				.row( nTr )
				.child( mHtml, sClass )
				.show()
				.child()[0];
		};
		
		
		/**
		 * Change the pagination - provides the internal logic for pagination in a simple API
		 * function. With this function you can have a DataTables table go to the next,
		 * previous, first or last pages.
		 *  @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
		 *    or page number to jump to (integer), note that page 0 is the first page.
		 *  @param {bool} [bRedraw=true] Redraw the table or not
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *      oTable.fnPageChange( 'next' );
		 *    } );
		 */
		this.fnPageChange = function ( mAction, bRedraw )
		{
			var api = this.api( true ).page( mAction );
		
			if ( bRedraw === undefined || bRedraw ) {
				api.draw(false);
			}
		};
		
		
		/**
		 * Show a particular column
		 *  @param {int} iCol The column whose display should be changed
		 *  @param {bool} bShow Show (true) or hide (false) the column
		 *  @param {bool} [bRedraw=true] Redraw the table or not
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Hide the second column after initialisation
		 *      oTable.fnSetColumnVis( 1, false );
		 *    } );
		 */
		this.fnSetColumnVis = function ( iCol, bShow, bRedraw )
		{
			var api = this.api( true ).column( iCol ).visible( bShow );
		
			if ( bRedraw === undefined || bRedraw ) {
				api.columns.adjust().draw();
			}
		};
		
		
		/**
		 * Get the settings for a particular table for external manipulation
		 *  @returns {object} DataTables settings object. See
		 *    {@link DataTable.models.oSettings}
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *      var oSettings = oTable.fnSettings();
		 *
		 *      // Show an example parameter from the settings
		 *      alert( oSettings._iDisplayStart );
		 *    } );
		 */
		this.fnSettings = function()
		{
			return _fnSettingsFromNode( this[_ext.iApiIndex] );
		};
		
		
		/**
		 * Sort the table by a particular column
		 *  @param {int} iCol the data index to sort on. Note that this will not match the
		 *    'display index' if you have hidden data entries
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Sort immediately with columns 0 and 1
		 *      oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
		 *    } );
		 */
		this.fnSort = function( aaSort )
		{
			this.api( true ).order( aaSort ).draw();
		};
		
		
		/**
		 * Attach a sort listener to an element for a given column
		 *  @param {node} nNode the element to attach the sort listener to
		 *  @param {int} iColumn the column that a click on this node will sort on
		 *  @param {function} [fnCallback] callback function when sort is run
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *
		 *      // Sort on column 1, when 'sorter' is clicked on
		 *      oTable.fnSortListener( document.getElementById('sorter'), 1 );
		 *    } );
		 */
		this.fnSortListener = function( nNode, iColumn, fnCallback )
		{
			this.api( true ).order.listener( nNode, iColumn, fnCallback );
		};
		
		
		/**
		 * Update a table cell or row - this method will accept either a single value to
		 * update the cell with, an array of values with one element for each column or
		 * an object in the same format as the original data source. The function is
		 * self-referencing in order to make the multi column updates easier.
		 *  @param {object|array|string} mData Data to update the cell/row with
		 *  @param {node|int} mRow TR element you want to update or the aoData index
		 *  @param {int} [iColumn] The column to update, give as null or undefined to
		 *    update a whole row.
		 *  @param {bool} [bRedraw=true] Redraw the table or not
		 *  @param {bool} [bAction=true] Perform pre-draw actions or not
		 *  @returns {int} 0 on success, 1 on error
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *      oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell
		 *      oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row
		 *    } );
		 */
		this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction )
		{
			var api = this.api( true );
		
			if ( iColumn === undefined || iColumn === null ) {
				api.row( mRow ).data( mData );
			}
			else {
				api.cell( mRow, iColumn ).data( mData );
			}
		
			if ( bAction === undefined || bAction ) {
				api.columns.adjust();
			}
		
			if ( bRedraw === undefined || bRedraw ) {
				api.draw();
			}
			return 0;
		};
		
		
		/**
		 * Provide a common method for plug-ins to check the version of DataTables being used, in order
		 * to ensure compatibility.
		 *  @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
		 *    formats "X" and "X.Y" are also acceptable.
		 *  @returns {boolean} true if this version of DataTables is greater or equal to the required
		 *    version, or false if this version of DataTales is not suitable
		 *  @method
		 *  @dtopt API
		 *  @deprecated Since v1.10
		 *
		 *  @example
		 *    $(document).ready(function() {
		 *      var oTable = $('#example').dataTable();
		 *      alert( oTable.fnVersionCheck( '1.9.0' ) );
		 *    } );
		 */
		this.fnVersionCheck = _ext.fnVersionCheck;
		

		var _that = this;
		var emptyInit = options === undefined;
		var len = this.length;

		if ( emptyInit ) {
			options = {};
		}

		this.oApi = this.internal = _ext.internal;

		// Extend with old style plug-in API methods
		for ( var fn in DataTable.ext.internal ) {
			if ( fn ) {
				this[fn] = _fnExternApiFunc(fn);
			}
		}

		this.each(function() {
			// For each initialisation we want to give it a clean initialisation
			// object that can be bashed around
			var o = {};
			var oInit = len > 1 ? // optimisation for single table case
				_fnExtend( o, options, true ) :
				options;

			/*global oInit,_that,emptyInit*/
			var i=0, iLen, j, jLen, k, kLen;
			var sId = this.getAttribute( 'id' );
			var bInitHandedOff = false;
			var defaults = DataTable.defaults;
			var $this = $(this);
			
			
			/* Sanity check */
			if ( this.nodeName.toLowerCase() != 'table' )
			{
				_fnLog( null, 0, 'Non-table node initialisation ('+this.nodeName+')', 2 );
				return;
			}
			
			/* Backwards compatibility for the defaults */
			_fnCompatOpts( defaults );
			_fnCompatCols( defaults.column );
			
			/* Convert the camel-case defaults to Hungarian */
			_fnCamelToHungarian( defaults, defaults, true );
			_fnCamelToHungarian( defaults.column, defaults.column, true );
			
			/* Setting up the initialisation object */
			_fnCamelToHungarian( defaults, $.extend( oInit, $this.data() ) );
			
			
			
			/* Check to see if we are re-initialising a table */
			var allSettings = DataTable.settings;
			for ( i=0, iLen=allSettings.length ; i<iLen ; i++ )
			{
				var s = allSettings[i];
			
				/* Base check on table node */
				if ( s.nTable == this || s.nTHead.parentNode == this || (s.nTFoot && s.nTFoot.parentNode == this) )
				{
					var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve;
					var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy;
			
					if ( emptyInit || bRetrieve )
					{
						return s.oInstance;
					}
					else if ( bDestroy )
					{
						s.oInstance.fnDestroy();
						break;
					}
					else
					{
						_fnLog( s, 0, 'Cannot reinitialise DataTable', 3 );
						return;
					}
				}
			
				/* If the element we are initialising has the same ID as a table which was previously
				 * initialised, but the table nodes don't match (from before) then we destroy the old
				 * instance by simply deleting it. This is under the assumption that the table has been
				 * destroyed by other methods. Anyone using non-id selectors will need to do this manually
				 */
				if ( s.sTableId == this.id )
				{
					allSettings.splice( i, 1 );
					break;
				}
			}
			
			/* Ensure the table has an ID - required for accessibility */
			if ( sId === null || sId === "" )
			{
				sId = "DataTables_Table_"+(DataTable.ext._unique++);
				this.id = sId;
			}
			
			/* Create the settings object for this table and set some of the default parameters */
			var oSettings = $.extend( true, {}, DataTable.models.oSettings, {
				"sDestroyWidth": $this[0].style.width,
				"sInstance":     sId,
				"sTableId":      sId
			} );
			oSettings.nTable = this;
			oSettings.oApi   = _that.internal;
			oSettings.oInit  = oInit;
			
			allSettings.push( oSettings );
			
			// Need to add the instance after the instance after the settings object has been added
			// to the settings array, so we can self reference the table instance if more than one
			oSettings.oInstance = (_that.length===1) ? _that : $this.dataTable();
			
			// Backwards compatibility, before we apply all the defaults
			_fnCompatOpts( oInit );
			
			if ( oInit.oLanguage )
			{
				_fnLanguageCompat( oInit.oLanguage );
			}
			
			// If the length menu is given, but the init display length is not, use the length menu
			if ( oInit.aLengthMenu && ! oInit.iDisplayLength )
			{
				oInit.iDisplayLength = $.isArray( oInit.aLengthMenu[0] ) ?
					oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0];
			}
			
			// Apply the defaults and init options to make a single init object will all
			// options defined from defaults and instance options.
			oInit = _fnExtend( $.extend( true, {}, defaults ), oInit );
			
			
			// Map the initialisation options onto the settings object
			_fnMap( oSettings.oFeatures, oInit, [
				"bPaginate",
				"bLengthChange",
				"bFilter",
				"bSort",
				"bSortMulti",
				"bInfo",
				"bProcessing",
				"bAutoWidth",
				"bSortClasses",
				"bServerSide",
				"bDeferRender"
			] );
			_fnMap( oSettings, oInit, [
				"asStripeClasses",
				"ajax",
				"fnServerData",
				"fnFormatNumber",
				"sServerMethod",
				"aaSorting",
				"aaSortingFixed",
				"aLengthMenu",
				"sPaginationType",
				"sAjaxSource",
				"sAjaxDataProp",
				"iStateDuration",
				"sDom",
				"bSortCellsTop",
				"iTabIndex",
				"fnStateLoadCallback",
				"fnStateSaveCallback",
				"renderer",
				"searchDelay",
				"rowId",
				[ "iCookieDuration", "iStateDuration" ], // backwards compat
				[ "oSearch", "oPreviousSearch" ],
				[ "aoSearchCols", "aoPreSearchCols" ],
				[ "iDisplayLength", "_iDisplayLength" ],
				[ "bJQueryUI", "bJUI" ]
			] );
			_fnMap( oSettings.oScroll, oInit, [
				[ "sScrollX", "sX" ],
				[ "sScrollXInner", "sXInner" ],
				[ "sScrollY", "sY" ],
				[ "bScrollCollapse", "bCollapse" ]
			] );
			_fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" );
			
			/* Callback functions which are array driven */
			_fnCallbackReg( oSettings, 'aoDrawCallback',       oInit.fnDrawCallback,      'user' );
			_fnCallbackReg( oSettings, 'aoServerParams',       oInit.fnServerParams,      'user' );
			_fnCallbackReg( oSettings, 'aoStateSaveParams',    oInit.fnStateSaveParams,   'user' );
			_fnCallbackReg( oSettings, 'aoStateLoadParams',    oInit.fnStateLoadParams,   'user' );
			_fnCallbackReg( oSettings, 'aoStateLoaded',        oInit.fnStateLoaded,       'user' );
			_fnCallbackReg( oSettings, 'aoRowCallback',        oInit.fnRowCallback,       'user' );
			_fnCallbackReg( oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow,        'user' );
			_fnCallbackReg( oSettings, 'aoHeaderCallback',     oInit.fnHeaderCallback,    'user' );
			_fnCallbackReg( oSettings, 'aoFooterCallback',     oInit.fnFooterCallback,    'user' );
			_fnCallbackReg( oSettings, 'aoInitComplete',       oInit.fnInitComplete,      'user' );
			_fnCallbackReg( oSettings, 'aoPreDrawCallback',    oInit.fnPreDrawCallback,   'user' );
			
			oSettings.rowIdFn = _fnGetObjectDataFn( oInit.rowId );
			
			/* Browser support detection */
			_fnBrowserDetect( oSettings );
			
			var oClasses = oSettings.oClasses;
			
			// @todo Remove in 1.11
			if ( oInit.bJQueryUI )
			{
				/* Use the JUI classes object for display. You could clone the oStdClasses object if
				 * you want to have multiple tables with multiple independent classes
				 */
				$.extend( oClasses, DataTable.ext.oJUIClasses, oInit.oClasses );
			
				if ( oInit.sDom === defaults.sDom && defaults.sDom === "lfrtip" )
				{
					/* Set the DOM to use a layout suitable for jQuery UI's theming */
					oSettings.sDom = '<"H"lfr>t<"F"ip>';
				}
			
				if ( ! oSettings.renderer ) {
					oSettings.renderer = 'jqueryui';
				}
				else if ( $.isPlainObject( oSettings.renderer ) && ! oSettings.renderer.header ) {
					oSettings.renderer.header = 'jqueryui';
				}
			}
			else
			{
				$.extend( oClasses, DataTable.ext.classes, oInit.oClasses );
			}
			$this.addClass( oClasses.sTable );
			
			
			if ( oSettings.iInitDisplayStart === undefined )
			{
				/* Display start point, taking into account the save saving */
				oSettings.iInitDisplayStart = oInit.iDisplayStart;
				oSettings._iDisplayStart = oInit.iDisplayStart;
			}
			
			if ( oInit.iDeferLoading !== null )
			{
				oSettings.bDeferLoading = true;
				var tmp = $.isArray( oInit.iDeferLoading );
				oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading;
				oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading;
			}
			
			/* Language definitions */
			var oLanguage = oSettings.oLanguage;
			$.extend( true, oLanguage, oInit.oLanguage );
			
			if ( oLanguage.sUrl )
			{
				/* Get the language definitions from a file - because this Ajax call makes the language
				 * get async to the remainder of this function we use bInitHandedOff to indicate that
				 * _fnInitialise will be fired by the returned Ajax handler, rather than the constructor
				 */
				$.ajax( {
					dataType: 'json',
					url: oLanguage.sUrl,
					success: function ( json ) {
						_fnLanguageCompat( json );
						_fnCamelToHungarian( defaults.oLanguage, json );
						$.extend( true, oLanguage, json );
						_fnInitialise( oSettings );
					},
					error: function () {
						// Error occurred loading language file, continue on as best we can
						_fnInitialise( oSettings );
					}
				} );
				bInitHandedOff = true;
			}
			
			/*
			 * Stripes
			 */
			if ( oInit.asStripeClasses === null )
			{
				oSettings.asStripeClasses =[
					oClasses.sStripeOdd,
					oClasses.sStripeEven
				];
			}
			
			/* Remove row stripe classes if they are already on the table row */
			var stripeClasses = oSettings.asStripeClasses;
			var rowOne = $this.children('tbody').find('tr').eq(0);
			if ( $.inArray( true, $.map( stripeClasses, function(el, i) {
				return rowOne.hasClass(el);
			} ) ) !== -1 ) {
				$('tbody tr', this).removeClass( stripeClasses.join(' ') );
				oSettings.asDestroyStripes = stripeClasses.slice();
			}
			
			/*
			 * Columns
			 * See if we should load columns automatically or use defined ones
			 */
			var anThs = [];
			var aoColumnsInit;
			var nThead = this.getElementsByTagName('thead');
			if ( nThead.length !== 0 )
			{
				_fnDetectHeader( oSettings.aoHeader, nThead[0] );
				anThs = _fnGetUniqueThs( oSettings );
			}
			
			/* If not given a column array, generate one with nulls */
			if ( oInit.aoColumns === null )
			{
				aoColumnsInit = [];
				for ( i=0, iLen=anThs.length ; i<iLen ; i++ )
				{
					aoColumnsInit.push( null );
				}
			}
			else
			{
				aoColumnsInit = oInit.aoColumns;
			}
			
			/* Add the columns */
			for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ )
			{
				_fnAddColumn( oSettings, anThs ? anThs[i] : null );
			}
			
			/* Apply the column definitions */
			_fnApplyColumnDefs( oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) {
				_fnColumnOptions( oSettings, iCol, oDef );
			} );
			
			/* HTML5 attribute detection - build an mData object automatically if the
			 * attributes are found
			 */
			if ( rowOne.length ) {
				var a = function ( cell, name ) {
					return cell.getAttribute( 'data-'+name ) !== null ? name : null;
				};
			
				$( rowOne[0] ).children('th, td').each( function (i, cell) {
					var col = oSettings.aoColumns[i];
			
					if ( col.mData === i ) {
						var sort = a( cell, 'sort' ) || a( cell, 'order' );
						var filter = a( cell, 'filter' ) || a( cell, 'search' );
			
						if ( sort !== null || filter !== null ) {
							col.mData = {
								_:      i+'.display',
								sort:   sort !== null   ? i+'.@data-'+sort   : undefined,
								type:   sort !== null   ? i+'.@data-'+sort   : undefined,
								filter: filter !== null ? i+'.@data-'+filter : undefined
							};
			
							_fnColumnOptions( oSettings, i );
						}
					}
				} );
			}
			
			var features = oSettings.oFeatures;
			var loadedInit = function () {
				/*
				 * Sorting
				 * @todo For modularisation (1.11) this needs to do into a sort start up handler
				 */
			
				// If aaSorting is not defined, then we use the first indicator in asSorting
				// in case that has been altered, so the default sort reflects that option
				if ( oInit.aaSorting === undefined ) {
					var sorting = oSettings.aaSorting;
					for ( i=0, iLen=sorting.length ; i<iLen ; i++ ) {
						sorting[i][1] = oSettings.aoColumns[ i ].asSorting[0];
					}
				}
			
				/* Do a first pass on the sorting classes (allows any size changes to be taken into
				 * account, and also will apply sorting disabled classes if disabled
				 */
				_fnSortingClasses( oSettings );
			
				if ( features.bSort ) {
					_fnCallbackReg( oSettings, 'aoDrawCallback', function () {
						if ( oSettings.bSorted ) {
							var aSort = _fnSortFlatten( oSettings );
							var sortedColumns = {};
			
							$.each( aSort, function (i, val) {
								sortedColumns[ val.src ] = val.dir;
							} );
			
							_fnCallbackFire( oSettings, null, 'order', [oSettings, aSort, sortedColumns] );
							_fnSortAria( oSettings );
						}
					} );
				}
			
				_fnCallbackReg( oSettings, 'aoDrawCallback', function () {
					if ( oSettings.bSorted || _fnDataSource( oSettings ) === 'ssp' || features.bDeferRender ) {
						_fnSortingClasses( oSettings );
					}
				}, 'sc' );
			
			
				/*
				 * Final init
				 * Cache the header, body and footer as required, creating them if needed
				 */
			
				// Work around for Webkit bug 83867 - store the caption-side before removing from doc
				var captions = $this.children('caption').each( function () {
					this._captionSide = $(this).css('caption-side');
				} );
			
				var thead = $this.children('thead');
				if ( thead.length === 0 ) {
					thead = $('<thead/>').appendTo($this);
				}
				oSettings.nTHead = thead[0];
			
				var tbody = $this.children('tbody');
				if ( tbody.length === 0 ) {
					tbody = $('<tbody/>').appendTo($this);
				}
				oSettings.nTBody = tbody[0];
			
				var tfoot = $this.children('tfoot');
				if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") ) {
					// If we are a scrolling table, and no footer has been given, then we need to create
					// a tfoot element for the caption element to be appended to
					tfoot = $('<tfoot/>').appendTo($this);
				}
			
				if ( tfoot.length === 0 || tfoot.children().length === 0 ) {
					$this.addClass( oClasses.sNoFooter );
				}
				else if ( tfoot.length > 0 ) {
					oSettings.nTFoot = tfoot[0];
					_fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot );
				}
			
				/* Check if there is data passing into the constructor */
				if ( oInit.aaData ) {
					for ( i=0 ; i<oInit.aaData.length ; i++ ) {
						_fnAddData( oSettings, oInit.aaData[ i ] );
					}
				}
				else if ( oSettings.bDeferLoading || _fnDataSource( oSettings ) == 'dom' ) {
					/* Grab the data from the page - only do this when deferred loading or no Ajax
					 * source since there is no point in reading the DOM data if we are then going
					 * to replace it with Ajax data
					 */
					_fnAddTr( oSettings, $(oSettings.nTBody).children('tr') );
				}
			
				/* Copy the data index array */
				oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
			
				/* Initialisation complete - table can be drawn */
				oSettings.bInitialised = true;
			
				/* Check if we need to initialise the table (it might not have been handed off to the
				 * language processor)
				 */
				if ( bInitHandedOff === false ) {
					_fnInitialise( oSettings );
				}
			};
			
			/* Must be done after everything which can be overridden by the state saving! */
			if ( oInit.bStateSave )
			{
				features.bStateSave = true;
				_fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' );
				_fnLoadState( oSettings, oInit, loadedInit );
			}
			else {
				loadedInit();
			}
			
		} );
		_that = null;
		return this;
	};

	
	/*
	 * It is useful to have variables which are scoped locally so only the
	 * DataTables functions can access them and they don't leak into global space.
	 * At the same time these functions are often useful over multiple files in the
	 * core and API, so we list, or at least document, all variables which are used
	 * by DataTables as private variables here. This also ensures that there is no
	 * clashing of variable names and that they can easily referenced for reuse.
	 */
	
	
	// Defined else where
	//  _selector_run
	//  _selector_opts
	//  _selector_first
	//  _selector_row_indexes
	
	var _ext; // DataTable.ext
	var _Api; // DataTable.Api
	var _api_register; // DataTable.Api.register
	var _api_registerPlural; // DataTable.Api.registerPlural
	
	var _re_dic = {};
	var _re_new_lines = /[\r\n]/g;
	var _re_html = /<.*?>/g;
	
	// This is not strict ISO8601 - Date.parse() is quite lax, although
	// implementations differ between browsers.
	var _re_date = /^\d{2,4}[\.\/\-]\d{1,2}[\.\/\-]\d{1,2}([T ]{1}\d{1,2}[:\.]\d{2}([\.:]\d{2})?)?$/;
	
	// Escape regular expression special characters
	var _re_escape_regex = new RegExp( '(\\' + [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ].join('|\\') + ')', 'g' );
	
	// http://en.wikipedia.org/wiki/Foreign_exchange_market
	// - \u20BD - Russian ruble.
	// - \u20a9 - South Korean Won
	// - \u20BA - Turkish Lira
	// - \u20B9 - Indian Rupee
	// - R - Brazil (R$) and South Africa
	// - fr - Swiss Franc
	// - kr - Swedish krona, Norwegian krone and Danish krone
	// - \u2009 is thin space and \u202F is narrow no-break space, both used in many
	//   standards as thousands separators.
	var _re_formatted_numeric = /[',$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi;
	
	
	var _empty = function ( d ) {
		return !d || d === true || d === '-' ? true : false;
	};
	
	
	var _intVal = function ( s ) {
		var integer = parseInt( s, 10 );
		return !isNaN(integer) && isFinite(s) ? integer : null;
	};
	
	// Convert from a formatted number with characters other than `.` as the
	// decimal place, to a Javascript number
	var _numToDecimal = function ( num, decimalPoint ) {
		// Cache created regular expressions for speed as this function is called often
		if ( ! _re_dic[ decimalPoint ] ) {
			_re_dic[ decimalPoint ] = new RegExp( _fnEscapeRegex( decimalPoint ), 'g' );
		}
		return typeof num === 'string' && decimalPoint !== '.' ?
			num.replace( /\./g, '' ).replace( _re_dic[ decimalPoint ], '.' ) :
			num;
	};
	
	
	var _isNumber = function ( d, decimalPoint, formatted ) {
		var strType = typeof d === 'string';
	
		// If empty return immediately so there must be a number if it is a
		// formatted string (this stops the string "k", or "kr", etc being detected
		// as a formatted number for currency
		if ( _empty( d ) ) {
			return true;
		}
	
		if ( decimalPoint && strType ) {
			d = _numToDecimal( d, decimalPoint );
		}
	
		if ( formatted && strType ) {
			d = d.replace( _re_formatted_numeric, '' );
		}
	
		return !isNaN( parseFloat(d) ) && isFinite( d );
	};
	
	
	// A string without HTML in it can be considered to be HTML still
	var _isHtml = function ( d ) {
		return _empty( d ) || typeof d === 'string';
	};
	
	
	var _htmlNumeric = function ( d, decimalPoint, formatted ) {
		if ( _empty( d ) ) {
			return true;
		}
	
		var html = _isHtml( d );
		return ! html ?
			null :
			_isNumber( _stripHtml( d ), decimalPoint, formatted ) ?
				true :
				null;
	};
	
	
	var _pluck = function ( a, prop, prop2 ) {
		var out = [];
		var i=0, ien=a.length;
	
		// Could have the test in the loop for slightly smaller code, but speed
		// is essential here
		if ( prop2 !== undefined ) {
			for ( ; i<ien ; i++ ) {
				if ( a[i] && a[i][ prop ] ) {
					out.push( a[i][ prop ][ prop2 ] );
				}
			}
		}
		else {
			for ( ; i<ien ; i++ ) {
				if ( a[i] ) {
					out.push( a[i][ prop ] );
				}
			}
		}
	
		return out;
	};
	
	
	// Basically the same as _pluck, but rather than looping over `a` we use `order`
	// as the indexes to pick from `a`
	var _pluck_order = function ( a, order, prop, prop2 )
	{
		var out = [];
		var i=0, ien=order.length;
	
		// Could have the test in the loop for slightly smaller code, but speed
		// is essential here
		if ( prop2 !== undefined ) {
			for ( ; i<ien ; i++ ) {
				if ( a[ order[i] ][ prop ] ) {
					out.push( a[ order[i] ][ prop ][ prop2 ] );
				}
			}
		}
		else {
			for ( ; i<ien ; i++ ) {
				out.push( a[ order[i] ][ prop ] );
			}
		}
	
		return out;
	};
	
	
	var _range = function ( len, start )
	{
		var out = [];
		var end;
	
		if ( start === undefined ) {
			start = 0;
			end = len;
		}
		else {
			end = start;
			start = len;
		}
	
		for ( var i=start ; i<end ; i++ ) {
			out.push( i );
		}
	
		return out;
	};
	
	
	var _removeEmpty = function ( a )
	{
		var out = [];
	
		for ( var i=0, ien=a.length ; i<ien ; i++ ) {
			if ( a[i] ) { // careful - will remove all falsy values!
				out.push( a[i] );
			}
		}
	
		return out;
	};
	
	
	var _stripHtml = function ( d ) {
		return d.replace( _re_html, '' );
	};
	
	
	/**
	 * Determine if all values in the array are unique. This means we can short
	 * cut the _unique method at the cost of a single loop. A sorted array is used
	 * to easily check the values.
	 *
	 * @param  {array} src Source array
	 * @return {boolean} true if all unique, false otherwise
	 * @ignore
	 */
	var _areAllUnique = function ( src ) {
		if ( src.length < 2 ) {
			return true;
		}
	
		var sorted = src.slice().sort();
		var last = sorted[0];
	
		for ( var i=1, ien=sorted.length ; i<ien ; i++ ) {
			if ( sorted[i] === last ) {
				return false;
			}
	
			last = sorted[i];
		}
	
		return true;
	};
	
	
	/**
	 * Find the unique elements in a source array.
	 *
	 * @param  {array} src Source array
	 * @return {array} Array of unique items
	 * @ignore
	 */
	var _unique = function ( src )
	{
		if ( _areAllUnique( src ) ) {
			return src.slice();
		}
	
		// A faster unique method is to use object keys to identify used values,
		// but this doesn't work with arrays or objects, which we must also
		// consider. See jsperf.com/compare-array-unique-versions/4 for more
		// information.
		var
			out = [],
			val,
			i, ien=src.length,
			j, k=0;
	
		again: for ( i=0 ; i<ien ; i++ ) {
			val = src[i];
	
			for ( j=0 ; j<k ; j++ ) {
				if ( out[j] === val ) {
					continue again;
				}
			}
	
			out.push( val );
			k++;
		}
	
		return out;
	};
	
	
	/**
	 * DataTables utility methods
	 * 
	 * This namespace provides helper methods that DataTables uses internally to
	 * create a DataTable, but which are not exclusively used only for DataTables.
	 * These methods can be used by extension authors to save the duplication of
	 * code.
	 *
	 *  @namespace
	 */
	DataTable.util = {
		/**
		 * Throttle the calls to a function. Arguments and context are maintained
		 * for the throttled function.
		 *
		 * @param {function} fn Function to be called
		 * @param {integer} freq Call frequency in mS
		 * @return {function} Wrapped function
		 */
		throttle: function ( fn, freq ) {
			var
				frequency = freq !== undefined ? freq : 200,
				last,
				timer;
	
			return function () {
				var
					that = this,
					now  = +new Date(),
					args = arguments;
	
				if ( last && now < last + frequency ) {
					clearTimeout( timer );
	
					timer = setTimeout( function () {
						last = undefined;
						fn.apply( that, args );
					}, frequency );
				}
				else {
					last = now;
					fn.apply( that, args );
				}
			};
		},
	
	
		/**
		 * Escape a string such that it can be used in a regular expression
		 *
		 *  @param {string} val string to escape
		 *  @returns {string} escaped string
		 */
		escapeRegex: function ( val ) {
			return val.replace( _re_escape_regex, '\\$1' );
		}
	};
	
	
	
	/**
	 * Create a mapping object that allows camel case parameters to be looked up
	 * for their Hungarian counterparts. The mapping is stored in a private
	 * parameter called `_hungarianMap` which can be accessed on the source object.
	 *  @param {object} o
	 *  @memberof DataTable#oApi
	 */
	function _fnHungarianMap ( o )
	{
		var
			hungarian = 'a aa ai ao as b fn i m o s ',
			match,
			newKey,
			map = {};
	
		$.each( o, function (key, val) {
			match = key.match(/^([^A-Z]+?)([A-Z])/);
	
			if ( match && hungarian.indexOf(match[1]+' ') !== -1 )
			{
				newKey = key.replace( match[0], match[2].toLowerCase() );
				map[ newKey ] = key;
	
				if ( match[1] === 'o' )
				{
					_fnHungarianMap( o[key] );
				}
			}
		} );
	
		o._hungarianMap = map;
	}
	
	
	/**
	 * Convert from camel case parameters to Hungarian, based on a Hungarian map
	 * created by _fnHungarianMap.
	 *  @param {object} src The model object which holds all parameters that can be
	 *    mapped.
	 *  @param {object} user The object to convert from camel case to Hungarian.
	 *  @param {boolean} force When set to `true`, properties which already have a
	 *    Hungarian value in the `user` object will be overwritten. Otherwise they
	 *    won't be.
	 *  @memberof DataTable#oApi
	 */
	function _fnCamelToHungarian ( src, user, force )
	{
		if ( ! src._hungarianMap ) {
			_fnHungarianMap( src );
		}
	
		var hungarianKey;
	
		$.each( user, function (key, val) {
			hungarianKey = src._hungarianMap[ key ];
	
			if ( hungarianKey !== undefined && (force || user[hungarianKey] === undefined) )
			{
				// For objects, we need to buzz down into the object to copy parameters
				if ( hungarianKey.charAt(0) === 'o' )
				{
					// Copy the camelCase options over to the hungarian
					if ( ! user[ hungarianKey ] ) {
						user[ hungarianKey ] = {};
					}
					$.extend( true, user[hungarianKey], user[key] );
	
					_fnCamelToHungarian( src[hungarianKey], user[hungarianKey], force );
				}
				else {
					user[hungarianKey] = user[ key ];
				}
			}
		} );
	}
	
	
	/**
	 * Language compatibility - when certain options are given, and others aren't, we
	 * need to duplicate the values over, in order to provide backwards compatibility
	 * with older language files.
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnLanguageCompat( lang )
	{
		var defaults = DataTable.defaults.oLanguage;
		var zeroRecords = lang.sZeroRecords;
	
		/* Backwards compatibility - if there is no sEmptyTable given, then use the same as
		 * sZeroRecords - assuming that is given.
		 */
		if ( ! lang.sEmptyTable && zeroRecords &&
			defaults.sEmptyTable === "No data available in table" )
		{
			_fnMap( lang, lang, 'sZeroRecords', 'sEmptyTable' );
		}
	
		/* Likewise with loading records */
		if ( ! lang.sLoadingRecords && zeroRecords &&
			defaults.sLoadingRecords === "Loading..." )
		{
			_fnMap( lang, lang, 'sZeroRecords', 'sLoadingRecords' );
		}
	
		// Old parameter name of the thousands separator mapped onto the new
		if ( lang.sInfoThousands ) {
			lang.sThousands = lang.sInfoThousands;
		}
	
		var decimal = lang.sDecimal;
		if ( decimal ) {
			_addNumericSort( decimal );
		}
	}
	
	
	/**
	 * Map one parameter onto another
	 *  @param {object} o Object to map
	 *  @param {*} knew The new parameter name
	 *  @param {*} old The old parameter name
	 */
	var _fnCompatMap = function ( o, knew, old ) {
		if ( o[ knew ] !== undefined ) {
			o[ old ] = o[ knew ];
		}
	};
	
	
	/**
	 * Provide backwards compatibility for the main DT options. Note that the new
	 * options are mapped onto the old parameters, so this is an external interface
	 * change only.
	 *  @param {object} init Object to map
	 */
	function _fnCompatOpts ( init )
	{
		_fnCompatMap( init, 'ordering',      'bSort' );
		_fnCompatMap( init, 'orderMulti',    'bSortMulti' );
		_fnCompatMap( init, 'orderClasses',  'bSortClasses' );
		_fnCompatMap( init, 'orderCellsTop', 'bSortCellsTop' );
		_fnCompatMap( init, 'order',         'aaSorting' );
		_fnCompatMap( init, 'orderFixed',    'aaSortingFixed' );
		_fnCompatMap( init, 'paging',        'bPaginate' );
		_fnCompatMap( init, 'pagingType',    'sPaginationType' );
		_fnCompatMap( init, 'pageLength',    'iDisplayLength' );
		_fnCompatMap( init, 'searching',     'bFilter' );
	
		// Boolean initialisation of x-scrolling
		if ( typeof init.sScrollX === 'boolean' ) {
			init.sScrollX = init.sScrollX ? '100%' : '';
		}
		if ( typeof init.scrollX === 'boolean' ) {
			init.scrollX = init.scrollX ? '100%' : '';
		}
	
		// Column search objects are in an array, so it needs to be converted
		// element by element
		var searchCols = init.aoSearchCols;
	
		if ( searchCols ) {
			for ( var i=0, ien=searchCols.length ; i<ien ; i++ ) {
				if ( searchCols[i] ) {
					_fnCamelToHungarian( DataTable.models.oSearch, searchCols[i] );
				}
			}
		}
	}
	
	
	/**
	 * Provide backwards compatibility for column options. Note that the new options
	 * are mapped onto the old parameters, so this is an external interface change
	 * only.
	 *  @param {object} init Object to map
	 */
	function _fnCompatCols ( init )
	{
		_fnCompatMap( init, 'orderable',     'bSortable' );
		_fnCompatMap( init, 'orderData',     'aDataSort' );
		_fnCompatMap( init, 'orderSequence', 'asSorting' );
		_fnCompatMap( init, 'orderDataType', 'sortDataType' );
	
		// orderData can be given as an integer
		var dataSort = init.aDataSort;
		if ( typeof dataSort === 'number' && ! $.isArray( dataSort ) ) {
			init.aDataSort = [ dataSort ];
		}
	}
	
	
	/**
	 * Browser feature detection for capabilities, quirks
	 *  @param {object} settings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnBrowserDetect( settings )
	{
		// We don't need to do this every time DataTables is constructed, the values
		// calculated are specific to the browser and OS configuration which we
		// don't expect to change between initialisations
		if ( ! DataTable.__browser ) {
			var browser = {};
			DataTable.__browser = browser;
	
			// Scrolling feature / quirks detection
			var n = $('<div/>')
				.css( {
					position: 'fixed',
					top: 0,
					left: $(window).scrollLeft()*-1, // allow for scrolling
					height: 1,
					width: 1,
					overflow: 'hidden'
				} )
				.append(
					$('<div/>')
						.css( {
							position: 'absolute',
							top: 1,
							left: 1,
							width: 100,
							overflow: 'scroll'
						} )
						.append(
							$('<div/>')
								.css( {
									width: '100%',
									height: 10
								} )
						)
				)
				.appendTo( 'body' );
	
			var outer = n.children();
			var inner = outer.children();
	
			// Numbers below, in order, are:
			// inner.offsetWidth, inner.clientWidth, outer.offsetWidth, outer.clientWidth
			//
			// IE6 XP:                           100 100 100  83
			// IE7 Vista:                        100 100 100  83
			// IE 8+ Windows:                     83  83 100  83
			// Evergreen Windows:                 83  83 100  83
			// Evergreen Mac with scrollbars:     85  85 100  85
			// Evergreen Mac without scrollbars: 100 100 100 100
	
			// Get scrollbar width
			browser.barWidth = outer[0].offsetWidth - outer[0].clientWidth;
	
			// IE6/7 will oversize a width 100% element inside a scrolling element, to
			// include the width of the scrollbar, while other browsers ensure the inner
			// element is contained without forcing scrolling
			browser.bScrollOversize = inner[0].offsetWidth === 100 && outer[0].clientWidth !== 100;
	
			// In rtl text layout, some browsers (most, but not all) will place the
			// scrollbar on the left, rather than the right.
			browser.bScrollbarLeft = Math.round( inner.offset().left ) !== 1;
	
			// IE8- don't provide height and width for getBoundingClientRect
			browser.bBounding = n[0].getBoundingClientRect().width ? true : false;
	
			n.remove();
		}
	
		$.extend( settings.oBrowser, DataTable.__browser );
		settings.oScroll.iBarWidth = DataTable.__browser.barWidth;
	}
	
	
	/**
	 * Array.prototype reduce[Right] method, used for browsers which don't support
	 * JS 1.6. Done this way to reduce code size, since we iterate either way
	 *  @param {object} settings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnReduce ( that, fn, init, start, end, inc )
	{
		var
			i = start,
			value,
			isSet = false;
	
		if ( init !== undefined ) {
			value = init;
			isSet = true;
		}
	
		while ( i !== end ) {
			if ( ! that.hasOwnProperty(i) ) {
				continue;
			}
	
			value = isSet ?
				fn( value, that[i], i, that ) :
				that[i];
	
			isSet = true;
			i += inc;
		}
	
		return value;
	}
	
	/**
	 * Add a column to the list used for the table with default values
	 *  @param {object} oSettings dataTables settings object
	 *  @param {node} nTh The th element for this column
	 *  @memberof DataTable#oApi
	 */
	function _fnAddColumn( oSettings, nTh )
	{
		// Add column to aoColumns array
		var oDefaults = DataTable.defaults.column;
		var iCol = oSettings.aoColumns.length;
		var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, {
			"nTh": nTh ? nTh : document.createElement('th'),
			"sTitle":    oDefaults.sTitle    ? oDefaults.sTitle    : nTh ? nTh.innerHTML : '',
			"aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
			"mData": oDefaults.mData ? oDefaults.mData : iCol,
			idx: iCol
		} );
		oSettings.aoColumns.push( oCol );
	
		// Add search object for column specific search. Note that the `searchCols[ iCol ]`
		// passed into extend can be undefined. This allows the user to give a default
		// with only some of the parameters defined, and also not give a default
		var searchCols = oSettings.aoPreSearchCols;
		searchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch, searchCols[ iCol ] );
	
		// Use the default column options function to initialise classes etc
		_fnColumnOptions( oSettings, iCol, $(nTh).data() );
	}
	
	
	/**
	 * Apply options for a column
	 *  @param {object} oSettings dataTables settings object
	 *  @param {int} iCol column index to consider
	 *  @param {object} oOptions object with sType, bVisible and bSearchable etc
	 *  @memberof DataTable#oApi
	 */
	function _fnColumnOptions( oSettings, iCol, oOptions )
	{
		var oCol = oSettings.aoColumns[ iCol ];
		var oClasses = oSettings.oClasses;
		var th = $(oCol.nTh);
	
		// Try to get width information from the DOM. We can't get it from CSS
		// as we'd need to parse the CSS stylesheet. `width` option can override
		if ( ! oCol.sWidthOrig ) {
			// Width attribute
			oCol.sWidthOrig = th.attr('width') || null;
	
			// Style attribute
			var t = (th.attr('style') || '').match(/width:\s*(\d+[pxem%]+)/);
			if ( t ) {
				oCol.sWidthOrig = t[1];
			}
		}
	
		/* User specified column options */
		if ( oOptions !== undefined && oOptions !== null )
		{
			// Backwards compatibility
			_fnCompatCols( oOptions );
	
			// Map camel case parameters to their Hungarian counterparts
			_fnCamelToHungarian( DataTable.defaults.column, oOptions );
	
			/* Backwards compatibility for mDataProp */
			if ( oOptions.mDataProp !== undefined && !oOptions.mData )
			{
				oOptions.mData = oOptions.mDataProp;
			}
	
			if ( oOptions.sType )
			{
				oCol._sManualType = oOptions.sType;
			}
	
			// `class` is a reserved word in Javascript, so we need to provide
			// the ability to use a valid name for the camel case input
			if ( oOptions.className && ! oOptions.sClass )
			{
				oOptions.sClass = oOptions.className;
			}
	
			$.extend( oCol, oOptions );
			_fnMap( oCol, oOptions, "sWidth", "sWidthOrig" );
	
			/* iDataSort to be applied (backwards compatibility), but aDataSort will take
			 * priority if defined
			 */
			if ( oOptions.iDataSort !== undefined )
			{
				oCol.aDataSort = [ oOptions.iDataSort ];
			}
			_fnMap( oCol, oOptions, "aDataSort" );
		}
	
		/* Cache the data get and set functions for speed */
		var mDataSrc = oCol.mData;
		var mData = _fnGetObjectDataFn( mDataSrc );
		var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null;
	
		var attrTest = function( src ) {
			return typeof src === 'string' && src.indexOf('@') !== -1;
		};
		oCol._bAttrSrc = $.isPlainObject( mDataSrc ) && (
			attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter)
		);
		oCol._setter = null;
	
		oCol.fnGetData = function (rowData, type, meta) {
			var innerData = mData( rowData, type, undefined, meta );
	
			return mRender && type ?
				mRender( innerData, type, rowData, meta ) :
				innerData;
		};
		oCol.fnSetData = function ( rowData, val, meta ) {
			return _fnSetObjectDataFn( mDataSrc )( rowData, val, meta );
		};
	
		// Indicate if DataTables should read DOM data as an object or array
		// Used in _fnGetRowElements
		if ( typeof mDataSrc !== 'number' ) {
			oSettings._rowReadObject = true;
		}
	
		/* Feature sorting overrides column specific when off */
		if ( !oSettings.oFeatures.bSort )
		{
			oCol.bSortable = false;
			th.addClass( oClasses.sSortableNone ); // Have to add class here as order event isn't called
		}
	
		/* Check that the class assignment is correct for sorting */
		var bAsc = $.inArray('asc', oCol.asSorting) !== -1;
		var bDesc = $.inArray('desc', oCol.asSorting) !== -1;
		if ( !oCol.bSortable || (!bAsc && !bDesc) )
		{
			oCol.sSortingClass = oClasses.sSortableNone;
			oCol.sSortingClassJUI = "";
		}
		else if ( bAsc && !bDesc )
		{
			oCol.sSortingClass = oClasses.sSortableAsc;
			oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed;
		}
		else if ( !bAsc && bDesc )
		{
			oCol.sSortingClass = oClasses.sSortableDesc;
			oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed;
		}
		else
		{
			oCol.sSortingClass = oClasses.sSortable;
			oCol.sSortingClassJUI = oClasses.sSortJUI;
		}
	}
	
	
	/**
	 * Adjust the table column widths for new data. Note: you would probably want to
	 * do a redraw after calling this function!
	 *  @param {object} settings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnAdjustColumnSizing ( settings )
	{
		/* Not interested in doing column width calculation if auto-width is disabled */
		if ( settings.oFeatures.bAutoWidth !== false )
		{
			var columns = settings.aoColumns;
	
			_fnCalculateColumnWidths( settings );
			for ( var i=0 , iLen=columns.length ; i<iLen ; i++ )
			{
				columns[i].nTh.style.width = columns[i].sWidth;
			}
		}
	
		var scroll = settings.oScroll;
		if ( scroll.sY !== '' || scroll.sX !== '')
		{
			_fnScrollDraw( settings );
		}
	
		_fnCallbackFire( settings, null, 'column-sizing', [settings] );
	}
	
	
	/**
	 * Covert the index of a visible column to the index in the data array (take account
	 * of hidden columns)
	 *  @param {object} oSettings dataTables settings object
	 *  @param {int} iMatch Visible column index to lookup
	 *  @returns {int} i the data index
	 *  @memberof DataTable#oApi
	 */
	function _fnVisibleToColumnIndex( oSettings, iMatch )
	{
		var aiVis = _fnGetColumns( oSettings, 'bVisible' );
	
		return typeof aiVis[iMatch] === 'number' ?
			aiVis[iMatch] :
			null;
	}
	
	
	/**
	 * Covert the index of an index in the data array and convert it to the visible
	 *   column index (take account of hidden columns)
	 *  @param {int} iMatch Column index to lookup
	 *  @param {object} oSettings dataTables settings object
	 *  @returns {int} i the data index
	 *  @memberof DataTable#oApi
	 */
	function _fnColumnIndexToVisible( oSettings, iMatch )
	{
		var aiVis = _fnGetColumns( oSettings, 'bVisible' );
		var iPos = $.inArray( iMatch, aiVis );
	
		return iPos !== -1 ? iPos : null;
	}
	
	
	/**
	 * Get the number of visible columns
	 *  @param {object} oSettings dataTables settings object
	 *  @returns {int} i the number of visible columns
	 *  @memberof DataTable#oApi
	 */
	function _fnVisbleColumns( oSettings )
	{
		var vis = 0;
	
		// No reduce in IE8, use a loop for now
		$.each( oSettings.aoColumns, function ( i, col ) {
			if ( col.bVisible && $(col.nTh).css('display') !== 'none' ) {
				vis++;
			}
		} );
	
		return vis;
	}
	
	
	/**
	 * Get an array of column indexes that match a given property
	 *  @param {object} oSettings dataTables settings object
	 *  @param {string} sParam Parameter in aoColumns to look for - typically
	 *    bVisible or bSearchable
	 *  @returns {array} Array of indexes with matched properties
	 *  @memberof DataTable#oApi
	 */
	function _fnGetColumns( oSettings, sParam )
	{
		var a = [];
	
		$.map( oSettings.aoColumns, function(val, i) {
			if ( val[sParam] ) {
				a.push( i );
			}
		} );
	
		return a;
	}
	
	
	/**
	 * Calculate the 'type' of a column
	 *  @param {object} settings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnColumnTypes ( settings )
	{
		var columns = settings.aoColumns;
		var data = settings.aoData;
		var types = DataTable.ext.type.detect;
		var i, ien, j, jen, k, ken;
		var col, cell, detectedType, cache;
	
		// For each column, spin over the 
		for ( i=0, ien=columns.length ; i<ien ; i++ ) {
			col = columns[i];
			cache = [];
	
			if ( ! col.sType && col._sManualType ) {
				col.sType = col._sManualType;
			}
			else if ( ! col.sType ) {
				for ( j=0, jen=types.length ; j<jen ; j++ ) {
					for ( k=0, ken=data.length ; k<ken ; k++ ) {
						// Use a cache array so we only need to get the type data
						// from the formatter once (when using multiple detectors)
						if ( cache[k] === undefined ) {
							cache[k] = _fnGetCellData( settings, k, i, 'type' );
						}
	
						detectedType = types[j]( cache[k], settings );
	
						// If null, then this type can't apply to this column, so
						// rather than testing all cells, break out. There is an
						// exception for the last type which is `html`. We need to
						// scan all rows since it is possible to mix string and HTML
						// types
						if ( ! detectedType && j !== types.length-1 ) {
							break;
						}
	
						// Only a single match is needed for html type since it is
						// bottom of the pile and very similar to string
						if ( detectedType === 'html' ) {
							break;
						}
					}
	
					// Type is valid for all data points in the column - use this
					// type
					if ( detectedType ) {
						col.sType = detectedType;
						break;
					}
				}
	
				// Fall back - if no type was detected, always use string
				if ( ! col.sType ) {
					col.sType = 'string';
				}
			}
		}
	}
	
	
	/**
	 * Take the column definitions and static columns arrays and calculate how
	 * they relate to column indexes. The callback function will then apply the
	 * definition found for a column to a suitable configuration object.
	 *  @param {object} oSettings dataTables settings object
	 *  @param {array} aoColDefs The aoColumnDefs array that is to be applied
	 *  @param {array} aoCols The aoColumns array that defines columns individually
	 *  @param {function} fn Callback function - takes two parameters, the calculated
	 *    column index and the definition for that column.
	 *  @memberof DataTable#oApi
	 */
	function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn )
	{
		var i, iLen, j, jLen, k, kLen, def;
		var columns = oSettings.aoColumns;
	
		// Column definitions with aTargets
		if ( aoColDefs )
		{
			/* Loop over the definitions array - loop in reverse so first instance has priority */
			for ( i=aoColDefs.length-1 ; i>=0 ; i-- )
			{
				def = aoColDefs[i];
	
				/* Each definition can target multiple columns, as it is an array */
				var aTargets = def.targets !== undefined ?
					def.targets :
					def.aTargets;
	
				if ( ! $.isArray( aTargets ) )
				{
					aTargets = [ aTargets ];
				}
	
				for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
				{
					if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 )
					{
						/* Add columns that we don't yet know about */
						while( columns.length <= aTargets[j] )
						{
							_fnAddColumn( oSettings );
						}
	
						/* Integer, basic index */
						fn( aTargets[j], def );
					}
					else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 )
					{
						/* Negative integer, right to left column counting */
						fn( columns.length+aTargets[j], def );
					}
					else if ( typeof aTargets[j] === 'string' )
					{
						/* Class name matching on TH element */
						for ( k=0, kLen=columns.length ; k<kLen ; k++ )
						{
							if ( aTargets[j] == "_all" ||
							     $(columns[k].nTh).hasClass( aTargets[j] ) )
							{
								fn( k, def );
							}
						}
					}
				}
			}
		}
	
		// Statically defined columns array
		if ( aoCols )
		{
			for ( i=0, iLen=aoCols.length ; i<iLen ; i++ )
			{
				fn( i, aoCols[i] );
			}
		}
	}
	
	/**
	 * Add a data array to the table, creating DOM node etc. This is the parallel to
	 * _fnGatherData, but for adding rows from a Javascript source, rather than a
	 * DOM source.
	 *  @param {object} oSettings dataTables settings object
	 *  @param {array} aData data array to be added
	 *  @param {node} [nTr] TR element to add to the table - optional. If not given,
	 *    DataTables will create a row automatically
	 *  @param {array} [anTds] Array of TD|TH elements for the row - must be given
	 *    if nTr is.
	 *  @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
	 *  @memberof DataTable#oApi
	 */
	function _fnAddData ( oSettings, aDataIn, nTr, anTds )
	{
		/* Create the object for storing information about this new row */
		var iRow = oSettings.aoData.length;
		var oData = $.extend( true, {}, DataTable.models.oRow, {
			src: nTr ? 'dom' : 'data',
			idx: iRow
		} );
	
		oData._aData = aDataIn;
		oSettings.aoData.push( oData );
	
		/* Create the cells */
		var nTd, sThisType;
		var columns = oSettings.aoColumns;
	
		// Invalidate the column types as the new data needs to be revalidated
		for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
		{
			columns[i].sType = null;
		}
	
		/* Add to the display array */
		oSettings.aiDisplayMaster.push( iRow );
	
		var id = oSettings.rowIdFn( aDataIn );
		if ( id !== undefined ) {
			oSettings.aIds[ id ] = oData;
		}
	
		/* Create the DOM information, or register it if already present */
		if ( nTr || ! oSettings.oFeatures.bDeferRender )
		{
			_fnCreateTr( oSettings, iRow, nTr, anTds );
		}
	
		return iRow;
	}
	
	
	/**
	 * Add one or more TR elements to the table. Generally we'd expect to
	 * use this for reading data from a DOM sourced table, but it could be
	 * used for an TR element. Note that if a TR is given, it is used (i.e.
	 * it is not cloned).
	 *  @param {object} settings dataTables settings object
	 *  @param {array|node|jQuery} trs The TR element(s) to add to the table
	 *  @returns {array} Array of indexes for the added rows
	 *  @memberof DataTable#oApi
	 */
	function _fnAddTr( settings, trs )
	{
		var row;
	
		// Allow an individual node to be passed in
		if ( ! (trs instanceof $) ) {
			trs = $(trs);
		}
	
		return trs.map( function (i, el) {
			row = _fnGetRowElements( settings, el );
			return _fnAddData( settings, row.data, el, row.cells );
		} );
	}
	
	
	/**
	 * Take a TR element and convert it to an index in aoData
	 *  @param {object} oSettings dataTables settings object
	 *  @param {node} n the TR element to find
	 *  @returns {int} index if the node is found, null if not
	 *  @memberof DataTable#oApi
	 */
	function _fnNodeToDataIndex( oSettings, n )
	{
		return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;
	}
	
	
	/**
	 * Take a TD element and convert it into a column data index (not the visible index)
	 *  @param {object} oSettings dataTables settings object
	 *  @param {int} iRow The row number the TD/TH can be found in
	 *  @param {node} n The TD/TH element to find
	 *  @returns {int} index if the node is found, -1 if not
	 *  @memberof DataTable#oApi
	 */
	function _fnNodeToColumnIndex( oSettings, iRow, n )
	{
		return $.inArray( n, oSettings.aoData[ iRow ].anCells );
	}
	
	
	/**
	 * Get the data for a given cell from the internal cache, taking into account data mapping
	 *  @param {object} settings dataTables settings object
	 *  @param {int} rowIdx aoData row id
	 *  @param {int} colIdx Column index
	 *  @param {string} type data get type ('display', 'type' 'filter' 'sort')
	 *  @returns {*} Cell data
	 *  @memberof DataTable#oApi
	 */
	function _fnGetCellData( settings, rowIdx, colIdx, type )
	{
		var draw           = settings.iDraw;
		var col            = settings.aoColumns[colIdx];
		var rowData        = settings.aoData[rowIdx]._aData;
		var defaultContent = col.sDefaultContent;
		var cellData       = col.fnGetData( rowData, type, {
			settings: settings,
			row:      rowIdx,
			col:      colIdx
		} );
	
		if ( cellData === undefined ) {
			if ( settings.iDrawError != draw && defaultContent === null ) {
				_fnLog( settings, 0, "Requested unknown parameter "+
					(typeof col.mData=='function' ? '{function}' : "'"+col.mData+"'")+
					" for row "+rowIdx+", column "+colIdx, 4 );
				settings.iDrawError = draw;
			}
			return defaultContent;
		}
	
		// When the data source is null and a specific data type is requested (i.e.
		// not the original data), we can use default column data
		if ( (cellData === rowData || cellData === null) && defaultContent !== null && type !== undefined ) {
			cellData = defaultContent;
		}
		else if ( typeof cellData === 'function' ) {
			// If the data source is a function, then we run it and use the return,
			// executing in the scope of the data object (for instances)
			return cellData.call( rowData );
		}
	
		if ( cellData === null && type == 'display' ) {
			return '';
		}
		return cellData;
	}
	
	
	/**
	 * Set the value for a specific cell, into the internal data cache
	 *  @param {object} settings dataTables settings object
	 *  @param {int} rowIdx aoData row id
	 *  @param {int} colIdx Column index
	 *  @param {*} val Value to set
	 *  @memberof DataTable#oApi
	 */
	function _fnSetCellData( settings, rowIdx, colIdx, val )
	{
		var col     = settings.aoColumns[colIdx];
		var rowData = settings.aoData[rowIdx]._aData;
	
		col.fnSetData( rowData, val, {
			settings: settings,
			row:      rowIdx,
			col:      colIdx
		}  );
	}
	
	
	// Private variable that is used to match action syntax in the data property object
	var __reArray = /\[.*?\]$/;
	var __reFn = /\(\)$/;
	
	/**
	 * Split string on periods, taking into account escaped periods
	 * @param  {string} str String to split
	 * @return {array} Split string
	 */
	function _fnSplitObjNotation( str )
	{
		return $.map( str.match(/(\\.|[^\.])+/g) || [''], function ( s ) {
			return s.replace(/\\\./g, '.');
		} );
	}
	
	
	/**
	 * Return a function that can be used to get data from a source object, taking
	 * into account the ability to use nested objects as a source
	 *  @param {string|int|function} mSource The data source for the object
	 *  @returns {function} Data get function
	 *  @memberof DataTable#oApi
	 */
	function _fnGetObjectDataFn( mSource )
	{
		if ( $.isPlainObject( mSource ) )
		{
			/* Build an object of get functions, and wrap them in a single call */
			var o = {};
			$.each( mSource, function (key, val) {
				if ( val ) {
					o[key] = _fnGetObjectDataFn( val );
				}
			} );
	
			return function (data, type, row, meta) {
				var t = o[type] || o._;
				return t !== undefined ?
					t(data, type, row, meta) :
					data;
			};
		}
		else if ( mSource === null )
		{
			/* Give an empty string for rendering / sorting etc */
			return function (data) { // type, row and meta also passed, but not used
				return data;
			};
		}
		else if ( typeof mSource === 'function' )
		{
			return function (data, type, row, meta) {
				return mSource( data, type, row, meta );
			};
		}
		else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
			      mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
		{
			/* If there is a . in the source string then the data source is in a
			 * nested object so we loop over the data for each level to get the next
			 * level down. On each loop we test for undefined, and if found immediately
			 * return. This allows entire objects to be missing and sDefaultContent to
			 * be used if defined, rather than throwing an error
			 */
			var fetchData = function (data, type, src) {
				var arrayNotation, funcNotation, out, innerSrc;
	
				if ( src !== "" )
				{
					var a = _fnSplitObjNotation( src );
	
					for ( var i=0, iLen=a.length ; i<iLen ; i++ )
					{
						// Check if we are dealing with special notation
						arrayNotation = a[i].match(__reArray);
						funcNotation = a[i].match(__reFn);
	
						if ( arrayNotation )
						{
							// Array notation
							a[i] = a[i].replace(__reArray, '');
	
							// Condition allows simply [] to be passed in
							if ( a[i] !== "" ) {
								data = data[ a[i] ];
							}
							out = [];
	
							// Get the remainder of the nested object to get
							a.splice( 0, i+1 );
							innerSrc = a.join('.');
	
							// Traverse each entry in the array getting the properties requested
							if ( $.isArray( data ) ) {
								for ( var j=0, jLen=data.length ; j<jLen ; j++ ) {
									out.push( fetchData( data[j], type, innerSrc ) );
								}
							}
	
							// If a string is given in between the array notation indicators, that
							// is used to join the strings together, otherwise an array is returned
							var join = arrayNotation[0].substring(1, arrayNotation[0].length-1);
							data = (join==="") ? out : out.join(join);
	
							// The inner call to fetchData has already traversed through the remainder
							// of the source requested, so we exit from the loop
							break;
						}
						else if ( funcNotation )
						{
							// Function call
							a[i] = a[i].replace(__reFn, '');
							data = data[ a[i] ]();
							continue;
						}
	
						if ( data === null || data[ a[i] ] === undefined )
						{
							return undefined;
						}
						data = data[ a[i] ];
					}
				}
	
				return data;
			};
	
			return function (data, type) { // row and meta also passed, but not used
				return fetchData( data, type, mSource );
			};
		}
		else
		{
			/* Array or flat object mapping */
			return function (data, type) { // row and meta also passed, but not used
				return data[mSource];
			};
		}
	}
	
	
	/**
	 * Return a function that can be used to set data from a source object, taking
	 * into account the ability to use nested objects as a source
	 *  @param {string|int|function} mSource The data source for the object
	 *  @returns {function} Data set function
	 *  @memberof DataTable#oApi
	 */
	function _fnSetObjectDataFn( mSource )
	{
		if ( $.isPlainObject( mSource ) )
		{
			/* Unlike get, only the underscore (global) option is used for for
			 * setting data since we don't know the type here. This is why an object
			 * option is not documented for `mData` (which is read/write), but it is
			 * for `mRender` which is read only.
			 */
			return _fnSetObjectDataFn( mSource._ );
		}
		else if ( mSource === null )
		{
			/* Nothing to do when the data source is null */
			return function () {};
		}
		else if ( typeof mSource === 'function' )
		{
			return function (data, val, meta) {
				mSource( data, 'set', val, meta );
			};
		}
		else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
			      mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
		{
			/* Like the get, we need to get data from a nested object */
			var setData = function (data, val, src) {
				var a = _fnSplitObjNotation( src ), b;
				var aLast = a[a.length-1];
				var arrayNotation, funcNotation, o, innerSrc;
	
				for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )
				{
					// Check if we are dealing with an array notation request
					arrayNotation = a[i].match(__reArray);
					funcNotation = a[i].match(__reFn);
	
					if ( arrayNotation )
					{
						a[i] = a[i].replace(__reArray, '');
						data[ a[i] ] = [];
	
						// Get the remainder of the nested object to set so we can recurse
						b = a.slice();
						b.splice( 0, i+1 );
						innerSrc = b.join('.');
	
						// Traverse each entry in the array setting the properties requested
						if ( $.isArray( val ) )
						{
							for ( var j=0, jLen=val.length ; j<jLen ; j++ )
							{
								o = {};
								setData( o, val[j], innerSrc );
								data[ a[i] ].push( o );
							}
						}
						else
						{
							// We've been asked to save data to an array, but it
							// isn't array data to be saved. Best that can be done
							// is to just save the value.
							data[ a[i] ] = val;
						}
	
						// The inner call to setData has already traversed through the remainder
						// of the source and has set the data, thus we can exit here
						return;
					}
					else if ( funcNotation )
					{
						// Function call
						a[i] = a[i].replace(__reFn, '');
						data = data[ a[i] ]( val );
					}
	
					// If the nested object doesn't currently exist - since we are
					// trying to set the value - create it
					if ( data[ a[i] ] === null || data[ a[i] ] === undefined )
					{
						data[ a[i] ] = {};
					}
					data = data[ a[i] ];
				}
	
				// Last item in the input - i.e, the actual set
				if ( aLast.match(__reFn ) )
				{
					// Function call
					data = data[ aLast.replace(__reFn, '') ]( val );
				}
				else
				{
					// If array notation is used, we just want to strip it and use the property name
					// and assign the value. If it isn't used, then we get the result we want anyway
					data[ aLast.replace(__reArray, '') ] = val;
				}
			};
	
			return function (data, val) { // meta is also passed in, but not used
				return setData( data, val, mSource );
			};
		}
		else
		{
			/* Array or flat object mapping */
			return function (data, val) { // meta is also passed in, but not used
				data[mSource] = val;
			};
		}
	}
	
	
	/**
	 * Return an array with the full table data
	 *  @param {object} oSettings dataTables settings object
	 *  @returns array {array} aData Master data array
	 *  @memberof DataTable#oApi
	 */
	function _fnGetDataMaster ( settings )
	{
		return _pluck( settings.aoData, '_aData' );
	}
	
	
	/**
	 * Nuke the table
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnClearTable( settings )
	{
		settings.aoData.length = 0;
		settings.aiDisplayMaster.length = 0;
		settings.aiDisplay.length = 0;
		settings.aIds = {};
	}
	
	
	 /**
	 * Take an array of integers (index array) and remove a target integer (value - not
	 * the key!)
	 *  @param {array} a Index array to target
	 *  @param {int} iTarget value to find
	 *  @memberof DataTable#oApi
	 */
	function _fnDeleteIndex( a, iTarget, splice )
	{
		var iTargetIndex = -1;
	
		for ( var i=0, iLen=a.length ; i<iLen ; i++ )
		{
			if ( a[i] == iTarget )
			{
				iTargetIndex = i;
			}
			else if ( a[i] > iTarget )
			{
				a[i]--;
			}
		}
	
		if ( iTargetIndex != -1 && splice === undefined )
		{
			a.splice( iTargetIndex, 1 );
		}
	}
	
	
	/**
	 * Mark cached data as invalid such that a re-read of the data will occur when
	 * the cached data is next requested. Also update from the data source object.
	 *
	 * @param {object} settings DataTables settings object
	 * @param {int}    rowIdx   Row index to invalidate
	 * @param {string} [src]    Source to invalidate from: undefined, 'auto', 'dom'
	 *     or 'data'
	 * @param {int}    [colIdx] Column index to invalidate. If undefined the whole
	 *     row will be invalidated
	 * @memberof DataTable#oApi
	 *
	 * @todo For the modularisation of v1.11 this will need to become a callback, so
	 *   the sort and filter methods can subscribe to it. That will required
	 *   initialisation options for sorting, which is why it is not already baked in
	 */
	function _fnInvalidate( settings, rowIdx, src, colIdx )
	{
		var row = settings.aoData[ rowIdx ];
		var i, ien;
		var cellWrite = function ( cell, col ) {
			// This is very frustrating, but in IE if you just write directly
			// to innerHTML, and elements that are overwritten are GC'ed,
			// even if there is a reference to them elsewhere
			while ( cell.childNodes.length ) {
				cell.removeChild( cell.firstChild );
			}
	
			cell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' );
		};
	
		// Are we reading last data from DOM or the data object?
		if ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) {
			// Read the data from the DOM
			row._aData = _fnGetRowElements(
					settings, row, colIdx, colIdx === undefined ? undefined : row._aData
				)
				.data;
		}
		else {
			// Reading from data object, update the DOM
			var cells = row.anCells;
	
			if ( cells ) {
				if ( colIdx !== undefined ) {
					cellWrite( cells[colIdx], colIdx );
				}
				else {
					for ( i=0, ien=cells.length ; i<ien ; i++ ) {
						cellWrite( cells[i], i );
					}
				}
			}
		}
	
		// For both row and cell invalidation, the cached data for sorting and
		// filtering is nulled out
		row._aSortData = null;
		row._aFilterData = null;
	
		// Invalidate the type for a specific column (if given) or all columns since
		// the data might have changed
		var cols = settings.aoColumns;
		if ( colIdx !== undefined ) {
			cols[ colIdx ].sType = null;
		}
		else {
			for ( i=0, ien=cols.length ; i<ien ; i++ ) {
				cols[i].sType = null;
			}
	
			// Update DataTables special `DT_*` attributes for the row
			_fnRowAttributes( settings, row );
		}
	}
	
	
	/**
	 * Build a data source object from an HTML row, reading the contents of the
	 * cells that are in the row.
	 *
	 * @param {object} settings DataTables settings object
	 * @param {node|object} TR element from which to read data or existing row
	 *   object from which to re-read the data from the cells
	 * @param {int} [colIdx] Optional column index
	 * @param {array|object} [d] Data source object. If `colIdx` is given then this
	 *   parameter should also be given and will be used to write the data into.
	 *   Only the column in question will be written
	 * @returns {object} Object with two parameters: `data` the data read, in
	 *   document order, and `cells` and array of nodes (they can be useful to the
	 *   caller, so rather than needing a second traversal to get them, just return
	 *   them from here).
	 * @memberof DataTable#oApi
	 */
	function _fnGetRowElements( settings, row, colIdx, d )
	{
		var
			tds = [],
			td = row.firstChild,
			name, col, o, i=0, contents,
			columns = settings.aoColumns,
			objectRead = settings._rowReadObject;
	
		// Allow the data object to be passed in, or construct
		d = d !== undefined ?
			d :
			objectRead ?
				{} :
				[];
	
		var attr = function ( str, td  ) {
			if ( typeof str === 'string' ) {
				var idx = str.indexOf('@');
	
				if ( idx !== -1 ) {
					var attr = str.substring( idx+1 );
					var setter = _fnSetObjectDataFn( str );
					setter( d, td.getAttribute( attr ) );
				}
			}
		};
	
		// Read data from a cell and store into the data object
		var cellProcess = function ( cell ) {
			if ( colIdx === undefined || colIdx === i ) {
				col = columns[i];
				contents = $.trim(cell.innerHTML);
	
				if ( col && col._bAttrSrc ) {
					var setter = _fnSetObjectDataFn( col.mData._ );
					setter( d, contents );
	
					attr( col.mData.sort, cell );
					attr( col.mData.type, cell );
					attr( col.mData.filter, cell );
				}
				else {
					// Depending on the `data` option for the columns the data can
					// be read to either an object or an array.
					if ( objectRead ) {
						if ( ! col._setter ) {
							// Cache the setter function
							col._setter = _fnSetObjectDataFn( col.mData );
						}
						col._setter( d, contents );
					}
					else {
						d[i] = contents;
					}
				}
			}
	
			i++;
		};
	
		if ( td ) {
			// `tr` element was passed in
			while ( td ) {
				name = td.nodeName.toUpperCase();
	
				if ( name == "TD" || name == "TH" ) {
					cellProcess( td );
					tds.push( td );
				}
	
				td = td.nextSibling;
			}
		}
		else {
			// Existing row object passed in
			tds = row.anCells;
	
			for ( var j=0, jen=tds.length ; j<jen ; j++ ) {
				cellProcess( tds[j] );
			}
		}
	
		// Read the ID from the DOM if present
		var rowNode = row.firstChild ? row : row.nTr;
	
		if ( rowNode ) {
			var id = rowNode.getAttribute( 'id' );
	
			if ( id ) {
				_fnSetObjectDataFn( settings.rowId )( d, id );
			}
		}
	
		return {
			data: d,
			cells: tds
		};
	}
	/**
	 * Create a new TR element (and it's TD children) for a row
	 *  @param {object} oSettings dataTables settings object
	 *  @param {int} iRow Row to consider
	 *  @param {node} [nTrIn] TR element to add to the table - optional. If not given,
	 *    DataTables will create a row automatically
	 *  @param {array} [anTds] Array of TD|TH elements for the row - must be given
	 *    if nTr is.
	 *  @memberof DataTable#oApi
	 */
	function _fnCreateTr ( oSettings, iRow, nTrIn, anTds )
	{
		var
			row = oSettings.aoData[iRow],
			rowData = row._aData,
			cells = [],
			nTr, nTd, oCol,
			i, iLen;
	
		if ( row.nTr === null )
		{
			nTr = nTrIn || document.createElement('tr');
	
			row.nTr = nTr;
			row.anCells = cells;
	
			/* Use a private property on the node to allow reserve mapping from the node
			 * to the aoData array for fast look up
			 */
			nTr._DT_RowIndex = iRow;
	
			/* Special parameters can be given by the data source to be used on the row */
			_fnRowAttributes( oSettings, row );
	
			/* Process each column */
			for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
			{
				oCol = oSettings.aoColumns[i];
	
				nTd = nTrIn ? anTds[i] : document.createElement( oCol.sCellType );
				nTd._DT_CellIndex = {
					row: iRow,
					column: i
				};
				
				cells.push( nTd );
	
				// Need to create the HTML if new, or if a rendering function is defined
				if ( (!nTrIn || oCol.mRender || oCol.mData !== i) &&
					 (!$.isPlainObject(oCol.mData) || oCol.mData._ !== i+'.display')
				) {
					nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' );
				}
	
				/* Add user defined class */
				if ( oCol.sClass )
				{
					nTd.className += ' '+oCol.sClass;
				}
	
				// Visibility - add or remove as required
				if ( oCol.bVisible && ! nTrIn )
				{
					nTr.appendChild( nTd );
				}
				else if ( ! oCol.bVisible && nTrIn )
				{
					nTd.parentNode.removeChild( nTd );
				}
	
				if ( oCol.fnCreatedCell )
				{
					oCol.fnCreatedCell.call( oSettings.oInstance,
						nTd, _fnGetCellData( oSettings, iRow, i ), rowData, iRow, i
					);
				}
			}
	
			_fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow] );
		}
	
		// Remove once webkit bug 131819 and Chromium bug 365619 have been resolved
		// and deployed
		row.nTr.setAttribute( 'role', 'row' );
	}
	
	
	/**
	 * Add attributes to a row based on the special `DT_*` parameters in a data
	 * source object.
	 *  @param {object} settings DataTables settings object
	 *  @param {object} DataTables row object for the row to be modified
	 *  @memberof DataTable#oApi
	 */
	function _fnRowAttributes( settings, row )
	{
		var tr = row.nTr;
		var data = row._aData;
	
		if ( tr ) {
			var id = settings.rowIdFn( data );
	
			if ( id ) {
				tr.id = id;
			}
	
			if ( data.DT_RowClass ) {
				// Remove any classes added by DT_RowClass before
				var a = data.DT_RowClass.split(' ');
				row.__rowc = row.__rowc ?
					_unique( row.__rowc.concat( a ) ) :
					a;
	
				$(tr)
					.removeClass( row.__rowc.join(' ') )
					.addClass( data.DT_RowClass );
			}
	
			if ( data.DT_RowAttr ) {
				$(tr).attr( data.DT_RowAttr );
			}
	
			if ( data.DT_RowData ) {
				$(tr).data( data.DT_RowData );
			}
		}
	}
	
	
	/**
	 * Create the HTML header for the table
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnBuildHead( oSettings )
	{
		var i, ien, cell, row, column;
		var thead = oSettings.nTHead;
		var tfoot = oSettings.nTFoot;
		var createHeader = $('th, td', thead).length === 0;
		var classes = oSettings.oClasses;
		var columns = oSettings.aoColumns;
	
		if ( createHeader ) {
			row = $('<tr/>').appendTo( thead );
		}
	
		for ( i=0, ien=columns.length ; i<ien ; i++ ) {
			column = columns[i];
			cell = $( column.nTh ).addClass( column.sClass );
	
			if ( createHeader ) {
				cell.appendTo( row );
			}
	
			// 1.11 move into sorting
			if ( oSettings.oFeatures.bSort ) {
				cell.addClass( column.sSortingClass );
	
				if ( column.bSortable !== false ) {
					cell
						.attr( 'tabindex', oSettings.iTabIndex )
						.attr( 'aria-controls', oSettings.sTableId );
	
					_fnSortAttachListener( oSettings, column.nTh, i );
				}
			}
	
			if ( column.sTitle != cell[0].innerHTML ) {
				cell.html( column.sTitle );
			}
	
			_fnRenderer( oSettings, 'header' )(
				oSettings, cell, column, classes
			);
		}
	
		if ( createHeader ) {
			_fnDetectHeader( oSettings.aoHeader, thead );
		}
		
		/* ARIA role for the rows */
	 	$(thead).find('>tr').attr('role', 'row');
	
		/* Deal with the footer - add classes if required */
		$(thead).find('>tr>th, >tr>td').addClass( classes.sHeaderTH );
		$(tfoot).find('>tr>th, >tr>td').addClass( classes.sFooterTH );
	
		// Cache the footer cells. Note that we only take the cells from the first
		// row in the footer. If there is more than one row the user wants to
		// interact with, they need to use the table().foot() method. Note also this
		// allows cells to be used for multiple columns using colspan
		if ( tfoot !== null ) {
			var cells = oSettings.aoFooter[0];
	
			for ( i=0, ien=cells.length ; i<ien ; i++ ) {
				column = columns[i];
				column.nTf = cells[i].cell;
	
				if ( column.sClass ) {
					$(column.nTf).addClass( column.sClass );
				}
			}
		}
	}
	
	
	/**
	 * Draw the header (or footer) element based on the column visibility states. The
	 * methodology here is to use the layout array from _fnDetectHeader, modified for
	 * the instantaneous column visibility, to construct the new layout. The grid is
	 * traversed over cell at a time in a rows x columns grid fashion, although each
	 * cell insert can cover multiple elements in the grid - which is tracks using the
	 * aApplied array. Cell inserts in the grid will only occur where there isn't
	 * already a cell in that position.
	 *  @param {object} oSettings dataTables settings object
	 *  @param array {objects} aoSource Layout array from _fnDetectHeader
	 *  @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
	 *  @memberof DataTable#oApi
	 */
	function _fnDrawHead( oSettings, aoSource, bIncludeHidden )
	{
		var i, iLen, j, jLen, k, kLen, n, nLocalTr;
		var aoLocal = [];
		var aApplied = [];
		var iColumns = oSettings.aoColumns.length;
		var iRowspan, iColspan;
	
		if ( ! aoSource )
		{
			return;
		}
	
		if (  bIncludeHidden === undefined )
		{
			bIncludeHidden = false;
		}
	
		/* Make a copy of the master layout array, but without the visible columns in it */
		for ( i=0, iLen=aoSource.length ; i<iLen ; i++ )
		{
			aoLocal[i] = aoSource[i].slice();
			aoLocal[i].nTr = aoSource[i].nTr;
	
			/* Remove any columns which are currently hidden */
			for ( j=iColumns-1 ; j>=0 ; j-- )
			{
				if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden )
				{
					aoLocal[i].splice( j, 1 );
				}
			}
	
			/* Prep the applied array - it needs an element for each row */
			aApplied.push( [] );
		}
	
		for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ )
		{
			nLocalTr = aoLocal[i].nTr;
	
			/* All cells are going to be replaced, so empty out the row */
			if ( nLocalTr )
			{
				while( (n = nLocalTr.firstChild) )
				{
					nLocalTr.removeChild( n );
				}
			}
	
			for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ )
			{
				iRowspan = 1;
				iColspan = 1;
	
				/* Check to see if there is already a cell (row/colspan) covering our target
				 * insert point. If there is, then there is nothing to do.
				 */
				if ( aApplied[i][j] === undefined )
				{
					nLocalTr.appendChild( aoLocal[i][j].cell );
					aApplied[i][j] = 1;
	
					/* Expand the cell to cover as many rows as needed */
					while ( aoLocal[i+iRowspan] !== undefined &&
					        aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell )
					{
						aApplied[i+iRowspan][j] = 1;
						iRowspan++;
					}
	
					/* Expand the cell to cover as many columns as needed */
					while ( aoLocal[i][j+iColspan] !== undefined &&
					        aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell )
					{
						/* Must update the applied array over the rows for the columns */
						for ( k=0 ; k<iRowspan ; k++ )
						{
							aApplied[i+k][j+iColspan] = 1;
						}
						iColspan++;
					}
	
					/* Do the actual expansion in the DOM */
					$(aoLocal[i][j].cell)
						.attr('rowspan', iRowspan)
						.attr('colspan', iColspan);
				}
			}
		}
	}
	
	
	/**
	 * Insert the required TR nodes into the table for display
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnDraw( oSettings )
	{
		/* Provide a pre-callback function which can be used to cancel the draw is false is returned */
		var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] );
		if ( $.inArray( false, aPreDraw ) !== -1 )
		{
			_fnProcessingDisplay( oSettings, false );
			return;
		}
	
		var i, iLen, n;
		var anRows = [];
		var iRowCount = 0;
		var asStripeClasses = oSettings.asStripeClasses;
		var iStripes = asStripeClasses.length;
		var iOpenRows = oSettings.aoOpenRows.length;
		var oLang = oSettings.oLanguage;
		var iInitDisplayStart = oSettings.iInitDisplayStart;
		var bServerSide = _fnDataSource( oSettings ) == 'ssp';
		var aiDisplay = oSettings.aiDisplay;
	
		oSettings.bDrawing = true;
	
		/* Check and see if we have an initial draw position from state saving */
		if ( iInitDisplayStart !== undefined && iInitDisplayStart !== -1 )
		{
			oSettings._iDisplayStart = bServerSide ?
				iInitDisplayStart :
				iInitDisplayStart >= oSettings.fnRecordsDisplay() ?
					0 :
					iInitDisplayStart;
	
			oSettings.iInitDisplayStart = -1;
		}
	
		var iDisplayStart = oSettings._iDisplayStart;
		var iDisplayEnd = oSettings.fnDisplayEnd();
	
		/* Server-side processing draw intercept */
		if ( oSettings.bDeferLoading )
		{
			oSettings.bDeferLoading = false;
			oSettings.iDraw++;
			_fnProcessingDisplay( oSettings, false );
		}
		else if ( !bServerSide )
		{
			oSettings.iDraw++;
		}
		else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) )
		{
			return;
		}
	
		if ( aiDisplay.length !== 0 )
		{
			var iStart = bServerSide ? 0 : iDisplayStart;
			var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd;
	
			for ( var j=iStart ; j<iEnd ; j++ )
			{
				var iDataIndex = aiDisplay[j];
				var aoData = oSettings.aoData[ iDataIndex ];
				if ( aoData.nTr === null )
				{
					_fnCreateTr( oSettings, iDataIndex );
				}
	
				var nRow = aoData.nTr;
	
				/* Remove the old striping classes and then add the new one */
				if ( iStripes !== 0 )
				{
					var sStripe = asStripeClasses[ iRowCount % iStripes ];
					if ( aoData._sRowStripe != sStripe )
					{
						$(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe );
						aoData._sRowStripe = sStripe;
					}
				}
	
				// Row callback functions - might want to manipulate the row
				// iRowCount and j are not currently documented. Are they at all
				// useful?
				_fnCallbackFire( oSettings, 'aoRowCallback', null,
					[nRow, aoData._aData, iRowCount, j] );
	
				anRows.push( nRow );
				iRowCount++;
			}
		}
		else
		{
			/* Table is empty - create a row with an empty message in it */
			var sZero = oLang.sZeroRecords;
			if ( oSettings.iDraw == 1 &&  _fnDataSource( oSettings ) == 'ajax' )
			{
				sZero = oLang.sLoadingRecords;
			}
			else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 )
			{
				sZero = oLang.sEmptyTable;
			}
	
			anRows[ 0 ] = $( '<tr/>', { 'class': iStripes ? asStripeClasses[0] : '' } )
				.append( $('<td />', {
					'valign':  'top',
					'colSpan': _fnVisbleColumns( oSettings ),
					'class':   oSettings.oClasses.sRowEmpty
				} ).html( sZero ) )[0];
		}
	
		/* Header and footer callbacks */
		_fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0],
			_fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
	
		_fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0],
			_fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
	
		var body = $(oSettings.nTBody);
	
		body.children().detach();
		body.append( $(anRows) );
	
		/* Call all required callback functions for the end of a draw */
		_fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] );
	
		/* Draw is complete, sorting and filtering must be as well */
		oSettings.bSorted = false;
		oSettings.bFiltered = false;
		oSettings.bDrawing = false;
	}
	
	
	/**
	 * Redraw the table - taking account of the various features which are enabled
	 *  @param {object} oSettings dataTables settings object
	 *  @param {boolean} [holdPosition] Keep the current paging position. By default
	 *    the paging is reset to the first page
	 *  @memberof DataTable#oApi
	 */
	function _fnReDraw( settings, holdPosition )
	{
		var
			features = settings.oFeatures,
			sort     = features.bSort,
			filter   = features.bFilter;
	
		if ( sort ) {
			_fnSort( settings );
		}
	
		if ( filter ) {
			_fnFilterComplete( settings, settings.oPreviousSearch );
		}
		else {
			// No filtering, so we want to just use the display master
			settings.aiDisplay = settings.aiDisplayMaster.slice();
		}
	
		if ( holdPosition !== true ) {
			settings._iDisplayStart = 0;
		}
	
		// Let any modules know about the draw hold position state (used by
		// scrolling internally)
		settings._drawHold = holdPosition;
	
		_fnDraw( settings );
	
		settings._drawHold = false;
	}
	
	
	/**
	 * Add the options to the page HTML for the table
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnAddOptionsHtml ( oSettings )
	{
		var classes = oSettings.oClasses;
		var table = $(oSettings.nTable);
		var holding = $('<div/>').insertBefore( table ); // Holding element for speed
		var features = oSettings.oFeatures;
	
		// All DataTables are wrapped in a div
		var insert = $('<div/>', {
			id:      oSettings.sTableId+'_wrapper',
			'class': classes.sWrapper + (oSettings.nTFoot ? '' : ' '+classes.sNoFooter)
		} );
	
		oSettings.nHolding = holding[0];
		oSettings.nTableWrapper = insert[0];
		oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;
	
		/* Loop over the user set positioning and place the elements as needed */
		var aDom = oSettings.sDom.split('');
		var featureNode, cOption, nNewNode, cNext, sAttr, j;
		for ( var i=0 ; i<aDom.length ; i++ )
		{
			featureNode = null;
			cOption = aDom[i];
	
			if ( cOption == '<' )
			{
				/* New container div */
				nNewNode = $('<div/>')[0];
	
				/* Check to see if we should append an id and/or a class name to the container */
				cNext = aDom[i+1];
				if ( cNext == "'" || cNext == '"' )
				{
					sAttr = "";
					j = 2;
					while ( aDom[i+j] != cNext )
					{
						sAttr += aDom[i+j];
						j++;
					}
	
					/* Replace jQuery UI constants @todo depreciated */
					if ( sAttr == "H" )
					{
						sAttr = classes.sJUIHeader;
					}
					else if ( sAttr == "F" )
					{
						sAttr = classes.sJUIFooter;
					}
	
					/* The attribute can be in the format of "#id.class", "#id" or "class" This logic
					 * breaks the string into parts and applies them as needed
					 */
					if ( sAttr.indexOf('.') != -1 )
					{
						var aSplit = sAttr.split('.');
						nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1);
						nNewNode.className = aSplit[1];
					}
					else if ( sAttr.charAt(0) == "#" )
					{
						nNewNode.id = sAttr.substr(1, sAttr.length-1);
					}
					else
					{
						nNewNode.className = sAttr;
					}
	
					i += j; /* Move along the position array */
				}
	
				insert.append( nNewNode );
				insert = $(nNewNode);
			}
			else if ( cOption == '>' )
			{
				/* End container div */
				insert = insert.parent();
			}
			// @todo Move options into their own plugins?
			else if ( cOption == 'l' && features.bPaginate && features.bLengthChange )
			{
				/* Length */
				featureNode = _fnFeatureHtmlLength( oSettings );
			}
			else if ( cOption == 'f' && features.bFilter )
			{
				/* Filter */
				featureNode = _fnFeatureHtmlFilter( oSettings );
			}
			else if ( cOption == 'r' && features.bProcessing )
			{
				/* pRocessing */
				featureNode = _fnFeatureHtmlProcessing( oSettings );
			}
			else if ( cOption == 't' )
			{
				/* Table */
				featureNode = _fnFeatureHtmlTable( oSettings );
			}
			else if ( cOption ==  'i' && features.bInfo )
			{
				/* Info */
				featureNode = _fnFeatureHtmlInfo( oSettings );
			}
			else if ( cOption == 'p' && features.bPaginate )
			{
				/* Pagination */
				featureNode = _fnFeatureHtmlPaginate( oSettings );
			}
			else if ( DataTable.ext.feature.length !== 0 )
			{
				/* Plug-in features */
				var aoFeatures = DataTable.ext.feature;
				for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ )
				{
					if ( cOption == aoFeatures[k].cFeature )
					{
						featureNode = aoFeatures[k].fnInit( oSettings );
						break;
					}
				}
			}
	
			/* Add to the 2D features array */
			if ( featureNode )
			{
				var aanFeatures = oSettings.aanFeatures;
	
				if ( ! aanFeatures[cOption] )
				{
					aanFeatures[cOption] = [];
				}
	
				aanFeatures[cOption].push( featureNode );
				insert.append( featureNode );
			}
		}
	
		/* Built our DOM structure - replace the holding div with what we want */
		holding.replaceWith( insert );
		oSettings.nHolding = null;
	}
	
	
	/**
	 * Use the DOM source to create up an array of header cells. The idea here is to
	 * create a layout grid (array) of rows x columns, which contains a reference
	 * to the cell that that point in the grid (regardless of col/rowspan), such that
	 * any column / row could be removed and the new grid constructed
	 *  @param array {object} aLayout Array to store the calculated layout in
	 *  @param {node} nThead The header/footer element for the table
	 *  @memberof DataTable#oApi
	 */
	function _fnDetectHeader ( aLayout, nThead )
	{
		var nTrs = $(nThead).children('tr');
		var nTr, nCell;
		var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
		var bUnique;
		var fnShiftCol = function ( a, i, j ) {
			var k = a[i];
	                while ( k[j] ) {
				j++;
			}
			return j;
		};
	
		aLayout.splice( 0, aLayout.length );
	
		/* We know how many rows there are in the layout - so prep it */
		for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
		{
			aLayout.push( [] );
		}
	
		/* Calculate a layout array */
		for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
		{
			nTr = nTrs[i];
			iColumn = 0;
	
			/* For every cell in the row... */
			nCell = nTr.firstChild;
			while ( nCell ) {
				if ( nCell.nodeName.toUpperCase() == "TD" ||
				     nCell.nodeName.toUpperCase() == "TH" )
				{
					/* Get the col and rowspan attributes from the DOM and sanitise them */
					iColspan = nCell.getAttribute('colspan') * 1;
					iRowspan = nCell.getAttribute('rowspan') * 1;
					iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan;
					iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan;
	
					/* There might be colspan cells already in this row, so shift our target
					 * accordingly
					 */
					iColShifted = fnShiftCol( aLayout, i, iColumn );
	
					/* Cache calculation for unique columns */
					bUnique = iColspan === 1 ? true : false;
	
					/* If there is col / rowspan, copy the information into the layout grid */
					for ( l=0 ; l<iColspan ; l++ )
					{
						for ( k=0 ; k<iRowspan ; k++ )
						{
							aLayout[i+k][iColShifted+l] = {
								"cell": nCell,
								"unique": bUnique
							};
							aLayout[i+k].nTr = nTr;
						}
					}
				}
				nCell = nCell.nextSibling;
			}
		}
	}
	
	
	/**
	 * Get an array of unique th elements, one for each column
	 *  @param {object} oSettings dataTables settings object
	 *  @param {node} nHeader automatically detect the layout from this node - optional
	 *  @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
	 *  @returns array {node} aReturn list of unique th's
	 *  @memberof DataTable#oApi
	 */
	function _fnGetUniqueThs ( oSettings, nHeader, aLayout )
	{
		var aReturn = [];
		if ( !aLayout )
		{
			aLayout = oSettings.aoHeader;
			if ( nHeader )
			{
				aLayout = [];
				_fnDetectHeader( aLayout, nHeader );
			}
		}
	
		for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ )
		{
			for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ )
			{
				if ( aLayout[i][j].unique &&
					 (!aReturn[j] || !oSettings.bSortCellsTop) )
				{
					aReturn[j] = aLayout[i][j].cell;
				}
			}
		}
	
		return aReturn;
	}
	
	/**
	 * Create an Ajax call based on the table's settings, taking into account that
	 * parameters can have multiple forms, and backwards compatibility.
	 *
	 * @param {object} oSettings dataTables settings object
	 * @param {array} data Data to send to the server, required by
	 *     DataTables - may be augmented by developer callbacks
	 * @param {function} fn Callback function to run when data is obtained
	 */
	function _fnBuildAjax( oSettings, data, fn )
	{
		// Compatibility with 1.9-, allow fnServerData and event to manipulate
		_fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [data] );
	
		// Convert to object based for 1.10+ if using the old array scheme which can
		// come from server-side processing or serverParams
		if ( data && $.isArray(data) ) {
			var tmp = {};
			var rbracket = /(.*?)\[\]$/;
	
			$.each( data, function (key, val) {
				var match = val.name.match(rbracket);
	
				if ( match ) {
					// Support for arrays
					var name = match[0];
	
					if ( ! tmp[ name ] ) {
						tmp[ name ] = [];
					}
					tmp[ name ].push( val.value );
				}
				else {
					tmp[val.name] = val.value;
				}
			} );
			data = tmp;
		}
	
		var ajaxData;
		var ajax = oSettings.ajax;
		var instance = oSettings.oInstance;
		var callback = function ( json ) {
			_fnCallbackFire( oSettings, null, 'xhr', [oSettings, json, oSettings.jqXHR] );
			fn( json );
		};
	
		if ( $.isPlainObject( ajax ) && ajax.data )
		{
			ajaxData = ajax.data;
	
			var newData = $.isFunction( ajaxData ) ?
				ajaxData( data, oSettings ) :  // fn can manipulate data or return
				ajaxData;                      // an object object or array to merge
	
			// If the function returned something, use that alone
			data = $.isFunction( ajaxData ) && newData ?
				newData :
				$.extend( true, data, newData );
	
			// Remove the data property as we've resolved it already and don't want
			// jQuery to do it again (it is restored at the end of the function)
			delete ajax.data;
		}
	
		var baseAjax = {
			"data": data,
			"success": function (json) {
				var error = json.error || json.sError;
				if ( error ) {
					_fnLog( oSettings, 0, error );
				}
	
				oSettings.json = json;
				callback( json );
			},
			"dataType": "json",
			"cache": false,
			"type": oSettings.sServerMethod,
			"error": function (xhr, error, thrown) {
				var ret = _fnCallbackFire( oSettings, null, 'xhr', [oSettings, null, oSettings.jqXHR] );
	
				if ( $.inArray( true, ret ) === -1 ) {
					if ( error == "parsererror" ) {
						_fnLog( oSettings, 0, 'Invalid JSON response', 1 );
					}
					else if ( xhr.readyState === 4 ) {
						_fnLog( oSettings, 0, 'Ajax error', 7 );
					}
				}
	
				_fnProcessingDisplay( oSettings, false );
			}
		};
	
		// Store the data submitted for the API
		oSettings.oAjaxData = data;
	
		// Allow plug-ins and external processes to modify the data
		_fnCallbackFire( oSettings, null, 'preXhr', [oSettings, data] );
	
		if ( oSettings.fnServerData )
		{
			// DataTables 1.9- compatibility
			oSettings.fnServerData.call( instance,
				oSettings.sAjaxSource,
				$.map( data, function (val, key) { // Need to convert back to 1.9 trad format
					return { name: key, value: val };
				} ),
				callback,
				oSettings
			);
		}
		else if ( oSettings.sAjaxSource || typeof ajax === 'string' )
		{
			// DataTables 1.9- compatibility
			oSettings.jqXHR = $.ajax( $.extend( baseAjax, {
				url: ajax || oSettings.sAjaxSource
			} ) );
		}
		else if ( $.isFunction( ajax ) )
		{
			// Is a function - let the caller define what needs to be done
			oSettings.jqXHR = ajax.call( instance, data, callback, oSettings );
		}
		else
		{
			// Object to extend the base settings
			oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) );
	
			// Restore for next time around
			ajax.data = ajaxData;
		}
	}
	
	
	/**
	 * Update the table using an Ajax call
	 *  @param {object} settings dataTables settings object
	 *  @returns {boolean} Block the table drawing or not
	 *  @memberof DataTable#oApi
	 */
	function _fnAjaxUpdate( settings )
	{
		if ( settings.bAjaxDataGet ) {
			settings.iDraw++;
			_fnProcessingDisplay( settings, true );
	
			_fnBuildAjax(
				settings,
				_fnAjaxParameters( settings ),
				function(json) {
					_fnAjaxUpdateDraw( settings, json );
				}
			);
	
			return false;
		}
		return true;
	}
	
	
	/**
	 * Build up the parameters in an object needed for a server-side processing
	 * request. Note that this is basically done twice, is different ways - a modern
	 * method which is used by default in DataTables 1.10 which uses objects and
	 * arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if
	 * the sAjaxSource option is used in the initialisation, or the legacyAjax
	 * option is set.
	 *  @param {object} oSettings dataTables settings object
	 *  @returns {bool} block the table drawing or not
	 *  @memberof DataTable#oApi
	 */
	function _fnAjaxParameters( settings )
	{
		var
			columns = settings.aoColumns,
			columnCount = columns.length,
			features = settings.oFeatures,
			preSearch = settings.oPreviousSearch,
			preColSearch = settings.aoPreSearchCols,
			i, data = [], dataProp, column, columnSearch,
			sort = _fnSortFlatten( settings ),
			displayStart = settings._iDisplayStart,
			displayLength = features.bPaginate !== false ?
				settings._iDisplayLength :
				-1;
	
		var param = function ( name, value ) {
			data.push( { 'name': name, 'value': value } );
		};
	
		// DataTables 1.9- compatible method
		param( 'sEcho',          settings.iDraw );
		param( 'iColumns',       columnCount );
		param( 'sColumns',       _pluck( columns, 'sName' ).join(',') );
		param( 'iDisplayStart',  displayStart );
		param( 'iDisplayLength', displayLength );
	
		// DataTables 1.10+ method
		var d = {
			draw:    settings.iDraw,
			columns: [],
			order:   [],
			start:   displayStart,
			length:  displayLength,
			search:  {
				value: preSearch.sSearch,
				regex: preSearch.bRegex
			}
		};
	
		for ( i=0 ; i<columnCount ; i++ ) {
			column = columns[i];
			columnSearch = preColSearch[i];
			dataProp = typeof column.mData=="function" ? 'function' : column.mData ;
	
			d.columns.push( {
				data:       dataProp,
				name:       column.sName,
				searchable: column.bSearchable,
				orderable:  column.bSortable,
				search:     {
					value: columnSearch.sSearch,
					regex: columnSearch.bRegex
				}
			} );
	
			param( "mDataProp_"+i, dataProp );
	
			if ( features.bFilter ) {
				param( 'sSearch_'+i,     columnSearch.sSearch );
				param( 'bRegex_'+i,      columnSearch.bRegex );
				param( 'bSearchable_'+i, column.bSearchable );
			}
	
			if ( features.bSort ) {
				param( 'bSortable_'+i, column.bSortable );
			}
		}
	
		if ( features.bFilter ) {
			param( 'sSearch', preSearch.sSearch );
			param( 'bRegex', preSearch.bRegex );
		}
	
		if ( features.bSort ) {
			$.each( sort, function ( i, val ) {
				d.order.push( { column: val.col, dir: val.dir } );
	
				param( 'iSortCol_'+i, val.col );
				param( 'sSortDir_'+i, val.dir );
			} );
	
			param( 'iSortingCols', sort.length );
		}
	
		// If the legacy.ajax parameter is null, then we automatically decide which
		// form to use, based on sAjaxSource
		var legacy = DataTable.ext.legacy.ajax;
		if ( legacy === null ) {
			return settings.sAjaxSource ? data : d;
		}
	
		// Otherwise, if legacy has been specified then we use that to decide on the
		// form
		return legacy ? data : d;
	}
	
	
	/**
	 * Data the data from the server (nuking the old) and redraw the table
	 *  @param {object} oSettings dataTables settings object
	 *  @param {object} json json data return from the server.
	 *  @param {string} json.sEcho Tracking flag for DataTables to match requests
	 *  @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
	 *  @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
	 *  @param {array} json.aaData The data to display on this page
	 *  @param {string} [json.sColumns] Column ordering (sName, comma separated)
	 *  @memberof DataTable#oApi
	 */
	function _fnAjaxUpdateDraw ( settings, json )
	{
		// v1.10 uses camelCase variables, while 1.9 uses Hungarian notation.
		// Support both
		var compat = function ( old, modern ) {
			return json[old] !== undefined ? json[old] : json[modern];
		};
	
		var data = _fnAjaxDataSrc( settings, json );
		var draw            = compat( 'sEcho',                'draw' );
		var recordsTotal    = compat( 'iTotalRecords',        'recordsTotal' );
		var recordsFiltered = compat( 'iTotalDisplayRecords', 'recordsFiltered' );
	
		if ( draw ) {
			// Protect against out of sequence returns
			if ( draw*1 < settings.iDraw ) {
				return;
			}
			settings.iDraw = draw * 1;
		}
	
		_fnClearTable( settings );
		settings._iRecordsTotal   = parseInt(recordsTotal, 10);
		settings._iRecordsDisplay = parseInt(recordsFiltered, 10);
	
		for ( var i=0, ien=data.length ; i<ien ; i++ ) {
			_fnAddData( settings, data[i] );
		}
		settings.aiDisplay = settings.aiDisplayMaster.slice();
	
		settings.bAjaxDataGet = false;
		_fnDraw( settings );
	
		if ( ! settings._bInitComplete ) {
			_fnInitComplete( settings, json );
		}
	
		settings.bAjaxDataGet = true;
		_fnProcessingDisplay( settings, false );
	}
	
	
	/**
	 * Get the data from the JSON data source to use for drawing a table. Using
	 * `_fnGetObjectDataFn` allows the data to be sourced from a property of the
	 * source object, or from a processing function.
	 *  @param {object} oSettings dataTables settings object
	 *  @param  {object} json Data source object / array from the server
	 *  @return {array} Array of data to use
	 */
	function _fnAjaxDataSrc ( oSettings, json )
	{
		var dataSrc = $.isPlainObject( oSettings.ajax ) && oSettings.ajax.dataSrc !== undefined ?
			oSettings.ajax.dataSrc :
			oSettings.sAjaxDataProp; // Compatibility with 1.9-.
	
		// Compatibility with 1.9-. In order to read from aaData, check if the
		// default has been changed, if not, check for aaData
		if ( dataSrc === 'data' ) {
			return json.aaData || json[dataSrc];
		}
	
		return dataSrc !== "" ?
			_fnGetObjectDataFn( dataSrc )( json ) :
			json;
	}
	
	/**
	 * Generate the node required for filtering text
	 *  @returns {node} Filter control element
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnFeatureHtmlFilter ( settings )
	{
		var classes = settings.oClasses;
		var tableId = settings.sTableId;
		var language = settings.oLanguage;
		var previousSearch = settings.oPreviousSearch;
		var features = settings.aanFeatures;
		var input = '<input type="search" class="'+classes.sFilterInput+'"/>';
	
		var str = language.sSearch;
		str = str.match(/_INPUT_/) ?
			str.replace('_INPUT_', input) :
			str+input;
	
		var filter = $('<div/>', {
				'id': ! features.f ? tableId+'_filter' : null,
				'class': classes.sFilter
			} )
			.append( $('<label/>' ).append( str ) );
	
		var searchFn = function() {
			/* Update all other filter input elements for the new display */
			var n = features.f;
			var val = !this.value ? "" : this.value; // mental IE8 fix :-(
	
			/* Now do the filter */
			if ( val != previousSearch.sSearch ) {
				_fnFilterComplete( settings, {
					"sSearch": val,
					"bRegex": previousSearch.bRegex,
					"bSmart": previousSearch.bSmart ,
					"bCaseInsensitive": previousSearch.bCaseInsensitive
				} );
	
				// Need to redraw, without resorting
				settings._iDisplayStart = 0;
				_fnDraw( settings );
			}
		};
	
		var searchDelay = settings.searchDelay !== null ?
			settings.searchDelay :
			_fnDataSource( settings ) === 'ssp' ?
				400 :
				0;
	
		var jqFilter = $('input', filter)
			.val( previousSearch.sSearch )
			.attr( 'placeholder', language.sSearchPlaceholder )
			.on(
				'keyup.DT search.DT input.DT paste.DT cut.DT',
				searchDelay ?
					_fnThrottle( searchFn, searchDelay ) :
					searchFn
			)
			.on( 'keypress.DT', function(e) {
				/* Prevent form submission */
				if ( e.keyCode == 13 ) {
					return false;
				}
			} )
			.attr('aria-controls', tableId);
	
		// Update the input elements whenever the table is filtered
		$(settings.nTable).on( 'search.dt.DT', function ( ev, s ) {
			if ( settings === s ) {
				// IE9 throws an 'unknown error' if document.activeElement is used
				// inside an iframe or frame...
				try {
					if ( jqFilter[0] !== document.activeElement ) {
						jqFilter.val( previousSearch.sSearch );
					}
				}
				catch ( e ) {}
			}
		} );
	
		return filter[0];
	}
	
	
	/**
	 * Filter the table using both the global filter and column based filtering
	 *  @param {object} oSettings dataTables settings object
	 *  @param {object} oSearch search information
	 *  @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
	 *  @memberof DataTable#oApi
	 */
	function _fnFilterComplete ( oSettings, oInput, iForce )
	{
		var oPrevSearch = oSettings.oPreviousSearch;
		var aoPrevSearch = oSettings.aoPreSearchCols;
		var fnSaveFilter = function ( oFilter ) {
			/* Save the filtering values */
			oPrevSearch.sSearch = oFilter.sSearch;
			oPrevSearch.bRegex = oFilter.bRegex;
			oPrevSearch.bSmart = oFilter.bSmart;
			oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
		};
		var fnRegex = function ( o ) {
			// Backwards compatibility with the bEscapeRegex option
			return o.bEscapeRegex !== undefined ? !o.bEscapeRegex : o.bRegex;
		};
	
		// Resolve any column types that are unknown due to addition or invalidation
		// @todo As per sort - can this be moved into an event handler?
		_fnColumnTypes( oSettings );
	
		/* In server-side processing all filtering is done by the server, so no point hanging around here */
		if ( _fnDataSource( oSettings ) != 'ssp' )
		{
			/* Global filter */
			_fnFilter( oSettings, oInput.sSearch, iForce, fnRegex(oInput), oInput.bSmart, oInput.bCaseInsensitive );
			fnSaveFilter( oInput );
	
			/* Now do the individual column filter */
			for ( var i=0 ; i<aoPrevSearch.length ; i++ )
			{
				_fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, fnRegex(aoPrevSearch[i]),
					aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive );
			}
	
			/* Custom filtering */
			_fnFilterCustom( oSettings );
		}
		else
		{
			fnSaveFilter( oInput );
		}
	
		/* Tell the draw function we have been filtering */
		oSettings.bFiltered = true;
		_fnCallbackFire( oSettings, null, 'search', [oSettings] );
	}
	
	
	/**
	 * Apply custom filtering functions
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnFilterCustom( settings )
	{
		var filters = DataTable.ext.search;
		var displayRows = settings.aiDisplay;
		var row, rowIdx;
	
		for ( var i=0, ien=filters.length ; i<ien ; i++ ) {
			var rows = [];
	
			// Loop over each row and see if it should be included
			for ( var j=0, jen=displayRows.length ; j<jen ; j++ ) {
				rowIdx = displayRows[ j ];
				row = settings.aoData[ rowIdx ];
	
				if ( filters[i]( settings, row._aFilterData, rowIdx, row._aData, j ) ) {
					rows.push( rowIdx );
				}
			}
	
			// So the array reference doesn't break set the results into the
			// existing array
			displayRows.length = 0;
			$.merge( displayRows, rows );
		}
	}
	
	
	/**
	 * Filter the table on a per-column basis
	 *  @param {object} oSettings dataTables settings object
	 *  @param {string} sInput string to filter on
	 *  @param {int} iColumn column to filter
	 *  @param {bool} bRegex treat search string as a regular expression or not
	 *  @param {bool} bSmart use smart filtering or not
	 *  @param {bool} bCaseInsensitive Do case insenstive matching or not
	 *  @memberof DataTable#oApi
	 */
	function _fnFilterColumn ( settings, searchStr, colIdx, regex, smart, caseInsensitive )
	{
		if ( searchStr === '' ) {
			return;
		}
	
		var data;
		var out = [];
		var display = settings.aiDisplay;
		var rpSearch = _fnFilterCreateSearch( searchStr, regex, smart, caseInsensitive );
	
		for ( var i=0 ; i<display.length ; i++ ) {
			data = settings.aoData[ display[i] ]._aFilterData[ colIdx ];
	
			if ( rpSearch.test( data ) ) {
				out.push( display[i] );
			}
		}
	
		settings.aiDisplay = out;
	}
	
	
	/**
	 * Filter the data table based on user input and draw the table
	 *  @param {object} settings dataTables settings object
	 *  @param {string} input string to filter on
	 *  @param {int} force optional - force a research of the master array (1) or not (undefined or 0)
	 *  @param {bool} regex treat as a regular expression or not
	 *  @param {bool} smart perform smart filtering or not
	 *  @param {bool} caseInsensitive Do case insenstive matching or not
	 *  @memberof DataTable#oApi
	 */
	function _fnFilter( settings, input, force, regex, smart, caseInsensitive )
	{
		var rpSearch = _fnFilterCreateSearch( input, regex, smart, caseInsensitive );
		var prevSearch = settings.oPreviousSearch.sSearch;
		var displayMaster = settings.aiDisplayMaster;
		var display, invalidated, i;
		var filtered = [];
	
		// Need to take account of custom filtering functions - always filter
		if ( DataTable.ext.search.length !== 0 ) {
			force = true;
		}
	
		// Check if any of the rows were invalidated
		invalidated = _fnFilterData( settings );
	
		// If the input is blank - we just want the full data set
		if ( input.length <= 0 ) {
			settings.aiDisplay = displayMaster.slice();
		}
		else {
			// New search - start from the master array
			if ( invalidated ||
				 force ||
				 prevSearch.length > input.length ||
				 input.indexOf(prevSearch) !== 0 ||
				 settings.bSorted // On resort, the display master needs to be
				                  // re-filtered since indexes will have changed
			) {
				settings.aiDisplay = displayMaster.slice();
			}
	
			// Search the display array
			display = settings.aiDisplay;
	
			for ( i=0 ; i<display.length ; i++ ) {
				if ( rpSearch.test( settings.aoData[ display[i] ]._sFilterRow ) ) {
					filtered.push( display[i] );
				}
			}
	
			settings.aiDisplay = filtered;
		}
	}
	
	
	/**
	 * Build a regular expression object suitable for searching a table
	 *  @param {string} sSearch string to search for
	 *  @param {bool} bRegex treat as a regular expression or not
	 *  @param {bool} bSmart perform smart filtering or not
	 *  @param {bool} bCaseInsensitive Do case insensitive matching or not
	 *  @returns {RegExp} constructed object
	 *  @memberof DataTable#oApi
	 */
	function _fnFilterCreateSearch( search, regex, smart, caseInsensitive )
	{
		search = regex ?
			search :
			_fnEscapeRegex( search );
		
		if ( smart ) {
			/* For smart filtering we want to allow the search to work regardless of
			 * word order. We also want double quoted text to be preserved, so word
			 * order is important - a la google. So this is what we want to
			 * generate:
			 * 
			 * ^(?=.*?\bone\b)(?=.*?\btwo three\b)(?=.*?\bfour\b).*$
			 */
			var a = $.map( search.match( /"[^"]+"|[^ ]+/g ) || [''], function ( word ) {
				if ( word.charAt(0) === '"' ) {
					var m = word.match( /^"(.*)"$/ );
					word = m ? m[1] : word;
				}
	
				return word.replace('"', '');
			} );
	
			search = '^(?=.*?'+a.join( ')(?=.*?' )+').*$';
		}
	
		return new RegExp( search, caseInsensitive ? 'i' : '' );
	}
	
	
	/**
	 * Escape a string such that it can be used in a regular expression
	 *  @param {string} sVal string to escape
	 *  @returns {string} escaped string
	 *  @memberof DataTable#oApi
	 */
	var _fnEscapeRegex = DataTable.util.escapeRegex;
	
	var __filter_div = $('<div>')[0];
	var __filter_div_textContent = __filter_div.textContent !== undefined;
	
	// Update the filtering data for each row if needed (by invalidation or first run)
	function _fnFilterData ( settings )
	{
		var columns = settings.aoColumns;
		var column;
		var i, j, ien, jen, filterData, cellData, row;
		var fomatters = DataTable.ext.type.search;
		var wasInvalidated = false;
	
		for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
			row = settings.aoData[i];
	
			if ( ! row._aFilterData ) {
				filterData = [];
	
				for ( j=0, jen=columns.length ; j<jen ; j++ ) {
					column = columns[j];
	
					if ( column.bSearchable ) {
						cellData = _fnGetCellData( settings, i, j, 'filter' );
	
						if ( fomatters[ column.sType ] ) {
							cellData = fomatters[ column.sType ]( cellData );
						}
	
						// Search in DataTables 1.10 is string based. In 1.11 this
						// should be altered to also allow strict type checking.
						if ( cellData === null ) {
							cellData = '';
						}
	
						if ( typeof cellData !== 'string' && cellData.toString ) {
							cellData = cellData.toString();
						}
					}
					else {
						cellData = '';
					}
	
					// If it looks like there is an HTML entity in the string,
					// attempt to decode it so sorting works as expected. Note that
					// we could use a single line of jQuery to do this, but the DOM
					// method used here is much faster http://jsperf.com/html-decode
					if ( cellData.indexOf && cellData.indexOf('&') !== -1 ) {
						__filter_div.innerHTML = cellData;
						cellData = __filter_div_textContent ?
							__filter_div.textContent :
							__filter_div.innerText;
					}
	
					if ( cellData.replace ) {
						cellData = cellData.replace(/[\r\n]/g, '');
					}
	
					filterData.push( cellData );
				}
	
				row._aFilterData = filterData;
				row._sFilterRow = filterData.join('  ');
				wasInvalidated = true;
			}
		}
	
		return wasInvalidated;
	}
	
	
	/**
	 * Convert from the internal Hungarian notation to camelCase for external
	 * interaction
	 *  @param {object} obj Object to convert
	 *  @returns {object} Inverted object
	 *  @memberof DataTable#oApi
	 */
	function _fnSearchToCamel ( obj )
	{
		return {
			search:          obj.sSearch,
			smart:           obj.bSmart,
			regex:           obj.bRegex,
			caseInsensitive: obj.bCaseInsensitive
		};
	}
	
	
	
	/**
	 * Convert from camelCase notation to the internal Hungarian. We could use the
	 * Hungarian convert function here, but this is cleaner
	 *  @param {object} obj Object to convert
	 *  @returns {object} Inverted object
	 *  @memberof DataTable#oApi
	 */
	function _fnSearchToHung ( obj )
	{
		return {
			sSearch:          obj.search,
			bSmart:           obj.smart,
			bRegex:           obj.regex,
			bCaseInsensitive: obj.caseInsensitive
		};
	}
	
	/**
	 * Generate the node required for the info display
	 *  @param {object} oSettings dataTables settings object
	 *  @returns {node} Information element
	 *  @memberof DataTable#oApi
	 */
	function _fnFeatureHtmlInfo ( settings )
	{
		var
			tid = settings.sTableId,
			nodes = settings.aanFeatures.i,
			n = $('<div/>', {
				'class': settings.oClasses.sInfo,
				'id': ! nodes ? tid+'_info' : null
			} );
	
		if ( ! nodes ) {
			// Update display on each draw
			settings.aoDrawCallback.push( {
				"fn": _fnUpdateInfo,
				"sName": "information"
			} );
	
			n
				.attr( 'role', 'status' )
				.attr( 'aria-live', 'polite' );
	
			// Table is described by our info div
			$(settings.nTable).attr( 'aria-describedby', tid+'_info' );
		}
	
		return n[0];
	}
	
	
	/**
	 * Update the information elements in the display
	 *  @param {object} settings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnUpdateInfo ( settings )
	{
		/* Show information about the table */
		var nodes = settings.aanFeatures.i;
		if ( nodes.length === 0 ) {
			return;
		}
	
		var
			lang  = settings.oLanguage,
			start = settings._iDisplayStart+1,
			end   = settings.fnDisplayEnd(),
			max   = settings.fnRecordsTotal(),
			total = settings.fnRecordsDisplay(),
			out   = total ?
				lang.sInfo :
				lang.sInfoEmpty;
	
		if ( total !== max ) {
			/* Record set after filtering */
			out += ' ' + lang.sInfoFiltered;
		}
	
		// Convert the macros
		out += lang.sInfoPostFix;
		out = _fnInfoMacros( settings, out );
	
		var callback = lang.fnInfoCallback;
		if ( callback !== null ) {
			out = callback.call( settings.oInstance,
				settings, start, end, max, total, out
			);
		}
	
		$(nodes).html( out );
	}
	
	
	function _fnInfoMacros ( settings, str )
	{
		// When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
		// internally
		var
			formatter  = settings.fnFormatNumber,
			start      = settings._iDisplayStart+1,
			len        = settings._iDisplayLength,
			vis        = settings.fnRecordsDisplay(),
			all        = len === -1;
	
		return str.
			replace(/_START_/g, formatter.call( settings, start ) ).
			replace(/_END_/g,   formatter.call( settings, settings.fnDisplayEnd() ) ).
			replace(/_MAX_/g,   formatter.call( settings, settings.fnRecordsTotal() ) ).
			replace(/_TOTAL_/g, formatter.call( settings, vis ) ).
			replace(/_PAGE_/g,  formatter.call( settings, all ? 1 : Math.ceil( start / len ) ) ).
			replace(/_PAGES_/g, formatter.call( settings, all ? 1 : Math.ceil( vis / len ) ) );
	}
	
	
	
	/**
	 * Draw the table for the first time, adding all required features
	 *  @param {object} settings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnInitialise ( settings )
	{
		var i, iLen, iAjaxStart=settings.iInitDisplayStart;
		var columns = settings.aoColumns, column;
		var features = settings.oFeatures;
		var deferLoading = settings.bDeferLoading; // value modified by the draw
	
		/* Ensure that the table data is fully initialised */
		if ( ! settings.bInitialised ) {
			setTimeout( function(){ _fnInitialise( settings ); }, 200 );
			return;
		}
	
		/* Show the display HTML options */
		_fnAddOptionsHtml( settings );
	
		/* Build and draw the header / footer for the table */
		_fnBuildHead( settings );
		_fnDrawHead( settings, settings.aoHeader );
		_fnDrawHead( settings, settings.aoFooter );
	
		/* Okay to show that something is going on now */
		_fnProcessingDisplay( settings, true );
	
		/* Calculate sizes for columns */
		if ( features.bAutoWidth ) {
			_fnCalculateColumnWidths( settings );
		}
	
		for ( i=0, iLen=columns.length ; i<iLen ; i++ ) {
			column = columns[i];
	
			if ( column.sWidth ) {
				column.nTh.style.width = _fnStringToCss( column.sWidth );
			}
		}
	
		_fnCallbackFire( settings, null, 'preInit', [settings] );
	
		// If there is default sorting required - let's do it. The sort function
		// will do the drawing for us. Otherwise we draw the table regardless of the
		// Ajax source - this allows the table to look initialised for Ajax sourcing
		// data (show 'loading' message possibly)
		_fnReDraw( settings );
	
		// Server-side processing init complete is done by _fnAjaxUpdateDraw
		var dataSrc = _fnDataSource( settings );
		if ( dataSrc != 'ssp' || deferLoading ) {
			// if there is an ajax source load the data
			if ( dataSrc == 'ajax' ) {
				_fnBuildAjax( settings, [], function(json) {
					var aData = _fnAjaxDataSrc( settings, json );
	
					// Got the data - add it to the table
					for ( i=0 ; i<aData.length ; i++ ) {
						_fnAddData( settings, aData[i] );
					}
	
					// Reset the init display for cookie saving. We've already done
					// a filter, and therefore cleared it before. So we need to make
					// it appear 'fresh'
					settings.iInitDisplayStart = iAjaxStart;
	
					_fnReDraw( settings );
	
					_fnProcessingDisplay( settings, false );
					_fnInitComplete( settings, json );
				}, settings );
			}
			else {
				_fnProcessingDisplay( settings, false );
				_fnInitComplete( settings );
			}
		}
	}
	
	
	/**
	 * Draw the table for the first time, adding all required features
	 *  @param {object} oSettings dataTables settings object
	 *  @param {object} [json] JSON from the server that completed the table, if using Ajax source
	 *    with client-side processing (optional)
	 *  @memberof DataTable#oApi
	 */
	function _fnInitComplete ( settings, json )
	{
		settings._bInitComplete = true;
	
		// When data was added after the initialisation (data or Ajax) we need to
		// calculate the column sizing
		if ( json || settings.oInit.aaData ) {
			_fnAdjustColumnSizing( settings );
		}
	
		_fnCallbackFire( settings, null, 'plugin-init', [settings, json] );
		_fnCallbackFire( settings, 'aoInitComplete', 'init', [settings, json] );
	}
	
	
	function _fnLengthChange ( settings, val )
	{
		var len = parseInt( val, 10 );
		settings._iDisplayLength = len;
	
		_fnLengthOverflow( settings );
	
		// Fire length change event
		_fnCallbackFire( settings, null, 'length', [settings, len] );
	}
	
	
	/**
	 * Generate the node required for user display length changing
	 *  @param {object} settings dataTables settings object
	 *  @returns {node} Display length feature node
	 *  @memberof DataTable#oApi
	 */
	function _fnFeatureHtmlLength ( settings )
	{
		var
			classes  = settings.oClasses,
			tableId  = settings.sTableId,
			menu     = settings.aLengthMenu,
			d2       = $.isArray( menu[0] ),
			lengths  = d2 ? menu[0] : menu,
			language = d2 ? menu[1] : menu;
	
		var select = $('<select/>', {
			'name':          tableId+'_length',
			'aria-controls': tableId,
			'class':         classes.sLengthSelect
		} );
	
		for ( var i=0, ien=lengths.length ; i<ien ; i++ ) {
			select[0][ i ] = new Option( language[i], lengths[i] );
		}
	
		var div = $('<div><label/></div>').addClass( classes.sLength );
		if ( ! settings.aanFeatures.l ) {
			div[0].id = tableId+'_length';
		}
	
		div.children().append(
			settings.oLanguage.sLengthMenu.replace( '_MENU_', select[0].outerHTML )
		);
	
		// Can't use `select` variable as user might provide their own and the
		// reference is broken by the use of outerHTML
		$('select', div)
			.val( settings._iDisplayLength )
			.on( 'change.DT', function(e) {
				_fnLengthChange( settings, $(this).val() );
				_fnDraw( settings );
			} );
	
		// Update node value whenever anything changes the table's length
		$(settings.nTable).on( 'length.dt.DT', function (e, s, len) {
			if ( settings === s ) {
				$('select', div).val( len );
			}
		} );
	
		return div[0];
	}
	
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Note that most of the paging logic is done in
	 * DataTable.ext.pager
	 */
	
	/**
	 * Generate the node required for default pagination
	 *  @param {object} oSettings dataTables settings object
	 *  @returns {node} Pagination feature node
	 *  @memberof DataTable#oApi
	 */
	function _fnFeatureHtmlPaginate ( settings )
	{
		var
			type   = settings.sPaginationType,
			plugin = DataTable.ext.pager[ type ],
			modern = typeof plugin === 'function',
			redraw = function( settings ) {
				_fnDraw( settings );
			},
			node = $('<div/>').addClass( settings.oClasses.sPaging + type )[0],
			features = settings.aanFeatures;
	
		if ( ! modern ) {
			plugin.fnInit( settings, node, redraw );
		}
	
		/* Add a draw callback for the pagination on first instance, to update the paging display */
		if ( ! features.p )
		{
			node.id = settings.sTableId+'_paginate';
	
			settings.aoDrawCallback.push( {
				"fn": function( settings ) {
					if ( modern ) {
						var
							start      = settings._iDisplayStart,
							len        = settings._iDisplayLength,
							visRecords = settings.fnRecordsDisplay(),
							all        = len === -1,
							page = all ? 0 : Math.ceil( start / len ),
							pages = all ? 1 : Math.ceil( visRecords / len ),
							buttons = plugin(page, pages),
							i, ien;
	
						for ( i=0, ien=features.p.length ; i<ien ; i++ ) {
							_fnRenderer( settings, 'pageButton' )(
								settings, features.p[i], i, buttons, page, pages
							);
						}
					}
					else {
						plugin.fnUpdate( settings, redraw );
					}
				},
				"sName": "pagination"
			} );
		}
	
		return node;
	}
	
	
	/**
	 * Alter the display settings to change the page
	 *  @param {object} settings DataTables settings object
	 *  @param {string|int} action Paging action to take: "first", "previous",
	 *    "next" or "last" or page number to jump to (integer)
	 *  @param [bool] redraw Automatically draw the update or not
	 *  @returns {bool} true page has changed, false - no change
	 *  @memberof DataTable#oApi
	 */
	function _fnPageChange ( settings, action, redraw )
	{
		var
			start     = settings._iDisplayStart,
			len       = settings._iDisplayLength,
			records   = settings.fnRecordsDisplay();
	
		if ( records === 0 || len === -1 )
		{
			start = 0;
		}
		else if ( typeof action === "number" )
		{
			start = action * len;
	
			if ( start > records )
			{
				start = 0;
			}
		}
		else if ( action == "first" )
		{
			start = 0;
		}
		else if ( action == "previous" )
		{
			start = len >= 0 ?
				start - len :
				0;
	
			if ( start < 0 )
			{
			  start = 0;
			}
		}
		else if ( action == "next" )
		{
			if ( start + len < records )
			{
				start += len;
			}
		}
		else if ( action == "last" )
		{
			start = Math.floor( (records-1) / len) * len;
		}
		else
		{
			_fnLog( settings, 0, "Unknown paging action: "+action, 5 );
		}
	
		var changed = settings._iDisplayStart !== start;
		settings._iDisplayStart = start;
	
		if ( changed ) {
			_fnCallbackFire( settings, null, 'page', [settings] );
	
			if ( redraw ) {
				_fnDraw( settings );
			}
		}
	
		return changed;
	}
	
	
	
	/**
	 * Generate the node required for the processing node
	 *  @param {object} settings dataTables settings object
	 *  @returns {node} Processing element
	 *  @memberof DataTable#oApi
	 */
	function _fnFeatureHtmlProcessing ( settings )
	{
		return $('<div/>', {
				'id': ! settings.aanFeatures.r ? settings.sTableId+'_processing' : null,
				'class': settings.oClasses.sProcessing
			} )
			.html( settings.oLanguage.sProcessing )
			.insertBefore( settings.nTable )[0];
	}
	
	
	/**
	 * Display or hide the processing indicator
	 *  @param {object} settings dataTables settings object
	 *  @param {bool} show Show the processing indicator (true) or not (false)
	 *  @memberof DataTable#oApi
	 */
	function _fnProcessingDisplay ( settings, show )
	{
		if ( settings.oFeatures.bProcessing ) {
			$(settings.aanFeatures.r).css( 'display', show ? 'block' : 'none' );
		}
	
		_fnCallbackFire( settings, null, 'processing', [settings, show] );
	}
	
	/**
	 * Add any control elements for the table - specifically scrolling
	 *  @param {object} settings dataTables settings object
	 *  @returns {node} Node to add to the DOM
	 *  @memberof DataTable#oApi
	 */
	function _fnFeatureHtmlTable ( settings )
	{
		var table = $(settings.nTable);
	
		// Add the ARIA grid role to the table
		table.attr( 'role', 'grid' );
	
		// Scrolling from here on in
		var scroll = settings.oScroll;
	
		if ( scroll.sX === '' && scroll.sY === '' ) {
			return settings.nTable;
		}
	
		var scrollX = scroll.sX;
		var scrollY = scroll.sY;
		var classes = settings.oClasses;
		var caption = table.children('caption');
		var captionSide = caption.length ? caption[0]._captionSide : null;
		var headerClone = $( table[0].cloneNode(false) );
		var footerClone = $( table[0].cloneNode(false) );
		var footer = table.children('tfoot');
		var _div = '<div/>';
		var size = function ( s ) {
			return !s ? null : _fnStringToCss( s );
		};
	
		if ( ! footer.length ) {
			footer = null;
		}
	
		/*
		 * The HTML structure that we want to generate in this function is:
		 *  div - scroller
		 *    div - scroll head
		 *      div - scroll head inner
		 *        table - scroll head table
		 *          thead - thead
		 *    div - scroll body
		 *      table - table (master table)
		 *        thead - thead clone for sizing
		 *        tbody - tbody
		 *    div - scroll foot
		 *      div - scroll foot inner
		 *        table - scroll foot table
		 *          tfoot - tfoot
		 */
		var scroller = $( _div, { 'class': classes.sScrollWrapper } )
			.append(
				$(_div, { 'class': classes.sScrollHead } )
					.css( {
						overflow: 'hidden',
						position: 'relative',
						border: 0,
						width: scrollX ? size(scrollX) : '100%'
					} )
					.append(
						$(_div, { 'class': classes.sScrollHeadInner } )
							.css( {
								'box-sizing': 'content-box',
								width: scroll.sXInner || '100%'
							} )
							.append(
								headerClone
									.removeAttr('id')
									.css( 'margin-left', 0 )
									.append( captionSide === 'top' ? caption : null )
									.append(
										table.children('thead')
									)
							)
					)
			)
			.append(
				$(_div, { 'class': classes.sScrollBody } )
					.css( {
						position: 'relative',
						overflow: 'auto',
						width: size( scrollX )
					} )
					.append( table )
			);
	
		if ( footer ) {
			scroller.append(
				$(_div, { 'class': classes.sScrollFoot } )
					.css( {
						overflow: 'hidden',
						border: 0,
						width: scrollX ? size(scrollX) : '100%'
					} )
					.append(
						$(_div, { 'class': classes.sScrollFootInner } )
							.append(
								footerClone
									.removeAttr('id')
									.css( 'margin-left', 0 )
									.append( captionSide === 'bottom' ? caption : null )
									.append(
										table.children('tfoot')
									)
							)
					)
			);
		}
	
		var children = scroller.children();
		var scrollHead = children[0];
		var scrollBody = children[1];
		var scrollFoot = footer ? children[2] : null;
	
		// When the body is scrolled, then we also want to scroll the headers
		if ( scrollX ) {
			$(scrollBody).on( 'scroll.DT', function (e) {
				var scrollLeft = this.scrollLeft;
	
				scrollHead.scrollLeft = scrollLeft;
	
				if ( footer ) {
					scrollFoot.scrollLeft = scrollLeft;
				}
			} );
		}
	
		$(scrollBody).css(
			scrollY && scroll.bCollapse ? 'max-height' : 'height', 
			scrollY
		);
	
		settings.nScrollHead = scrollHead;
		settings.nScrollBody = scrollBody;
		settings.nScrollFoot = scrollFoot;
	
		// On redraw - align columns
		settings.aoDrawCallback.push( {
			"fn": _fnScrollDraw,
			"sName": "scrolling"
		} );
	
		return scroller[0];
	}
	
	
	
	/**
	 * Update the header, footer and body tables for resizing - i.e. column
	 * alignment.
	 *
	 * Welcome to the most horrible function DataTables. The process that this
	 * function follows is basically:
	 *   1. Re-create the table inside the scrolling div
	 *   2. Take live measurements from the DOM
	 *   3. Apply the measurements to align the columns
	 *   4. Clean up
	 *
	 *  @param {object} settings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnScrollDraw ( settings )
	{
		// Given that this is such a monster function, a lot of variables are use
		// to try and keep the minimised size as small as possible
		var
			scroll         = settings.oScroll,
			scrollX        = scroll.sX,
			scrollXInner   = scroll.sXInner,
			scrollY        = scroll.sY,
			barWidth       = scroll.iBarWidth,
			divHeader      = $(settings.nScrollHead),
			divHeaderStyle = divHeader[0].style,
			divHeaderInner = divHeader.children('div'),
			divHeaderInnerStyle = divHeaderInner[0].style,
			divHeaderTable = divHeaderInner.children('table'),
			divBodyEl      = settings.nScrollBody,
			divBody        = $(divBodyEl),
			divBodyStyle   = divBodyEl.style,
			divFooter      = $(settings.nScrollFoot),
			divFooterInner = divFooter.children('div'),
			divFooterTable = divFooterInner.children('table'),
			header         = $(settings.nTHead),
			table          = $(settings.nTable),
			tableEl        = table[0],
			tableStyle     = tableEl.style,
			footer         = settings.nTFoot ? $(settings.nTFoot) : null,
			browser        = settings.oBrowser,
			ie67           = browser.bScrollOversize,
			dtHeaderCells  = _pluck( settings.aoColumns, 'nTh' ),
			headerTrgEls, footerTrgEls,
			headerSrcEls, footerSrcEls,
			headerCopy, footerCopy,
			headerWidths=[], footerWidths=[],
			headerContent=[], footerContent=[],
			idx, correction, sanityWidth,
			zeroOut = function(nSizer) {
				var style = nSizer.style;
				style.paddingTop = "0";
				style.paddingBottom = "0";
				style.borderTopWidth = "0";
				style.borderBottomWidth = "0";
				style.height = 0;
			};
	
		// If the scrollbar visibility has changed from the last draw, we need to
		// adjust the column sizes as the table width will have changed to account
		// for the scrollbar
		var scrollBarVis = divBodyEl.scrollHeight > divBodyEl.clientHeight;
		
		if ( settings.scrollBarVis !== scrollBarVis && settings.scrollBarVis !== undefined ) {
			settings.scrollBarVis = scrollBarVis;
			_fnAdjustColumnSizing( settings );
			return; // adjust column sizing will call this function again
		}
		else {
			settings.scrollBarVis = scrollBarVis;
		}
	
		/*
		 * 1. Re-create the table inside the scrolling div
		 */
	
		// Remove the old minimised thead and tfoot elements in the inner table
		table.children('thead, tfoot').remove();
	
		if ( footer ) {
			footerCopy = footer.clone().prependTo( table );
			footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized
			footerSrcEls = footerCopy.find('tr');
		}
	
		// Clone the current header and footer elements and then place it into the inner table
		headerCopy = header.clone().prependTo( table );
		headerTrgEls = header.find('tr'); // original header is in its own table
		headerSrcEls = headerCopy.find('tr');
		headerCopy.find('th, td').removeAttr('tabindex');
	
	
		/*
		 * 2. Take live measurements from the DOM - do not alter the DOM itself!
		 */
	
		// Remove old sizing and apply the calculated column widths
		// Get the unique column headers in the newly created (cloned) header. We want to apply the
		// calculated sizes to this header
		if ( ! scrollX )
		{
			divBodyStyle.width = '100%';
			divHeader[0].style.width = '100%';
		}
	
		$.each( _fnGetUniqueThs( settings, headerCopy ), function ( i, el ) {
			idx = _fnVisibleToColumnIndex( settings, i );
			el.style.width = settings.aoColumns[idx].sWidth;
		} );
	
		if ( footer ) {
			_fnApplyToChildren( function(n) {
				n.style.width = "";
			}, footerSrcEls );
		}
	
		// Size the table as a whole
		sanityWidth = table.outerWidth();
		if ( scrollX === "" ) {
			// No x scrolling
			tableStyle.width = "100%";
	
			// IE7 will make the width of the table when 100% include the scrollbar
			// - which is shouldn't. When there is a scrollbar we need to take this
			// into account.
			if ( ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight ||
				divBody.css('overflow-y') == "scroll")
			) {
				tableStyle.width = _fnStringToCss( table.outerWidth() - barWidth);
			}
	
			// Recalculate the sanity width
			sanityWidth = table.outerWidth();
		}
		else if ( scrollXInner !== "" ) {
			// legacy x scroll inner has been given - use it
			tableStyle.width = _fnStringToCss(scrollXInner);
	
			// Recalculate the sanity width
			sanityWidth = table.outerWidth();
		}
	
		// Hidden header should have zero height, so remove padding and borders. Then
		// set the width based on the real headers
	
		// Apply all styles in one pass
		_fnApplyToChildren( zeroOut, headerSrcEls );
	
		// Read all widths in next pass
		_fnApplyToChildren( function(nSizer) {
			headerContent.push( nSizer.innerHTML );
			headerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
		}, headerSrcEls );
	
		// Apply all widths in final pass
		_fnApplyToChildren( function(nToSize, i) {
			// Only apply widths to the DataTables detected header cells - this
			// prevents complex headers from having contradictory sizes applied
			if ( $.inArray( nToSize, dtHeaderCells ) !== -1 ) {
				nToSize.style.width = headerWidths[i];
			}
		}, headerTrgEls );
	
		$(headerSrcEls).height(0);
	
		/* Same again with the footer if we have one */
		if ( footer )
		{
			_fnApplyToChildren( zeroOut, footerSrcEls );
	
			_fnApplyToChildren( function(nSizer) {
				footerContent.push( nSizer.innerHTML );
				footerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
			}, footerSrcEls );
	
			_fnApplyToChildren( function(nToSize, i) {
				nToSize.style.width = footerWidths[i];
			}, footerTrgEls );
	
			$(footerSrcEls).height(0);
		}
	
	
		/*
		 * 3. Apply the measurements
		 */
	
		// "Hide" the header and footer that we used for the sizing. We need to keep
		// the content of the cell so that the width applied to the header and body
		// both match, but we want to hide it completely. We want to also fix their
		// width to what they currently are
		_fnApplyToChildren( function(nSizer, i) {
			nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+headerContent[i]+'</div>';
			nSizer.style.width = headerWidths[i];
		}, headerSrcEls );
	
		if ( footer )
		{
			_fnApplyToChildren( function(nSizer, i) {
				nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+footerContent[i]+'</div>';
				nSizer.style.width = footerWidths[i];
			}, footerSrcEls );
		}
	
		// Sanity check that the table is of a sensible width. If not then we are going to get
		// misalignment - try to prevent this by not allowing the table to shrink below its min width
		if ( table.outerWidth() < sanityWidth )
		{
			// The min width depends upon if we have a vertical scrollbar visible or not */
			correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight ||
				divBody.css('overflow-y') == "scroll")) ?
					sanityWidth+barWidth :
					sanityWidth;
	
			// IE6/7 are a law unto themselves...
			if ( ie67 && (divBodyEl.scrollHeight >
				divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")
			) {
				tableStyle.width = _fnStringToCss( correction-barWidth );
			}
	
			// And give the user a warning that we've stopped the table getting too small
			if ( scrollX === "" || scrollXInner !== "" ) {
				_fnLog( settings, 1, 'Possible column misalignment', 6 );
			}
		}
		else
		{
			correction = '100%';
		}
	
		// Apply to the container elements
		divBodyStyle.width = _fnStringToCss( correction );
		divHeaderStyle.width = _fnStringToCss( correction );
	
		if ( footer ) {
			settings.nScrollFoot.style.width = _fnStringToCss( correction );
		}
	
	
		/*
		 * 4. Clean up
		 */
		if ( ! scrollY ) {
			/* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
			 * the scrollbar height from the visible display, rather than adding it on. We need to
			 * set the height in order to sort this. Don't want to do it in any other browsers.
			 */
			if ( ie67 ) {
				divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+barWidth );
			}
		}
	
		/* Finally set the width's of the header and footer tables */
		var iOuterWidth = table.outerWidth();
		divHeaderTable[0].style.width = _fnStringToCss( iOuterWidth );
		divHeaderInnerStyle.width = _fnStringToCss( iOuterWidth );
	
		// Figure out if there are scrollbar present - if so then we need a the header and footer to
		// provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
		var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll";
		var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right' );
		divHeaderInnerStyle[ padding ] = bScrolling ? barWidth+"px" : "0px";
	
		if ( footer ) {
			divFooterTable[0].style.width = _fnStringToCss( iOuterWidth );
			divFooterInner[0].style.width = _fnStringToCss( iOuterWidth );
			divFooterInner[0].style[padding] = bScrolling ? barWidth+"px" : "0px";
		}
	
		// Correct DOM ordering for colgroup - comes before the thead
		table.children('colgroup').insertBefore( table.children('thead') );
	
		/* Adjust the position of the header in case we loose the y-scrollbar */
		divBody.scroll();
	
		// If sorting or filtering has occurred, jump the scrolling back to the top
		// only if we aren't holding the position
		if ( (settings.bSorted || settings.bFiltered) && ! settings._drawHold ) {
			divBodyEl.scrollTop = 0;
		}
	}
	
	
	
	/**
	 * Apply a given function to the display child nodes of an element array (typically
	 * TD children of TR rows
	 *  @param {function} fn Method to apply to the objects
	 *  @param array {nodes} an1 List of elements to look through for display children
	 *  @param array {nodes} an2 Another list (identical structure to the first) - optional
	 *  @memberof DataTable#oApi
	 */
	function _fnApplyToChildren( fn, an1, an2 )
	{
		var index=0, i=0, iLen=an1.length;
		var nNode1, nNode2;
	
		while ( i < iLen ) {
			nNode1 = an1[i].firstChild;
			nNode2 = an2 ? an2[i].firstChild : null;
	
			while ( nNode1 ) {
				if ( nNode1.nodeType === 1 ) {
					if ( an2 ) {
						fn( nNode1, nNode2, index );
					}
					else {
						fn( nNode1, index );
					}
	
					index++;
				}
	
				nNode1 = nNode1.nextSibling;
				nNode2 = an2 ? nNode2.nextSibling : null;
			}
	
			i++;
		}
	}
	
	
	
	var __re_html_remove = /<.*?>/g;
	
	
	/**
	 * Calculate the width of columns for the table
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnCalculateColumnWidths ( oSettings )
	{
		var
			table = oSettings.nTable,
			columns = oSettings.aoColumns,
			scroll = oSettings.oScroll,
			scrollY = scroll.sY,
			scrollX = scroll.sX,
			scrollXInner = scroll.sXInner,
			columnCount = columns.length,
			visibleColumns = _fnGetColumns( oSettings, 'bVisible' ),
			headerCells = $('th', oSettings.nTHead),
			tableWidthAttr = table.getAttribute('width'), // from DOM element
			tableContainer = table.parentNode,
			userInputs = false,
			i, column, columnIdx, width, outerWidth,
			browser = oSettings.oBrowser,
			ie67 = browser.bScrollOversize;
	
		var styleWidth = table.style.width;
		if ( styleWidth && styleWidth.indexOf('%') !== -1 ) {
			tableWidthAttr = styleWidth;
		}
	
		/* Convert any user input sizes into pixel sizes */
		for ( i=0 ; i<visibleColumns.length ; i++ ) {
			column = columns[ visibleColumns[i] ];
	
			if ( column.sWidth !== null ) {
				column.sWidth = _fnConvertToWidth( column.sWidthOrig, tableContainer );
	
				userInputs = true;
			}
		}
	
		/* If the number of columns in the DOM equals the number that we have to
		 * process in DataTables, then we can use the offsets that are created by
		 * the web- browser. No custom sizes can be set in order for this to happen,
		 * nor scrolling used
		 */
		if ( ie67 || ! userInputs && ! scrollX && ! scrollY &&
		     columnCount == _fnVisbleColumns( oSettings ) &&
		     columnCount == headerCells.length
		) {
			for ( i=0 ; i<columnCount ; i++ ) {
				var colIdx = _fnVisibleToColumnIndex( oSettings, i );
	
				if ( colIdx !== null ) {
					columns[ colIdx ].sWidth = _fnStringToCss( headerCells.eq(i).width() );
				}
			}
		}
		else
		{
			// Otherwise construct a single row, worst case, table with the widest
			// node in the data, assign any user defined widths, then insert it into
			// the DOM and allow the browser to do all the hard work of calculating
			// table widths
			var tmpTable = $(table).clone() // don't use cloneNode - IE8 will remove events on the main table
				.css( 'visibility', 'hidden' )
				.removeAttr( 'id' );
	
			// Clean up the table body
			tmpTable.find('tbody tr').remove();
			var tr = $('<tr/>').appendTo( tmpTable.find('tbody') );
	
			// Clone the table header and footer - we can't use the header / footer
			// from the cloned table, since if scrolling is active, the table's
			// real header and footer are contained in different table tags
			tmpTable.find('thead, tfoot').remove();
			tmpTable
				.append( $(oSettings.nTHead).clone() )
				.append( $(oSettings.nTFoot).clone() );
	
			// Remove any assigned widths from the footer (from scrolling)
			tmpTable.find('tfoot th, tfoot td').css('width', '');
	
			// Apply custom sizing to the cloned header
			headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0] );
	
			for ( i=0 ; i<visibleColumns.length ; i++ ) {
				column = columns[ visibleColumns[i] ];
	
				headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
					_fnStringToCss( column.sWidthOrig ) :
					'';
	
				// For scrollX we need to force the column width otherwise the
				// browser will collapse it. If this width is smaller than the
				// width the column requires, then it will have no effect
				if ( column.sWidthOrig && scrollX ) {
					$( headerCells[i] ).append( $('<div/>').css( {
						width: column.sWidthOrig,
						margin: 0,
						padding: 0,
						border: 0,
						height: 1
					} ) );
				}
			}
	
			// Find the widest cell for each column and put it into the table
			if ( oSettings.aoData.length ) {
				for ( i=0 ; i<visibleColumns.length ; i++ ) {
					columnIdx = visibleColumns[i];
					column = columns[ columnIdx ];
	
					$( _fnGetWidestNode( oSettings, columnIdx ) )
						.clone( false )
						.append( column.sContentPadding )
						.appendTo( tr );
				}
			}
	
			// Tidy the temporary table - remove name attributes so there aren't
			// duplicated in the dom (radio elements for example)
			$('[name]', tmpTable).removeAttr('name');
	
			// Table has been built, attach to the document so we can work with it.
			// A holding element is used, positioned at the top of the container
			// with minimal height, so it has no effect on if the container scrolls
			// or not. Otherwise it might trigger scrolling when it actually isn't
			// needed
			var holder = $('<div/>').css( scrollX || scrollY ?
					{
						position: 'absolute',
						top: 0,
						left: 0,
						height: 1,
						right: 0,
						overflow: 'hidden'
					} :
					{}
				)
				.append( tmpTable )
				.appendTo( tableContainer );
	
			// When scrolling (X or Y) we want to set the width of the table as 
			// appropriate. However, when not scrolling leave the table width as it
			// is. This results in slightly different, but I think correct behaviour
			if ( scrollX && scrollXInner ) {
				tmpTable.width( scrollXInner );
			}
			else if ( scrollX ) {
				tmpTable.css( 'width', 'auto' );
				tmpTable.removeAttr('width');
	
				// If there is no width attribute or style, then allow the table to
				// collapse
				if ( tmpTable.width() < tableContainer.clientWidth && tableWidthAttr ) {
					tmpTable.width( tableContainer.clientWidth );
				}
			}
			else if ( scrollY ) {
				tmpTable.width( tableContainer.clientWidth );
			}
			else if ( tableWidthAttr ) {
				tmpTable.width( tableWidthAttr );
			}
	
			// Get the width of each column in the constructed table - we need to
			// know the inner width (so it can be assigned to the other table's
			// cells) and the outer width so we can calculate the full width of the
			// table. This is safe since DataTables requires a unique cell for each
			// column, but if ever a header can span multiple columns, this will
			// need to be modified.
			var total = 0;
			for ( i=0 ; i<visibleColumns.length ; i++ ) {
				var cell = $(headerCells[i]);
				var border = cell.outerWidth() - cell.width();
	
				// Use getBounding... where possible (not IE8-) because it can give
				// sub-pixel accuracy, which we then want to round up!
				var bounding = browser.bBounding ?
					Math.ceil( headerCells[i].getBoundingClientRect().width ) :
					cell.outerWidth();
	
				// Total is tracked to remove any sub-pixel errors as the outerWidth
				// of the table might not equal the total given here (IE!).
				total += bounding;
	
				// Width for each column to use
				columns[ visibleColumns[i] ].sWidth = _fnStringToCss( bounding - border );
			}
	
			table.style.width = _fnStringToCss( total );
	
			// Finished with the table - ditch it
			holder.remove();
		}
	
		// If there is a width attr, we want to attach an event listener which
		// allows the table sizing to automatically adjust when the window is
		// resized. Use the width attr rather than CSS, since we can't know if the
		// CSS is a relative value or absolute - DOM read is always px.
		if ( tableWidthAttr ) {
			table.style.width = _fnStringToCss( tableWidthAttr );
		}
	
		if ( (tableWidthAttr || scrollX) && ! oSettings._reszEvt ) {
			var bindResize = function () {
				$(window).on('resize.DT-'+oSettings.sInstance, _fnThrottle( function () {
					_fnAdjustColumnSizing( oSettings );
				} ) );
			};
	
			// IE6/7 will crash if we bind a resize event handler on page load.
			// To be removed in 1.11 which drops IE6/7 support
			if ( ie67 ) {
				setTimeout( bindResize, 1000 );
			}
			else {
				bindResize();
			}
	
			oSettings._reszEvt = true;
		}
	}
	
	
	/**
	 * Throttle the calls to a function. Arguments and context are maintained for
	 * the throttled function
	 *  @param {function} fn Function to be called
	 *  @param {int} [freq=200] call frequency in mS
	 *  @returns {function} wrapped function
	 *  @memberof DataTable#oApi
	 */
	var _fnThrottle = DataTable.util.throttle;
	
	
	/**
	 * Convert a CSS unit width to pixels (e.g. 2em)
	 *  @param {string} width width to be converted
	 *  @param {node} parent parent to get the with for (required for relative widths) - optional
	 *  @returns {int} width in pixels
	 *  @memberof DataTable#oApi
	 */
	function _fnConvertToWidth ( width, parent )
	{
		if ( ! width ) {
			return 0;
		}
	
		var n = $('<div/>')
			.css( 'width', _fnStringToCss( width ) )
			.appendTo( parent || document.body );
	
		var val = n[0].offsetWidth;
		n.remove();
	
		return val;
	}
	
	
	/**
	 * Get the widest node
	 *  @param {object} settings dataTables settings object
	 *  @param {int} colIdx column of interest
	 *  @returns {node} widest table node
	 *  @memberof DataTable#oApi
	 */
	function _fnGetWidestNode( settings, colIdx )
	{
		var idx = _fnGetMaxLenString( settings, colIdx );
		if ( idx < 0 ) {
			return null;
		}
	
		var data = settings.aoData[ idx ];
		return ! data.nTr ? // Might not have been created when deferred rendering
			$('<td/>').html( _fnGetCellData( settings, idx, colIdx, 'display' ) )[0] :
			data.anCells[ colIdx ];
	}
	
	
	/**
	 * Get the maximum strlen for each data column
	 *  @param {object} settings dataTables settings object
	 *  @param {int} colIdx column of interest
	 *  @returns {string} max string length for each column
	 *  @memberof DataTable#oApi
	 */
	function _fnGetMaxLenString( settings, colIdx )
	{
		var s, max=-1, maxIdx = -1;
	
		for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
			s = _fnGetCellData( settings, i, colIdx, 'display' )+'';
			s = s.replace( __re_html_remove, '' );
			s = s.replace( /&nbsp;/g, ' ' );
	
			if ( s.length > max ) {
				max = s.length;
				maxIdx = i;
			}
		}
	
		return maxIdx;
	}
	
	
	/**
	 * Append a CSS unit (only if required) to a string
	 *  @param {string} value to css-ify
	 *  @returns {string} value with css unit
	 *  @memberof DataTable#oApi
	 */
	function _fnStringToCss( s )
	{
		if ( s === null ) {
			return '0px';
		}
	
		if ( typeof s == 'number' ) {
			return s < 0 ?
				'0px' :
				s+'px';
		}
	
		// Check it has a unit character already
		return s.match(/\d$/) ?
			s+'px' :
			s;
	}
	
	
	
	function _fnSortFlatten ( settings )
	{
		var
			i, iLen, k, kLen,
			aSort = [],
			aiOrig = [],
			aoColumns = settings.aoColumns,
			aDataSort, iCol, sType, srcCol,
			fixed = settings.aaSortingFixed,
			fixedObj = $.isPlainObject( fixed ),
			nestedSort = [],
			add = function ( a ) {
				if ( a.length && ! $.isArray( a[0] ) ) {
					// 1D array
					nestedSort.push( a );
				}
				else {
					// 2D array
					$.merge( nestedSort, a );
				}
			};
	
		// Build the sort array, with pre-fix and post-fix options if they have been
		// specified
		if ( $.isArray( fixed ) ) {
			add( fixed );
		}
	
		if ( fixedObj && fixed.pre ) {
			add( fixed.pre );
		}
	
		add( settings.aaSorting );
	
		if (fixedObj && fixed.post ) {
			add( fixed.post );
		}
	
		for ( i=0 ; i<nestedSort.length ; i++ )
		{
			srcCol = nestedSort[i][0];
			aDataSort = aoColumns[ srcCol ].aDataSort;
	
			for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ )
			{
				iCol = aDataSort[k];
				sType = aoColumns[ iCol ].sType || 'string';
	
				if ( nestedSort[i]._idx === undefined ) {
					nestedSort[i]._idx = $.inArray( nestedSort[i][1], aoColumns[iCol].asSorting );
				}
	
				aSort.push( {
					src:       srcCol,
					col:       iCol,
					dir:       nestedSort[i][1],
					index:     nestedSort[i]._idx,
					type:      sType,
					formatter: DataTable.ext.type.order[ sType+"-pre" ]
				} );
			}
		}
	
		return aSort;
	}
	
	/**
	 * Change the order of the table
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 *  @todo This really needs split up!
	 */
	function _fnSort ( oSettings )
	{
		var
			i, ien, iLen, j, jLen, k, kLen,
			sDataType, nTh,
			aiOrig = [],
			oExtSort = DataTable.ext.type.order,
			aoData = oSettings.aoData,
			aoColumns = oSettings.aoColumns,
			aDataSort, data, iCol, sType, oSort,
			formatters = 0,
			sortCol,
			displayMaster = oSettings.aiDisplayMaster,
			aSort;
	
		// Resolve any column types that are unknown due to addition or invalidation
		// @todo Can this be moved into a 'data-ready' handler which is called when
		//   data is going to be used in the table?
		_fnColumnTypes( oSettings );
	
		aSort = _fnSortFlatten( oSettings );
	
		for ( i=0, ien=aSort.length ; i<ien ; i++ ) {
			sortCol = aSort[i];
	
			// Track if we can use the fast sort algorithm
			if ( sortCol.formatter ) {
				formatters++;
			}
	
			// Load the data needed for the sort, for each cell
			_fnSortData( oSettings, sortCol.col );
		}
	
		/* No sorting required if server-side or no sorting array */
		if ( _fnDataSource( oSettings ) != 'ssp' && aSort.length !== 0 )
		{
			// Create a value - key array of the current row positions such that we can use their
			// current position during the sort, if values match, in order to perform stable sorting
			for ( i=0, iLen=displayMaster.length ; i<iLen ; i++ ) {
				aiOrig[ displayMaster[i] ] = i;
			}
	
			/* Do the sort - here we want multi-column sorting based on a given data source (column)
			 * and sorting function (from oSort) in a certain direction. It's reasonably complex to
			 * follow on it's own, but this is what we want (example two column sorting):
			 *  fnLocalSorting = function(a,b){
			 *    var iTest;
			 *    iTest = oSort['string-asc']('data11', 'data12');
			 *      if (iTest !== 0)
			 *        return iTest;
			 *    iTest = oSort['numeric-desc']('data21', 'data22');
			 *    if (iTest !== 0)
			 *      return iTest;
			 *    return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
			 *  }
			 * Basically we have a test for each sorting column, if the data in that column is equal,
			 * test the next column. If all columns match, then we use a numeric sort on the row
			 * positions in the original data array to provide a stable sort.
			 *
			 * Note - I know it seems excessive to have two sorting methods, but the first is around
			 * 15% faster, so the second is only maintained for backwards compatibility with sorting
			 * methods which do not have a pre-sort formatting function.
			 */
			if ( formatters === aSort.length ) {
				// All sort types have formatting functions
				displayMaster.sort( function ( a, b ) {
					var
						x, y, k, test, sort,
						len=aSort.length,
						dataA = aoData[a]._aSortData,
						dataB = aoData[b]._aSortData;
	
					for ( k=0 ; k<len ; k++ ) {
						sort = aSort[k];
	
						x = dataA[ sort.col ];
						y = dataB[ sort.col ];
	
						test = x<y ? -1 : x>y ? 1 : 0;
						if ( test !== 0 ) {
							return sort.dir === 'asc' ? test : -test;
						}
					}
	
					x = aiOrig[a];
					y = aiOrig[b];
					return x<y ? -1 : x>y ? 1 : 0;
				} );
			}
			else {
				// Depreciated - remove in 1.11 (providing a plug-in option)
				// Not all sort types have formatting methods, so we have to call their sorting
				// methods.
				displayMaster.sort( function ( a, b ) {
					var
						x, y, k, l, test, sort, fn,
						len=aSort.length,
						dataA = aoData[a]._aSortData,
						dataB = aoData[b]._aSortData;
	
					for ( k=0 ; k<len ; k++ ) {
						sort = aSort[k];
	
						x = dataA[ sort.col ];
						y = dataB[ sort.col ];
	
						fn = oExtSort[ sort.type+"-"+sort.dir ] || oExtSort[ "string-"+sort.dir ];
						test = fn( x, y );
						if ( test !== 0 ) {
							return test;
						}
					}
	
					x = aiOrig[a];
					y = aiOrig[b];
					return x<y ? -1 : x>y ? 1 : 0;
				} );
			}
		}
	
		/* Tell the draw function that we have sorted the data */
		oSettings.bSorted = true;
	}
	
	
	function _fnSortAria ( settings )
	{
		var label;
		var nextSort;
		var columns = settings.aoColumns;
		var aSort = _fnSortFlatten( settings );
		var oAria = settings.oLanguage.oAria;
	
		// ARIA attributes - need to loop all columns, to update all (removing old
		// attributes as needed)
		for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
		{
			var col = columns[i];
			var asSorting = col.asSorting;
			var sTitle = col.sTitle.replace( /<.*?>/g, "" );
			var th = col.nTh;
	
			// IE7 is throwing an error when setting these properties with jQuery's
			// attr() and removeAttr() methods...
			th.removeAttribute('aria-sort');
	
			/* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
			if ( col.bSortable ) {
				if ( aSort.length > 0 && aSort[0].col == i ) {
					th.setAttribute('aria-sort', aSort[0].dir=="asc" ? "ascending" : "descending" );
					nextSort = asSorting[ aSort[0].index+1 ] || asSorting[0];
				}
				else {
					nextSort = asSorting[0];
				}
	
				label = sTitle + ( nextSort === "asc" ?
					oAria.sSortAscending :
					oAria.sSortDescending
				);
			}
			else {
				label = sTitle;
			}
	
			th.setAttribute('aria-label', label);
		}
	}
	
	
	/**
	 * Function to run on user sort request
	 *  @param {object} settings dataTables settings object
	 *  @param {node} attachTo node to attach the handler to
	 *  @param {int} colIdx column sorting index
	 *  @param {boolean} [append=false] Append the requested sort to the existing
	 *    sort if true (i.e. multi-column sort)
	 *  @param {function} [callback] callback function
	 *  @memberof DataTable#oApi
	 */
	function _fnSortListener ( settings, colIdx, append, callback )
	{
		var col = settings.aoColumns[ colIdx ];
		var sorting = settings.aaSorting;
		var asSorting = col.asSorting;
		var nextSortIdx;
		var next = function ( a, overflow ) {
			var idx = a._idx;
			if ( idx === undefined ) {
				idx = $.inArray( a[1], asSorting );
			}
	
			return idx+1 < asSorting.length ?
				idx+1 :
				overflow ?
					null :
					0;
		};
	
		// Convert to 2D array if needed
		if ( typeof sorting[0] === 'number' ) {
			sorting = settings.aaSorting = [ sorting ];
		}
	
		// If appending the sort then we are multi-column sorting
		if ( append && settings.oFeatures.bSortMulti ) {
			// Are we already doing some kind of sort on this column?
			var sortIdx = $.inArray( colIdx, _pluck(sorting, '0') );
	
			if ( sortIdx !== -1 ) {
				// Yes, modify the sort
				nextSortIdx = next( sorting[sortIdx], true );
	
				if ( nextSortIdx === null && sorting.length === 1 ) {
					nextSortIdx = 0; // can't remove sorting completely
				}
	
				if ( nextSortIdx === null ) {
					sorting.splice( sortIdx, 1 );
				}
				else {
					sorting[sortIdx][1] = asSorting[ nextSortIdx ];
					sorting[sortIdx]._idx = nextSortIdx;
				}
			}
			else {
				// No sort on this column yet
				sorting.push( [ colIdx, asSorting[0], 0 ] );
				sorting[sorting.length-1]._idx = 0;
			}
		}
		else if ( sorting.length && sorting[0][0] == colIdx ) {
			// Single column - already sorting on this column, modify the sort
			nextSortIdx = next( sorting[0] );
	
			sorting.length = 1;
			sorting[0][1] = asSorting[ nextSortIdx ];
			sorting[0]._idx = nextSortIdx;
		}
		else {
			// Single column - sort only on this column
			sorting.length = 0;
			sorting.push( [ colIdx, asSorting[0] ] );
			sorting[0]._idx = 0;
		}
	
		// Run the sort by calling a full redraw
		_fnReDraw( settings );
	
		// callback used for async user interaction
		if ( typeof callback == 'function' ) {
			callback( settings );
		}
	}
	
	
	/**
	 * Attach a sort handler (click) to a node
	 *  @param {object} settings dataTables settings object
	 *  @param {node} attachTo node to attach the handler to
	 *  @param {int} colIdx column sorting index
	 *  @param {function} [callback] callback function
	 *  @memberof DataTable#oApi
	 */
	function _fnSortAttachListener ( settings, attachTo, colIdx, callback )
	{
		var col = settings.aoColumns[ colIdx ];
	
		_fnBindAction( attachTo, {}, function (e) {
			/* If the column is not sortable - don't to anything */
			if ( col.bSortable === false ) {
				return;
			}
	
			// If processing is enabled use a timeout to allow the processing
			// display to be shown - otherwise to it synchronously
			if ( settings.oFeatures.bProcessing ) {
				_fnProcessingDisplay( settings, true );
	
				setTimeout( function() {
					_fnSortListener( settings, colIdx, e.shiftKey, callback );
	
					// In server-side processing, the draw callback will remove the
					// processing display
					if ( _fnDataSource( settings ) !== 'ssp' ) {
						_fnProcessingDisplay( settings, false );
					}
				}, 0 );
			}
			else {
				_fnSortListener( settings, colIdx, e.shiftKey, callback );
			}
		} );
	}
	
	
	/**
	 * Set the sorting classes on table's body, Note: it is safe to call this function
	 * when bSort and bSortClasses are false
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnSortingClasses( settings )
	{
		var oldSort = settings.aLastSort;
		var sortClass = settings.oClasses.sSortColumn;
		var sort = _fnSortFlatten( settings );
		var features = settings.oFeatures;
		var i, ien, colIdx;
	
		if ( features.bSort && features.bSortClasses ) {
			// Remove old sorting classes
			for ( i=0, ien=oldSort.length ; i<ien ; i++ ) {
				colIdx = oldSort[i].src;
	
				// Remove column sorting
				$( _pluck( settings.aoData, 'anCells', colIdx ) )
					.removeClass( sortClass + (i<2 ? i+1 : 3) );
			}
	
			// Add new column sorting
			for ( i=0, ien=sort.length ; i<ien ; i++ ) {
				colIdx = sort[i].src;
	
				$( _pluck( settings.aoData, 'anCells', colIdx ) )
					.addClass( sortClass + (i<2 ? i+1 : 3) );
			}
		}
	
		settings.aLastSort = sort;
	}
	
	
	// Get the data to sort a column, be it from cache, fresh (populating the
	// cache), or from a sort formatter
	function _fnSortData( settings, idx )
	{
		// Custom sorting function - provided by the sort data type
		var column = settings.aoColumns[ idx ];
		var customSort = DataTable.ext.order[ column.sSortDataType ];
		var customData;
	
		if ( customSort ) {
			customData = customSort.call( settings.oInstance, settings, idx,
				_fnColumnIndexToVisible( settings, idx )
			);
		}
	
		// Use / populate cache
		var row, cellData;
		var formatter = DataTable.ext.type.order[ column.sType+"-pre" ];
	
		for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
			row = settings.aoData[i];
	
			if ( ! row._aSortData ) {
				row._aSortData = [];
			}
	
			if ( ! row._aSortData[idx] || customSort ) {
				cellData = customSort ?
					customData[i] : // If there was a custom sort function, use data from there
					_fnGetCellData( settings, i, idx, 'sort' );
	
				row._aSortData[ idx ] = formatter ?
					formatter( cellData ) :
					cellData;
			}
		}
	}
	
	
	
	/**
	 * Save the state of a table
	 *  @param {object} oSettings dataTables settings object
	 *  @memberof DataTable#oApi
	 */
	function _fnSaveState ( settings )
	{
		if ( !settings.oFeatures.bStateSave || settings.bDestroying )
		{
			return;
		}
	
		/* Store the interesting variables */
		var state = {
			time:    +new Date(),
			start:   settings._iDisplayStart,
			length:  settings._iDisplayLength,
			order:   $.extend( true, [], settings.aaSorting ),
			search:  _fnSearchToCamel( settings.oPreviousSearch ),
			columns: $.map( settings.aoColumns, function ( col, i ) {
				return {
					visible: col.bVisible,
					search: _fnSearchToCamel( settings.aoPreSearchCols[i] )
				};
			} )
		};
	
		_fnCallbackFire( settings, "aoStateSaveParams", 'stateSaveParams', [settings, state] );
	
		settings.oSavedState = state;
		settings.fnStateSaveCallback.call( settings.oInstance, settings, state );
	}
	
	
	/**
	 * Attempt to load a saved table state
	 *  @param {object} oSettings dataTables settings object
	 *  @param {object} oInit DataTables init object so we can override settings
	 *  @param {function} callback Callback to execute when the state has been loaded
	 *  @memberof DataTable#oApi
	 */
	function _fnLoadState ( settings, oInit, callback )
	{
		var i, ien;
		var columns = settings.aoColumns;
		var loaded = function ( s ) {
			if ( ! s || ! s.time ) {
				callback();
				return;
			}
	
			// Allow custom and plug-in manipulation functions to alter the saved data set and
			// cancelling of loading by returning false
			var abStateLoad = _fnCallbackFire( settings, 'aoStateLoadParams', 'stateLoadParams', [settings, s] );
			if ( $.inArray( false, abStateLoad ) !== -1 ) {
				callback();
				return;
			}
	
			// Reject old data
			var duration = settings.iStateDuration;
			if ( duration > 0 && s.time < +new Date() - (duration*1000) ) {
				callback();
				return;
			}
	
			// Number of columns have changed - all bets are off, no restore of settings
			if ( s.columns && columns.length !== s.columns.length ) {
				callback();
				return;
			}
	
			// Store the saved state so it might be accessed at any time
			settings.oLoadedState = $.extend( true, {}, s );
	
			// Restore key features - todo - for 1.11 this needs to be done by
			// subscribed events
			if ( s.start !== undefined ) {
				settings._iDisplayStart    = s.start;
				settings.iInitDisplayStart = s.start;
			}
			if ( s.length !== undefined ) {
				settings._iDisplayLength   = s.length;
			}
	
			// Order
			if ( s.order !== undefined ) {
				settings.aaSorting = [];
				$.each( s.order, function ( i, col ) {
					settings.aaSorting.push( col[0] >= columns.length ?
						[ 0, col[1] ] :
						col
					);
				} );
			}
	
			// Search
			if ( s.search !== undefined ) {
				$.extend( settings.oPreviousSearch, _fnSearchToHung( s.search ) );
			}
	
			// Columns
			//
			if ( s.columns ) {
				for ( i=0, ien=s.columns.length ; i<ien ; i++ ) {
					var col = s.columns[i];
	
					// Visibility
					if ( col.visible !== undefined ) {
						columns[i].bVisible = col.visible;
					}
	
					// Search
					if ( col.search !== undefined ) {
						$.extend( settings.aoPreSearchCols[i], _fnSearchToHung( col.search ) );
					}
				}
			}
	
			_fnCallbackFire( settings, 'aoStateLoaded', 'stateLoaded', [settings, s] );
			callback();
		}
	
		if ( ! settings.oFeatures.bStateSave ) {
			callback();
			return;
		}
	
		var state = settings.fnStateLoadCallback.call( settings.oInstance, settings, loaded );
	
		if ( state !== undefined ) {
			loaded( state );
		}
		// otherwise, wait for the loaded callback to be executed
	}
	
	
	/**
	 * Return the settings object for a particular table
	 *  @param {node} table table we are using as a dataTable
	 *  @returns {object} Settings object - or null if not found
	 *  @memberof DataTable#oApi
	 */
	function _fnSettingsFromNode ( table )
	{
		var settings = DataTable.settings;
		var idx = $.inArray( table, _pluck( settings, 'nTable' ) );
	
		return idx !== -1 ?
			settings[ idx ] :
			null;
	}
	
	
	/**
	 * Log an error message
	 *  @param {object} settings dataTables settings object
	 *  @param {int} level log error messages, or display them to the user
	 *  @param {string} msg error message
	 *  @param {int} tn Technical note id to get more information about the error.
	 *  @memberof DataTable#oApi
	 */
	function _fnLog( settings, level, msg, tn )
	{
		msg = 'DataTables warning: '+
			(settings ? 'table id='+settings.sTableId+' - ' : '')+msg;
	
		if ( tn ) {
			msg += '. For more information about this error, please see '+
			'http://datatables.net/tn/'+tn;
		}
	
		if ( ! level  ) {
			// Backwards compatibility pre 1.10
			var ext = DataTable.ext;
			var type = ext.sErrMode || ext.errMode;
	
			if ( settings ) {
				_fnCallbackFire( settings, null, 'error', [ settings, tn, msg ] );
			}
	
			if ( type == 'alert' ) {
				alert( msg );
			}
			else if ( type == 'throw' ) {
				throw new Error(msg);
			}
			else if ( typeof type == 'function' ) {
				type( settings, tn, msg );
			}
		}
		else if ( window.console && console.log ) {
			console.log( msg );
		}
	}
	
	
	/**
	 * See if a property is defined on one object, if so assign it to the other object
	 *  @param {object} ret target object
	 *  @param {object} src source object
	 *  @param {string} name property
	 *  @param {string} [mappedName] name to map too - optional, name used if not given
	 *  @memberof DataTable#oApi
	 */
	function _fnMap( ret, src, name, mappedName )
	{
		if ( $.isArray( name ) ) {
			$.each( name, function (i, val) {
				if ( $.isArray( val ) ) {
					_fnMap( ret, src, val[0], val[1] );
				}
				else {
					_fnMap( ret, src, val );
				}
			} );
	
			return;
		}
	
		if ( mappedName === undefined ) {
			mappedName = name;
		}
	
		if ( src[name] !== undefined ) {
			ret[mappedName] = src[name];
		}
	}
	
	
	/**
	 * Extend objects - very similar to jQuery.extend, but deep copy objects, and
	 * shallow copy arrays. The reason we need to do this, is that we don't want to
	 * deep copy array init values (such as aaSorting) since the dev wouldn't be
	 * able to override them, but we do want to deep copy arrays.
	 *  @param {object} out Object to extend
	 *  @param {object} extender Object from which the properties will be applied to
	 *      out
	 *  @param {boolean} breakRefs If true, then arrays will be sliced to take an
	 *      independent copy with the exception of the `data` or `aaData` parameters
	 *      if they are present. This is so you can pass in a collection to
	 *      DataTables and have that used as your data source without breaking the
	 *      references
	 *  @returns {object} out Reference, just for convenience - out === the return.
	 *  @memberof DataTable#oApi
	 *  @todo This doesn't take account of arrays inside the deep copied objects.
	 */
	function _fnExtend( out, extender, breakRefs )
	{
		var val;
	
		for ( var prop in extender ) {
			if ( extender.hasOwnProperty(prop) ) {
				val = extender[prop];
	
				if ( $.isPlainObject( val ) ) {
					if ( ! $.isPlainObject( out[prop] ) ) {
						out[prop] = {};
					}
					$.extend( true, out[prop], val );
				}
				else if ( breakRefs && prop !== 'data' && prop !== 'aaData' && $.isArray(val) ) {
					out[prop] = val.slice();
				}
				else {
					out[prop] = val;
				}
			}
		}
	
		return out;
	}
	
	
	/**
	 * Bind an event handers to allow a click or return key to activate the callback.
	 * This is good for accessibility since a return on the keyboard will have the
	 * same effect as a click, if the element has focus.
	 *  @param {element} n Element to bind the action to
	 *  @param {object} oData Data object to pass to the triggered function
	 *  @param {function} fn Callback function for when the event is triggered
	 *  @memberof DataTable#oApi
	 */
	function _fnBindAction( n, oData, fn )
	{
		$(n)
			.on( 'click.DT', oData, function (e) {
					n.blur(); // Remove focus outline for mouse users
					fn(e);
				} )
			.on( 'keypress.DT', oData, function (e){
					if ( e.which === 13 ) {
						e.preventDefault();
						fn(e);
					}
				} )
			.on( 'selectstart.DT', function () {
					/* Take the brutal approach to cancelling text selection */
					return false;
				} );
	}
	
	
	/**
	 * Register a callback function. Easily allows a callback function to be added to
	 * an array store of callback functions that can then all be called together.
	 *  @param {object} oSettings dataTables settings object
	 *  @param {string} sStore Name of the array storage for the callbacks in oSettings
	 *  @param {function} fn Function to be called back
	 *  @param {string} sName Identifying name for the callback (i.e. a label)
	 *  @memberof DataTable#oApi
	 */
	function _fnCallbackReg( oSettings, sStore, fn, sName )
	{
		if ( fn )
		{
			oSettings[sStore].push( {
				"fn": fn,
				"sName": sName
			} );
		}
	}
	
	
	/**
	 * Fire callback functions and trigger events. Note that the loop over the
	 * callback array store is done backwards! Further note that you do not want to
	 * fire off triggers in time sensitive applications (for example cell creation)
	 * as its slow.
	 *  @param {object} settings dataTables settings object
	 *  @param {string} callbackArr Name of the array storage for the callbacks in
	 *      oSettings
	 *  @param {string} eventName Name of the jQuery custom event to trigger. If
	 *      null no trigger is fired
	 *  @param {array} args Array of arguments to pass to the callback function /
	 *      trigger
	 *  @memberof DataTable#oApi
	 */
	function _fnCallbackFire( settings, callbackArr, eventName, args )
	{
		var ret = [];
	
		if ( callbackArr ) {
			ret = $.map( settings[callbackArr].slice().reverse(), function (val, i) {
				return val.fn.apply( settings.oInstance, args );
			} );
		}
	
		if ( eventName !== null ) {
			var e = $.Event( eventName+'.dt' );
	
			$(settings.nTable).trigger( e, args );
	
			ret.push( e.result );
		}
	
		return ret;
	}
	
	
	function _fnLengthOverflow ( settings )
	{
		var
			start = settings._iDisplayStart,
			end = settings.fnDisplayEnd(),
			len = settings._iDisplayLength;
	
		/* If we have space to show extra rows (backing up from the end point - then do so */
		if ( start >= end )
		{
			start = end - len;
		}
	
		// Keep the start record on the current page
		start -= (start % len);
	
		if ( len === -1 || start < 0 )
		{
			start = 0;
		}
	
		settings._iDisplayStart = start;
	}
	
	
	function _fnRenderer( settings, type )
	{
		var renderer = settings.renderer;
		var host = DataTable.ext.renderer[type];
	
		if ( $.isPlainObject( renderer ) && renderer[type] ) {
			// Specific renderer for this type. If available use it, otherwise use
			// the default.
			return host[renderer[type]] || host._;
		}
		else if ( typeof renderer === 'string' ) {
			// Common renderer - if there is one available for this type use it,
			// otherwise use the default
			return host[renderer] || host._;
		}
	
		// Use the default
		return host._;
	}
	
	
	/**
	 * Detect the data source being used for the table. Used to simplify the code
	 * a little (ajax) and to make it compress a little smaller.
	 *
	 *  @param {object} settings dataTables settings object
	 *  @returns {string} Data source
	 *  @memberof DataTable#oApi
	 */
	function _fnDataSource ( settings )
	{
		if ( settings.oFeatures.bServerSide ) {
			return 'ssp';
		}
		else if ( settings.ajax || settings.sAjaxSource ) {
			return 'ajax';
		}
		return 'dom';
	}
	

	
	
	/**
	 * Computed structure of the DataTables API, defined by the options passed to
	 * `DataTable.Api.register()` when building the API.
	 *
	 * The structure is built in order to speed creation and extension of the Api
	 * objects since the extensions are effectively pre-parsed.
	 *
	 * The array is an array of objects with the following structure, where this
	 * base array represents the Api prototype base:
	 *
	 *     [
	 *       {
	 *         name:      'data'                -- string   - Property name
	 *         val:       function () {},       -- function - Api method (or undefined if just an object
	 *         methodExt: [ ... ],              -- array    - Array of Api object definitions to extend the method result
	 *         propExt:   [ ... ]               -- array    - Array of Api object definitions to extend the property
	 *       },
	 *       {
	 *         name:     'row'
	 *         val:       {},
	 *         methodExt: [ ... ],
	 *         propExt:   [
	 *           {
	 *             name:      'data'
	 *             val:       function () {},
	 *             methodExt: [ ... ],
	 *             propExt:   [ ... ]
	 *           },
	 *           ...
	 *         ]
	 *       }
	 *     ]
	 *
	 * @type {Array}
	 * @ignore
	 */
	var __apiStruct = [];
	
	
	/**
	 * `Array.prototype` reference.
	 *
	 * @type object
	 * @ignore
	 */
	var __arrayProto = Array.prototype;
	
	
	/**
	 * Abstraction for `context` parameter of the `Api` constructor to allow it to
	 * take several different forms for ease of use.
	 *
	 * Each of the input parameter types will be converted to a DataTables settings
	 * object where possible.
	 *
	 * @param  {string|node|jQuery|object} mixed DataTable identifier. Can be one
	 *   of:
	 *
	 *   * `string` - jQuery selector. Any DataTables' matching the given selector
	 *     with be found and used.
	 *   * `node` - `TABLE` node which has already been formed into a DataTable.
	 *   * `jQuery` - A jQuery object of `TABLE` nodes.
	 *   * `object` - DataTables settings object
	 *   * `DataTables.Api` - API instance
	 * @return {array|null} Matching DataTables settings objects. `null` or
	 *   `undefined` is returned if no matching DataTable is found.
	 * @ignore
	 */
	var _toSettings = function ( mixed )
	{
		var idx, jq;
		var settings = DataTable.settings;
		var tables = $.map( settings, function (el, i) {
			return el.nTable;
		} );
	
		if ( ! mixed ) {
			return [];
		}
		else if ( mixed.nTable && mixed.oApi ) {
			// DataTables settings object
			return [ mixed ];
		}
		else if ( mixed.nodeName && mixed.nodeName.toLowerCase() === 'table' ) {
			// Table node
			idx = $.inArray( mixed, tables );
			return idx !== -1 ? [ settings[idx] ] : null;
		}
		else if ( mixed && typeof mixed.settings === 'function' ) {
			return mixed.settings().toArray();
		}
		else if ( typeof mixed === 'string' ) {
			// jQuery selector
			jq = $(mixed);
		}
		else if ( mixed instanceof $ ) {
			// jQuery object (also DataTables instance)
			jq = mixed;
		}
	
		if ( jq ) {
			return jq.map( function(i) {
				idx = $.inArray( this, tables );
				return idx !== -1 ? settings[idx] : null;
			} ).toArray();
		}
	};
	
	
	/**
	 * DataTables API class - used to control and interface with  one or more
	 * DataTables enhanced tables.
	 *
	 * The API class is heavily based on jQuery, presenting a chainable interface
	 * that you can use to interact with tables. Each instance of the API class has
	 * a "context" - i.e. the tables that it will operate on. This could be a single
	 * table, all tables on a page or a sub-set thereof.
	 *
	 * Additionally the API is designed to allow you to easily work with the data in
	 * the tables, retrieving and manipulating it as required. This is done by
	 * presenting the API class as an array like interface. The contents of the
	 * array depend upon the actions requested by each method (for example
	 * `rows().nodes()` will return an array of nodes, while `rows().data()` will
	 * return an array of objects or arrays depending upon your table's
	 * configuration). The API object has a number of array like methods (`push`,
	 * `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`,
	 * `unique` etc) to assist your working with the data held in a table.
	 *
	 * Most methods (those which return an Api instance) are chainable, which means
	 * the return from a method call also has all of the methods available that the
	 * top level object had. For example, these two calls are equivalent:
	 *
	 *     // Not chained
	 *     api.row.add( {...} );
	 *     api.draw();
	 *
	 *     // Chained
	 *     api.row.add( {...} ).draw();
	 *
	 * @class DataTable.Api
	 * @param {array|object|string|jQuery} context DataTable identifier. This is
	 *   used to define which DataTables enhanced tables this API will operate on.
	 *   Can be one of:
	 *
	 *   * `string` - jQuery selector. Any DataTables' matching the given selector
	 *     with be found and used.
	 *   * `node` - `TABLE` node which has already been formed into a DataTable.
	 *   * `jQuery` - A jQuery object of `TABLE` nodes.
	 *   * `object` - DataTables settings object
	 * @param {array} [data] Data to initialise the Api instance with.
	 *
	 * @example
	 *   // Direct initialisation during DataTables construction
	 *   var api = $('#example').DataTable();
	 *
	 * @example
	 *   // Initialisation using a DataTables jQuery object
	 *   var api = $('#example').dataTable().api();
	 *
	 * @example
	 *   // Initialisation as a constructor
	 *   var api = new $.fn.DataTable.Api( 'table.dataTable' );
	 */
	_Api = function ( context, data )
	{
		if ( ! (this instanceof _Api) ) {
			return new _Api( context, data );
		}
	
		var settings = [];
		var ctxSettings = function ( o ) {
			var a = _toSettings( o );
			if ( a ) {
				settings = settings.concat( a );
			}
		};
	
		if ( $.isArray( context ) ) {
			for ( var i=0, ien=context.length ; i<ien ; i++ ) {
				ctxSettings( context[i] );
			}
		}
		else {
			ctxSettings( context );
		}
	
		// Remove duplicates
		this.context = _unique( settings );
	
		// Initial data
		if ( data ) {
			$.merge( this, data );
		}
	
		// selector
		this.selector = {
			rows: null,
			cols: null,
			opts: null
		};
	
		_Api.extend( this, this, __apiStruct );
	};
	
	DataTable.Api = _Api;
	
	// Don't destroy the existing prototype, just extend it. Required for jQuery 2's
	// isPlainObject.
	$.extend( _Api.prototype, {
		any: function ()
		{
			return this.count() !== 0;
		},
	
	
		concat:  __arrayProto.concat,
	
	
		context: [], // array of table settings objects
	
	
		count: function ()
		{
			return this.flatten().length;
		},
	
	
		each: function ( fn )
		{
			for ( var i=0, ien=this.length ; i<ien; i++ ) {
				fn.call( this, this[i], i, this );
			}
	
			return this;
		},
	
	
		eq: function ( idx )
		{
			var ctx = this.context;
	
			return ctx.length > idx ?
				new _Api( ctx[idx], this[idx] ) :
				null;
		},
	
	
		filter: function ( fn )
		{
			var a = [];
	
			if ( __arrayProto.filter ) {
				a = __arrayProto.filter.call( this, fn, this );
			}
			else {
				// Compatibility for browsers without EMCA-252-5 (JS 1.6)
				for ( var i=0, ien=this.length ; i<ien ; i++ ) {
					if ( fn.call( this, this[i], i, this ) ) {
						a.push( this[i] );
					}
				}
			}
	
			return new _Api( this.context, a );
		},
	
	
		flatten: function ()
		{
			var a = [];
			return new _Api( this.context, a.concat.apply( a, this.toArray() ) );
		},
	
	
		join:    __arrayProto.join,
	
	
		indexOf: __arrayProto.indexOf || function (obj, start)
		{
			for ( var i=(start || 0), ien=this.length ; i<ien ; i++ ) {
				if ( this[i] === obj ) {
					return i;
				}
			}
			return -1;
		},
	
		iterator: function ( flatten, type, fn, alwaysNew ) {
			var
				a = [], ret,
				i, ien, j, jen,
				context = this.context,
				rows, items, item,
				selector = this.selector;
	
			// Argument shifting
			if ( typeof flatten === 'string' ) {
				alwaysNew = fn;
				fn = type;
				type = flatten;
				flatten = false;
			}
	
			for ( i=0, ien=context.length ; i<ien ; i++ ) {
				var apiInst = new _Api( context[i] );
	
				if ( type === 'table' ) {
					ret = fn.call( apiInst, context[i], i );
	
					if ( ret !== undefined ) {
						a.push( ret );
					}
				}
				else if ( type === 'columns' || type === 'rows' ) {
					// this has same length as context - one entry for each table
					ret = fn.call( apiInst, context[i], this[i], i );
	
					if ( ret !== undefined ) {
						a.push( ret );
					}
				}
				else if ( type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell' ) {
					// columns and rows share the same structure.
					// 'this' is an array of column indexes for each context
					items = this[i];
	
					if ( type === 'column-rows' ) {
						rows = _selector_row_indexes( context[i], selector.opts );
					}
	
					for ( j=0, jen=items.length ; j<jen ; j++ ) {
						item = items[j];
	
						if ( type === 'cell' ) {
							ret = fn.call( apiInst, context[i], item.row, item.column, i, j );
						}
						else {
							ret = fn.call( apiInst, context[i], item, i, j, rows );
						}
	
						if ( ret !== undefined ) {
							a.push( ret );
						}
					}
				}
			}
	
			if ( a.length || alwaysNew ) {
				var api = new _Api( context, flatten ? a.concat.apply( [], a ) : a );
				var apiSelector = api.selector;
				apiSelector.rows = selector.rows;
				apiSelector.cols = selector.cols;
				apiSelector.opts = selector.opts;
				return api;
			}
			return this;
		},
	
	
		lastIndexOf: __arrayProto.lastIndexOf || function (obj, start)
		{
			// Bit cheeky...
			return this.indexOf.apply( this.toArray.reverse(), arguments );
		},
	
	
		length:  0,
	
	
		map: function ( fn )
		{
			var a = [];
	
			if ( __arrayProto.map ) {
				a = __arrayProto.map.call( this, fn, this );
			}
			else {
				// Compatibility for browsers without EMCA-252-5 (JS 1.6)
				for ( var i=0, ien=this.length ; i<ien ; i++ ) {
					a.push( fn.call( this, this[i], i ) );
				}
			}
	
			return new _Api( this.context, a );
		},
	
	
		pluck: function ( prop )
		{
			return this.map( function ( el ) {
				return el[ prop ];
			} );
		},
	
		pop:     __arrayProto.pop,
	
	
		push:    __arrayProto.push,
	
	
		// Does not return an API instance
		reduce: __arrayProto.reduce || function ( fn, init )
		{
			return _fnReduce( this, fn, init, 0, this.length, 1 );
		},
	
	
		reduceRight: __arrayProto.reduceRight || function ( fn, init )
		{
			return _fnReduce( this, fn, init, this.length-1, -1, -1 );
		},
	
	
		reverse: __arrayProto.reverse,
	
	
		// Object with rows, columns and opts
		selector: null,
	
	
		shift:   __arrayProto.shift,
	
	
		slice: function () {
			return new _Api( this.context, this );
		},
	
	
		sort:    __arrayProto.sort, // ? name - order?
	
	
		splice:  __arrayProto.splice,
	
	
		toArray: function ()
		{
			return __arrayProto.slice.call( this );
		},
	
	
		to$: function ()
		{
			return $( this );
		},
	
	
		toJQuery: function ()
		{
			return $( this );
		},
	
	
		unique: function ()
		{
			return new _Api( this.context, _unique(this) );
		},
	
	
		unshift: __arrayProto.unshift
	} );
	
	
	_Api.extend = function ( scope, obj, ext )
	{
		// Only extend API instances and static properties of the API
		if ( ! ext.length || ! obj || ( ! (obj instanceof _Api) && ! obj.__dt_wrapper ) ) {
			return;
		}
	
		var
			i, ien,
			j, jen,
			struct, inner,
			methodScoping = function ( scope, fn, struc ) {
				return function () {
					var ret = fn.apply( scope, arguments );
	
					// Method extension
					_Api.extend( ret, ret, struc.methodExt );
					return ret;
				};
			};
	
		for ( i=0, ien=ext.length ; i<ien ; i++ ) {
			struct = ext[i];
	
			// Value
			obj[ struct.name ] = typeof struct.val === 'function' ?
				methodScoping( scope, struct.val, struct ) :
				$.isPlainObject( struct.val ) ?
					{} :
					struct.val;
	
			obj[ struct.name ].__dt_wrapper = true;
	
			// Property extension
			_Api.extend( scope, obj[ struct.name ], struct.propExt );
		}
	};
	
	
	// @todo - Is there need for an augment function?
	// _Api.augment = function ( inst, name )
	// {
	// 	// Find src object in the structure from the name
	// 	var parts = name.split('.');
	
	// 	_Api.extend( inst, obj );
	// };
	
	
	//     [
	//       {
	//         name:      'data'                -- string   - Property name
	//         val:       function () {},       -- function - Api method (or undefined if just an object
	//         methodExt: [ ... ],              -- array    - Array of Api object definitions to extend the method result
	//         propExt:   [ ... ]               -- array    - Array of Api object definitions to extend the property
	//       },
	//       {
	//         name:     'row'
	//         val:       {},
	//         methodExt: [ ... ],
	//         propExt:   [
	//           {
	//             name:      'data'
	//             val:       function () {},
	//             methodExt: [ ... ],
	//             propExt:   [ ... ]
	//           },
	//           ...
	//         ]
	//       }
	//     ]
	
	_Api.register = _api_register = function ( name, val )
	{
		if ( $.isArray( name ) ) {
			for ( var j=0, jen=name.length ; j<jen ; j++ ) {
				_Api.register( name[j], val );
			}
			return;
		}
	
		var
			i, ien,
			heir = name.split('.'),
			struct = __apiStruct,
			key, method;
	
		var find = function ( src, name ) {
			for ( var i=0, ien=src.length ; i<ien ; i++ ) {
				if ( src[i].name === name ) {
					return src[i];
				}
			}
			return null;
		};
	
		for ( i=0, ien=heir.length ; i<ien ; i++ ) {
			method = heir[i].indexOf('()') !== -1;
			key = method ?
				heir[i].replace('()', '') :
				heir[i];
	
			var src = find( struct, key );
			if ( ! src ) {
				src = {
					name:      key,
					val:       {},
					methodExt: [],
					propExt:   []
				};
				struct.push( src );
			}
	
			if ( i === ien-1 ) {
				src.val = val;
			}
			else {
				struct = method ?
					src.methodExt :
					src.propExt;
			}
		}
	};
	
	
	_Api.registerPlural = _api_registerPlural = function ( pluralName, singularName, val ) {
		_Api.register( pluralName, val );
	
		_Api.register( singularName, function () {
			var ret = val.apply( this, arguments );
	
			if ( ret === this ) {
				// Returned item is the API instance that was passed in, return it
				return this;
			}
			else if ( ret instanceof _Api ) {
				// New API instance returned, want the value from the first item
				// in the returned array for the singular result.
				return ret.length ?
					$.isArray( ret[0] ) ?
						new _Api( ret.context, ret[0] ) : // Array results are 'enhanced'
						ret[0] :
					undefined;
			}
	
			// Non-API return - just fire it back
			return ret;
		} );
	};
	
	
	/**
	 * Selector for HTML tables. Apply the given selector to the give array of
	 * DataTables settings objects.
	 *
	 * @param {string|integer} [selector] jQuery selector string or integer
	 * @param  {array} Array of DataTables settings objects to be filtered
	 * @return {array}
	 * @ignore
	 */
	var __table_selector = function ( selector, a )
	{
		// Integer is used to pick out a table by index
		if ( typeof selector === 'number' ) {
			return [ a[ selector ] ];
		}
	
		// Perform a jQuery selector on the table nodes
		var nodes = $.map( a, function (el, i) {
			return el.nTable;
		} );
	
		return $(nodes)
			.filter( selector )
			.map( function (i) {
				// Need to translate back from the table node to the settings
				var idx = $.inArray( this, nodes );
				return a[ idx ];
			} )
			.toArray();
	};
	
	
	
	/**
	 * Context selector for the API's context (i.e. the tables the API instance
	 * refers to.
	 *
	 * @name    DataTable.Api#tables
	 * @param {string|integer} [selector] Selector to pick which tables the iterator
	 *   should operate on. If not given, all tables in the current context are
	 *   used. This can be given as a jQuery selector (for example `':gt(0)'`) to
	 *   select multiple tables or as an integer to select a single table.
	 * @returns {DataTable.Api} Returns a new API instance if a selector is given.
	 */
	_api_register( 'tables()', function ( selector ) {
		// A new instance is created if there was a selector specified
		return selector ?
			new _Api( __table_selector( selector, this.context ) ) :
			this;
	} );
	
	
	_api_register( 'table()', function ( selector ) {
		var tables = this.tables( selector );
		var ctx = tables.context;
	
		// Truncate to the first matched table
		return ctx.length ?
			new _Api( ctx[0] ) :
			tables;
	} );
	
	
	_api_registerPlural( 'tables().nodes()', 'table().node()' , function () {
		return this.iterator( 'table', function ( ctx ) {
			return ctx.nTable;
		}, 1 );
	} );
	
	
	_api_registerPlural( 'tables().body()', 'table().body()' , function () {
		return this.iterator( 'table', function ( ctx ) {
			return ctx.nTBody;
		}, 1 );
	} );
	
	
	_api_registerPlural( 'tables().header()', 'table().header()' , function () {
		return this.iterator( 'table', function ( ctx ) {
			return ctx.nTHead;
		}, 1 );
	} );
	
	
	_api_registerPlural( 'tables().footer()', 'table().footer()' , function () {
		return this.iterator( 'table', function ( ctx ) {
			return ctx.nTFoot;
		}, 1 );
	} );
	
	
	_api_registerPlural( 'tables().containers()', 'table().container()' , function () {
		return this.iterator( 'table', function ( ctx ) {
			return ctx.nTableWrapper;
		}, 1 );
	} );
	
	
	
	/**
	 * Redraw the tables in the current context.
	 */
	_api_register( 'draw()', function ( paging ) {
		return this.iterator( 'table', function ( settings ) {
			if ( paging === 'page' ) {
				_fnDraw( settings );
			}
			else {
				if ( typeof paging === 'string' ) {
					paging = paging === 'full-hold' ?
						false :
						true;
				}
	
				_fnReDraw( settings, paging===false );
			}
		} );
	} );
	
	
	
	/**
	 * Get the current page index.
	 *
	 * @return {integer} Current page index (zero based)
	 *//**
	 * Set the current page.
	 *
	 * Note that if you attempt to show a page which does not exist, DataTables will
	 * not throw an error, but rather reset the paging.
	 *
	 * @param {integer|string} action The paging action to take. This can be one of:
	 *  * `integer` - The page index to jump to
	 *  * `string` - An action to take:
	 *    * `first` - Jump to first page.
	 *    * `next` - Jump to the next page
	 *    * `previous` - Jump to previous page
	 *    * `last` - Jump to the last page.
	 * @returns {DataTables.Api} this
	 */
	_api_register( 'page()', function ( action ) {
		if ( action === undefined ) {
			return this.page.info().page; // not an expensive call
		}
	
		// else, have an action to take on all tables
		return this.iterator( 'table', function ( settings ) {
			_fnPageChange( settings, action );
		} );
	} );
	
	
	/**
	 * Paging information for the first table in the current context.
	 *
	 * If you require paging information for another table, use the `table()` method
	 * with a suitable selector.
	 *
	 * @return {object} Object with the following properties set:
	 *  * `page` - Current page index (zero based - i.e. the first page is `0`)
	 *  * `pages` - Total number of pages
	 *  * `start` - Display index for the first record shown on the current page
	 *  * `end` - Display index for the last record shown on the current page
	 *  * `length` - Display length (number of records). Note that generally `start
	 *    + length = end`, but this is not always true, for example if there are
	 *    only 2 records to show on the final page, with a length of 10.
	 *  * `recordsTotal` - Full data set length
	 *  * `recordsDisplay` - Data set length once the current filtering criterion
	 *    are applied.
	 */
	_api_register( 'page.info()', function ( action ) {
		if ( this.context.length === 0 ) {
			return undefined;
		}
	
		var
			settings   = this.context[0],
			start      = settings._iDisplayStart,
			len        = settings.oFeatures.bPaginate ? settings._iDisplayLength : -1,
			visRecords = settings.fnRecordsDisplay(),
			all        = len === -1;
	
		return {
			"page":           all ? 0 : Math.floor( start / len ),
			"pages":          all ? 1 : Math.ceil( visRecords / len ),
			"start":          start,
			"end":            settings.fnDisplayEnd(),
			"length":         len,
			"recordsTotal":   settings.fnRecordsTotal(),
			"recordsDisplay": visRecords,
			"serverSide":     _fnDataSource( settings ) === 'ssp'
		};
	} );
	
	
	/**
	 * Get the current page length.
	 *
	 * @return {integer} Current page length. Note `-1` indicates that all records
	 *   are to be shown.
	 *//**
	 * Set the current page length.
	 *
	 * @param {integer} Page length to set. Use `-1` to show all records.
	 * @returns {DataTables.Api} this
	 */
	_api_register( 'page.len()', function ( len ) {
		// Note that we can't call this function 'length()' because `length`
		// is a Javascript property of functions which defines how many arguments
		// the function expects.
		if ( len === undefined ) {
			return this.context.length !== 0 ?
				this.context[0]._iDisplayLength :
				undefined;
		}
	
		// else, set the page length
		return this.iterator( 'table', function ( settings ) {
			_fnLengthChange( settings, len );
		} );
	} );
	
	
	
	var __reload = function ( settings, holdPosition, callback ) {
		// Use the draw event to trigger a callback
		if ( callback ) {
			var api = new _Api( settings );
	
			api.one( 'draw', function () {
				callback( api.ajax.json() );
			} );
		}
	
		if ( _fnDataSource( settings ) == 'ssp' ) {
			_fnReDraw( settings, holdPosition );
		}
		else {
			_fnProcessingDisplay( settings, true );
	
			// Cancel an existing request
			var xhr = settings.jqXHR;
			if ( xhr && xhr.readyState !== 4 ) {
				xhr.abort();
			}
	
			// Trigger xhr
			_fnBuildAjax( settings, [], function( json ) {
				_fnClearTable( settings );
	
				var data = _fnAjaxDataSrc( settings, json );
				for ( var i=0, ien=data.length ; i<ien ; i++ ) {
					_fnAddData( settings, data[i] );
				}
	
				_fnReDraw( settings, holdPosition );
				_fnProcessingDisplay( settings, false );
			} );
		}
	};
	
	
	/**
	 * Get the JSON response from the last Ajax request that DataTables made to the
	 * server. Note that this returns the JSON from the first table in the current
	 * context.
	 *
	 * @return {object} JSON received from the server.
	 */
	_api_register( 'ajax.json()', function () {
		var ctx = this.context;
	
		if ( ctx.length > 0 ) {
			return ctx[0].json;
		}
	
		// else return undefined;
	} );
	
	
	/**
	 * Get the data submitted in the last Ajax request
	 */
	_api_register( 'ajax.params()', function () {
		var ctx = this.context;
	
		if ( ctx.length > 0 ) {
			return ctx[0].oAjaxData;
		}
	
		// else return undefined;
	} );
	
	
	/**
	 * Reload tables from the Ajax data source. Note that this function will
	 * automatically re-draw the table when the remote data has been loaded.
	 *
	 * @param {boolean} [reset=true] Reset (default) or hold the current paging
	 *   position. A full re-sort and re-filter is performed when this method is
	 *   called, which is why the pagination reset is the default action.
	 * @returns {DataTables.Api} this
	 */
	_api_register( 'ajax.reload()', function ( callback, resetPaging ) {
		return this.iterator( 'table', function (settings) {
			__reload( settings, resetPaging===false, callback );
		} );
	} );
	
	
	/**
	 * Get the current Ajax URL. Note that this returns the URL from the first
	 * table in the current context.
	 *
	 * @return {string} Current Ajax source URL
	 *//**
	 * Set the Ajax URL. Note that this will set the URL for all tables in the
	 * current context.
	 *
	 * @param {string} url URL to set.
	 * @returns {DataTables.Api} this
	 */
	_api_register( 'ajax.url()', function ( url ) {
		var ctx = this.context;
	
		if ( url === undefined ) {
			// get
			if ( ctx.length === 0 ) {
				return undefined;
			}
			ctx = ctx[0];
	
			return ctx.ajax ?
				$.isPlainObject( ctx.ajax ) ?
					ctx.ajax.url :
					ctx.ajax :
				ctx.sAjaxSource;
		}
	
		// set
		return this.iterator( 'table', function ( settings ) {
			if ( $.isPlainObject( settings.ajax ) ) {
				settings.ajax.url = url;
			}
			else {
				settings.ajax = url;
			}
			// No need to consider sAjaxSource here since DataTables gives priority
			// to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any
			// value of `sAjaxSource` redundant.
		} );
	} );
	
	
	/**
	 * Load data from the newly set Ajax URL. Note that this method is only
	 * available when `ajax.url()` is used to set a URL. Additionally, this method
	 * has the same effect as calling `ajax.reload()` but is provided for
	 * convenience when setting a new URL. Like `ajax.reload()` it will
	 * automatically redraw the table once the remote data has been loaded.
	 *
	 * @returns {DataTables.Api} this
	 */
	_api_register( 'ajax.url().load()', function ( callback, resetPaging ) {
		// Same as a reload, but makes sense to present it for easy access after a
		// url change
		return this.iterator( 'table', function ( ctx ) {
			__reload( ctx, resetPaging===false, callback );
		} );
	} );
	
	
	
	
	var _selector_run = function ( type, selector, selectFn, settings, opts )
	{
		var
			out = [], res,
			a, i, ien, j, jen,
			selectorType = typeof selector;
	
		// Can't just check for isArray here, as an API or jQuery instance might be
		// given with their array like look
		if ( ! selector || selectorType === 'string' || selectorType === 'function' || selector.length === undefined ) {
			selector = [ selector ];
		}
	
		for ( i=0, ien=selector.length ; i<ien ; i++ ) {
			// Only split on simple strings - complex expressions will be jQuery selectors
			a = selector[i] && selector[i].split && ! selector[i].match(/[\[\(:]/) ?
				selector[i].split(',') :
				[ selector[i] ];
	
			for ( j=0, jen=a.length ; j<jen ; j++ ) {
				res = selectFn( typeof a[j] === 'string' ? $.trim(a[j]) : a[j] );
	
				if ( res && res.length ) {
					out = out.concat( res );
				}
			}
		}
	
		// selector extensions
		var ext = _ext.selector[ type ];
		if ( ext.length ) {
			for ( i=0, ien=ext.length ; i<ien ; i++ ) {
				out = ext[i]( settings, opts, out );
			}
		}
	
		return _unique( out );
	};
	
	
	var _selector_opts = function ( opts )
	{
		if ( ! opts ) {
			opts = {};
		}
	
		// Backwards compatibility for 1.9- which used the terminology filter rather
		// than search
		if ( opts.filter && opts.search === undefined ) {
			opts.search = opts.filter;
		}
	
		return $.extend( {
			search: 'none',
			order: 'current',
			page: 'all'
		}, opts );
	};
	
	
	var _selector_first = function ( inst )
	{
		// Reduce the API instance to the first item found
		for ( var i=0, ien=inst.length ; i<ien ; i++ ) {
			if ( inst[i].length > 0 ) {
				// Assign the first element to the first item in the instance
				// and truncate the instance and context
				inst[0] = inst[i];
				inst[0].length = 1;
				inst.length = 1;
				inst.context = [ inst.context[i] ];
	
				return inst;
			}
		}
	
		// Not found - return an empty instance
		inst.length = 0;
		return inst;
	};
	
	
	var _selector_row_indexes = function ( settings, opts )
	{
		var
			i, ien, tmp, a=[],
			displayFiltered = settings.aiDisplay,
			displayMaster = settings.aiDisplayMaster;
	
		var
			search = opts.search,  // none, applied, removed
			order  = opts.order,   // applied, current, index (original - compatibility with 1.9)
			page   = opts.page;    // all, current
	
		if ( _fnDataSource( settings ) == 'ssp' ) {
			// In server-side processing mode, most options are irrelevant since
			// rows not shown don't exist and the index order is the applied order
			// Removed is a special case - for consistency just return an empty
			// array
			return search === 'removed' ?
				[] :
				_range( 0, displayMaster.length );
		}
		else if ( page == 'current' ) {
			// Current page implies that order=current and fitler=applied, since it is
			// fairly senseless otherwise, regardless of what order and search actually
			// are
			for ( i=settings._iDisplayStart, ien=settings.fnDisplayEnd() ; i<ien ; i++ ) {
				a.push( displayFiltered[i] );
			}
		}
		else if ( order == 'current' || order == 'applied' ) {
			a = search == 'none' ?
				displayMaster.slice() :                      // no search
				search == 'applied' ?
					displayFiltered.slice() :                // applied search
					$.map( displayMaster, function (el, i) { // removed search
						return $.inArray( el, displayFiltered ) === -1 ? el : null;
					} );
		}
		else if ( order == 'index' || order == 'original' ) {
			for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
				if ( search == 'none' ) {
					a.push( i );
				}
				else { // applied | removed
					tmp = $.inArray( i, displayFiltered );
	
					if ((tmp === -1 && search == 'removed') ||
						(tmp >= 0   && search == 'applied') )
					{
						a.push( i );
					}
				}
			}
		}
	
		return a;
	};
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Rows
	 *
	 * {}          - no selector - use all available rows
	 * {integer}   - row aoData index
	 * {node}      - TR node
	 * {string}    - jQuery selector to apply to the TR elements
	 * {array}     - jQuery array of nodes, or simply an array of TR nodes
	 *
	 */
	
	
	var __row_selector = function ( settings, selector, opts )
	{
		var rows;
		var run = function ( sel ) {
			var selInt = _intVal( sel );
			var i, ien;
	
			// Short cut - selector is a number and no options provided (default is
			// all records, so no need to check if the index is in there, since it
			// must be - dev error if the index doesn't exist).
			if ( selInt !== null && ! opts ) {
				return [ selInt ];
			}
	
			if ( ! rows ) {
				rows = _selector_row_indexes( settings, opts );
			}
	
			if ( selInt !== null && $.inArray( selInt, rows ) !== -1 ) {
				// Selector - integer
				return [ selInt ];
			}
			else if ( sel === null || sel === undefined || sel === '' ) {
				// Selector - none
				return rows;
			}
	
			// Selector - function
			if ( typeof sel === 'function' ) {
				return $.map( rows, function (idx) {
					var row = settings.aoData[ idx ];
					return sel( idx, row._aData, row.nTr ) ? idx : null;
				} );
			}
	
			// Get nodes in the order from the `rows` array with null values removed
			var nodes = _removeEmpty(
				_pluck_order( settings.aoData, rows, 'nTr' )
			);
	
			// Selector - node
			if ( sel.nodeName ) {
				if ( sel._DT_RowIndex !== undefined ) {
					return [ sel._DT_RowIndex ]; // Property added by DT for fast lookup
				}
				else if ( sel._DT_CellIndex ) {
					return [ sel._DT_CellIndex.row ];
				}
				else {
					var host = $(sel).closest('*[data-dt-row]');
					return host.length ?
						[ host.data('dt-row') ] :
						[];
				}
			}
	
			// ID selector. Want to always be able to select rows by id, regardless
			// of if the tr element has been created or not, so can't rely upon
			// jQuery here - hence a custom implementation. This does not match
			// Sizzle's fast selector or HTML4 - in HTML5 the ID can be anything,
			// but to select it using a CSS selector engine (like Sizzle or
			// querySelect) it would need to need to be escaped for some characters.
			// DataTables simplifies this for row selectors since you can select
			// only a row. A # indicates an id any anything that follows is the id -
			// unescaped.
			if ( typeof sel === 'string' && sel.charAt(0) === '#' ) {
				// get row index from id
				var rowObj = settings.aIds[ sel.replace( /^#/, '' ) ];
				if ( rowObj !== undefined ) {
					return [ rowObj.idx ];
				}
	
				// need to fall through to jQuery in case there is DOM id that
				// matches
			}
	
			// Selector - jQuery selector string, array of nodes or jQuery object/
			// As jQuery's .filter() allows jQuery objects to be passed in filter,
			// it also allows arrays, so this will cope with all three options
			return $(nodes)
				.filter( sel )
				.map( function () {
					return this._DT_RowIndex;
				} )
				.toArray();
		};
	
		return _selector_run( 'row', selector, run, settings, opts );
	};
	
	
	_api_register( 'rows()', function ( selector, opts ) {
		// argument shifting
		if ( selector === undefined ) {
			selector = '';
		}
		else if ( $.isPlainObject( selector ) ) {
			opts = selector;
			selector = '';
		}
	
		opts = _selector_opts( opts );
	
		var inst = this.iterator( 'table', function ( settings ) {
			return __row_selector( settings, selector, opts );
		}, 1 );
	
		// Want argument shifting here and in __row_selector?
		inst.selector.rows = selector;
		inst.selector.opts = opts;
	
		return inst;
	} );
	
	_api_register( 'rows().nodes()', function () {
		return this.iterator( 'row', function ( settings, row ) {
			return settings.aoData[ row ].nTr || undefined;
		}, 1 );
	} );
	
	_api_register( 'rows().data()', function () {
		return this.iterator( true, 'rows', function ( settings, rows ) {
			return _pluck_order( settings.aoData, rows, '_aData' );
		}, 1 );
	} );
	
	_api_registerPlural( 'rows().cache()', 'row().cache()', function ( type ) {
		return this.iterator( 'row', function ( settings, row ) {
			var r = settings.aoData[ row ];
			return type === 'search' ? r._aFilterData : r._aSortData;
		}, 1 );
	} );
	
	_api_registerPlural( 'rows().invalidate()', 'row().invalidate()', function ( src ) {
		return this.iterator( 'row', function ( settings, row ) {
			_fnInvalidate( settings, row, src );
		} );
	} );
	
	_api_registerPlural( 'rows().indexes()', 'row().index()', function () {
		return this.iterator( 'row', function ( settings, row ) {
			return row;
		}, 1 );
	} );
	
	_api_registerPlural( 'rows().ids()', 'row().id()', function ( hash ) {
		var a = [];
		var context = this.context;
	
		// `iterator` will drop undefined values, but in this case we want them
		for ( var i=0, ien=context.length ; i<ien ; i++ ) {
			for ( var j=0, jen=this[i].length ; j<jen ; j++ ) {
				var id = context[i].rowIdFn( context[i].aoData[ this[i][j] ]._aData );
				a.push( (hash === true ? '#' : '' )+ id );
			}
		}
	
		return new _Api( context, a );
	} );
	
	_api_registerPlural( 'rows().remove()', 'row().remove()', function () {
		var that = this;
	
		this.iterator( 'row', function ( settings, row, thatIdx ) {
			var data = settings.aoData;
			var rowData = data[ row ];
			var i, ien, j, jen;
			var loopRow, loopCells;
	
			data.splice( row, 1 );
	
			// Update the cached indexes
			for ( i=0, ien=data.length ; i<ien ; i++ ) {
				loopRow = data[i];
				loopCells = loopRow.anCells;
	
				// Rows
				if ( loopRow.nTr !== null ) {
					loopRow.nTr._DT_RowIndex = i;
				}
	
				// Cells
				if ( loopCells !== null ) {
					for ( j=0, jen=loopCells.length ; j<jen ; j++ ) {
						loopCells[j]._DT_CellIndex.row = i;
					}
				}
			}
	
			// Delete from the display arrays
			_fnDeleteIndex( settings.aiDisplayMaster, row );
			_fnDeleteIndex( settings.aiDisplay, row );
			_fnDeleteIndex( that[ thatIdx ], row, false ); // maintain local indexes
	
			// Check for an 'overflow' they case for displaying the table
			_fnLengthOverflow( settings );
	
			// Remove the row's ID reference if there is one
			var id = settings.rowIdFn( rowData._aData );
			if ( id !== undefined ) {
				delete settings.aIds[ id ];
			}
		} );
	
		this.iterator( 'table', function ( settings ) {
			for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
				settings.aoData[i].idx = i;
			}
		} );
	
		return this;
	} );
	
	
	_api_register( 'rows.add()', function ( rows ) {
		var newRows = this.iterator( 'table', function ( settings ) {
				var row, i, ien;
				var out = [];
	
				for ( i=0, ien=rows.length ; i<ien ; i++ ) {
					row = rows[i];
	
					if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
						out.push( _fnAddTr( settings, row )[0] );
					}
					else {
						out.push( _fnAddData( settings, row ) );
					}
				}
	
				return out;
			}, 1 );
	
		// Return an Api.rows() extended instance, so rows().nodes() etc can be used
		var modRows = this.rows( -1 );
		modRows.pop();
		$.merge( modRows, newRows );
	
		return modRows;
	} );
	
	
	
	
	
	/**
	 *
	 */
	_api_register( 'row()', function ( selector, opts ) {
		return _selector_first( this.rows( selector, opts ) );
	} );
	
	
	_api_register( 'row().data()', function ( data ) {
		var ctx = this.context;
	
		if ( data === undefined ) {
			// Get
			return ctx.length && this.length ?
				ctx[0].aoData[ this[0] ]._aData :
				undefined;
		}
	
		// Set
		ctx[0].aoData[ this[0] ]._aData = data;
	
		// Automatically invalidate
		_fnInvalidate( ctx[0], this[0], 'data' );
	
		return this;
	} );
	
	
	_api_register( 'row().node()', function () {
		var ctx = this.context;
	
		return ctx.length && this.length ?
			ctx[0].aoData[ this[0] ].nTr || null :
			null;
	} );
	
	
	_api_register( 'row.add()', function ( row ) {
		// Allow a jQuery object to be passed in - only a single row is added from
		// it though - the first element in the set
		if ( row instanceof $ && row.length ) {
			row = row[0];
		}
	
		var rows = this.iterator( 'table', function ( settings ) {
			if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
				return _fnAddTr( settings, row )[0];
			}
			return _fnAddData( settings, row );
		} );
	
		// Return an Api.rows() extended instance, with the newly added row selected
		return this.row( rows[0] );
	} );
	
	
	
	var __details_add = function ( ctx, row, data, klass )
	{
		// Convert to array of TR elements
		var rows = [];
		var addRow = function ( r, k ) {
			// Recursion to allow for arrays of jQuery objects
			if ( $.isArray( r ) || r instanceof $ ) {
				for ( var i=0, ien=r.length ; i<ien ; i++ ) {
					addRow( r[i], k );
				}
				return;
			}
	
			// If we get a TR element, then just add it directly - up to the dev
			// to add the correct number of columns etc
			if ( r.nodeName && r.nodeName.toLowerCase() === 'tr' ) {
				rows.push( r );
			}
			else {
				// Otherwise create a row with a wrapper
				var created = $('<tr><td/></tr>').addClass( k );
				$('td', created)
					.addClass( k )
					.html( r )
					[0].colSpan = _fnVisbleColumns( ctx );
	
				rows.push( created[0] );
			}
		};
	
		addRow( data, klass );
	
		if ( row._details ) {
			row._details.detach();
		}
	
		row._details = $(rows);
	
		// If the children were already shown, that state should be retained
		if ( row._detailsShow ) {
			row._details.insertAfter( row.nTr );
		}
	};
	
	
	var __details_remove = function ( api, idx )
	{
		var ctx = api.context;
	
		if ( ctx.length ) {
			var row = ctx[0].aoData[ idx !== undefined ? idx : api[0] ];
	
			if ( row && row._details ) {
				row._details.remove();
	
				row._detailsShow = undefined;
				row._details = undefined;
			}
		}
	};
	
	
	var __details_display = function ( api, show ) {
		var ctx = api.context;
	
		if ( ctx.length && api.length ) {
			var row = ctx[0].aoData[ api[0] ];
	
			if ( row._details ) {
				row._detailsShow = show;
	
				if ( show ) {
					row._details.insertAfter( row.nTr );
				}
				else {
					row._details.detach();
				}
	
				__details_events( ctx[0] );
			}
		}
	};
	
	
	var __details_events = function ( settings )
	{
		var api = new _Api( settings );
		var namespace = '.dt.DT_details';
		var drawEvent = 'draw'+namespace;
		var colvisEvent = 'column-visibility'+namespace;
		var destroyEvent = 'destroy'+namespace;
		var data = settings.aoData;
	
		api.off( drawEvent +' '+ colvisEvent +' '+ destroyEvent );
	
		if ( _pluck( data, '_details' ).length > 0 ) {
			// On each draw, insert the required elements into the document
			api.on( drawEvent, function ( e, ctx ) {
				if ( settings !== ctx ) {
					return;
				}
	
				api.rows( {page:'current'} ).eq(0).each( function (idx) {
					// Internal data grab
					var row = data[ idx ];
	
					if ( row._detailsShow ) {
						row._details.insertAfter( row.nTr );
					}
				} );
			} );
	
			// Column visibility change - update the colspan
			api.on( colvisEvent, function ( e, ctx, idx, vis ) {
				if ( settings !== ctx ) {
					return;
				}
	
				// Update the colspan for the details rows (note, only if it already has
				// a colspan)
				var row, visible = _fnVisbleColumns( ctx );
	
				for ( var i=0, ien=data.length ; i<ien ; i++ ) {
					row = data[i];
	
					if ( row._details ) {
						row._details.children('td[colspan]').attr('colspan', visible );
					}
				}
			} );
	
			// Table destroyed - nuke any child rows
			api.on( destroyEvent, function ( e, ctx ) {
				if ( settings !== ctx ) {
					return;
				}
	
				for ( var i=0, ien=data.length ; i<ien ; i++ ) {
					if ( data[i]._details ) {
						__details_remove( api, i );
					}
				}
			} );
		}
	};
	
	// Strings for the method names to help minification
	var _emp = '';
	var _child_obj = _emp+'row().child';
	var _child_mth = _child_obj+'()';
	
	// data can be:
	//  tr
	//  string
	//  jQuery or array of any of the above
	_api_register( _child_mth, function ( data, klass ) {
		var ctx = this.context;
	
		if ( data === undefined ) {
			// get
			return ctx.length && this.length ?
				ctx[0].aoData[ this[0] ]._details :
				undefined;
		}
		else if ( data === true ) {
			// show
			this.child.show();
		}
		else if ( data === false ) {
			// remove
			__details_remove( this );
		}
		else if ( ctx.length && this.length ) {
			// set
			__details_add( ctx[0], ctx[0].aoData[ this[0] ], data, klass );
		}
	
		return this;
	} );
	
	
	_api_register( [
		_child_obj+'.show()',
		_child_mth+'.show()' // only when `child()` was called with parameters (without
	], function ( show ) {   // it returns an object and this method is not executed)
		__details_display( this, true );
		return this;
	} );
	
	
	_api_register( [
		_child_obj+'.hide()',
		_child_mth+'.hide()' // only when `child()` was called with parameters (without
	], function () {         // it returns an object and this method is not executed)
		__details_display( this, false );
		return this;
	} );
	
	
	_api_register( [
		_child_obj+'.remove()',
		_child_mth+'.remove()' // only when `child()` was called with parameters (without
	], function () {           // it returns an object and this method is not executed)
		__details_remove( this );
		return this;
	} );
	
	
	_api_register( _child_obj+'.isShown()', function () {
		var ctx = this.context;
	
		if ( ctx.length && this.length ) {
			// _detailsShown as false or undefined will fall through to return false
			return ctx[0].aoData[ this[0] ]._detailsShow || false;
		}
		return false;
	} );
	
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Columns
	 *
	 * {integer}           - column index (>=0 count from left, <0 count from right)
	 * "{integer}:visIdx"  - visible column index (i.e. translate to column index)  (>=0 count from left, <0 count from right)
	 * "{integer}:visible" - alias for {integer}:visIdx  (>=0 count from left, <0 count from right)
	 * "{string}:name"     - column name
	 * "{string}"          - jQuery selector on column header nodes
	 *
	 */
	
	// can be an array of these items, comma separated list, or an array of comma
	// separated lists
	
	var __re_column_selector = /^([^:]+):(name|visIdx|visible)$/;
	
	
	// r1 and r2 are redundant - but it means that the parameters match for the
	// iterator callback in columns().data()
	var __columnData = function ( settings, column, r1, r2, rows ) {
		var a = [];
		for ( var row=0, ien=rows.length ; row<ien ; row++ ) {
			a.push( _fnGetCellData( settings, rows[row], column ) );
		}
		return a;
	};
	
	
	var __column_selector = function ( settings, selector, opts )
	{
		var
			columns = settings.aoColumns,
			names = _pluck( columns, 'sName' ),
			nodes = _pluck( columns, 'nTh' );
	
		var run = function ( s ) {
			var selInt = _intVal( s );
	
			// Selector - all
			if ( s === '' ) {
				return _range( columns.length );
			}
	
			// Selector - index
			if ( selInt !== null ) {
				return [ selInt >= 0 ?
					selInt : // Count from left
					columns.length + selInt // Count from right (+ because its a negative value)
				];
			}
	
			// Selector = function
			if ( typeof s === 'function' ) {
				var rows = _selector_row_indexes( settings, opts );
	
				return $.map( columns, function (col, idx) {
					return s(
							idx,
							__columnData( settings, idx, 0, 0, rows ),
							nodes[ idx ]
						) ? idx : null;
				} );
			}
	
			// jQuery or string selector
			var match = typeof s === 'string' ?
				s.match( __re_column_selector ) :
				'';
	
			if ( match ) {
				switch( match[2] ) {
					case 'visIdx':
					case 'visible':
						var idx = parseInt( match[1], 10 );
						// Visible index given, convert to column index
						if ( idx < 0 ) {
							// Counting from the right
							var visColumns = $.map( columns, function (col,i) {
								return col.bVisible ? i : null;
							} );
							return [ visColumns[ visColumns.length + idx ] ];
						}
						// Counting from the left
						return [ _fnVisibleToColumnIndex( settings, idx ) ];
	
					case 'name':
						// match by name. `names` is column index complete and in order
						return $.map( names, function (name, i) {
							return name === match[1] ? i : null;
						} );
	
					default:
						return [];
				}
			}
	
			// Cell in the table body
			if ( s.nodeName && s._DT_CellIndex ) {
				return [ s._DT_CellIndex.column ];
			}
	
			// jQuery selector on the TH elements for the columns
			var jqResult = $( nodes )
				.filter( s )
				.map( function () {
					return $.inArray( this, nodes ); // `nodes` is column index complete and in order
				} )
				.toArray();
	
			if ( jqResult.length || ! s.nodeName ) {
				return jqResult;
			}
	
			// Otherwise a node which might have a `dt-column` data attribute, or be
			// a child or such an element
			var host = $(s).closest('*[data-dt-column]');
			return host.length ?
				[ host.data('dt-column') ] :
				[];
		};
	
		return _selector_run( 'column', selector, run, settings, opts );
	};
	
	
	var __setColumnVis = function ( settings, column, vis ) {
		var
			cols = settings.aoColumns,
			col  = cols[ column ],
			data = settings.aoData,
			row, cells, i, ien, tr;
	
		// Get
		if ( vis === undefined ) {
			return col.bVisible;
		}
	
		// Set
		// No change
		if ( col.bVisible === vis ) {
			return;
		}
	
		if ( vis ) {
			// Insert column
			// Need to decide if we should use appendChild or insertBefore
			var insertBefore = $.inArray( true, _pluck(cols, 'bVisible'), column+1 );
	
			for ( i=0, ien=data.length ; i<ien ; i++ ) {
				tr = data[i].nTr;
				cells = data[i].anCells;
	
				if ( tr ) {
					// insertBefore can act like appendChild if 2nd arg is null
					tr.insertBefore( cells[ column ], cells[ insertBefore ] || null );
				}
			}
		}
		else {
			// Remove column
			$( _pluck( settings.aoData, 'anCells', column ) ).detach();
		}
	
		// Common actions
		col.bVisible = vis;
		_fnDrawHead( settings, settings.aoHeader );
		_fnDrawHead( settings, settings.aoFooter );
	
		_fnSaveState( settings );
	};
	
	
	_api_register( 'columns()', function ( selector, opts ) {
		// argument shifting
		if ( selector === undefined ) {
			selector = '';
		}
		else if ( $.isPlainObject( selector ) ) {
			opts = selector;
			selector = '';
		}
	
		opts = _selector_opts( opts );
	
		var inst = this.iterator( 'table', function ( settings ) {
			return __column_selector( settings, selector, opts );
		}, 1 );
	
		// Want argument shifting here and in _row_selector?
		inst.selector.cols = selector;
		inst.selector.opts = opts;
	
		return inst;
	} );
	
	_api_registerPlural( 'columns().header()', 'column().header()', function ( selector, opts ) {
		return this.iterator( 'column', function ( settings, column ) {
			return settings.aoColumns[column].nTh;
		}, 1 );
	} );
	
	_api_registerPlural( 'columns().footer()', 'column().footer()', function ( selector, opts ) {
		return this.iterator( 'column', function ( settings, column ) {
			return settings.aoColumns[column].nTf;
		}, 1 );
	} );
	
	_api_registerPlural( 'columns().data()', 'column().data()', function () {
		return this.iterator( 'column-rows', __columnData, 1 );
	} );
	
	_api_registerPlural( 'columns().dataSrc()', 'column().dataSrc()', function () {
		return this.iterator( 'column', function ( settings, column ) {
			return settings.aoColumns[column].mData;
		}, 1 );
	} );
	
	_api_registerPlural( 'columns().cache()', 'column().cache()', function ( type ) {
		return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
			return _pluck_order( settings.aoData, rows,
				type === 'search' ? '_aFilterData' : '_aSortData', column
			);
		}, 1 );
	} );
	
	_api_registerPlural( 'columns().nodes()', 'column().nodes()', function () {
		return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
			return _pluck_order( settings.aoData, rows, 'anCells', column ) ;
		}, 1 );
	} );
	
	_api_registerPlural( 'columns().visible()', 'column().visible()', function ( vis, calc ) {
		var ret = this.iterator( 'column', function ( settings, column ) {
			if ( vis === undefined ) {
				return settings.aoColumns[ column ].bVisible;
			} // else
			__setColumnVis( settings, column, vis );
		} );
	
		// Group the column visibility changes
		if ( vis !== undefined ) {
			// Second loop once the first is done for events
			this.iterator( 'column', function ( settings, column ) {
				_fnCallbackFire( settings, null, 'column-visibility', [settings, column, vis, calc] );
			} );
	
			if ( calc === undefined || calc ) {
				this.columns.adjust();
			}
		}
	
		return ret;
	} );
	
	_api_registerPlural( 'columns().indexes()', 'column().index()', function ( type ) {
		return this.iterator( 'column', function ( settings, column ) {
			return type === 'visible' ?
				_fnColumnIndexToVisible( settings, column ) :
				column;
		}, 1 );
	} );
	
	_api_register( 'columns.adjust()', function () {
		return this.iterator( 'table', function ( settings ) {
			_fnAdjustColumnSizing( settings );
		}, 1 );
	} );
	
	_api_register( 'column.index()', function ( type, idx ) {
		if ( this.context.length !== 0 ) {
			var ctx = this.context[0];
	
			if ( type === 'fromVisible' || type === 'toData' ) {
				return _fnVisibleToColumnIndex( ctx, idx );
			}
			else if ( type === 'fromData' || type === 'toVisible' ) {
				return _fnColumnIndexToVisible( ctx, idx );
			}
		}
	} );
	
	_api_register( 'column()', function ( selector, opts ) {
		return _selector_first( this.columns( selector, opts ) );
	} );
	
	
	
	var __cell_selector = function ( settings, selector, opts )
	{
		var data = settings.aoData;
		var rows = _selector_row_indexes( settings, opts );
		var cells = _removeEmpty( _pluck_order( data, rows, 'anCells' ) );
		var allCells = $( [].concat.apply([], cells) );
		var row;
		var columns = settings.aoColumns.length;
		var a, i, ien, j, o, host;
	
		var run = function ( s ) {
			var fnSelector = typeof s === 'function';
	
			if ( s === null || s === undefined || fnSelector ) {
				// All cells and function selectors
				a = [];
	
				for ( i=0, ien=rows.length ; i<ien ; i++ ) {
					row = rows[i];
	
					for ( j=0 ; j<columns ; j++ ) {
						o = {
							row: row,
							column: j
						};
	
						if ( fnSelector ) {
							// Selector - function
							host = data[ row ];
	
							if ( s( o, _fnGetCellData(settings, row, j), host.anCells ? host.anCells[j] : null ) ) {
								a.push( o );
							}
						}
						else {
							// Selector - all
							a.push( o );
						}
					}
				}
	
				return a;
			}
			
			// Selector - index
			if ( $.isPlainObject( s ) ) {
				return [s];
			}
	
			// Selector - jQuery filtered cells
			var jqResult = allCells
				.filter( s )
				.map( function (i, el) {
					return { // use a new object, in case someone changes the values
						row:    el._DT_CellIndex.row,
						column: el._DT_CellIndex.column
	 				};
				} )
				.toArray();
	
			if ( jqResult.length || ! s.nodeName ) {
				return jqResult;
			}
	
			// Otherwise the selector is a node, and there is one last option - the
			// element might be a child of an element which has dt-row and dt-column
			// data attributes
			host = $(s).closest('*[data-dt-row]');
			return host.length ?
				[ {
					row: host.data('dt-row'),
					column: host.data('dt-column')
				} ] :
				[];
		};
	
		return _selector_run( 'cell', selector, run, settings, opts );
	};
	
	
	
	
	_api_register( 'cells()', function ( rowSelector, columnSelector, opts ) {
		// Argument shifting
		if ( $.isPlainObject( rowSelector ) ) {
			// Indexes
			if ( rowSelector.row === undefined ) {
				// Selector options in first parameter
				opts = rowSelector;
				rowSelector = null;
			}
			else {
				// Cell index objects in first parameter
				opts = columnSelector;
				columnSelector = null;
			}
		}
		if ( $.isPlainObject( columnSelector ) ) {
			opts = columnSelector;
			columnSelector = null;
		}
	
		// Cell selector
		if ( columnSelector === null || columnSelector === undefined ) {
			return this.iterator( 'table', function ( settings ) {
				return __cell_selector( settings, rowSelector, _selector_opts( opts ) );
			} );
		}
	
		// Row + column selector
		var columns = this.columns( columnSelector, opts );
		var rows = this.rows( rowSelector, opts );
		var a, i, ien, j, jen;
	
		var cells = this.iterator( 'table', function ( settings, idx ) {
			a = [];
	
			for ( i=0, ien=rows[idx].length ; i<ien ; i++ ) {
				for ( j=0, jen=columns[idx].length ; j<jen ; j++ ) {
					a.push( {
						row:    rows[idx][i],
						column: columns[idx][j]
					} );
				}
			}
	
			return a;
		}, 1 );
	
		$.extend( cells.selector, {
			cols: columnSelector,
			rows: rowSelector,
			opts: opts
		} );
	
		return cells;
	} );
	
	
	_api_registerPlural( 'cells().nodes()', 'cell().node()', function () {
		return this.iterator( 'cell', function ( settings, row, column ) {
			var data = settings.aoData[ row ];
	
			return data && data.anCells ?
				data.anCells[ column ] :
				undefined;
		}, 1 );
	} );
	
	
	_api_register( 'cells().data()', function () {
		return this.iterator( 'cell', function ( settings, row, column ) {
			return _fnGetCellData( settings, row, column );
		}, 1 );
	} );
	
	
	_api_registerPlural( 'cells().cache()', 'cell().cache()', function ( type ) {
		type = type === 'search' ? '_aFilterData' : '_aSortData';
	
		return this.iterator( 'cell', function ( settings, row, column ) {
			return settings.aoData[ row ][ type ][ column ];
		}, 1 );
	} );
	
	
	_api_registerPlural( 'cells().render()', 'cell().render()', function ( type ) {
		return this.iterator( 'cell', function ( settings, row, column ) {
			return _fnGetCellData( settings, row, column, type );
		}, 1 );
	} );
	
	
	_api_registerPlural( 'cells().indexes()', 'cell().index()', function () {
		return this.iterator( 'cell', function ( settings, row, column ) {
			return {
				row: row,
				column: column,
				columnVisible: _fnColumnIndexToVisible( settings, column )
			};
		}, 1 );
	} );
	
	
	_api_registerPlural( 'cells().invalidate()', 'cell().invalidate()', function ( src ) {
		return this.iterator( 'cell', function ( settings, row, column ) {
			_fnInvalidate( settings, row, src, column );
		} );
	} );
	
	
	
	_api_register( 'cell()', function ( rowSelector, columnSelector, opts ) {
		return _selector_first( this.cells( rowSelector, columnSelector, opts ) );
	} );
	
	
	_api_register( 'cell().data()', function ( data ) {
		var ctx = this.context;
		var cell = this[0];
	
		if ( data === undefined ) {
			// Get
			return ctx.length && cell.length ?
				_fnGetCellData( ctx[0], cell[0].row, cell[0].column ) :
				undefined;
		}
	
		// Set
		_fnSetCellData( ctx[0], cell[0].row, cell[0].column, data );
		_fnInvalidate( ctx[0], cell[0].row, 'data', cell[0].column );
	
		return this;
	} );
	
	
	
	/**
	 * Get current ordering (sorting) that has been applied to the table.
	 *
	 * @returns {array} 2D array containing the sorting information for the first
	 *   table in the current context. Each element in the parent array represents
	 *   a column being sorted upon (i.e. multi-sorting with two columns would have
	 *   2 inner arrays). The inner arrays may have 2 or 3 elements. The first is
	 *   the column index that the sorting condition applies to, the second is the
	 *   direction of the sort (`desc` or `asc`) and, optionally, the third is the
	 *   index of the sorting order from the `column.sorting` initialisation array.
	 *//**
	 * Set the ordering for the table.
	 *
	 * @param {integer} order Column index to sort upon.
	 * @param {string} direction Direction of the sort to be applied (`asc` or `desc`)
	 * @returns {DataTables.Api} this
	 *//**
	 * Set the ordering for the table.
	 *
	 * @param {array} order 1D array of sorting information to be applied.
	 * @param {array} [...] Optional additional sorting conditions
	 * @returns {DataTables.Api} this
	 *//**
	 * Set the ordering for the table.
	 *
	 * @param {array} order 2D array of sorting information to be applied.
	 * @returns {DataTables.Api} this
	 */
	_api_register( 'order()', function ( order, dir ) {
		var ctx = this.context;
	
		if ( order === undefined ) {
			// get
			return ctx.length !== 0 ?
				ctx[0].aaSorting :
				undefined;
		}
	
		// set
		if ( typeof order === 'number' ) {
			// Simple column / direction passed in
			order = [ [ order, dir ] ];
		}
		else if ( order.length && ! $.isArray( order[0] ) ) {
			// Arguments passed in (list of 1D arrays)
			order = Array.prototype.slice.call( arguments );
		}
		// otherwise a 2D array was passed in
	
		return this.iterator( 'table', function ( settings ) {
			settings.aaSorting = order.slice();
		} );
	} );
	
	
	/**
	 * Attach a sort listener to an element for a given column
	 *
	 * @param {node|jQuery|string} node Identifier for the element(s) to attach the
	 *   listener to. This can take the form of a single DOM node, a jQuery
	 *   collection of nodes or a jQuery selector which will identify the node(s).
	 * @param {integer} column the column that a click on this node will sort on
	 * @param {function} [callback] callback function when sort is run
	 * @returns {DataTables.Api} this
	 */
	_api_register( 'order.listener()', function ( node, column, callback ) {
		return this.iterator( 'table', function ( settings ) {
			_fnSortAttachListener( settings, node, column, callback );
		} );
	} );
	
	
	_api_register( 'order.fixed()', function ( set ) {
		if ( ! set ) {
			var ctx = this.context;
			var fixed = ctx.length ?
				ctx[0].aaSortingFixed :
				undefined;
	
			return $.isArray( fixed ) ?
				{ pre: fixed } :
				fixed;
		}
	
		return this.iterator( 'table', function ( settings ) {
			settings.aaSortingFixed = $.extend( true, {}, set );
		} );
	} );
	
	
	// Order by the selected column(s)
	_api_register( [
		'columns().order()',
		'column().order()'
	], function ( dir ) {
		var that = this;
	
		return this.iterator( 'table', function ( settings, i ) {
			var sort = [];
	
			$.each( that[i], function (j, col) {
				sort.push( [ col, dir ] );
			} );
	
			settings.aaSorting = sort;
		} );
	} );
	
	
	
	_api_register( 'search()', function ( input, regex, smart, caseInsen ) {
		var ctx = this.context;
	
		if ( input === undefined ) {
			// get
			return ctx.length !== 0 ?
				ctx[0].oPreviousSearch.sSearch :
				undefined;
		}
	
		// set
		return this.iterator( 'table', function ( settings ) {
			if ( ! settings.oFeatures.bFilter ) {
				return;
			}
	
			_fnFilterComplete( settings, $.extend( {}, settings.oPreviousSearch, {
				"sSearch": input+"",
				"bRegex":  regex === null ? false : regex,
				"bSmart":  smart === null ? true  : smart,
				"bCaseInsensitive": caseInsen === null ? true : caseInsen
			} ), 1 );
		} );
	} );
	
	
	_api_registerPlural(
		'columns().search()',
		'column().search()',
		function ( input, regex, smart, caseInsen ) {
			return this.iterator( 'column', function ( settings, column ) {
				var preSearch = settings.aoPreSearchCols;
	
				if ( input === undefined ) {
					// get
					return preSearch[ column ].sSearch;
				}
	
				// set
				if ( ! settings.oFeatures.bFilter ) {
					return;
				}
	
				$.extend( preSearch[ column ], {
					"sSearch": input+"",
					"bRegex":  regex === null ? false : regex,
					"bSmart":  smart === null ? true  : smart,
					"bCaseInsensitive": caseInsen === null ? true : caseInsen
				} );
	
				_fnFilterComplete( settings, settings.oPreviousSearch, 1 );
			} );
		}
	);
	
	/*
	 * State API methods
	 */
	
	_api_register( 'state()', function () {
		return this.context.length ?
			this.context[0].oSavedState :
			null;
	} );
	
	
	_api_register( 'state.clear()', function () {
		return this.iterator( 'table', function ( settings ) {
			// Save an empty object
			settings.fnStateSaveCallback.call( settings.oInstance, settings, {} );
		} );
	} );
	
	
	_api_register( 'state.loaded()', function () {
		return this.context.length ?
			this.context[0].oLoadedState :
			null;
	} );
	
	
	_api_register( 'state.save()', function () {
		return this.iterator( 'table', function ( settings ) {
			_fnSaveState( settings );
		} );
	} );
	
	
	
	/**
	 * Provide a common method for plug-ins to check the version of DataTables being
	 * used, in order to ensure compatibility.
	 *
	 *  @param {string} version Version string to check for, in the format "X.Y.Z".
	 *    Note that the formats "X" and "X.Y" are also acceptable.
	 *  @returns {boolean} true if this version of DataTables is greater or equal to
	 *    the required version, or false if this version of DataTales is not
	 *    suitable
	 *  @static
	 *  @dtopt API-Static
	 *
	 *  @example
	 *    alert( $.fn.dataTable.versionCheck( '1.9.0' ) );
	 */
	DataTable.versionCheck = DataTable.fnVersionCheck = function( version )
	{
		var aThis = DataTable.version.split('.');
		var aThat = version.split('.');
		var iThis, iThat;
	
		for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) {
			iThis = parseInt( aThis[i], 10 ) || 0;
			iThat = parseInt( aThat[i], 10 ) || 0;
	
			// Parts are the same, keep comparing
			if (iThis === iThat) {
				continue;
			}
	
			// Parts are different, return immediately
			return iThis > iThat;
		}
	
		return true;
	};
	
	
	/**
	 * Check if a `<table>` node is a DataTable table already or not.
	 *
	 *  @param {node|jquery|string} table Table node, jQuery object or jQuery
	 *      selector for the table to test. Note that if more than more than one
	 *      table is passed on, only the first will be checked
	 *  @returns {boolean} true the table given is a DataTable, or false otherwise
	 *  @static
	 *  @dtopt API-Static
	 *
	 *  @example
	 *    if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
	 *      $('#example').dataTable();
	 *    }
	 */
	DataTable.isDataTable = DataTable.fnIsDataTable = function ( table )
	{
		var t = $(table).get(0);
		var is = false;
	
		if ( table instanceof DataTable.Api ) {
			return true;
		}
	
		$.each( DataTable.settings, function (i, o) {
			var head = o.nScrollHead ? $('table', o.nScrollHead)[0] : null;
			var foot = o.nScrollFoot ? $('table', o.nScrollFoot)[0] : null;
	
			if ( o.nTable === t || head === t || foot === t ) {
				is = true;
			}
		} );
	
		return is;
	};
	
	
	/**
	 * Get all DataTable tables that have been initialised - optionally you can
	 * select to get only currently visible tables.
	 *
	 *  @param {boolean} [visible=false] Flag to indicate if you want all (default)
	 *    or visible tables only.
	 *  @returns {array} Array of `table` nodes (not DataTable instances) which are
	 *    DataTables
	 *  @static
	 *  @dtopt API-Static
	 *
	 *  @example
	 *    $.each( $.fn.dataTable.tables(true), function () {
	 *      $(table).DataTable().columns.adjust();
	 *    } );
	 */
	DataTable.tables = DataTable.fnTables = function ( visible )
	{
		var api = false;
	
		if ( $.isPlainObject( visible ) ) {
			api = visible.api;
			visible = visible.visible;
		}
	
		var a = $.map( DataTable.settings, function (o) {
			if ( !visible || (visible && $(o.nTable).is(':visible')) ) {
				return o.nTable;
			}
		} );
	
		return api ?
			new _Api( a ) :
			a;
	};
	
	
	/**
	 * Convert from camel case parameters to Hungarian notation. This is made public
	 * for the extensions to provide the same ability as DataTables core to accept
	 * either the 1.9 style Hungarian notation, or the 1.10+ style camelCase
	 * parameters.
	 *
	 *  @param {object} src The model object which holds all parameters that can be
	 *    mapped.
	 *  @param {object} user The object to convert from camel case to Hungarian.
	 *  @param {boolean} force When set to `true`, properties which already have a
	 *    Hungarian value in the `user` object will be overwritten. Otherwise they
	 *    won't be.
	 */
	DataTable.camelToHungarian = _fnCamelToHungarian;
	
	
	
	/**
	 *
	 */
	_api_register( '$()', function ( selector, opts ) {
		var
			rows   = this.rows( opts ).nodes(), // Get all rows
			jqRows = $(rows);
	
		return $( [].concat(
			jqRows.filter( selector ).toArray(),
			jqRows.find( selector ).toArray()
		) );
	} );
	
	
	// jQuery functions to operate on the tables
	$.each( [ 'on', 'one', 'off' ], function (i, key) {
		_api_register( key+'()', function ( /* event, handler */ ) {
			var args = Array.prototype.slice.call(arguments);
	
			// Add the `dt` namespace automatically if it isn't already present
			args[0] = $.map( args[0].split( /\s/ ), function ( e ) {
				return ! e.match(/\.dt\b/) ?
					e+'.dt' :
					e;
				} ).join( ' ' );
	
			var inst = $( this.tables().nodes() );
			inst[key].apply( inst, args );
			return this;
		} );
	} );
	
	
	_api_register( 'clear()', function () {
		return this.iterator( 'table', function ( settings ) {
			_fnClearTable( settings );
		} );
	} );
	
	
	_api_register( 'settings()', function () {
		return new _Api( this.context, this.context );
	} );
	
	
	_api_register( 'init()', function () {
		var ctx = this.context;
		return ctx.length ? ctx[0].oInit : null;
	} );
	
	
	_api_register( 'data()', function () {
		return this.iterator( 'table', function ( settings ) {
			return _pluck( settings.aoData, '_aData' );
		} ).flatten();
	} );
	
	
	_api_register( 'destroy()', function ( remove ) {
		remove = remove || false;
	
		return this.iterator( 'table', function ( settings ) {
			var orig      = settings.nTableWrapper.parentNode;
			var classes   = settings.oClasses;
			var table     = settings.nTable;
			var tbody     = settings.nTBody;
			var thead     = settings.nTHead;
			var tfoot     = settings.nTFoot;
			var jqTable   = $(table);
			var jqTbody   = $(tbody);
			var jqWrapper = $(settings.nTableWrapper);
			var rows      = $.map( settings.aoData, function (r) { return r.nTr; } );
			var i, ien;
	
			// Flag to note that the table is currently being destroyed - no action
			// should be taken
			settings.bDestroying = true;
	
			// Fire off the destroy callbacks for plug-ins etc
			_fnCallbackFire( settings, "aoDestroyCallback", "destroy", [settings] );
	
			// If not being removed from the document, make all columns visible
			if ( ! remove ) {
				new _Api( settings ).columns().visible( true );
			}
	
			// Blitz all `DT` namespaced events (these are internal events, the
			// lowercase, `dt` events are user subscribed and they are responsible
			// for removing them
			jqWrapper.off('.DT').find(':not(tbody *)').off('.DT');
			$(window).off('.DT-'+settings.sInstance);
	
			// When scrolling we had to break the table up - restore it
			if ( table != thead.parentNode ) {
				jqTable.children('thead').detach();
				jqTable.append( thead );
			}
	
			if ( tfoot && table != tfoot.parentNode ) {
				jqTable.children('tfoot').detach();
				jqTable.append( tfoot );
			}
	
			settings.aaSorting = [];
			settings.aaSortingFixed = [];
			_fnSortingClasses( settings );
	
			$( rows ).removeClass( settings.asStripeClasses.join(' ') );
	
			$('th, td', thead).removeClass( classes.sSortable+' '+
				classes.sSortableAsc+' '+classes.sSortableDesc+' '+classes.sSortableNone
			);
	
			if ( settings.bJUI ) {
				$('th span.'+classes.sSortIcon+ ', td span.'+classes.sSortIcon, thead).detach();
				$('th, td', thead).each( function () {
					var wrapper = $('div.'+classes.sSortJUIWrapper, this);
					$(this).append( wrapper.contents() );
					wrapper.detach();
				} );
			}
	
			// Add the TR elements back into the table in their original order
			jqTbody.children().detach();
			jqTbody.append( rows );
	
			// Remove the DataTables generated nodes, events and classes
			var removedMethod = remove ? 'remove' : 'detach';
			jqTable[ removedMethod ]();
			jqWrapper[ removedMethod ]();
	
			// If we need to reattach the table to the document
			if ( ! remove && orig ) {
				// insertBefore acts like appendChild if !arg[1]
				orig.insertBefore( table, settings.nTableReinsertBefore );
	
				// Restore the width of the original table - was read from the style property,
				// so we can restore directly to that
				jqTable
					.css( 'width', settings.sDestroyWidth )
					.removeClass( classes.sTable );
	
				// If the were originally stripe classes - then we add them back here.
				// Note this is not fool proof (for example if not all rows had stripe
				// classes - but it's a good effort without getting carried away
				ien = settings.asDestroyStripes.length;
	
				if ( ien ) {
					jqTbody.children().each( function (i) {
						$(this).addClass( settings.asDestroyStripes[i % ien] );
					} );
				}
			}
	
			/* Remove the settings object from the settings array */
			var idx = $.inArray( settings, DataTable.settings );
			if ( idx !== -1 ) {
				DataTable.settings.splice( idx, 1 );
			}
		} );
	} );
	
	
	// Add the `every()` method for rows, columns and cells in a compact form
	$.each( [ 'column', 'row', 'cell' ], function ( i, type ) {
		_api_register( type+'s().every()', function ( fn ) {
			var opts = this.selector.opts;
			var api = this;
	
			return this.iterator( type, function ( settings, arg1, arg2, arg3, arg4 ) {
				// Rows and columns:
				//  arg1 - index
				//  arg2 - table counter
				//  arg3 - loop counter
				//  arg4 - undefined
				// Cells:
				//  arg1 - row index
				//  arg2 - column index
				//  arg3 - table counter
				//  arg4 - loop counter
				fn.call(
					api[ type ](
						arg1,
						type==='cell' ? arg2 : opts,
						type==='cell' ? opts : undefined
					),
					arg1, arg2, arg3, arg4
				);
			} );
		} );
	} );
	
	
	// i18n method for extensions to be able to use the language object from the
	// DataTable
	_api_register( 'i18n()', function ( token, def, plural ) {
		var ctx = this.context[0];
		var resolved = _fnGetObjectDataFn( token )( ctx.oLanguage );
	
		if ( resolved === undefined ) {
			resolved = def;
		}
	
		if ( plural !== undefined && $.isPlainObject( resolved ) ) {
			resolved = resolved[ plural ] !== undefined ?
				resolved[ plural ] :
				resolved._;
		}
	
		return resolved.replace( '%d', plural ); // nb: plural might be undefined,
	} );

	/**
	 * Version string for plug-ins to check compatibility. Allowed format is
	 * `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used
	 * only for non-release builds. See http://semver.org/ for more information.
	 *  @member
	 *  @type string
	 *  @default Version number
	 */
	DataTable.version = "1.10.15";

	/**
	 * Private data store, containing all of the settings objects that are
	 * created for the tables on a given page.
	 *
	 * Note that the `DataTable.settings` object is aliased to
	 * `jQuery.fn.dataTableExt` through which it may be accessed and
	 * manipulated, or `jQuery.fn.dataTable.settings`.
	 *  @member
	 *  @type array
	 *  @default []
	 *  @private
	 */
	DataTable.settings = [];

	/**
	 * Object models container, for the various models that DataTables has
	 * available to it. These models define the objects that are used to hold
	 * the active state and configuration of the table.
	 *  @namespace
	 */
	DataTable.models = {};
	
	
	
	/**
	 * Template object for the way in which DataTables holds information about
	 * search information for the global filter and individual column filters.
	 *  @namespace
	 */
	DataTable.models.oSearch = {
		/**
		 * Flag to indicate if the filtering should be case insensitive or not
		 *  @type boolean
		 *  @default true
		 */
		"bCaseInsensitive": true,
	
		/**
		 * Applied search term
		 *  @type string
		 *  @default <i>Empty string</i>
		 */
		"sSearch": "",
	
		/**
		 * Flag to indicate if the search term should be interpreted as a
		 * regular expression (true) or not (false) and therefore and special
		 * regex characters escaped.
		 *  @type boolean
		 *  @default false
		 */
		"bRegex": false,
	
		/**
		 * Flag to indicate if DataTables is to use its smart filtering or not.
		 *  @type boolean
		 *  @default true
		 */
		"bSmart": true
	};
	
	
	
	
	/**
	 * Template object for the way in which DataTables holds information about
	 * each individual row. This is the object format used for the settings
	 * aoData array.
	 *  @namespace
	 */
	DataTable.models.oRow = {
		/**
		 * TR element for the row
		 *  @type node
		 *  @default null
		 */
		"nTr": null,
	
		/**
		 * Array of TD elements for each row. This is null until the row has been
		 * created.
		 *  @type array nodes
		 *  @default []
		 */
		"anCells": null,
	
		/**
		 * Data object from the original data source for the row. This is either
		 * an array if using the traditional form of DataTables, or an object if
		 * using mData options. The exact type will depend on the passed in
		 * data from the data source, or will be an array if using DOM a data
		 * source.
		 *  @type array|object
		 *  @default []
		 */
		"_aData": [],
	
		/**
		 * Sorting data cache - this array is ostensibly the same length as the
		 * number of columns (although each index is generated only as it is
		 * needed), and holds the data that is used for sorting each column in the
		 * row. We do this cache generation at the start of the sort in order that
		 * the formatting of the sort data need be done only once for each cell
		 * per sort. This array should not be read from or written to by anything
		 * other than the master sorting methods.
		 *  @type array
		 *  @default null
		 *  @private
		 */
		"_aSortData": null,
	
		/**
		 * Per cell filtering data cache. As per the sort data cache, used to
		 * increase the performance of the filtering in DataTables
		 *  @type array
		 *  @default null
		 *  @private
		 */
		"_aFilterData": null,
	
		/**
		 * Filtering data cache. This is the same as the cell filtering cache, but
		 * in this case a string rather than an array. This is easily computed with
		 * a join on `_aFilterData`, but is provided as a cache so the join isn't
		 * needed on every search (memory traded for performance)
		 *  @type array
		 *  @default null
		 *  @private
		 */
		"_sFilterRow": null,
	
		/**
		 * Cache of the class name that DataTables has applied to the row, so we
		 * can quickly look at this variable rather than needing to do a DOM check
		 * on className for the nTr property.
		 *  @type string
		 *  @default <i>Empty string</i>
		 *  @private
		 */
		"_sRowStripe": "",
	
		/**
		 * Denote if the original data source was from the DOM, or the data source
		 * object. This is used for invalidating data, so DataTables can
		 * automatically read data from the original source, unless uninstructed
		 * otherwise.
		 *  @type string
		 *  @default null
		 *  @private
		 */
		"src": null,
	
		/**
		 * Index in the aoData array. This saves an indexOf lookup when we have the
		 * object, but want to know the index
		 *  @type integer
		 *  @default -1
		 *  @private
		 */
		"idx": -1
	};
	
	
	/**
	 * Template object for the column information object in DataTables. This object
	 * is held in the settings aoColumns array and contains all the information that
	 * DataTables needs about each individual column.
	 *
	 * Note that this object is related to {@link DataTable.defaults.column}
	 * but this one is the internal data store for DataTables's cache of columns.
	 * It should NOT be manipulated outside of DataTables. Any configuration should
	 * be done through the initialisation options.
	 *  @namespace
	 */
	DataTable.models.oColumn = {
		/**
		 * Column index. This could be worked out on-the-fly with $.inArray, but it
		 * is faster to just hold it as a variable
		 *  @type integer
		 *  @default null
		 */
		"idx": null,
	
		/**
		 * A list of the columns that sorting should occur on when this column
		 * is sorted. That this property is an array allows multi-column sorting
		 * to be defined for a column (for example first name / last name columns
		 * would benefit from this). The values are integers pointing to the
		 * columns to be sorted on (typically it will be a single integer pointing
		 * at itself, but that doesn't need to be the case).
		 *  @type array
		 */
		"aDataSort": null,
	
		/**
		 * Define the sorting directions that are applied to the column, in sequence
		 * as the column is repeatedly sorted upon - i.e. the first value is used
		 * as the sorting direction when the column if first sorted (clicked on).
		 * Sort it again (click again) and it will move on to the next index.
		 * Repeat until loop.
		 *  @type array
		 */
		"asSorting": null,
	
		/**
		 * Flag to indicate if the column is searchable, and thus should be included
		 * in the filtering or not.
		 *  @type boolean
		 */
		"bSearchable": null,
	
		/**
		 * Flag to indicate if the column is sortable or not.
		 *  @type boolean
		 */
		"bSortable": null,
	
		/**
		 * Flag to indicate if the column is currently visible in the table or not
		 *  @type boolean
		 */
		"bVisible": null,
	
		/**
		 * Store for manual type assignment using the `column.type` option. This
		 * is held in store so we can manipulate the column's `sType` property.
		 *  @type string
		 *  @default null
		 *  @private
		 */
		"_sManualType": null,
	
		/**
		 * Flag to indicate if HTML5 data attributes should be used as the data
		 * source for filtering or sorting. True is either are.
		 *  @type boolean
		 *  @default false
		 *  @private
		 */
		"_bAttrSrc": false,
	
		/**
		 * Developer definable function that is called whenever a cell is created (Ajax source,
		 * etc) or processed for input (DOM source). This can be used as a compliment to mRender
		 * allowing you to modify the DOM element (add background colour for example) when the
		 * element is available.
		 *  @type function
		 *  @param {element} nTd The TD node that has been created
		 *  @param {*} sData The Data for the cell
		 *  @param {array|object} oData The data for the whole row
		 *  @param {int} iRow The row index for the aoData data store
		 *  @default null
		 */
		"fnCreatedCell": null,
	
		/**
		 * Function to get data from a cell in a column. You should <b>never</b>
		 * access data directly through _aData internally in DataTables - always use
		 * the method attached to this property. It allows mData to function as
		 * required. This function is automatically assigned by the column
		 * initialisation method
		 *  @type function
		 *  @param {array|object} oData The data array/object for the array
		 *    (i.e. aoData[]._aData)
		 *  @param {string} sSpecific The specific data type you want to get -
		 *    'display', 'type' 'filter' 'sort'
		 *  @returns {*} The data for the cell from the given row's data
		 *  @default null
		 */
		"fnGetData": null,
	
		/**
		 * Function to set data for a cell in the column. You should <b>never</b>
		 * set the data directly to _aData internally in DataTables - always use
		 * this method. It allows mData to function as required. This function
		 * is automatically assigned by the column initialisation method
		 *  @type function
		 *  @param {array|object} oData The data array/object for the array
		 *    (i.e. aoData[]._aData)
		 *  @param {*} sValue Value to set
		 *  @default null
		 */
		"fnSetData": null,
	
		/**
		 * Property to read the value for the cells in the column from the data
		 * source array / object. If null, then the default content is used, if a
		 * function is given then the return from the function is used.
		 *  @type function|int|string|null
		 *  @default null
		 */
		"mData": null,
	
		/**
		 * Partner property to mData which is used (only when defined) to get
		 * the data - i.e. it is basically the same as mData, but without the
		 * 'set' option, and also the data fed to it is the result from mData.
		 * This is the rendering method to match the data method of mData.
		 *  @type function|int|string|null
		 *  @default null
		 */
		"mRender": null,
	
		/**
		 * Unique header TH/TD element for this column - this is what the sorting
		 * listener is attached to (if sorting is enabled.)
		 *  @type node
		 *  @default null
		 */
		"nTh": null,
	
		/**
		 * Unique footer TH/TD element for this column (if there is one). Not used
		 * in DataTables as such, but can be used for plug-ins to reference the
		 * footer for each column.
		 *  @type node
		 *  @default null
		 */
		"nTf": null,
	
		/**
		 * The class to apply to all TD elements in the table's TBODY for the column
		 *  @type string
		 *  @default null
		 */
		"sClass": null,
	
		/**
		 * When DataTables calculates the column widths to assign to each column,
		 * it finds the longest string in each column and then constructs a
		 * temporary table and reads the widths from that. The problem with this
		 * is that "mmm" is much wider then "iiii", but the latter is a longer
		 * string - thus the calculation can go wrong (doing it properly and putting
		 * it into an DOM object and measuring that is horribly(!) slow). Thus as
		 * a "work around" we provide this option. It will append its value to the
		 * text that is found to be the longest string for the column - i.e. padding.
		 *  @type string
		 */
		"sContentPadding": null,
	
		/**
		 * Allows a default value to be given for a column's data, and will be used
		 * whenever a null data source is encountered (this can be because mData
		 * is set to null, or because the data source itself is null).
		 *  @type string
		 *  @default null
		 */
		"sDefaultContent": null,
	
		/**
		 * Name for the column, allowing reference to the column by name as well as
		 * by index (needs a lookup to work by name).
		 *  @type string
		 */
		"sName": null,
	
		/**
		 * Custom sorting data type - defines which of the available plug-ins in
		 * afnSortData the custom sorting will use - if any is defined.
		 *  @type string
		 *  @default std
		 */
		"sSortDataType": 'std',
	
		/**
		 * Class to be applied to the header element when sorting on this column
		 *  @type string
		 *  @default null
		 */
		"sSortingClass": null,
	
		/**
		 * Class to be applied to the header element when sorting on this column -
		 * when jQuery UI theming is used.
		 *  @type string
		 *  @default null
		 */
		"sSortingClassJUI": null,
	
		/**
		 * Title of the column - what is seen in the TH element (nTh).
		 *  @type string
		 */
		"sTitle": null,
	
		/**
		 * Column sorting and filtering type
		 *  @type string
		 *  @default null
		 */
		"sType": null,
	
		/**
		 * Width of the column
		 *  @type string
		 *  @default null
		 */
		"sWidth": null,
	
		/**
		 * Width of the column when it was first "encountered"
		 *  @type string
		 *  @default null
		 */
		"sWidthOrig": null
	};
	
	
	/*
	 * Developer note: The properties of the object below are given in Hungarian
	 * notation, that was used as the interface for DataTables prior to v1.10, however
	 * from v1.10 onwards the primary interface is camel case. In order to avoid
	 * breaking backwards compatibility utterly with this change, the Hungarian
	 * version is still, internally the primary interface, but is is not documented
	 * - hence the @name tags in each doc comment. This allows a Javascript function
	 * to create a map from Hungarian notation to camel case (going the other direction
	 * would require each property to be listed, which would at around 3K to the size
	 * of DataTables, while this method is about a 0.5K hit.
	 *
	 * Ultimately this does pave the way for Hungarian notation to be dropped
	 * completely, but that is a massive amount of work and will break current
	 * installs (therefore is on-hold until v2).
	 */
	
	/**
	 * Initialisation options that can be given to DataTables at initialisation
	 * time.
	 *  @namespace
	 */
	DataTable.defaults = {
		/**
		 * An array of data to use for the table, passed in at initialisation which
		 * will be used in preference to any data which is already in the DOM. This is
		 * particularly useful for constructing tables purely in Javascript, for
		 * example with a custom Ajax call.
		 *  @type array
		 *  @default null
		 *
		 *  @dtopt Option
		 *  @name DataTable.defaults.data
		 *
		 *  @example
		 *    // Using a 2D array data source
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "data": [
		 *          ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'],
		 *          ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'],
		 *        ],
		 *        "columns": [
		 *          { "title": "Engine" },
		 *          { "title": "Browser" },
		 *          { "title": "Platform" },
		 *          { "title": "Version" },
		 *          { "title": "Grade" }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using an array of objects as a data source (`data`)
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "data": [
		 *          {
		 *            "engine":   "Trident",
		 *            "browser":  "Internet Explorer 4.0",
		 *            "platform": "Win 95+",
		 *            "version":  4,
		 *            "grade":    "X"
		 *          },
		 *          {
		 *            "engine":   "Trident",
		 *            "browser":  "Internet Explorer 5.0",
		 *            "platform": "Win 95+",
		 *            "version":  5,
		 *            "grade":    "C"
		 *          }
		 *        ],
		 *        "columns": [
		 *          { "title": "Engine",   "data": "engine" },
		 *          { "title": "Browser",  "data": "browser" },
		 *          { "title": "Platform", "data": "platform" },
		 *          { "title": "Version",  "data": "version" },
		 *          { "title": "Grade",    "data": "grade" }
		 *        ]
		 *      } );
		 *    } );
		 */
		"aaData": null,
	
	
		/**
		 * If ordering is enabled, then DataTables will perform a first pass sort on
		 * initialisation. You can define which column(s) the sort is performed
		 * upon, and the sorting direction, with this variable. The `sorting` array
		 * should contain an array for each column to be sorted initially containing
		 * the column's index and a direction string ('asc' or 'desc').
		 *  @type array
		 *  @default [[0,'asc']]
		 *
		 *  @dtopt Option
		 *  @name DataTable.defaults.order
		 *
		 *  @example
		 *    // Sort by 3rd column first, and then 4th column
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "order": [[2,'asc'], [3,'desc']]
		 *      } );
		 *    } );
		 *
		 *    // No initial sorting
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "order": []
		 *      } );
		 *    } );
		 */
		"aaSorting": [[0,'asc']],
	
	
		/**
		 * This parameter is basically identical to the `sorting` parameter, but
		 * cannot be overridden by user interaction with the table. What this means
		 * is that you could have a column (visible or hidden) which the sorting
		 * will always be forced on first - any sorting after that (from the user)
		 * will then be performed as required. This can be useful for grouping rows
		 * together.
		 *  @type array
		 *  @default null
		 *
		 *  @dtopt Option
		 *  @name DataTable.defaults.orderFixed
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "orderFixed": [[0,'asc']]
		 *      } );
		 *    } )
		 */
		"aaSortingFixed": [],
	
	
		/**
		 * DataTables can be instructed to load data to display in the table from a
		 * Ajax source. This option defines how that Ajax call is made and where to.
		 *
		 * The `ajax` property has three different modes of operation, depending on
		 * how it is defined. These are:
		 *
		 * * `string` - Set the URL from where the data should be loaded from.
		 * * `object` - Define properties for `jQuery.ajax`.
		 * * `function` - Custom data get function
		 *
		 * `string`
		 * --------
		 *
		 * As a string, the `ajax` property simply defines the URL from which
		 * DataTables will load data.
		 *
		 * `object`
		 * --------
		 *
		 * As an object, the parameters in the object are passed to
		 * [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control
		 * of the Ajax request. DataTables has a number of default parameters which
		 * you can override using this option. Please refer to the jQuery
		 * documentation for a full description of the options available, although
		 * the following parameters provide additional options in DataTables or
		 * require special consideration:
		 *
		 * * `data` - As with jQuery, `data` can be provided as an object, but it
		 *   can also be used as a function to manipulate the data DataTables sends
		 *   to the server. The function takes a single parameter, an object of
		 *   parameters with the values that DataTables has readied for sending. An
		 *   object may be returned which will be merged into the DataTables
		 *   defaults, or you can add the items to the object that was passed in and
		 *   not return anything from the function. This supersedes `fnServerParams`
		 *   from DataTables 1.9-.
		 *
		 * * `dataSrc` - By default DataTables will look for the property `data` (or
		 *   `aaData` for compatibility with DataTables 1.9-) when obtaining data
		 *   from an Ajax source or for server-side processing - this parameter
		 *   allows that property to be changed. You can use Javascript dotted
		 *   object notation to get a data source for multiple levels of nesting, or
		 *   it my be used as a function. As a function it takes a single parameter,
		 *   the JSON returned from the server, which can be manipulated as
		 *   required, with the returned value being that used by DataTables as the
		 *   data source for the table. This supersedes `sAjaxDataProp` from
		 *   DataTables 1.9-.
		 *
		 * * `success` - Should not be overridden it is used internally in
		 *   DataTables. To manipulate / transform the data returned by the server
		 *   use `ajax.dataSrc`, or use `ajax` as a function (see below).
		 *
		 * `function`
		 * ----------
		 *
		 * As a function, making the Ajax call is left up to yourself allowing
		 * complete control of the Ajax request. Indeed, if desired, a method other
		 * than Ajax could be used to obtain the required data, such as Web storage
		 * or an AIR database.
		 *
		 * The function is given four parameters and no return is required. The
		 * parameters are:
		 *
		 * 1. _object_ - Data to send to the server
		 * 2. _function_ - Callback function that must be executed when the required
		 *    data has been obtained. That data should be passed into the callback
		 *    as the only parameter
		 * 3. _object_ - DataTables settings object for the table
		 *
		 * Note that this supersedes `fnServerData` from DataTables 1.9-.
		 *
		 *  @type string|object|function
		 *  @default null
		 *
		 *  @dtopt Option
		 *  @name DataTable.defaults.ajax
		 *  @since 1.10.0
		 *
		 * @example
		 *   // Get JSON data from a file via Ajax.
		 *   // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default).
		 *   $('#example').dataTable( {
		 *     "ajax": "data.json"
		 *   } );
		 *
		 * @example
		 *   // Get JSON data from a file via Ajax, using `dataSrc` to change
		 *   // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`)
		 *   $('#example').dataTable( {
		 *     "ajax": {
		 *       "url": "data.json",
		 *       "dataSrc": "tableData"
		 *     }
		 *   } );
		 *
		 * @example
		 *   // Get JSON data from a file via Ajax, using `dataSrc` to read data
		 *   // from a plain array rather than an array in an object
		 *   $('#example').dataTable( {
		 *     "ajax": {
		 *       "url": "data.json",
		 *       "dataSrc": ""
		 *     }
		 *   } );
		 *
		 * @example
		 *   // Manipulate the data returned from the server - add a link to data
		 *   // (note this can, should, be done using `render` for the column - this
		 *   // is just a simple example of how the data can be manipulated).
		 *   $('#example').dataTable( {
		 *     "ajax": {
		 *       "url": "data.json",
		 *       "dataSrc": function ( json ) {
		 *         for ( var i=0, ien=json.length ; i<ien ; i++ ) {
		 *           json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>';
		 *         }
		 *         return json;
		 *       }
		 *     }
		 *   } );
		 *
		 * @example
		 *   // Add data to the request
		 *   $('#example').dataTable( {
		 *     "ajax": {
		 *       "url": "data.json",
		 *       "data": function ( d ) {
		 *         return {
		 *           "extra_search": $('#extra').val()
		 *         };
		 *       }
		 *     }
		 *   } );
		 *
		 * @example
		 *   // Send request as POST
		 *   $('#example').dataTable( {
		 *     "ajax": {
		 *       "url": "data.json",
		 *       "type": "POST"
		 *     }
		 *   } );
		 *
		 * @example
		 *   // Get the data from localStorage (could interface with a form for
		 *   // adding, editing and removing rows).
		 *   $('#example').dataTable( {
		 *     "ajax": function (data, callback, settings) {
		 *       callback(
		 *         JSON.parse( localStorage.getItem('dataTablesData') )
		 *       );
		 *     }
		 *   } );
		 */
		"ajax": null,
	
	
		/**
		 * This parameter allows you to readily specify the entries in the length drop
		 * down menu that DataTables shows when pagination is enabled. It can be
		 * either a 1D array of options which will be used for both the displayed
		 * option and the value, or a 2D array which will use the array in the first
		 * position as the value, and the array in the second position as the
		 * displayed options (useful for language strings such as 'All').
		 *
		 * Note that the `pageLength` property will be automatically set to the
		 * first value given in this array, unless `pageLength` is also provided.
		 *  @type array
		 *  @default [ 10, 25, 50, 100 ]
		 *
		 *  @dtopt Option
		 *  @name DataTable.defaults.lengthMenu
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
		 *      } );
		 *    } );
		 */
		"aLengthMenu": [ 10, 25, 50, 100 ],
	
	
		/**
		 * The `columns` option in the initialisation parameter allows you to define
		 * details about the way individual columns behave. For a full list of
		 * column options that can be set, please see
		 * {@link DataTable.defaults.column}. Note that if you use `columns` to
		 * define your columns, you must have an entry in the array for every single
		 * column that you have in your table (these can be null if you don't which
		 * to specify any options).
		 *  @member
		 *
		 *  @name DataTable.defaults.column
		 */
		"aoColumns": null,
	
		/**
		 * Very similar to `columns`, `columnDefs` allows you to target a specific
		 * column, multiple columns, or all columns, using the `targets` property of
		 * each object in the array. This allows great flexibility when creating
		 * tables, as the `columnDefs` arrays can be of any length, targeting the
		 * columns you specifically want. `columnDefs` may use any of the column
		 * options available: {@link DataTable.defaults.column}, but it _must_
		 * have `targets` defined in each object in the array. Values in the `targets`
		 * array may be:
		 *   <ul>
		 *     <li>a string - class name will be matched on the TH for the column</li>
		 *     <li>0 or a positive integer - column index counting from the left</li>
		 *     <li>a negative integer - column index counting from the right</li>
		 *     <li>the string "_all" - all columns (i.e. assign a default)</li>
		 *   </ul>
		 *  @member
		 *
		 *  @name DataTable.defaults.columnDefs
		 */
		"aoColumnDefs": null,
	
	
		/**
		 * Basically the same as `search`, this parameter defines the individual column
		 * filtering state at initialisation time. The array must be of the same size
		 * as the number of columns, and each element be an object with the parameters
		 * `search` and `escapeRegex` (the latter is optional). 'null' is also
		 * accepted and the default will be used.
		 *  @type array
		 *  @default []
		 *
		 *  @dtopt Option
		 *  @name DataTable.defaults.searchCols
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "searchCols": [
		 *          null,
		 *          { "search": "My filter" },
		 *          null,
		 *          { "search": "^[0-9]", "escapeRegex": false }
		 *        ]
		 *      } );
		 *    } )
		 */
		"aoSearchCols": [],
	
	
		/**
		 * An array of CSS classes that should be applied to displayed rows. This
		 * array may be of any length, and DataTables will apply each class
		 * sequentially, looping when required.
		 *  @type array
		 *  @default null <i>Will take the values determined by the `oClasses.stripe*`
		 *    options</i>
		 *
		 *  @dtopt Option
		 *  @name DataTable.defaults.stripeClasses
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "stripeClasses": [ 'strip1', 'strip2', 'strip3' ]
		 *      } );
		 *    } )
		 */
		"asStripeClasses": null,
	
	
		/**
		 * Enable or disable automatic column width calculation. This can be disabled
		 * as an optimisation (it takes some time to calculate the widths) if the
		 * tables widths are passed in using `columns`.
		 *  @type boolean
		 *  @default true
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.autoWidth
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "autoWidth": false
		 *      } );
		 *    } );
		 */
		"bAutoWidth": true,
	
	
		/**
		 * Deferred rendering can provide DataTables with a huge speed boost when you
		 * are using an Ajax or JS data source for the table. This option, when set to
		 * true, will cause DataTables to defer the creation of the table elements for
		 * each row until they are needed for a draw - saving a significant amount of
		 * time.
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.deferRender
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "ajax": "sources/arrays.txt",
		 *        "deferRender": true
		 *      } );
		 *    } );
		 */
		"bDeferRender": false,
	
	
		/**
		 * Replace a DataTable which matches the given selector and replace it with
		 * one which has the properties of the new initialisation object passed. If no
		 * table matches the selector, then the new DataTable will be constructed as
		 * per normal.
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.destroy
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "srollY": "200px",
		 *        "paginate": false
		 *      } );
		 *
		 *      // Some time later....
		 *      $('#example').dataTable( {
		 *        "filter": false,
		 *        "destroy": true
		 *      } );
		 *    } );
		 */
		"bDestroy": false,
	
	
		/**
		 * Enable or disable filtering of data. Filtering in DataTables is "smart" in
		 * that it allows the end user to input multiple words (space separated) and
		 * will match a row containing those words, even if not in the order that was
		 * specified (this allow matching across multiple columns). Note that if you
		 * wish to use filtering in DataTables this must remain 'true' - to remove the
		 * default filtering input box and retain filtering abilities, please use
		 * {@link DataTable.defaults.dom}.
		 *  @type boolean
		 *  @default true
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.searching
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "searching": false
		 *      } );
		 *    } );
		 */
		"bFilter": true,
	
	
		/**
		 * Enable or disable the table information display. This shows information
		 * about the data that is currently visible on the page, including information
		 * about filtered data if that action is being performed.
		 *  @type boolean
		 *  @default true
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.info
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "info": false
		 *      } );
		 *    } );
		 */
		"bInfo": true,
	
	
		/**
		 * Enable jQuery UI ThemeRoller support (required as ThemeRoller requires some
		 * slightly different and additional mark-up from what DataTables has
		 * traditionally used).
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.jQueryUI
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "jQueryUI": true
		 *      } );
		 *    } );
		 */
		"bJQueryUI": false,
	
	
		/**
		 * Allows the end user to select the size of a formatted page from a select
		 * menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`).
		 *  @type boolean
		 *  @default true
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.lengthChange
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "lengthChange": false
		 *      } );
		 *    } );
		 */
		"bLengthChange": true,
	
	
		/**
		 * Enable or disable pagination.
		 *  @type boolean
		 *  @default true
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.paging
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "paging": false
		 *      } );
		 *    } );
		 */
		"bPaginate": true,
	
	
		/**
		 * Enable or disable the display of a 'processing' indicator when the table is
		 * being processed (e.g. a sort). This is particularly useful for tables with
		 * large amounts of data where it can take a noticeable amount of time to sort
		 * the entries.
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.processing
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "processing": true
		 *      } );
		 *    } );
		 */
		"bProcessing": false,
	
	
		/**
		 * Retrieve the DataTables object for the given selector. Note that if the
		 * table has already been initialised, this parameter will cause DataTables
		 * to simply return the object that has already been set up - it will not take
		 * account of any changes you might have made to the initialisation object
		 * passed to DataTables (setting this parameter to true is an acknowledgement
		 * that you understand this). `destroy` can be used to reinitialise a table if
		 * you need.
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.retrieve
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      initTable();
		 *      tableActions();
		 *    } );
		 *
		 *    function initTable ()
		 *    {
		 *      return $('#example').dataTable( {
		 *        "scrollY": "200px",
		 *        "paginate": false,
		 *        "retrieve": true
		 *      } );
		 *    }
		 *
		 *    function tableActions ()
		 *    {
		 *      var table = initTable();
		 *      // perform API operations with oTable
		 *    }
		 */
		"bRetrieve": false,
	
	
		/**
		 * When vertical (y) scrolling is enabled, DataTables will force the height of
		 * the table's viewport to the given height at all times (useful for layout).
		 * However, this can look odd when filtering data down to a small data set,
		 * and the footer is left "floating" further down. This parameter (when
		 * enabled) will cause DataTables to collapse the table's viewport down when
		 * the result set will fit within the given Y height.
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.scrollCollapse
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "scrollY": "200",
		 *        "scrollCollapse": true
		 *      } );
		 *    } );
		 */
		"bScrollCollapse": false,
	
	
		/**
		 * Configure DataTables to use server-side processing. Note that the
		 * `ajax` parameter must also be given in order to give DataTables a
		 * source to obtain the required data for each draw.
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Features
		 *  @dtopt Server-side
		 *  @name DataTable.defaults.serverSide
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "serverSide": true,
		 *        "ajax": "xhr.php"
		 *      } );
		 *    } );
		 */
		"bServerSide": false,
	
	
		/**
		 * Enable or disable sorting of columns. Sorting of individual columns can be
		 * disabled by the `sortable` option for each column.
		 *  @type boolean
		 *  @default true
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.ordering
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "ordering": false
		 *      } );
		 *    } );
		 */
		"bSort": true,
	
	
		/**
		 * Enable or display DataTables' ability to sort multiple columns at the
		 * same time (activated by shift-click by the user).
		 *  @type boolean
		 *  @default true
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.orderMulti
		 *
		 *  @example
		 *    // Disable multiple column sorting ability
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "orderMulti": false
		 *      } );
		 *    } );
		 */
		"bSortMulti": true,
	
	
		/**
		 * Allows control over whether DataTables should use the top (true) unique
		 * cell that is found for a single column, or the bottom (false - default).
		 * This is useful when using complex headers.
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.orderCellsTop
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "orderCellsTop": true
		 *      } );
		 *    } );
		 */
		"bSortCellsTop": false,
	
	
		/**
		 * Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and
		 * `sorting\_3` to the columns which are currently being sorted on. This is
		 * presented as a feature switch as it can increase processing time (while
		 * classes are removed and added) so for large data sets you might want to
		 * turn this off.
		 *  @type boolean
		 *  @default true
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.orderClasses
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "orderClasses": false
		 *      } );
		 *    } );
		 */
		"bSortClasses": true,
	
	
		/**
		 * Enable or disable state saving. When enabled HTML5 `localStorage` will be
		 * used to save table display information such as pagination information,
		 * display length, filtering and sorting. As such when the end user reloads
		 * the page the display display will match what thy had previously set up.
		 *
		 * Due to the use of `localStorage` the default state saving is not supported
		 * in IE6 or 7. If state saving is required in those browsers, use
		 * `stateSaveCallback` to provide a storage solution such as cookies.
		 *  @type boolean
		 *  @default false
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.stateSave
		 *
		 *  @example
		 *    $(document).ready( function () {
		 *      $('#example').dataTable( {
		 *        "stateSave": true
		 *      } );
		 *    } );
		 */
		"bStateSave": false,
	
	
		/**
		 * This function is called when a TR element is created (and all TD child
		 * elements have been inserted), or registered if using a DOM source, allowing
		 * manipulation of the TR element (adding classes etc).
		 *  @type function
		 *  @param {node} row "TR" element for the current row
		 *  @param {array} data Raw data array for this row
		 *  @param {int} dataIndex The index of this row in the internal aoData array
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.createdRow
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "createdRow": function( row, data, dataIndex ) {
		 *          // Bold the grade for all 'A' grade browsers
		 *          if ( data[4] == "A" )
		 *          {
		 *            $('td:eq(4)', row).html( '<b>A</b>' );
		 *          }
		 *        }
		 *      } );
		 *    } );
		 */
		"fnCreatedRow": null,
	
	
		/**
		 * This function is called on every 'draw' event, and allows you to
		 * dynamically modify any aspect you want about the created DOM.
		 *  @type function
		 *  @param {object} settings DataTables settings object
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.drawCallback
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "drawCallback": function( settings ) {
		 *          alert( 'DataTables has redrawn the table' );
		 *        }
		 *      } );
		 *    } );
		 */
		"fnDrawCallback": null,
	
	
		/**
		 * Identical to fnHeaderCallback() but for the table footer this function
		 * allows you to modify the table footer on every 'draw' event.
		 *  @type function
		 *  @param {node} foot "TR" element for the footer
		 *  @param {array} data Full table data (as derived from the original HTML)
		 *  @param {int} start Index for the current display starting point in the
		 *    display array
		 *  @param {int} end Index for the current display ending point in the
		 *    display array
		 *  @param {array int} display Index array to translate the visual position
		 *    to the full data array
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.footerCallback
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "footerCallback": function( tfoot, data, start, end, display ) {
		 *          tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start;
		 *        }
		 *      } );
		 *    } )
		 */
		"fnFooterCallback": null,
	
	
		/**
		 * When rendering large numbers in the information element for the table
		 * (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers
		 * to have a comma separator for the 'thousands' units (e.g. 1 million is
		 * rendered as "1,000,000") to help readability for the end user. This
		 * function will override the default method DataTables uses.
		 *  @type function
		 *  @member
		 *  @param {int} toFormat number to be formatted
		 *  @returns {string} formatted string for DataTables to show the number
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.formatNumber
		 *
		 *  @example
		 *    // Format a number using a single quote for the separator (note that
		 *    // this can also be done with the language.thousands option)
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "formatNumber": function ( toFormat ) {
		 *          return toFormat.toString().replace(
		 *            /\B(?=(\d{3})+(?!\d))/g, "'"
		 *          );
		 *        };
		 *      } );
		 *    } );
		 */
		"fnFormatNumber": function ( toFormat ) {
			return toFormat.toString().replace(
				/\B(?=(\d{3})+(?!\d))/g,
				this.oLanguage.sThousands
			);
		},
	
	
		/**
		 * This function is called on every 'draw' event, and allows you to
		 * dynamically modify the header row. This can be used to calculate and
		 * display useful information about the table.
		 *  @type function
		 *  @param {node} head "TR" element for the header
		 *  @param {array} data Full table data (as derived from the original HTML)
		 *  @param {int} start Index for the current display starting point in the
		 *    display array
		 *  @param {int} end Index for the current display ending point in the
		 *    display array
		 *  @param {array int} display Index array to translate the visual position
		 *    to the full data array
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.headerCallback
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "fheaderCallback": function( head, data, start, end, display ) {
		 *          head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records";
		 *        }
		 *      } );
		 *    } )
		 */
		"fnHeaderCallback": null,
	
	
		/**
		 * The information element can be used to convey information about the current
		 * state of the table. Although the internationalisation options presented by
		 * DataTables are quite capable of dealing with most customisations, there may
		 * be times where you wish to customise the string further. This callback
		 * allows you to do exactly that.
		 *  @type function
		 *  @param {object} oSettings DataTables settings object
		 *  @param {int} start Starting position in data for the draw
		 *  @param {int} end End position in data for the draw
		 *  @param {int} max Total number of rows in the table (regardless of
		 *    filtering)
		 *  @param {int} total Total number of rows in the data set, after filtering
		 *  @param {string} pre The string that DataTables has formatted using it's
		 *    own rules
		 *  @returns {string} The string to be displayed in the information element.
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.infoCallback
		 *
		 *  @example
		 *    $('#example').dataTable( {
		 *      "infoCallback": function( settings, start, end, max, total, pre ) {
		 *        return start +" to "+ end;
		 *      }
		 *    } );
		 */
		"fnInfoCallback": null,
	
	
		/**
		 * Called when the table has been initialised. Normally DataTables will
		 * initialise sequentially and there will be no need for this function,
		 * however, this does not hold true when using external language information
		 * since that is obtained using an async XHR call.
		 *  @type function
		 *  @param {object} settings DataTables settings object
		 *  @param {object} json The JSON object request from the server - only
		 *    present if client-side Ajax sourced data is used
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.initComplete
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "initComplete": function(settings, json) {
		 *          alert( 'DataTables has finished its initialisation.' );
		 *        }
		 *      } );
		 *    } )
		 */
		"fnInitComplete": null,
	
	
		/**
		 * Called at the very start of each table draw and can be used to cancel the
		 * draw by returning false, any other return (including undefined) results in
		 * the full draw occurring).
		 *  @type function
		 *  @param {object} settings DataTables settings object
		 *  @returns {boolean} False will cancel the draw, anything else (including no
		 *    return) will allow it to complete.
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.preDrawCallback
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "preDrawCallback": function( settings ) {
		 *          if ( $('#test').val() == 1 ) {
		 *            return false;
		 *          }
		 *        }
		 *      } );
		 *    } );
		 */
		"fnPreDrawCallback": null,
	
	
		/**
		 * This function allows you to 'post process' each row after it have been
		 * generated for each table draw, but before it is rendered on screen. This
		 * function might be used for setting the row class name etc.
		 *  @type function
		 *  @param {node} row "TR" element for the current row
		 *  @param {array} data Raw data array for this row
		 *  @param {int} displayIndex The display index for the current table draw
		 *  @param {int} displayIndexFull The index of the data in the full list of
		 *    rows (after filtering)
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.rowCallback
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "rowCallback": function( row, data, displayIndex, displayIndexFull ) {
		 *          // Bold the grade for all 'A' grade browsers
		 *          if ( data[4] == "A" ) {
		 *            $('td:eq(4)', row).html( '<b>A</b>' );
		 *          }
		 *        }
		 *      } );
		 *    } );
		 */
		"fnRowCallback": null,
	
	
		/**
		 * __Deprecated__ The functionality provided by this parameter has now been
		 * superseded by that provided through `ajax`, which should be used instead.
		 *
		 * This parameter allows you to override the default function which obtains
		 * the data from the server so something more suitable for your application.
		 * For example you could use POST data, or pull information from a Gears or
		 * AIR database.
		 *  @type function
		 *  @member
		 *  @param {string} source HTTP source to obtain the data from (`ajax`)
		 *  @param {array} data A key/value pair object containing the data to send
		 *    to the server
		 *  @param {function} callback to be called on completion of the data get
		 *    process that will draw the data on the page.
		 *  @param {object} settings DataTables settings object
		 *
		 *  @dtopt Callbacks
		 *  @dtopt Server-side
		 *  @name DataTable.defaults.serverData
		 *
		 *  @deprecated 1.10. Please use `ajax` for this functionality now.
		 */
		"fnServerData": null,
	
	
		/**
		 * __Deprecated__ The functionality provided by this parameter has now been
		 * superseded by that provided through `ajax`, which should be used instead.
		 *
		 *  It is often useful to send extra data to the server when making an Ajax
		 * request - for example custom filtering information, and this callback
		 * function makes it trivial to send extra information to the server. The
		 * passed in parameter is the data set that has been constructed by
		 * DataTables, and you can add to this or modify it as you require.
		 *  @type function
		 *  @param {array} data Data array (array of objects which are name/value
		 *    pairs) that has been constructed by DataTables and will be sent to the
		 *    server. In the case of Ajax sourced data with server-side processing
		 *    this will be an empty array, for server-side processing there will be a
		 *    significant number of parameters!
		 *  @returns {undefined} Ensure that you modify the data array passed in,
		 *    as this is passed by reference.
		 *
		 *  @dtopt Callbacks
		 *  @dtopt Server-side
		 *  @name DataTable.defaults.serverParams
		 *
		 *  @deprecated 1.10. Please use `ajax` for this functionality now.
		 */
		"fnServerParams": null,
	
	
		/**
		 * Load the table state. With this function you can define from where, and how, the
		 * state of a table is loaded. By default DataTables will load from `localStorage`
		 * but you might wish to use a server-side database or cookies.
		 *  @type function
		 *  @member
		 *  @param {object} settings DataTables settings object
		 *  @param {object} callback Callback that can be executed when done. It
		 *    should be passed the loaded state object.
		 *  @return {object} The DataTables state object to be loaded
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.stateLoadCallback
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "stateSave": true,
		 *        "stateLoadCallback": function (settings, callback) {
		 *          $.ajax( {
		 *            "url": "/state_load",
		 *            "dataType": "json",
		 *            "success": function (json) {
		 *              callback( json );
		 *            }
		 *          } );
		 *        }
		 *      } );
		 *    } );
		 */
		"fnStateLoadCallback": function ( settings ) {
			try {
				return JSON.parse(
					(settings.iStateDuration === -1 ? sessionStorage : localStorage).getItem(
						'DataTables_'+settings.sInstance+'_'+location.pathname
					)
				);
			} catch (e) {}
		},
	
	
		/**
		 * Callback which allows modification of the saved state prior to loading that state.
		 * This callback is called when the table is loading state from the stored data, but
		 * prior to the settings object being modified by the saved state. Note that for
		 * plug-in authors, you should use the `stateLoadParams` event to load parameters for
		 * a plug-in.
		 *  @type function
		 *  @param {object} settings DataTables settings object
		 *  @param {object} data The state object that is to be loaded
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.stateLoadParams
		 *
		 *  @example
		 *    // Remove a saved filter, so filtering is never loaded
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "stateSave": true,
		 *        "stateLoadParams": function (settings, data) {
		 *          data.oSearch.sSearch = "";
		 *        }
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Disallow state loading by returning false
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "stateSave": true,
		 *        "stateLoadParams": function (settings, data) {
		 *          return false;
		 *        }
		 *      } );
		 *    } );
		 */
		"fnStateLoadParams": null,
	
	
		/**
		 * Callback that is called when the state has been loaded from the state saving method
		 * and the DataTables settings object has been modified as a result of the loaded state.
		 *  @type function
		 *  @param {object} settings DataTables settings object
		 *  @param {object} data The state object that was loaded
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.stateLoaded
		 *
		 *  @example
		 *    // Show an alert with the filtering value that was saved
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "stateSave": true,
		 *        "stateLoaded": function (settings, data) {
		 *          alert( 'Saved filter was: '+data.oSearch.sSearch );
		 *        }
		 *      } );
		 *    } );
		 */
		"fnStateLoaded": null,
	
	
		/**
		 * Save the table state. This function allows you to define where and how the state
		 * information for the table is stored By default DataTables will use `localStorage`
		 * but you might wish to use a server-side database or cookies.
		 *  @type function
		 *  @member
		 *  @param {object} settings DataTables settings object
		 *  @param {object} data The state object to be saved
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.stateSaveCallback
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "stateSave": true,
		 *        "stateSaveCallback": function (settings, data) {
		 *          // Send an Ajax request to the server with the state object
		 *          $.ajax( {
		 *            "url": "/state_save",
		 *            "data": data,
		 *            "dataType": "json",
		 *            "method": "POST"
		 *            "success": function () {}
		 *          } );
		 *        }
		 *      } );
		 *    } );
		 */
		"fnStateSaveCallback": function ( settings, data ) {
			try {
				(settings.iStateDuration === -1 ? sessionStorage : localStorage).setItem(
					'DataTables_'+settings.sInstance+'_'+location.pathname,
					JSON.stringify( data )
				);
			} catch (e) {}
		},
	
	
		/**
		 * Callback which allows modification of the state to be saved. Called when the table
		 * has changed state a new state save is required. This method allows modification of
		 * the state saving object prior to actually doing the save, including addition or
		 * other state properties or modification. Note that for plug-in authors, you should
		 * use the `stateSaveParams` event to save parameters for a plug-in.
		 *  @type function
		 *  @param {object} settings DataTables settings object
		 *  @param {object} data The state object to be saved
		 *
		 *  @dtopt Callbacks
		 *  @name DataTable.defaults.stateSaveParams
		 *
		 *  @example
		 *    // Remove a saved filter, so filtering is never saved
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "stateSave": true,
		 *        "stateSaveParams": function (settings, data) {
		 *          data.oSearch.sSearch = "";
		 *        }
		 *      } );
		 *    } );
		 */
		"fnStateSaveParams": null,
	
	
		/**
		 * Duration for which the saved state information is considered valid. After this period
		 * has elapsed the state will be returned to the default.
		 * Value is given in seconds.
		 *  @type int
		 *  @default 7200 <i>(2 hours)</i>
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.stateDuration
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "stateDuration": 60*60*24; // 1 day
		 *      } );
		 *    } )
		 */
		"iStateDuration": 7200,
	
	
		/**
		 * When enabled DataTables will not make a request to the server for the first
		 * page draw - rather it will use the data already on the page (no sorting etc
		 * will be applied to it), thus saving on an XHR at load time. `deferLoading`
		 * is used to indicate that deferred loading is required, but it is also used
		 * to tell DataTables how many records there are in the full table (allowing
		 * the information element and pagination to be displayed correctly). In the case
		 * where a filtering is applied to the table on initial load, this can be
		 * indicated by giving the parameter as an array, where the first element is
		 * the number of records available after filtering and the second element is the
		 * number of records without filtering (allowing the table information element
		 * to be shown correctly).
		 *  @type int | array
		 *  @default null
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.deferLoading
		 *
		 *  @example
		 *    // 57 records available in the table, no filtering applied
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "serverSide": true,
		 *        "ajax": "scripts/server_processing.php",
		 *        "deferLoading": 57
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // 57 records after filtering, 100 without filtering (an initial filter applied)
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "serverSide": true,
		 *        "ajax": "scripts/server_processing.php",
		 *        "deferLoading": [ 57, 100 ],
		 *        "search": {
		 *          "search": "my_filter"
		 *        }
		 *      } );
		 *    } );
		 */
		"iDeferLoading": null,
	
	
		/**
		 * Number of rows to display on a single page when using pagination. If
		 * feature enabled (`lengthChange`) then the end user will be able to override
		 * this to a custom setting using a pop-up menu.
		 *  @type int
		 *  @default 10
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.pageLength
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "pageLength": 50
		 *      } );
		 *    } )
		 */
		"iDisplayLength": 10,
	
	
		/**
		 * Define the starting point for data display when using DataTables with
		 * pagination. Note that this parameter is the number of records, rather than
		 * the page number, so if you have 10 records per page and want to start on
		 * the third page, it should be "20".
		 *  @type int
		 *  @default 0
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.displayStart
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "displayStart": 20
		 *      } );
		 *    } )
		 */
		"iDisplayStart": 0,
	
	
		/**
		 * By default DataTables allows keyboard navigation of the table (sorting, paging,
		 * and filtering) by adding a `tabindex` attribute to the required elements. This
		 * allows you to tab through the controls and press the enter key to activate them.
		 * The tabindex is default 0, meaning that the tab follows the flow of the document.
		 * You can overrule this using this parameter if you wish. Use a value of -1 to
		 * disable built-in keyboard navigation.
		 *  @type int
		 *  @default 0
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.tabIndex
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "tabIndex": 1
		 *      } );
		 *    } );
		 */
		"iTabIndex": 0,
	
	
		/**
		 * Classes that DataTables assigns to the various components and features
		 * that it adds to the HTML table. This allows classes to be configured
		 * during initialisation in addition to through the static
		 * {@link DataTable.ext.oStdClasses} object).
		 *  @namespace
		 *  @name DataTable.defaults.classes
		 */
		"oClasses": {},
	
	
		/**
		 * All strings that DataTables uses in the user interface that it creates
		 * are defined in this object, allowing you to modified them individually or
		 * completely replace them all as required.
		 *  @namespace
		 *  @name DataTable.defaults.language
		 */
		"oLanguage": {
			/**
			 * Strings that are used for WAI-ARIA labels and controls only (these are not
			 * actually visible on the page, but will be read by screenreaders, and thus
			 * must be internationalised as well).
			 *  @namespace
			 *  @name DataTable.defaults.language.aria
			 */
			"oAria": {
				/**
				 * ARIA label that is added to the table headers when the column may be
				 * sorted ascending by activing the column (click or return when focused).
				 * Note that the column header is prefixed to this string.
				 *  @type string
				 *  @default : activate to sort column ascending
				 *
				 *  @dtopt Language
				 *  @name DataTable.defaults.language.aria.sortAscending
				 *
				 *  @example
				 *    $(document).ready( function() {
				 *      $('#example').dataTable( {
				 *        "language": {
				 *          "aria": {
				 *            "sortAscending": " - click/return to sort ascending"
				 *          }
				 *        }
				 *      } );
				 *    } );
				 */
				"sSortAscending": ": activate to sort column ascending",
	
				/**
				 * ARIA label that is added to the table headers when the column may be
				 * sorted descending by activing the column (click or return when focused).
				 * Note that the column header is prefixed to this string.
				 *  @type string
				 *  @default : activate to sort column ascending
				 *
				 *  @dtopt Language
				 *  @name DataTable.defaults.language.aria.sortDescending
				 *
				 *  @example
				 *    $(document).ready( function() {
				 *      $('#example').dataTable( {
				 *        "language": {
				 *          "aria": {
				 *            "sortDescending": " - click/return to sort descending"
				 *          }
				 *        }
				 *      } );
				 *    } );
				 */
				"sSortDescending": ": activate to sort column descending"
			},
	
			/**
			 * Pagination string used by DataTables for the built-in pagination
			 * control types.
			 *  @namespace
			 *  @name DataTable.defaults.language.paginate
			 */
			"oPaginate": {
				/**
				 * Text to use when using the 'full_numbers' type of pagination for the
				 * button to take the user to the first page.
				 *  @type string
				 *  @default First
				 *
				 *  @dtopt Language
				 *  @name DataTable.defaults.language.paginate.first
				 *
				 *  @example
				 *    $(document).ready( function() {
				 *      $('#example').dataTable( {
				 *        "language": {
				 *          "paginate": {
				 *            "first": "First page"
				 *          }
				 *        }
				 *      } );
				 *    } );
				 */
				"sFirst": "First",
	
	
				/**
				 * Text to use when using the 'full_numbers' type of pagination for the
				 * button to take the user to the last page.
				 *  @type string
				 *  @default Last
				 *
				 *  @dtopt Language
				 *  @name DataTable.defaults.language.paginate.last
				 *
				 *  @example
				 *    $(document).ready( function() {
				 *      $('#example').dataTable( {
				 *        "language": {
				 *          "paginate": {
				 *            "last": "Last page"
				 *          }
				 *        }
				 *      } );
				 *    } );
				 */
				"sLast": "Last",
	
	
				/**
				 * Text to use for the 'next' pagination button (to take the user to the
				 * next page).
				 *  @type string
				 *  @default Next
				 *
				 *  @dtopt Language
				 *  @name DataTable.defaults.language.paginate.next
				 *
				 *  @example
				 *    $(document).ready( function() {
				 *      $('#example').dataTable( {
				 *        "language": {
				 *          "paginate": {
				 *            "next": "Next page"
				 *          }
				 *        }
				 *      } );
				 *    } );
				 */
				"sNext": "Next",
	
	
				/**
				 * Text to use for the 'previous' pagination button (to take the user to
				 * the previous page).
				 *  @type string
				 *  @default Previous
				 *
				 *  @dtopt Language
				 *  @name DataTable.defaults.language.paginate.previous
				 *
				 *  @example
				 *    $(document).ready( function() {
				 *      $('#example').dataTable( {
				 *        "language": {
				 *          "paginate": {
				 *            "previous": "Previous page"
				 *          }
				 *        }
				 *      } );
				 *    } );
				 */
				"sPrevious": "Previous"
			},
	
			/**
			 * This string is shown in preference to `zeroRecords` when the table is
			 * empty of data (regardless of filtering). Note that this is an optional
			 * parameter - if it is not given, the value of `zeroRecords` will be used
			 * instead (either the default or given value).
			 *  @type string
			 *  @default No data available in table
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.emptyTable
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "emptyTable": "No data available in table"
			 *        }
			 *      } );
			 *    } );
			 */
			"sEmptyTable": "No data available in table",
	
	
			/**
			 * This string gives information to the end user about the information
			 * that is current on display on the page. The following tokens can be
			 * used in the string and will be dynamically replaced as the table
			 * display updates. This tokens can be placed anywhere in the string, or
			 * removed as needed by the language requires:
			 *
			 * * `\_START\_` - Display index of the first record on the current page
			 * * `\_END\_` - Display index of the last record on the current page
			 * * `\_TOTAL\_` - Number of records in the table after filtering
			 * * `\_MAX\_` - Number of records in the table without filtering
			 * * `\_PAGE\_` - Current page number
			 * * `\_PAGES\_` - Total number of pages of data in the table
			 *
			 *  @type string
			 *  @default Showing _START_ to _END_ of _TOTAL_ entries
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.info
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "info": "Showing page _PAGE_ of _PAGES_"
			 *        }
			 *      } );
			 *    } );
			 */
			"sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
	
	
			/**
			 * Display information string for when the table is empty. Typically the
			 * format of this string should match `info`.
			 *  @type string
			 *  @default Showing 0 to 0 of 0 entries
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.infoEmpty
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "infoEmpty": "No entries to show"
			 *        }
			 *      } );
			 *    } );
			 */
			"sInfoEmpty": "Showing 0 to 0 of 0 entries",
	
	
			/**
			 * When a user filters the information in a table, this string is appended
			 * to the information (`info`) to give an idea of how strong the filtering
			 * is. The variable _MAX_ is dynamically updated.
			 *  @type string
			 *  @default (filtered from _MAX_ total entries)
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.infoFiltered
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "infoFiltered": " - filtering from _MAX_ records"
			 *        }
			 *      } );
			 *    } );
			 */
			"sInfoFiltered": "(filtered from _MAX_ total entries)",
	
	
			/**
			 * If can be useful to append extra information to the info string at times,
			 * and this variable does exactly that. This information will be appended to
			 * the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are
			 * being used) at all times.
			 *  @type string
			 *  @default <i>Empty string</i>
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.infoPostFix
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "infoPostFix": "All records shown are derived from real information."
			 *        }
			 *      } );
			 *    } );
			 */
			"sInfoPostFix": "",
	
	
			/**
			 * This decimal place operator is a little different from the other
			 * language options since DataTables doesn't output floating point
			 * numbers, so it won't ever use this for display of a number. Rather,
			 * what this parameter does is modify the sort methods of the table so
			 * that numbers which are in a format which has a character other than
			 * a period (`.`) as a decimal place will be sorted numerically.
			 *
			 * Note that numbers with different decimal places cannot be shown in
			 * the same table and still be sortable, the table must be consistent.
			 * However, multiple different tables on the page can use different
			 * decimal place characters.
			 *  @type string
			 *  @default 
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.decimal
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "decimal": ","
			 *          "thousands": "."
			 *        }
			 *      } );
			 *    } );
			 */
			"sDecimal": "",
	
	
			/**
			 * DataTables has a build in number formatter (`formatNumber`) which is
			 * used to format large numbers that are used in the table information.
			 * By default a comma is used, but this can be trivially changed to any
			 * character you wish with this parameter.
			 *  @type string
			 *  @default ,
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.thousands
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "thousands": "'"
			 *        }
			 *      } );
			 *    } );
			 */
			"sThousands": ",",
	
	
			/**
			 * Detail the action that will be taken when the drop down menu for the
			 * pagination length option is changed. The '_MENU_' variable is replaced
			 * with a default select list of 10, 25, 50 and 100, and can be replaced
			 * with a custom select box if required.
			 *  @type string
			 *  @default Show _MENU_ entries
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.lengthMenu
			 *
			 *  @example
			 *    // Language change only
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "lengthMenu": "Display _MENU_ records"
			 *        }
			 *      } );
			 *    } );
			 *
			 *  @example
			 *    // Language and options change
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "lengthMenu": 'Display <select>'+
			 *            '<option value="10">10</option>'+
			 *            '<option value="20">20</option>'+
			 *            '<option value="30">30</option>'+
			 *            '<option value="40">40</option>'+
			 *            '<option value="50">50</option>'+
			 *            '<option value="-1">All</option>'+
			 *            '</select> records'
			 *        }
			 *      } );
			 *    } );
			 */
			"sLengthMenu": "Show _MENU_ entries",
	
	
			/**
			 * When using Ajax sourced data and during the first draw when DataTables is
			 * gathering the data, this message is shown in an empty row in the table to
			 * indicate to the end user the the data is being loaded. Note that this
			 * parameter is not used when loading data by server-side processing, just
			 * Ajax sourced data with client-side processing.
			 *  @type string
			 *  @default Loading...
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.loadingRecords
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "loadingRecords": "Please wait - loading..."
			 *        }
			 *      } );
			 *    } );
			 */
			"sLoadingRecords": "Loading...",
	
	
			/**
			 * Text which is displayed when the table is processing a user action
			 * (usually a sort command or similar).
			 *  @type string
			 *  @default Processing...
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.processing
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "processing": "DataTables is currently busy"
			 *        }
			 *      } );
			 *    } );
			 */
			"sProcessing": "Processing...",
	
	
			/**
			 * Details the actions that will be taken when the user types into the
			 * filtering input text box. The variable "_INPUT_", if used in the string,
			 * is replaced with the HTML text box for the filtering input allowing
			 * control over where it appears in the string. If "_INPUT_" is not given
			 * then the input box is appended to the string automatically.
			 *  @type string
			 *  @default Search:
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.search
			 *
			 *  @example
			 *    // Input text box will be appended at the end automatically
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "search": "Filter records:"
			 *        }
			 *      } );
			 *    } );
			 *
			 *  @example
			 *    // Specify where the filter should appear
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "search": "Apply filter _INPUT_ to table"
			 *        }
			 *      } );
			 *    } );
			 */
			"sSearch": "Search:",
	
	
			/**
			 * Assign a `placeholder` attribute to the search `input` element
			 *  @type string
			 *  @default 
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.searchPlaceholder
			 */
			"sSearchPlaceholder": "",
	
	
			/**
			 * All of the language information can be stored in a file on the
			 * server-side, which DataTables will look up if this parameter is passed.
			 * It must store the URL of the language file, which is in a JSON format,
			 * and the object has the same properties as the oLanguage object in the
			 * initialiser object (i.e. the above parameters). Please refer to one of
			 * the example language files to see how this works in action.
			 *  @type string
			 *  @default <i>Empty string - i.e. disabled</i>
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.url
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "url": "http://www.sprymedia.co.uk/dataTables/lang.txt"
			 *        }
			 *      } );
			 *    } );
			 */
			"sUrl": "",
	
	
			/**
			 * Text shown inside the table records when the is no information to be
			 * displayed after filtering. `emptyTable` is shown when there is simply no
			 * information in the table at all (regardless of filtering).
			 *  @type string
			 *  @default No matching records found
			 *
			 *  @dtopt Language
			 *  @name DataTable.defaults.language.zeroRecords
			 *
			 *  @example
			 *    $(document).ready( function() {
			 *      $('#example').dataTable( {
			 *        "language": {
			 *          "zeroRecords": "No records to display"
			 *        }
			 *      } );
			 *    } );
			 */
			"sZeroRecords": "No matching records found"
		},
	
	
		/**
		 * This parameter allows you to have define the global filtering state at
		 * initialisation time. As an object the `search` parameter must be
		 * defined, but all other parameters are optional. When `regex` is true,
		 * the search string will be treated as a regular expression, when false
		 * (default) it will be treated as a straight string. When `smart`
		 * DataTables will use it's smart filtering methods (to word match at
		 * any point in the data), when false this will not be done.
		 *  @namespace
		 *  @extends DataTable.models.oSearch
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.search
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "search": {"search": "Initial search"}
		 *      } );
		 *    } )
		 */
		"oSearch": $.extend( {}, DataTable.models.oSearch ),
	
	
		/**
		 * __Deprecated__ The functionality provided by this parameter has now been
		 * superseded by that provided through `ajax`, which should be used instead.
		 *
		 * By default DataTables will look for the property `data` (or `aaData` for
		 * compatibility with DataTables 1.9-) when obtaining data from an Ajax
		 * source or for server-side processing - this parameter allows that
		 * property to be changed. You can use Javascript dotted object notation to
		 * get a data source for multiple levels of nesting.
		 *  @type string
		 *  @default data
		 *
		 *  @dtopt Options
		 *  @dtopt Server-side
		 *  @name DataTable.defaults.ajaxDataProp
		 *
		 *  @deprecated 1.10. Please use `ajax` for this functionality now.
		 */
		"sAjaxDataProp": "data",
	
	
		/**
		 * __Deprecated__ The functionality provided by this parameter has now been
		 * superseded by that provided through `ajax`, which should be used instead.
		 *
		 * You can instruct DataTables to load data from an external
		 * source using this parameter (use aData if you want to pass data in you
		 * already have). Simply provide a url a JSON object can be obtained from.
		 *  @type string
		 *  @default null
		 *
		 *  @dtopt Options
		 *  @dtopt Server-side
		 *  @name DataTable.defaults.ajaxSource
		 *
		 *  @deprecated 1.10. Please use `ajax` for this functionality now.
		 */
		"sAjaxSource": null,
	
	
		/**
		 * This initialisation variable allows you to specify exactly where in the
		 * DOM you want DataTables to inject the various controls it adds to the page
		 * (for example you might want the pagination controls at the top of the
		 * table). DIV elements (with or without a custom class) can also be added to
		 * aid styling. The follow syntax is used:
		 *   <ul>
		 *     <li>The following options are allowed:
		 *       <ul>
		 *         <li>'l' - Length changing</li>
		 *         <li>'f' - Filtering input</li>
		 *         <li>'t' - The table!</li>
		 *         <li>'i' - Information</li>
		 *         <li>'p' - Pagination</li>
		 *         <li>'r' - pRocessing</li>
		 *       </ul>
		 *     </li>
		 *     <li>The following constants are allowed:
		 *       <ul>
		 *         <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li>
		 *         <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li>
		 *       </ul>
		 *     </li>
		 *     <li>The following syntax is expected:
		 *       <ul>
		 *         <li>'&lt;' and '&gt;' - div elements</li>
		 *         <li>'&lt;"class" and '&gt;' - div with a class</li>
		 *         <li>'&lt;"#id" and '&gt;' - div with an ID</li>
		 *       </ul>
		 *     </li>
		 *     <li>Examples:
		 *       <ul>
		 *         <li>'&lt;"wrapper"flipt&gt;'</li>
		 *         <li>'&lt;lf&lt;t&gt;ip&gt;'</li>
		 *       </ul>
		 *     </li>
		 *   </ul>
		 *  @type string
		 *  @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b>
		 *    <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i>
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.dom
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "dom": '&lt;"top"i&gt;rt&lt;"bottom"flp&gt;&lt;"clear"&gt;'
		 *      } );
		 *    } );
		 */
		"sDom": "lfrtip",
	
	
		/**
		 * Search delay option. This will throttle full table searches that use the
		 * DataTables provided search input element (it does not effect calls to
		 * `dt-api search()`, providing a delay before the search is made.
		 *  @type integer
		 *  @default 0
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.searchDelay
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "searchDelay": 200
		 *      } );
		 *    } )
		 */
		"searchDelay": null,
	
	
		/**
		 * DataTables features six different built-in options for the buttons to
		 * display for pagination control:
		 *
		 * * `numbers` - Page number buttons only
		 * * `simple` - 'Previous' and 'Next' buttons only
		 * * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers
		 * * `full` - 'First', 'Previous', 'Next' and 'Last' buttons
		 * * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus page numbers
		 * * `first_last_numbers` - 'First' and 'Last' buttons, plus page numbers
		 *  
		 * Further methods can be added using {@link DataTable.ext.oPagination}.
		 *  @type string
		 *  @default simple_numbers
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.pagingType
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "pagingType": "full_numbers"
		 *      } );
		 *    } )
		 */
		"sPaginationType": "simple_numbers",
	
	
		/**
		 * Enable horizontal scrolling. When a table is too wide to fit into a
		 * certain layout, or you have a large number of columns in the table, you
		 * can enable x-scrolling to show the table in a viewport, which can be
		 * scrolled. This property can be `true` which will allow the table to
		 * scroll horizontally when needed, or any CSS unit, or a number (in which
		 * case it will be treated as a pixel measurement). Setting as simply `true`
		 * is recommended.
		 *  @type boolean|string
		 *  @default <i>blank string - i.e. disabled</i>
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.scrollX
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "scrollX": true,
		 *        "scrollCollapse": true
		 *      } );
		 *    } );
		 */
		"sScrollX": "",
	
	
		/**
		 * This property can be used to force a DataTable to use more width than it
		 * might otherwise do when x-scrolling is enabled. For example if you have a
		 * table which requires to be well spaced, this parameter is useful for
		 * "over-sizing" the table, and thus forcing scrolling. This property can by
		 * any CSS unit, or a number (in which case it will be treated as a pixel
		 * measurement).
		 *  @type string
		 *  @default <i>blank string - i.e. disabled</i>
		 *
		 *  @dtopt Options
		 *  @name DataTable.defaults.scrollXInner
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "scrollX": "100%",
		 *        "scrollXInner": "110%"
		 *      } );
		 *    } );
		 */
		"sScrollXInner": "",
	
	
		/**
		 * Enable vertical scrolling. Vertical scrolling will constrain the DataTable
		 * to the given height, and enable scrolling for any data which overflows the
		 * current viewport. This can be used as an alternative to paging to display
		 * a lot of data in a small area (although paging and scrolling can both be
		 * enabled at the same time). This property can be any CSS unit, or a number
		 * (in which case it will be treated as a pixel measurement).
		 *  @type string
		 *  @default <i>blank string - i.e. disabled</i>
		 *
		 *  @dtopt Features
		 *  @name DataTable.defaults.scrollY
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "scrollY": "200px",
		 *        "paginate": false
		 *      } );
		 *    } );
		 */
		"sScrollY": "",
	
	
		/**
		 * __Deprecated__ The functionality provided by this parameter has now been
		 * superseded by that provided through `ajax`, which should be used instead.
		 *
		 * Set the HTTP method that is used to make the Ajax call for server-side
		 * processing or Ajax sourced data.
		 *  @type string
		 *  @default GET
		 *
		 *  @dtopt Options
		 *  @dtopt Server-side
		 *  @name DataTable.defaults.serverMethod
		 *
		 *  @deprecated 1.10. Please use `ajax` for this functionality now.
		 */
		"sServerMethod": "GET",
	
	
		/**
		 * DataTables makes use of renderers when displaying HTML elements for
		 * a table. These renderers can be added or modified by plug-ins to
		 * generate suitable mark-up for a site. For example the Bootstrap
		 * integration plug-in for DataTables uses a paging button renderer to
		 * display pagination buttons in the mark-up required by Bootstrap.
		 *
		 * For further information about the renderers available see
		 * DataTable.ext.renderer
		 *  @type string|object
		 *  @default null
		 *
		 *  @name DataTable.defaults.renderer
		 *
		 */
		"renderer": null,
	
	
		/**
		 * Set the data property name that DataTables should use to get a row's id
		 * to set as the `id` property in the node.
		 *  @type string
		 *  @default DT_RowId
		 *
		 *  @name DataTable.defaults.rowId
		 */
		"rowId": "DT_RowId"
	};
	
	_fnHungarianMap( DataTable.defaults );
	
	
	
	/*
	 * Developer note - See note in model.defaults.js about the use of Hungarian
	 * notation and camel case.
	 */
	
	/**
	 * Column options that can be given to DataTables at initialisation time.
	 *  @namespace
	 */
	DataTable.defaults.column = {
		/**
		 * Define which column(s) an order will occur on for this column. This
		 * allows a column's ordering to take multiple columns into account when
		 * doing a sort or use the data from a different column. For example first
		 * name / last name columns make sense to do a multi-column sort over the
		 * two columns.
		 *  @type array|int
		 *  @default null <i>Takes the value of the column index automatically</i>
		 *
		 *  @name DataTable.defaults.column.orderData
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "orderData": [ 0, 1 ], "targets": [ 0 ] },
		 *          { "orderData": [ 1, 0 ], "targets": [ 1 ] },
		 *          { "orderData": 2, "targets": [ 2 ] }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "orderData": [ 0, 1 ] },
		 *          { "orderData": [ 1, 0 ] },
		 *          { "orderData": 2 },
		 *          null,
		 *          null
		 *        ]
		 *      } );
		 *    } );
		 */
		"aDataSort": null,
		"iDataSort": -1,
	
	
		/**
		 * You can control the default ordering direction, and even alter the
		 * behaviour of the sort handler (i.e. only allow ascending ordering etc)
		 * using this parameter.
		 *  @type array
		 *  @default [ 'asc', 'desc' ]
		 *
		 *  @name DataTable.defaults.column.orderSequence
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "orderSequence": [ "asc" ], "targets": [ 1 ] },
		 *          { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] },
		 *          { "orderSequence": [ "desc" ], "targets": [ 3 ] }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          null,
		 *          { "orderSequence": [ "asc" ] },
		 *          { "orderSequence": [ "desc", "asc", "asc" ] },
		 *          { "orderSequence": [ "desc" ] },
		 *          null
		 *        ]
		 *      } );
		 *    } );
		 */
		"asSorting": [ 'asc', 'desc' ],
	
	
		/**
		 * Enable or disable filtering on the data in this column.
		 *  @type boolean
		 *  @default true
		 *
		 *  @name DataTable.defaults.column.searchable
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "searchable": false, "targets": [ 0 ] }
		 *        ] } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "searchable": false },
		 *          null,
		 *          null,
		 *          null,
		 *          null
		 *        ] } );
		 *    } );
		 */
		"bSearchable": true,
	
	
		/**
		 * Enable or disable ordering on this column.
		 *  @type boolean
		 *  @default true
		 *
		 *  @name DataTable.defaults.column.orderable
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "orderable": false, "targets": [ 0 ] }
		 *        ] } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "orderable": false },
		 *          null,
		 *          null,
		 *          null,
		 *          null
		 *        ] } );
		 *    } );
		 */
		"bSortable": true,
	
	
		/**
		 * Enable or disable the display of this column.
		 *  @type boolean
		 *  @default true
		 *
		 *  @name DataTable.defaults.column.visible
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "visible": false, "targets": [ 0 ] }
		 *        ] } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "visible": false },
		 *          null,
		 *          null,
		 *          null,
		 *          null
		 *        ] } );
		 *    } );
		 */
		"bVisible": true,
	
	
		/**
		 * Developer definable function that is called whenever a cell is created (Ajax source,
		 * etc) or processed for input (DOM source). This can be used as a compliment to mRender
		 * allowing you to modify the DOM element (add background colour for example) when the
		 * element is available.
		 *  @type function
		 *  @param {element} td The TD node that has been created
		 *  @param {*} cellData The Data for the cell
		 *  @param {array|object} rowData The data for the whole row
		 *  @param {int} row The row index for the aoData data store
		 *  @param {int} col The column index for aoColumns
		 *
		 *  @name DataTable.defaults.column.createdCell
		 *  @dtopt Columns
		 *
		 *  @example
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [ {
		 *          "targets": [3],
		 *          "createdCell": function (td, cellData, rowData, row, col) {
		 *            if ( cellData == "1.7" ) {
		 *              $(td).css('color', 'blue')
		 *            }
		 *          }
		 *        } ]
		 *      });
		 *    } );
		 */
		"fnCreatedCell": null,
	
	
		/**
		 * This parameter has been replaced by `data` in DataTables to ensure naming
		 * consistency. `dataProp` can still be used, as there is backwards
		 * compatibility in DataTables for this option, but it is strongly
		 * recommended that you use `data` in preference to `dataProp`.
		 *  @name DataTable.defaults.column.dataProp
		 */
	
	
		/**
		 * This property can be used to read data from any data source property,
		 * including deeply nested objects / properties. `data` can be given in a
		 * number of different ways which effect its behaviour:
		 *
		 * * `integer` - treated as an array index for the data source. This is the
		 *   default that DataTables uses (incrementally increased for each column).
		 * * `string` - read an object property from the data source. There are
		 *   three 'special' options that can be used in the string to alter how
		 *   DataTables reads the data from the source object:
		 *    * `.` - Dotted Javascript notation. Just as you use a `.` in
		 *      Javascript to read from nested objects, so to can the options
		 *      specified in `data`. For example: `browser.version` or
		 *      `browser.name`. If your object parameter name contains a period, use
		 *      `\\` to escape it - i.e. `first\\.name`.
		 *    * `[]` - Array notation. DataTables can automatically combine data
		 *      from and array source, joining the data with the characters provided
		 *      between the two brackets. For example: `name[, ]` would provide a
		 *      comma-space separated list from the source array. If no characters
		 *      are provided between the brackets, the original array source is
		 *      returned.
		 *    * `()` - Function notation. Adding `()` to the end of a parameter will
		 *      execute a function of the name given. For example: `browser()` for a
		 *      simple function on the data source, `browser.version()` for a
		 *      function in a nested property or even `browser().version` to get an
		 *      object property if the function called returns an object. Note that
		 *      function notation is recommended for use in `render` rather than
		 *      `data` as it is much simpler to use as a renderer.
		 * * `null` - use the original data source for the row rather than plucking
		 *   data directly from it. This action has effects on two other
		 *   initialisation options:
		 *    * `defaultContent` - When null is given as the `data` option and
		 *      `defaultContent` is specified for the column, the value defined by
		 *      `defaultContent` will be used for the cell.
		 *    * `render` - When null is used for the `data` option and the `render`
		 *      option is specified for the column, the whole data source for the
		 *      row is used for the renderer.
		 * * `function` - the function given will be executed whenever DataTables
		 *   needs to set or get the data for a cell in the column. The function
		 *   takes three parameters:
		 *    * Parameters:
		 *      * `{array|object}` The data source for the row
		 *      * `{string}` The type call data requested - this will be 'set' when
		 *        setting data or 'filter', 'display', 'type', 'sort' or undefined
		 *        when gathering data. Note that when `undefined` is given for the
		 *        type DataTables expects to get the raw data for the object back<
		 *      * `{*}` Data to set when the second parameter is 'set'.
		 *    * Return:
		 *      * The return value from the function is not required when 'set' is
		 *        the type of call, but otherwise the return is what will be used
		 *        for the data requested.
		 *
		 * Note that `data` is a getter and setter option. If you just require
		 * formatting of data for output, you will likely want to use `render` which
		 * is simply a getter and thus simpler to use.
		 *
		 * Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The
		 * name change reflects the flexibility of this property and is consistent
		 * with the naming of mRender. If 'mDataProp' is given, then it will still
		 * be used by DataTables, as it automatically maps the old name to the new
		 * if required.
		 *
		 *  @type string|int|function|null
		 *  @default null <i>Use automatically calculated column index</i>
		 *
		 *  @name DataTable.defaults.column.data
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Read table data from objects
		 *    // JSON structure for each row:
		 *    //   {
		 *    //      "engine": {value},
		 *    //      "browser": {value},
		 *    //      "platform": {value},
		 *    //      "version": {value},
		 *    //      "grade": {value}
		 *    //   }
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "ajaxSource": "sources/objects.txt",
		 *        "columns": [
		 *          { "data": "engine" },
		 *          { "data": "browser" },
		 *          { "data": "platform" },
		 *          { "data": "version" },
		 *          { "data": "grade" }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Read information from deeply nested objects
		 *    // JSON structure for each row:
		 *    //   {
		 *    //      "engine": {value},
		 *    //      "browser": {value},
		 *    //      "platform": {
		 *    //         "inner": {value}
		 *    //      },
		 *    //      "details": [
		 *    //         {value}, {value}
		 *    //      ]
		 *    //   }
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "ajaxSource": "sources/deep.txt",
		 *        "columns": [
		 *          { "data": "engine" },
		 *          { "data": "browser" },
		 *          { "data": "platform.inner" },
		 *          { "data": "platform.details.0" },
		 *          { "data": "platform.details.1" }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `data` as a function to provide different information for
		 *    // sorting, filtering and display. In this case, currency (price)
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [ {
		 *          "targets": [ 0 ],
		 *          "data": function ( source, type, val ) {
		 *            if (type === 'set') {
		 *              source.price = val;
		 *              // Store the computed dislay and filter values for efficiency
		 *              source.price_display = val=="" ? "" : "$"+numberFormat(val);
		 *              source.price_filter  = val=="" ? "" : "$"+numberFormat(val)+" "+val;
		 *              return;
		 *            }
		 *            else if (type === 'display') {
		 *              return source.price_display;
		 *            }
		 *            else if (type === 'filter') {
		 *              return source.price_filter;
		 *            }
		 *            // 'sort', 'type' and undefined all just use the integer
		 *            return source.price;
		 *          }
		 *        } ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using default content
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [ {
		 *          "targets": [ 0 ],
		 *          "data": null,
		 *          "defaultContent": "Click to edit"
		 *        } ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using array notation - outputting a list from an array
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [ {
		 *          "targets": [ 0 ],
		 *          "data": "name[, ]"
		 *        } ]
		 *      } );
		 *    } );
		 *
		 */
		"mData": null,
	
	
		/**
		 * This property is the rendering partner to `data` and it is suggested that
		 * when you want to manipulate data for display (including filtering,
		 * sorting etc) without altering the underlying data for the table, use this
		 * property. `render` can be considered to be the the read only companion to
		 * `data` which is read / write (then as such more complex). Like `data`
		 * this option can be given in a number of different ways to effect its
		 * behaviour:
		 *
		 * * `integer` - treated as an array index for the data source. This is the
		 *   default that DataTables uses (incrementally increased for each column).
		 * * `string` - read an object property from the data source. There are
		 *   three 'special' options that can be used in the string to alter how
		 *   DataTables reads the data from the source object:
		 *    * `.` - Dotted Javascript notation. Just as you use a `.` in
		 *      Javascript to read from nested objects, so to can the options
		 *      specified in `data`. For example: `browser.version` or
		 *      `browser.name`. If your object parameter name contains a period, use
		 *      `\\` to escape it - i.e. `first\\.name`.
		 *    * `[]` - Array notation. DataTables can automatically combine data
		 *      from and array source, joining the data with the characters provided
		 *      between the two brackets. For example: `name[, ]` would provide a
		 *      comma-space separated list from the source array. If no characters
		 *      are provided between the brackets, the original array source is
		 *      returned.
		 *    * `()` - Function notation. Adding `()` to the end of a parameter will
		 *      execute a function of the name given. For example: `browser()` for a
		 *      simple function on the data source, `browser.version()` for a
		 *      function in a nested property or even `browser().version` to get an
		 *      object property if the function called returns an object.
		 * * `object` - use different data for the different data types requested by
		 *   DataTables ('filter', 'display', 'type' or 'sort'). The property names
		 *   of the object is the data type the property refers to and the value can
		 *   defined using an integer, string or function using the same rules as
		 *   `render` normally does. Note that an `_` option _must_ be specified.
		 *   This is the default value to use if you haven't specified a value for
		 *   the data type requested by DataTables.
		 * * `function` - the function given will be executed whenever DataTables
		 *   needs to set or get the data for a cell in the column. The function
		 *   takes three parameters:
		 *    * Parameters:
		 *      * {array|object} The data source for the row (based on `data`)
		 *      * {string} The type call data requested - this will be 'filter',
		 *        'display', 'type' or 'sort'.
		 *      * {array|object} The full data source for the row (not based on
		 *        `data`)
		 *    * Return:
		 *      * The return value from the function is what will be used for the
		 *        data requested.
		 *
		 *  @type string|int|function|object|null
		 *  @default null Use the data source value.
		 *
		 *  @name DataTable.defaults.column.render
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Create a comma separated list from an array of objects
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "ajaxSource": "sources/deep.txt",
		 *        "columns": [
		 *          { "data": "engine" },
		 *          { "data": "browser" },
		 *          {
		 *            "data": "platform",
		 *            "render": "[, ].name"
		 *          }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Execute a function to obtain data
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [ {
		 *          "targets": [ 0 ],
		 *          "data": null, // Use the full data source object for the renderer's source
		 *          "render": "browserName()"
		 *        } ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // As an object, extracting different data for the different types
		 *    // This would be used with a data source such as:
		 *    //   { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" }
		 *    // Here the `phone` integer is used for sorting and type detection, while `phone_filter`
		 *    // (which has both forms) is used for filtering for if a user inputs either format, while
		 *    // the formatted phone number is the one that is shown in the table.
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [ {
		 *          "targets": [ 0 ],
		 *          "data": null, // Use the full data source object for the renderer's source
		 *          "render": {
		 *            "_": "phone",
		 *            "filter": "phone_filter",
		 *            "display": "phone_display"
		 *          }
		 *        } ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Use as a function to create a link from the data source
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [ {
		 *          "targets": [ 0 ],
		 *          "data": "download_link",
		 *          "render": function ( data, type, full ) {
		 *            return '<a href="'+data+'">Download</a>';
		 *          }
		 *        } ]
		 *      } );
		 *    } );
		 */
		"mRender": null,
	
	
		/**
		 * Change the cell type created for the column - either TD cells or TH cells. This
		 * can be useful as TH cells have semantic meaning in the table body, allowing them
		 * to act as a header for a row (you may wish to add scope='row' to the TH elements).
		 *  @type string
		 *  @default td
		 *
		 *  @name DataTable.defaults.column.cellType
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Make the first column use TH cells
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [ {
		 *          "targets": [ 0 ],
		 *          "cellType": "th"
		 *        } ]
		 *      } );
		 *    } );
		 */
		"sCellType": "td",
	
	
		/**
		 * Class to give to each cell in this column.
		 *  @type string
		 *  @default <i>Empty string</i>
		 *
		 *  @name DataTable.defaults.column.class
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "class": "my_class", "targets": [ 0 ] }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "class": "my_class" },
		 *          null,
		 *          null,
		 *          null,
		 *          null
		 *        ]
		 *      } );
		 *    } );
		 */
		"sClass": "",
	
		/**
		 * When DataTables calculates the column widths to assign to each column,
		 * it finds the longest string in each column and then constructs a
		 * temporary table and reads the widths from that. The problem with this
		 * is that "mmm" is much wider then "iiii", but the latter is a longer
		 * string - thus the calculation can go wrong (doing it properly and putting
		 * it into an DOM object and measuring that is horribly(!) slow). Thus as
		 * a "work around" we provide this option. It will append its value to the
		 * text that is found to be the longest string for the column - i.e. padding.
		 * Generally you shouldn't need this!
		 *  @type string
		 *  @default <i>Empty string<i>
		 *
		 *  @name DataTable.defaults.column.contentPadding
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          null,
		 *          null,
		 *          null,
		 *          {
		 *            "contentPadding": "mmm"
		 *          }
		 *        ]
		 *      } );
		 *    } );
		 */
		"sContentPadding": "",
	
	
		/**
		 * Allows a default value to be given for a column's data, and will be used
		 * whenever a null data source is encountered (this can be because `data`
		 * is set to null, or because the data source itself is null).
		 *  @type string
		 *  @default null
		 *
		 *  @name DataTable.defaults.column.defaultContent
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          {
		 *            "data": null,
		 *            "defaultContent": "Edit",
		 *            "targets": [ -1 ]
		 *          }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          null,
		 *          null,
		 *          null,
		 *          {
		 *            "data": null,
		 *            "defaultContent": "Edit"
		 *          }
		 *        ]
		 *      } );
		 *    } );
		 */
		"sDefaultContent": null,
	
	
		/**
		 * This parameter is only used in DataTables' server-side processing. It can
		 * be exceptionally useful to know what columns are being displayed on the
		 * client side, and to map these to database fields. When defined, the names
		 * also allow DataTables to reorder information from the server if it comes
		 * back in an unexpected order (i.e. if you switch your columns around on the
		 * client-side, your server-side code does not also need updating).
		 *  @type string
		 *  @default <i>Empty string</i>
		 *
		 *  @name DataTable.defaults.column.name
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "name": "engine", "targets": [ 0 ] },
		 *          { "name": "browser", "targets": [ 1 ] },
		 *          { "name": "platform", "targets": [ 2 ] },
		 *          { "name": "version", "targets": [ 3 ] },
		 *          { "name": "grade", "targets": [ 4 ] }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "name": "engine" },
		 *          { "name": "browser" },
		 *          { "name": "platform" },
		 *          { "name": "version" },
		 *          { "name": "grade" }
		 *        ]
		 *      } );
		 *    } );
		 */
		"sName": "",
	
	
		/**
		 * Defines a data source type for the ordering which can be used to read
		 * real-time information from the table (updating the internally cached
		 * version) prior to ordering. This allows ordering to occur on user
		 * editable elements such as form inputs.
		 *  @type string
		 *  @default std
		 *
		 *  @name DataTable.defaults.column.orderDataType
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "orderDataType": "dom-text", "targets": [ 2, 3 ] },
		 *          { "type": "numeric", "targets": [ 3 ] },
		 *          { "orderDataType": "dom-select", "targets": [ 4 ] },
		 *          { "orderDataType": "dom-checkbox", "targets": [ 5 ] }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          null,
		 *          null,
		 *          { "orderDataType": "dom-text" },
		 *          { "orderDataType": "dom-text", "type": "numeric" },
		 *          { "orderDataType": "dom-select" },
		 *          { "orderDataType": "dom-checkbox" }
		 *        ]
		 *      } );
		 *    } );
		 */
		"sSortDataType": "std",
	
	
		/**
		 * The title of this column.
		 *  @type string
		 *  @default null <i>Derived from the 'TH' value for this column in the
		 *    original HTML table.</i>
		 *
		 *  @name DataTable.defaults.column.title
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "title": "My column title", "targets": [ 0 ] }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "title": "My column title" },
		 *          null,
		 *          null,
		 *          null,
		 *          null
		 *        ]
		 *      } );
		 *    } );
		 */
		"sTitle": null,
	
	
		/**
		 * The type allows you to specify how the data for this column will be
		 * ordered. Four types (string, numeric, date and html (which will strip
		 * HTML tags before ordering)) are currently available. Note that only date
		 * formats understood by Javascript's Date() object will be accepted as type
		 * date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string',
		 * 'numeric', 'date' or 'html' (by default). Further types can be adding
		 * through plug-ins.
		 *  @type string
		 *  @default null <i>Auto-detected from raw data</i>
		 *
		 *  @name DataTable.defaults.column.type
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "type": "html", "targets": [ 0 ] }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "type": "html" },
		 *          null,
		 *          null,
		 *          null,
		 *          null
		 *        ]
		 *      } );
		 *    } );
		 */
		"sType": null,
	
	
		/**
		 * Defining the width of the column, this parameter may take any CSS value
		 * (3em, 20px etc). DataTables applies 'smart' widths to columns which have not
		 * been given a specific width through this interface ensuring that the table
		 * remains readable.
		 *  @type string
		 *  @default null <i>Automatic</i>
		 *
		 *  @name DataTable.defaults.column.width
		 *  @dtopt Columns
		 *
		 *  @example
		 *    // Using `columnDefs`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columnDefs": [
		 *          { "width": "20%", "targets": [ 0 ] }
		 *        ]
		 *      } );
		 *    } );
		 *
		 *  @example
		 *    // Using `columns`
		 *    $(document).ready( function() {
		 *      $('#example').dataTable( {
		 *        "columns": [
		 *          { "width": "20%" },
		 *          null,
		 *          null,
		 *          null,
		 *          null
		 *        ]
		 *      } );
		 *    } );
		 */
		"sWidth": null
	};
	
	_fnHungarianMap( DataTable.defaults.column );
	
	
	
	/**
	 * DataTables settings object - this holds all the information needed for a
	 * given table, including configuration, data and current application of the
	 * table options. DataTables does not have a single instance for each DataTable
	 * with the settings attached to that instance, but rather instances of the
	 * DataTable "class" are created on-the-fly as needed (typically by a
	 * $().dataTable() call) and the settings object is then applied to that
	 * instance.
	 *
	 * Note that this object is related to {@link DataTable.defaults} but this
	 * one is the internal data store for DataTables's cache of columns. It should
	 * NOT be manipulated outside of DataTables. Any configuration should be done
	 * through the initialisation options.
	 *  @namespace
	 *  @todo Really should attach the settings object to individual instances so we
	 *    don't need to create new instances on each $().dataTable() call (if the
	 *    table already exists). It would also save passing oSettings around and
	 *    into every single function. However, this is a very significant
	 *    architecture change for DataTables and will almost certainly break
	 *    backwards compatibility with older installations. This is something that
	 *    will be done in 2.0.
	 */
	DataTable.models.oSettings = {
		/**
		 * Primary features of DataTables and their enablement state.
		 *  @namespace
		 */
		"oFeatures": {
	
			/**
			 * Flag to say if DataTables should automatically try to calculate the
			 * optimum table and columns widths (true) or not (false).
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bAutoWidth": null,
	
			/**
			 * Delay the creation of TR and TD elements until they are actually
			 * needed by a driven page draw. This can give a significant speed
			 * increase for Ajax source and Javascript source data, but makes no
			 * difference at all fro DOM and server-side processing tables.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bDeferRender": null,
	
			/**
			 * Enable filtering on the table or not. Note that if this is disabled
			 * then there is no filtering at all on the table, including fnFilter.
			 * To just remove the filtering input use sDom and remove the 'f' option.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bFilter": null,
	
			/**
			 * Table information element (the 'Showing x of y records' div) enable
			 * flag.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bInfo": null,
	
			/**
			 * Present a user control allowing the end user to change the page size
			 * when pagination is enabled.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bLengthChange": null,
	
			/**
			 * Pagination enabled or not. Note that if this is disabled then length
			 * changing must also be disabled.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bPaginate": null,
	
			/**
			 * Processing indicator enable flag whenever DataTables is enacting a
			 * user request - typically an Ajax request for server-side processing.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bProcessing": null,
	
			/**
			 * Server-side processing enabled flag - when enabled DataTables will
			 * get all data from the server for every draw - there is no filtering,
			 * sorting or paging done on the client-side.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bServerSide": null,
	
			/**
			 * Sorting enablement flag.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bSort": null,
	
			/**
			 * Multi-column sorting
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bSortMulti": null,
	
			/**
			 * Apply a class to the columns which are being sorted to provide a
			 * visual highlight or not. This can slow things down when enabled since
			 * there is a lot of DOM interaction.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bSortClasses": null,
	
			/**
			 * State saving enablement flag.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bStateSave": null
		},
	
	
		/**
		 * Scrolling settings for a table.
		 *  @namespace
		 */
		"oScroll": {
			/**
			 * When the table is shorter in height than sScrollY, collapse the
			 * table container down to the height of the table (when true).
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type boolean
			 */
			"bCollapse": null,
	
			/**
			 * Width of the scrollbar for the web-browser's platform. Calculated
			 * during table initialisation.
			 *  @type int
			 *  @default 0
			 */
			"iBarWidth": 0,
	
			/**
			 * Viewport width for horizontal scrolling. Horizontal scrolling is
			 * disabled if an empty string.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type string
			 */
			"sX": null,
	
			/**
			 * Width to expand the table to when using x-scrolling. Typically you
			 * should not need to use this.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type string
			 *  @deprecated
			 */
			"sXInner": null,
	
			/**
			 * Viewport height for vertical scrolling. Vertical scrolling is disabled
			 * if an empty string.
			 * Note that this parameter will be set by the initialisation routine. To
			 * set a default use {@link DataTable.defaults}.
			 *  @type string
			 */
			"sY": null
		},
	
		/**
		 * Language information for the table.
		 *  @namespace
		 *  @extends DataTable.defaults.oLanguage
		 */
		"oLanguage": {
			/**
			 * Information callback function. See
			 * {@link DataTable.defaults.fnInfoCallback}
			 *  @type function
			 *  @default null
			 */
			"fnInfoCallback": null
		},
	
		/**
		 * Browser support parameters
		 *  @namespace
		 */
		"oBrowser": {
			/**
			 * Indicate if the browser incorrectly calculates width:100% inside a
			 * scrolling element (IE6/7)
			 *  @type boolean
			 *  @default false
			 */
			"bScrollOversize": false,
	
			/**
			 * Determine if the vertical scrollbar is on the right or left of the
			 * scrolling container - needed for rtl language layout, although not
			 * all browsers move the scrollbar (Safari).
			 *  @type boolean
			 *  @default false
			 */
			"bScrollbarLeft": false,
	
			/**
			 * Flag for if `getBoundingClientRect` is fully supported or not
			 *  @type boolean
			 *  @default false
			 */
			"bBounding": false,
	
			/**
			 * Browser scrollbar width
			 *  @type integer
			 *  @default 0
			 */
			"barWidth": 0
		},
	
	
		"ajax": null,
	
	
		/**
		 * Array referencing the nodes which are used for the features. The
		 * parameters of this object match what is allowed by sDom - i.e.
		 *   <ul>
		 *     <li>'l' - Length changing</li>
		 *     <li>'f' - Filtering input</li>
		 *     <li>'t' - The table!</li>
		 *     <li>'i' - Information</li>
		 *     <li>'p' - Pagination</li>
		 *     <li>'r' - pRocessing</li>
		 *   </ul>
		 *  @type array
		 *  @default []
		 */
		"aanFeatures": [],
	
		/**
		 * Store data information - see {@link DataTable.models.oRow} for detailed
		 * information.
		 *  @type array
		 *  @default []
		 */
		"aoData": [],
	
		/**
		 * Array of indexes which are in the current display (after filtering etc)
		 *  @type array
		 *  @default []
		 */
		"aiDisplay": [],
	
		/**
		 * Array of indexes for display - no filtering
		 *  @type array
		 *  @default []
		 */
		"aiDisplayMaster": [],
	
		/**
		 * Map of row ids to data indexes
		 *  @type object
		 *  @default {}
		 */
		"aIds": {},
	
		/**
		 * Store information about each column that is in use
		 *  @type array
		 *  @default []
		 */
		"aoColumns": [],
	
		/**
		 * Store information about the table's header
		 *  @type array
		 *  @default []
		 */
		"aoHeader": [],
	
		/**
		 * Store information about the table's footer
		 *  @type array
		 *  @default []
		 */
		"aoFooter": [],
	
		/**
		 * Store the applied global search information in case we want to force a
		 * research or compare the old search to a new one.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @namespace
		 *  @extends DataTable.models.oSearch
		 */
		"oPreviousSearch": {},
	
		/**
		 * Store the applied search for each column - see
		 * {@link DataTable.models.oSearch} for the format that is used for the
		 * filtering information for each column.
		 *  @type array
		 *  @default []
		 */
		"aoPreSearchCols": [],
	
		/**
		 * Sorting that is applied to the table. Note that the inner arrays are
		 * used in the following manner:
		 * <ul>
		 *   <li>Index 0 - column number</li>
		 *   <li>Index 1 - current sorting direction</li>
		 * </ul>
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type array
		 *  @todo These inner arrays should really be objects
		 */
		"aaSorting": null,
	
		/**
		 * Sorting that is always applied to the table (i.e. prefixed in front of
		 * aaSorting).
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type array
		 *  @default []
		 */
		"aaSortingFixed": [],
	
		/**
		 * Classes to use for the striping of a table.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type array
		 *  @default []
		 */
		"asStripeClasses": null,
	
		/**
		 * If restoring a table - we should restore its striping classes as well
		 *  @type array
		 *  @default []
		 */
		"asDestroyStripes": [],
	
		/**
		 * If restoring a table - we should restore its width
		 *  @type int
		 *  @default 0
		 */
		"sDestroyWidth": 0,
	
		/**
		 * Callback functions array for every time a row is inserted (i.e. on a draw).
		 *  @type array
		 *  @default []
		 */
		"aoRowCallback": [],
	
		/**
		 * Callback functions for the header on each draw.
		 *  @type array
		 *  @default []
		 */
		"aoHeaderCallback": [],
	
		/**
		 * Callback function for the footer on each draw.
		 *  @type array
		 *  @default []
		 */
		"aoFooterCallback": [],
	
		/**
		 * Array of callback functions for draw callback functions
		 *  @type array
		 *  @default []
		 */
		"aoDrawCallback": [],
	
		/**
		 * Array of callback functions for row created function
		 *  @type array
		 *  @default []
		 */
		"aoRowCreatedCallback": [],
	
		/**
		 * Callback functions for just before the table is redrawn. A return of
		 * false will be used to cancel the draw.
		 *  @type array
		 *  @default []
		 */
		"aoPreDrawCallback": [],
	
		/**
		 * Callback functions for when the table has been initialised.
		 *  @type array
		 *  @default []
		 */
		"aoInitComplete": [],
	
	
		/**
		 * Callbacks for modifying the settings to be stored for state saving, prior to
		 * saving state.
		 *  @type array
		 *  @default []
		 */
		"aoStateSaveParams": [],
	
		/**
		 * Callbacks for modifying the settings that have been stored for state saving
		 * prior to using the stored values to restore the state.
		 *  @type array
		 *  @default []
		 */
		"aoStateLoadParams": [],
	
		/**
		 * Callbacks for operating on the settings object once the saved state has been
		 * loaded
		 *  @type array
		 *  @default []
		 */
		"aoStateLoaded": [],
	
		/**
		 * Cache the table ID for quick access
		 *  @type string
		 *  @default <i>Empty string</i>
		 */
		"sTableId": "",
	
		/**
		 * The TABLE node for the main table
		 *  @type node
		 *  @default null
		 */
		"nTable": null,
	
		/**
		 * Permanent ref to the thead element
		 *  @type node
		 *  @default null
		 */
		"nTHead": null,
	
		/**
		 * Permanent ref to the tfoot element - if it exists
		 *  @type node
		 *  @default null
		 */
		"nTFoot": null,
	
		/**
		 * Permanent ref to the tbody element
		 *  @type node
		 *  @default null
		 */
		"nTBody": null,
	
		/**
		 * Cache the wrapper node (contains all DataTables controlled elements)
		 *  @type node
		 *  @default null
		 */
		"nTableWrapper": null,
	
		/**
		 * Indicate if when using server-side processing the loading of data
		 * should be deferred until the second draw.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type boolean
		 *  @default false
		 */
		"bDeferLoading": false,
	
		/**
		 * Indicate if all required information has been read in
		 *  @type boolean
		 *  @default false
		 */
		"bInitialised": false,
	
		/**
		 * Information about open rows. Each object in the array has the parameters
		 * 'nTr' and 'nParent'
		 *  @type array
		 *  @default []
		 */
		"aoOpenRows": [],
	
		/**
		 * Dictate the positioning of DataTables' control elements - see
		 * {@link DataTable.model.oInit.sDom}.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type string
		 *  @default null
		 */
		"sDom": null,
	
		/**
		 * Search delay (in mS)
		 *  @type integer
		 *  @default null
		 */
		"searchDelay": null,
	
		/**
		 * Which type of pagination should be used.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type string
		 *  @default two_button
		 */
		"sPaginationType": "two_button",
	
		/**
		 * The state duration (for `stateSave`) in seconds.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type int
		 *  @default 0
		 */
		"iStateDuration": 0,
	
		/**
		 * Array of callback functions for state saving. Each array element is an
		 * object with the following parameters:
		 *   <ul>
		 *     <li>function:fn - function to call. Takes two parameters, oSettings
		 *       and the JSON string to save that has been thus far created. Returns
		 *       a JSON string to be inserted into a json object
		 *       (i.e. '"param": [ 0, 1, 2]')</li>
		 *     <li>string:sName - name of callback</li>
		 *   </ul>
		 *  @type array
		 *  @default []
		 */
		"aoStateSave": [],
	
		/**
		 * Array of callback functions for state loading. Each array element is an
		 * object with the following parameters:
		 *   <ul>
		 *     <li>function:fn - function to call. Takes two parameters, oSettings
		 *       and the object stored. May return false to cancel state loading</li>
		 *     <li>string:sName - name of callback</li>
		 *   </ul>
		 *  @type array
		 *  @default []
		 */
		"aoStateLoad": [],
	
		/**
		 * State that was saved. Useful for back reference
		 *  @type object
		 *  @default null
		 */
		"oSavedState": null,
	
		/**
		 * State that was loaded. Useful for back reference
		 *  @type object
		 *  @default null
		 */
		"oLoadedState": null,
	
		/**
		 * Source url for AJAX data for the table.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type string
		 *  @default null
		 */
		"sAjaxSource": null,
	
		/**
		 * Property from a given object from which to read the table data from. This
		 * can be an empty string (when not server-side processing), in which case
		 * it is  assumed an an array is given directly.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type string
		 */
		"sAjaxDataProp": null,
	
		/**
		 * Note if draw should be blocked while getting data
		 *  @type boolean
		 *  @default true
		 */
		"bAjaxDataGet": true,
	
		/**
		 * The last jQuery XHR object that was used for server-side data gathering.
		 * This can be used for working with the XHR information in one of the
		 * callbacks
		 *  @type object
		 *  @default null
		 */
		"jqXHR": null,
	
		/**
		 * JSON returned from the server in the last Ajax request
		 *  @type object
		 *  @default undefined
		 */
		"json": undefined,
	
		/**
		 * Data submitted as part of the last Ajax request
		 *  @type object
		 *  @default undefined
		 */
		"oAjaxData": undefined,
	
		/**
		 * Function to get the server-side data.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type function
		 */
		"fnServerData": null,
	
		/**
		 * Functions which are called prior to sending an Ajax request so extra
		 * parameters can easily be sent to the server
		 *  @type array
		 *  @default []
		 */
		"aoServerParams": [],
	
		/**
		 * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
		 * required).
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type string
		 */
		"sServerMethod": null,
	
		/**
		 * Format numbers for display.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type function
		 */
		"fnFormatNumber": null,
	
		/**
		 * List of options that can be used for the user selectable length menu.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type array
		 *  @default []
		 */
		"aLengthMenu": null,
	
		/**
		 * Counter for the draws that the table does. Also used as a tracker for
		 * server-side processing
		 *  @type int
		 *  @default 0
		 */
		"iDraw": 0,
	
		/**
		 * Indicate if a redraw is being done - useful for Ajax
		 *  @type boolean
		 *  @default false
		 */
		"bDrawing": false,
	
		/**
		 * Draw index (iDraw) of the last error when parsing the returned data
		 *  @type int
		 *  @default -1
		 */
		"iDrawError": -1,
	
		/**
		 * Paging display length
		 *  @type int
		 *  @default 10
		 */
		"_iDisplayLength": 10,
	
		/**
		 * Paging start point - aiDisplay index
		 *  @type int
		 *  @default 0
		 */
		"_iDisplayStart": 0,
	
		/**
		 * Server-side processing - number of records in the result set
		 * (i.e. before filtering), Use fnRecordsTotal rather than
		 * this property to get the value of the number of records, regardless of
		 * the server-side processing setting.
		 *  @type int
		 *  @default 0
		 *  @private
		 */
		"_iRecordsTotal": 0,
	
		/**
		 * Server-side processing - number of records in the current display set
		 * (i.e. after filtering). Use fnRecordsDisplay rather than
		 * this property to get the value of the number of records, regardless of
		 * the server-side processing setting.
		 *  @type boolean
		 *  @default 0
		 *  @private
		 */
		"_iRecordsDisplay": 0,
	
		/**
		 * Flag to indicate if jQuery UI marking and classes should be used.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type boolean
		 */
		"bJUI": null,
	
		/**
		 * The classes to use for the table
		 *  @type object
		 *  @default {}
		 */
		"oClasses": {},
	
		/**
		 * Flag attached to the settings object so you can check in the draw
		 * callback if filtering has been done in the draw. Deprecated in favour of
		 * events.
		 *  @type boolean
		 *  @default false
		 *  @deprecated
		 */
		"bFiltered": false,
	
		/**
		 * Flag attached to the settings object so you can check in the draw
		 * callback if sorting has been done in the draw. Deprecated in favour of
		 * events.
		 *  @type boolean
		 *  @default false
		 *  @deprecated
		 */
		"bSorted": false,
	
		/**
		 * Indicate that if multiple rows are in the header and there is more than
		 * one unique cell per column, if the top one (true) or bottom one (false)
		 * should be used for sorting / title by DataTables.
		 * Note that this parameter will be set by the initialisation routine. To
		 * set a default use {@link DataTable.defaults}.
		 *  @type boolean
		 */
		"bSortCellsTop": null,
	
		/**
		 * Initialisation object that is used for the table
		 *  @type object
		 *  @default null
		 */
		"oInit": null,
	
		/**
		 * Destroy callback functions - for plug-ins to attach themselves to the
		 * destroy so they can clean up markup and events.
		 *  @type array
		 *  @default []
		 */
		"aoDestroyCallback": [],
	
	
		/**
		 * Get the number of records in the current record set, before filtering
		 *  @type function
		 */
		"fnRecordsTotal": function ()
		{
			return _fnDataSource( this ) == 'ssp' ?
				this._iRecordsTotal * 1 :
				this.aiDisplayMaster.length;
		},
	
		/**
		 * Get the number of records in the current record set, after filtering
		 *  @type function
		 */
		"fnRecordsDisplay": function ()
		{
			return _fnDataSource( this ) == 'ssp' ?
				this._iRecordsDisplay * 1 :
				this.aiDisplay.length;
		},
	
		/**
		 * Get the display end point - aiDisplay index
		 *  @type function
		 */
		"fnDisplayEnd": function ()
		{
			var
				len      = this._iDisplayLength,
				start    = this._iDisplayStart,
				calc     = start + len,
				records  = this.aiDisplay.length,
				features = this.oFeatures,
				paginate = features.bPaginate;
	
			if ( features.bServerSide ) {
				return paginate === false || len === -1 ?
					start + records :
					Math.min( start+len, this._iRecordsDisplay );
			}
			else {
				return ! paginate || calc>records || len===-1 ?
					records :
					calc;
			}
		},
	
		/**
		 * The DataTables object for this table
		 *  @type object
		 *  @default null
		 */
		"oInstance": null,
	
		/**
		 * Unique identifier for each instance of the DataTables object. If there
		 * is an ID on the table node, then it takes that value, otherwise an
		 * incrementing internal counter is used.
		 *  @type string
		 *  @default null
		 */
		"sInstance": null,
	
		/**
		 * tabindex attribute value that is added to DataTables control elements, allowing
		 * keyboard navigation of the table and its controls.
		 */
		"iTabIndex": 0,
	
		/**
		 * DIV container for the footer scrolling table if scrolling
		 */
		"nScrollHead": null,
	
		/**
		 * DIV container for the footer scrolling table if scrolling
		 */
		"nScrollFoot": null,
	
		/**
		 * Last applied sort
		 *  @type array
		 *  @default []
		 */
		"aLastSort": [],
	
		/**
		 * Stored plug-in instances
		 *  @type object
		 *  @default {}
		 */
		"oPlugins": {},
	
		/**
		 * Function used to get a row's id from the row's data
		 *  @type function
		 *  @default null
		 */
		"rowIdFn": null,
	
		/**
		 * Data location where to store a row's id
		 *  @type string
		 *  @default null
		 */
		"rowId": null
	};

	/**
	 * Extension object for DataTables that is used to provide all extension
	 * options.
	 *
	 * Note that the `DataTable.ext` object is available through
	 * `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is
	 * also aliased to `jQuery.fn.dataTableExt` for historic reasons.
	 *  @namespace
	 *  @extends DataTable.models.ext
	 */
	
	
	/**
	 * DataTables extensions
	 * 
	 * This namespace acts as a collection area for plug-ins that can be used to
	 * extend DataTables capabilities. Indeed many of the build in methods
	 * use this method to provide their own capabilities (sorting methods for
	 * example).
	 *
	 * Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy
	 * reasons
	 *
	 *  @namespace
	 */
	DataTable.ext = _ext = {
		/**
		 * Buttons. For use with the Buttons extension for DataTables. This is
		 * defined here so other extensions can define buttons regardless of load
		 * order. It is _not_ used by DataTables core.
		 *
		 *  @type object
		 *  @default {}
		 */
		buttons: {},
	
	
		/**
		 * Element class names
		 *
		 *  @type object
		 *  @default {}
		 */
		classes: {},
	
	
		/**
		 * DataTables build type (expanded by the download builder)
		 *
		 *  @type string
		 */
		builder: "-source-",
	
	
		/**
		 * Error reporting.
		 * 
		 * How should DataTables report an error. Can take the value 'alert',
		 * 'throw', 'none' or a function.
		 *
		 *  @type string|function
		 *  @default alert
		 */
		errMode: "alert",
	
	
		/**
		 * Feature plug-ins.
		 * 
		 * This is an array of objects which describe the feature plug-ins that are
		 * available to DataTables. These feature plug-ins are then available for
		 * use through the `dom` initialisation option.
		 * 
		 * Each feature plug-in is described by an object which must have the
		 * following properties:
		 * 
		 * * `fnInit` - function that is used to initialise the plug-in,
		 * * `cFeature` - a character so the feature can be enabled by the `dom`
		 *   instillation option. This is case sensitive.
		 *
		 * The `fnInit` function has the following input parameters:
		 *
		 * 1. `{object}` DataTables settings object: see
		 *    {@link DataTable.models.oSettings}
		 *
		 * And the following return is expected:
		 * 
		 * * {node|null} The element which contains your feature. Note that the
		 *   return may also be void if your plug-in does not require to inject any
		 *   DOM elements into DataTables control (`dom`) - for example this might
		 *   be useful when developing a plug-in which allows table control via
		 *   keyboard entry
		 *
		 *  @type array
		 *
		 *  @example
		 *    $.fn.dataTable.ext.features.push( {
		 *      "fnInit": function( oSettings ) {
		 *        return new TableTools( { "oDTSettings": oSettings } );
		 *      },
		 *      "cFeature": "T"
		 *    } );
		 */
		feature: [],
	
	
		/**
		 * Row searching.
		 * 
		 * This method of searching is complimentary to the default type based
		 * searching, and a lot more comprehensive as it allows you complete control
		 * over the searching logic. Each element in this array is a function
		 * (parameters described below) that is called for every row in the table,
		 * and your logic decides if it should be included in the searching data set
		 * or not.
		 *
		 * Searching functions have the following input parameters:
		 *
		 * 1. `{object}` DataTables settings object: see
		 *    {@link DataTable.models.oSettings}
		 * 2. `{array|object}` Data for the row to be processed (same as the
		 *    original format that was passed in as the data source, or an array
		 *    from a DOM data source
		 * 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which
		 *    can be useful to retrieve the `TR` element if you need DOM interaction.
		 *
		 * And the following return is expected:
		 *
		 * * {boolean} Include the row in the searched result set (true) or not
		 *   (false)
		 *
		 * Note that as with the main search ability in DataTables, technically this
		 * is "filtering", since it is subtractive. However, for consistency in
		 * naming we call it searching here.
		 *
		 *  @type array
		 *  @default []
		 *
		 *  @example
		 *    // The following example shows custom search being applied to the
		 *    // fourth column (i.e. the data[3] index) based on two input values
		 *    // from the end-user, matching the data in a certain range.
		 *    $.fn.dataTable.ext.search.push(
		 *      function( settings, data, dataIndex ) {
		 *        var min = document.getElementById('min').value * 1;
		 *        var max = document.getElementById('max').value * 1;
		 *        var version = data[3] == "-" ? 0 : data[3]*1;
		 *
		 *        if ( min == "" && max == "" ) {
		 *          return true;
		 *        }
		 *        else if ( min == "" && version < max ) {
		 *          return true;
		 *        }
		 *        else if ( min < version && "" == max ) {
		 *          return true;
		 *        }
		 *        else if ( min < version && version < max ) {
		 *          return true;
		 *        }
		 *        return false;
		 *      }
		 *    );
		 */
		search: [],
	
	
		/**
		 * Selector extensions
		 *
		 * The `selector` option can be used to extend the options available for the
		 * selector modifier options (`selector-modifier` object data type) that
		 * each of the three built in selector types offer (row, column and cell +
		 * their plural counterparts). For example the Select extension uses this
		 * mechanism to provide an option to select only rows, columns and cells
		 * that have been marked as selected by the end user (`{selected: true}`),
		 * which can be used in conjunction with the existing built in selector
		 * options.
		 *
		 * Each property is an array to which functions can be pushed. The functions
		 * take three attributes:
		 *
		 * * Settings object for the host table
		 * * Options object (`selector-modifier` object type)
		 * * Array of selected item indexes
		 *
		 * The return is an array of the resulting item indexes after the custom
		 * selector has been applied.
		 *
		 *  @type object
		 */
		selector: {
			cell: [],
			column: [],
			row: []
		},
	
	
		/**
		 * Internal functions, exposed for used in plug-ins.
		 * 
		 * Please note that you should not need to use the internal methods for
		 * anything other than a plug-in (and even then, try to avoid if possible).
		 * The internal function may change between releases.
		 *
		 *  @type object
		 *  @default {}
		 */
		internal: {},
	
	
		/**
		 * Legacy configuration options. Enable and disable legacy options that
		 * are available in DataTables.
		 *
		 *  @type object
		 */
		legacy: {
			/**
			 * Enable / disable DataTables 1.9 compatible server-side processing
			 * requests
			 *
			 *  @type boolean
			 *  @default null
			 */
			ajax: null
		},
	
	
		/**
		 * Pagination plug-in methods.
		 * 
		 * Each entry in this object is a function and defines which buttons should
		 * be shown by the pagination rendering method that is used for the table:
		 * {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the
		 * buttons are displayed in the document, while the functions here tell it
		 * what buttons to display. This is done by returning an array of button
		 * descriptions (what each button will do).
		 *
		 * Pagination types (the four built in options and any additional plug-in
		 * options defined here) can be used through the `paginationType`
		 * initialisation parameter.
		 *
		 * The functions defined take two parameters:
		 *
		 * 1. `{int} page` The current page index
		 * 2. `{int} pages` The number of pages in the table
		 *
		 * Each function is expected to return an array where each element of the
		 * array can be one of:
		 *
		 * * `first` - Jump to first page when activated
		 * * `last` - Jump to last page when activated
		 * * `previous` - Show previous page when activated
		 * * `next` - Show next page when activated
		 * * `{int}` - Show page of the index given
		 * * `{array}` - A nested array containing the above elements to add a
		 *   containing 'DIV' element (might be useful for styling).
		 *
		 * Note that DataTables v1.9- used this object slightly differently whereby
		 * an object with two functions would be defined for each plug-in. That
		 * ability is still supported by DataTables 1.10+ to provide backwards
		 * compatibility, but this option of use is now decremented and no longer
		 * documented in DataTables 1.10+.
		 *
		 *  @type object
		 *  @default {}
		 *
		 *  @example
		 *    // Show previous, next and current page buttons only
		 *    $.fn.dataTableExt.oPagination.current = function ( page, pages ) {
		 *      return [ 'previous', page, 'next' ];
		 *    };
		 */
		pager: {},
	
	
		renderer: {
			pageButton: {},
			header: {}
		},
	
	
		/**
		 * Ordering plug-ins - custom data source
		 * 
		 * The extension options for ordering of data available here is complimentary
		 * to the default type based ordering that DataTables typically uses. It
		 * allows much greater control over the the data that is being used to
		 * order a column, but is necessarily therefore more complex.
		 * 
		 * This type of ordering is useful if you want to do ordering based on data
		 * live from the DOM (for example the contents of an 'input' element) rather
		 * than just the static string that DataTables knows of.
		 * 
		 * The way these plug-ins work is that you create an array of the values you
		 * wish to be ordering for the column in question and then return that
		 * array. The data in the array much be in the index order of the rows in
		 * the table (not the currently ordering order!). Which order data gathering
		 * function is run here depends on the `dt-init columns.orderDataType`
		 * parameter that is used for the column (if any).
		 *
		 * The functions defined take two parameters:
		 *
		 * 1. `{object}` DataTables settings object: see
		 *    {@link DataTable.models.oSettings}
		 * 2. `{int}` Target column index
		 *
		 * Each function is expected to return an array:
		 *
		 * * `{array}` Data for the column to be ordering upon
		 *
		 *  @type array
		 *
		 *  @example
		 *    // Ordering using `input` node values
		 *    $.fn.dataTable.ext.order['dom-text'] = function  ( settings, col )
		 *    {
		 *      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
		 *        return $('input', td).val();
		 *      } );
		 *    }
		 */
		order: {},
	
	
		/**
		 * Type based plug-ins.
		 *
		 * Each column in DataTables has a type assigned to it, either by automatic
		 * detection or by direct assignment using the `type` option for the column.
		 * The type of a column will effect how it is ordering and search (plug-ins
		 * can also make use of the column type if required).
		 *
		 * @namespace
		 */
		type: {
			/**
			 * Type detection functions.
			 *
			 * The functions defined in this object are used to automatically detect
			 * a column's type, making initialisation of DataTables super easy, even
			 * when complex data is in the table.
			 *
			 * The functions defined take two parameters:
			 *
		     *  1. `{*}` Data from the column cell to be analysed
		     *  2. `{settings}` DataTables settings object. This can be used to
		     *     perform context specific type detection - for example detection
		     *     based on language settings such as using a comma for a decimal
		     *     place. Generally speaking the options from the settings will not
		     *     be required
			 *
			 * Each function is expected to return:
			 *
			 * * `{string|null}` Data type detected, or null if unknown (and thus
			 *   pass it on to the other type detection functions.
			 *
			 *  @type array
			 *
			 *  @example
			 *    // Currency type detection plug-in:
			 *    $.fn.dataTable.ext.type.detect.push(
			 *      function ( data, settings ) {
			 *        // Check the numeric part
			 *        if ( ! $.isNumeric( data.substring(1) ) ) {
			 *          return null;
			 *        }
			 *
			 *        // Check prefixed by currency
			 *        if ( data.charAt(0) == '$' || data.charAt(0) == '&pound;' ) {
			 *          return 'currency';
			 *        }
			 *        return null;
			 *      }
			 *    );
			 */
			detect: [],
	
	
			/**
			 * Type based search formatting.
			 *
			 * The type based searching functions can be used to pre-format the
			 * data to be search on. For example, it can be used to strip HTML
			 * tags or to de-format telephone numbers for numeric only searching.
			 *
			 * Note that is a search is not defined for a column of a given type,
			 * no search formatting will be performed.
			 * 
			 * Pre-processing of searching data plug-ins - When you assign the sType
			 * for a column (or have it automatically detected for you by DataTables
			 * or a type detection plug-in), you will typically be using this for
			 * custom sorting, but it can also be used to provide custom searching
			 * by allowing you to pre-processing the data and returning the data in
			 * the format that should be searched upon. This is done by adding
			 * functions this object with a parameter name which matches the sType
			 * for that target column. This is the corollary of <i>afnSortData</i>
			 * for searching data.
			 *
			 * The functions defined take a single parameter:
			 *
		     *  1. `{*}` Data from the column cell to be prepared for searching
			 *
			 * Each function is expected to return:
			 *
			 * * `{string|null}` Formatted string that will be used for the searching.
			 *
			 *  @type object
			 *  @default {}
			 *
			 *  @example
			 *    $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
			 *      return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
			 *    }
			 */
			search: {},
	
	
			/**
			 * Type based ordering.
			 *
			 * The column type tells DataTables what ordering to apply to the table
			 * when a column is sorted upon. The order for each type that is defined,
			 * is defined by the functions available in this object.
			 *
			 * Each ordering option can be described by three properties added to
			 * this object:
			 *
			 * * `{type}-pre` - Pre-formatting function
			 * * `{type}-asc` - Ascending order function
			 * * `{type}-desc` - Descending order function
			 *
			 * All three can be used together, only `{type}-pre` or only
			 * `{type}-asc` and `{type}-desc` together. It is generally recommended
			 * that only `{type}-pre` is used, as this provides the optimal
			 * implementation in terms of speed, although the others are provided
			 * for compatibility with existing Javascript sort functions.
			 *
			 * `{type}-pre`: Functions defined take a single parameter:
			 *
		     *  1. `{*}` Data from the column cell to be prepared for ordering
			 *
			 * And return:
			 *
			 * * `{*}` Data to be sorted upon
			 *
			 * `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort
			 * functions, taking two parameters:
			 *
		     *  1. `{*}` Data to compare to the second parameter
		     *  2. `{*}` Data to compare to the first parameter
			 *
			 * And returning:
			 *
			 * * `{*}` Ordering match: <0 if first parameter should be sorted lower
			 *   than the second parameter, ===0 if the two parameters are equal and
			 *   >0 if the first parameter should be sorted height than the second
			 *   parameter.
			 * 
			 *  @type object
			 *  @default {}
			 *
			 *  @example
			 *    // Numeric ordering of formatted numbers with a pre-formatter
			 *    $.extend( $.fn.dataTable.ext.type.order, {
			 *      "string-pre": function(x) {
			 *        a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" );
			 *        return parseFloat( a );
			 *      }
			 *    } );
			 *
			 *  @example
			 *    // Case-sensitive string ordering, with no pre-formatting method
			 *    $.extend( $.fn.dataTable.ext.order, {
			 *      "string-case-asc": function(x,y) {
			 *        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
			 *      },
			 *      "string-case-desc": function(x,y) {
			 *        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
			 *      }
			 *    } );
			 */
			order: {}
		},
	
		/**
		 * Unique DataTables instance counter
		 *
		 * @type int
		 * @private
		 */
		_unique: 0,
	
	
		//
		// Depreciated
		// The following properties are retained for backwards compatiblity only.
		// The should not be used in new projects and will be removed in a future
		// version
		//
	
		/**
		 * Version check function.
		 *  @type function
		 *  @depreciated Since 1.10
		 */
		fnVersionCheck: DataTable.fnVersionCheck,
	
	
		/**
		 * Index for what 'this' index API functions should use
		 *  @type int
		 *  @deprecated Since v1.10
		 */
		iApiIndex: 0,
	
	
		/**
		 * jQuery UI class container
		 *  @type object
		 *  @deprecated Since v1.10
		 */
		oJUIClasses: {},
	
	
		/**
		 * Software version
		 *  @type string
		 *  @deprecated Since v1.10
		 */
		sVersion: DataTable.version
	};
	
	
	//
	// Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts
	//
	$.extend( _ext, {
		afnFiltering: _ext.search,
		aTypes:       _ext.type.detect,
		ofnSearch:    _ext.type.search,
		oSort:        _ext.type.order,
		afnSortData:  _ext.order,
		aoFeatures:   _ext.feature,
		oApi:         _ext.internal,
		oStdClasses:  _ext.classes,
		oPagination:  _ext.pager
	} );
	
	
	$.extend( DataTable.ext.classes, {
		"sTable": "dataTable",
		"sNoFooter": "no-footer",
	
		/* Paging buttons */
		"sPageButton": "paginate_button",
		"sPageButtonActive": "current",
		"sPageButtonDisabled": "disabled",
	
		/* Striping classes */
		"sStripeOdd": "odd",
		"sStripeEven": "even",
	
		/* Empty row */
		"sRowEmpty": "dataTables_empty",
	
		/* Features */
		"sWrapper": "dataTables_wrapper",
		"sFilter": "dataTables_filter",
		"sInfo": "dataTables_info",
		"sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */
		"sLength": "dataTables_length",
		"sProcessing": "dataTables_processing",
	
		/* Sorting */
		"sSortAsc": "sorting_asc",
		"sSortDesc": "sorting_desc",
		"sSortable": "sorting", /* Sortable in both directions */
		"sSortableAsc": "sorting_asc_disabled",
		"sSortableDesc": "sorting_desc_disabled",
		"sSortableNone": "sorting_disabled",
		"sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */
	
		/* Filtering */
		"sFilterInput": "",
	
		/* Page length */
		"sLengthSelect": "",
	
		/* Scrolling */
		"sScrollWrapper": "dataTables_scroll",
		"sScrollHead": "dataTables_scrollHead",
		"sScrollHeadInner": "dataTables_scrollHeadInner",
		"sScrollBody": "dataTables_scrollBody",
		"sScrollFoot": "dataTables_scrollFoot",
		"sScrollFootInner": "dataTables_scrollFootInner",
	
		/* Misc */
		"sHeaderTH": "",
		"sFooterTH": "",
	
		// Deprecated
		"sSortJUIAsc": "",
		"sSortJUIDesc": "",
		"sSortJUI": "",
		"sSortJUIAscAllowed": "",
		"sSortJUIDescAllowed": "",
		"sSortJUIWrapper": "",
		"sSortIcon": "",
		"sJUIHeader": "",
		"sJUIFooter": ""
	} );
	
	
	(function() {
	
	// Reused strings for better compression. Closure compiler appears to have a
	// weird edge case where it is trying to expand strings rather than use the
	// variable version. This results in about 200 bytes being added, for very
	// little preference benefit since it this run on script load only.
	var _empty = '';
	_empty = '';
	
	var _stateDefault = _empty + 'ui-state-default';
	var _sortIcon     = _empty + 'css_right ui-icon ui-icon-';
	var _headerFooter = _empty + 'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix';
	
	$.extend( DataTable.ext.oJUIClasses, DataTable.ext.classes, {
		/* Full numbers paging buttons */
		"sPageButton":         "fg-button ui-button "+_stateDefault,
		"sPageButtonActive":   "ui-state-disabled",
		"sPageButtonDisabled": "ui-state-disabled",
	
		/* Features */
		"sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+
			"ui-buttonset-multi paging_", /* Note that the type is postfixed */
	
		/* Sorting */
		"sSortAsc":            _stateDefault+" sorting_asc",
		"sSortDesc":           _stateDefault+" sorting_desc",
		"sSortable":           _stateDefault+" sorting",
		"sSortableAsc":        _stateDefault+" sorting_asc_disabled",
		"sSortableDesc":       _stateDefault+" sorting_desc_disabled",
		"sSortableNone":       _stateDefault+" sorting_disabled",
		"sSortJUIAsc":         _sortIcon+"triangle-1-n",
		"sSortJUIDesc":        _sortIcon+"triangle-1-s",
		"sSortJUI":            _sortIcon+"carat-2-n-s",
		"sSortJUIAscAllowed":  _sortIcon+"carat-1-n",
		"sSortJUIDescAllowed": _sortIcon+"carat-1-s",
		"sSortJUIWrapper":     "DataTables_sort_wrapper",
		"sSortIcon":           "DataTables_sort_icon",
	
		/* Scrolling */
		"sScrollHead": "dataTables_scrollHead "+_stateDefault,
		"sScrollFoot": "dataTables_scrollFoot "+_stateDefault,
	
		/* Misc */
		"sHeaderTH":  _stateDefault,
		"sFooterTH":  _stateDefault,
		"sJUIHeader": _headerFooter+" ui-corner-tl ui-corner-tr",
		"sJUIFooter": _headerFooter+" ui-corner-bl ui-corner-br"
	} );
	
	}());
	
	
	
	var extPagination = DataTable.ext.pager;
	
	function _numbers ( page, pages ) {
		var
			numbers = [],
			buttons = extPagination.numbers_length,
			half = Math.floor( buttons / 2 ),
			i = 1;
	
		if ( pages <= buttons ) {
			numbers = _range( 0, pages );
		}
		else if ( page <= half ) {
			numbers = _range( 0, buttons-2 );
			numbers.push( 'ellipsis' );
			numbers.push( pages-1 );
		}
		else if ( page >= pages - 1 - half ) {
			numbers = _range( pages-(buttons-2), pages );
			numbers.splice( 0, 0, 'ellipsis' ); // no unshift in ie6
			numbers.splice( 0, 0, 0 );
		}
		else {
			numbers = _range( page-half+2, page+half-1 );
			numbers.push( 'ellipsis' );
			numbers.push( pages-1 );
			numbers.splice( 0, 0, 'ellipsis' );
			numbers.splice( 0, 0, 0 );
		}
	
		numbers.DT_el = 'span';
		return numbers;
	}
	
	
	$.extend( extPagination, {
		simple: function ( page, pages ) {
			return [ 'previous', 'next' ];
		},
	
		full: function ( page, pages ) {
			return [  'first', 'previous', 'next', 'last' ];
		},
	
		numbers: function ( page, pages ) {
			return [ _numbers(page, pages) ];
		},
	
		simple_numbers: function ( page, pages ) {
			return [ 'previous', _numbers(page, pages), 'next' ];
		},
	
		full_numbers: function ( page, pages ) {
			return [ 'first', 'previous', _numbers(page, pages), 'next', 'last' ];
		},
		
		first_last_numbers: function (page, pages) {
	 		return ['first', _numbers(page, pages), 'last'];
	 	},
	
		// For testing and plug-ins to use
		_numbers: _numbers,
	
		// Number of number buttons (including ellipsis) to show. _Must be odd!_
		numbers_length: 7
	} );
	
	
	$.extend( true, DataTable.ext.renderer, {
		pageButton: {
			_: function ( settings, host, idx, buttons, page, pages ) {
				var classes = settings.oClasses;
				var lang = settings.oLanguage.oPaginate;
				var aria = settings.oLanguage.oAria.paginate || {};
				var btnDisplay, btnClass, counter=0;
	
				var attach = function( container, buttons ) {
					var i, ien, node, button;
					var clickHandler = function ( e ) {
						_fnPageChange( settings, e.data.action, true );
					};
	
					for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
						button = buttons[i];
	
						if ( $.isArray( button ) ) {
							var inner = $( '<'+(button.DT_el || 'div')+'/>' )
								.appendTo( container );
							attach( inner, button );
						}
						else {
							btnDisplay = null;
							btnClass = '';
	
							switch ( button ) {
								case 'ellipsis':
									container.append('<span class="ellipsis">&#x2026;</span>');
									break;
	
								case 'first':
									btnDisplay = lang.sFirst;
									btnClass = button + (page > 0 ?
										'' : ' '+classes.sPageButtonDisabled);
									break;
	
								case 'previous':
									btnDisplay = lang.sPrevious;
									btnClass = button + (page > 0 ?
										'' : ' '+classes.sPageButtonDisabled);
									break;
	
								case 'next':
									btnDisplay = lang.sNext;
									btnClass = button + (page < pages-1 ?
										'' : ' '+classes.sPageButtonDisabled);
									break;
	
								case 'last':
									btnDisplay = lang.sLast;
									btnClass = button + (page < pages-1 ?
										'' : ' '+classes.sPageButtonDisabled);
									break;
	
								default:
									btnDisplay = button + 1;
									btnClass = page === button ?
										classes.sPageButtonActive : '';
									break;
							}
	
							if ( btnDisplay !== null ) {
								node = $('<a>', {
										'class': classes.sPageButton+' '+btnClass,
										'aria-controls': settings.sTableId,
										'aria-label': aria[ button ],
										'data-dt-idx': counter,
										'tabindex': settings.iTabIndex,
										'id': idx === 0 && typeof button === 'string' ?
											settings.sTableId +'_'+ button :
											null
									} )
									.html( btnDisplay )
									.appendTo( container );
	
								_fnBindAction(
									node, {action: button}, clickHandler
								);
	
								counter++;
							}
						}
					}
				};
	
				// IE9 throws an 'unknown error' if document.activeElement is used
				// inside an iframe or frame. Try / catch the error. Not good for
				// accessibility, but neither are frames.
				var activeEl;
	
				try {
					// Because this approach is destroying and recreating the paging
					// elements, focus is lost on the select button which is bad for
					// accessibility. So we want to restore focus once the draw has
					// completed
					activeEl = $(host).find(document.activeElement).data('dt-idx');
				}
				catch (e) {}
	
				attach( $(host).empty(), buttons );
	
				if ( activeEl !== undefined ) {
					$(host).find( '[data-dt-idx='+activeEl+']' ).focus();
				}
			}
		}
	} );
	
	
	
	// Built in type detection. See model.ext.aTypes for information about
	// what is required from this methods.
	$.extend( DataTable.ext.type.detect, [
		// Plain numbers - first since V8 detects some plain numbers as dates
		// e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...).
		function ( d, settings )
		{
			var decimal = settings.oLanguage.sDecimal;
			return _isNumber( d, decimal ) ? 'num'+decimal : null;
		},
	
		// Dates (only those recognised by the browser's Date.parse)
		function ( d, settings )
		{
			// V8 tries _very_ hard to make a string passed into `Date.parse()`
			// valid, so we need to use a regex to restrict date formats. Use a
			// plug-in for anything other than ISO8601 style strings
			if ( d && !(d instanceof Date) && ! _re_date.test(d) ) {
				return null;
			}
			var parsed = Date.parse(d);
			return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null;
		},
	
		// Formatted numbers
		function ( d, settings )
		{
			var decimal = settings.oLanguage.sDecimal;
			return _isNumber( d, decimal, true ) ? 'num-fmt'+decimal : null;
		},
	
		// HTML numeric
		function ( d, settings )
		{
			var decimal = settings.oLanguage.sDecimal;
			return _htmlNumeric( d, decimal ) ? 'html-num'+decimal : null;
		},
	
		// HTML numeric, formatted
		function ( d, settings )
		{
			var decimal = settings.oLanguage.sDecimal;
			return _htmlNumeric( d, decimal, true ) ? 'html-num-fmt'+decimal : null;
		},
	
		// HTML (this is strict checking - there must be html)
		function ( d, settings )
		{
			return _empty( d ) || (typeof d === 'string' && d.indexOf('<') !== -1) ?
				'html' : null;
		}
	] );
	
	
	
	// Filter formatting functions. See model.ext.ofnSearch for information about
	// what is required from these methods.
	// 
	// Note that additional search methods are added for the html numbers and
	// html formatted numbers by `_addNumericSort()` when we know what the decimal
	// place is
	
	
	$.extend( DataTable.ext.type.search, {
		html: function ( data ) {
			return _empty(data) ?
				data :
				typeof data === 'string' ?
					data
						.replace( _re_new_lines, " " )
						.replace( _re_html, "" ) :
					'';
		},
	
		string: function ( data ) {
			return _empty(data) ?
				data :
				typeof data === 'string' ?
					data.replace( _re_new_lines, " " ) :
					data;
		}
	} );
	
	
	
	var __numericReplace = function ( d, decimalPlace, re1, re2 ) {
		if ( d !== 0 && (!d || d === '-') ) {
			return -Infinity;
		}
	
		// If a decimal place other than `.` is used, it needs to be given to the
		// function so we can detect it and replace with a `.` which is the only
		// decimal place Javascript recognises - it is not locale aware.
		if ( decimalPlace ) {
			d = _numToDecimal( d, decimalPlace );
		}
	
		if ( d.replace ) {
			if ( re1 ) {
				d = d.replace( re1, '' );
			}
	
			if ( re2 ) {
				d = d.replace( re2, '' );
			}
		}
	
		return d * 1;
	};
	
	
	// Add the numeric 'deformatting' functions for sorting and search. This is done
	// in a function to provide an easy ability for the language options to add
	// additional methods if a non-period decimal place is used.
	function _addNumericSort ( decimalPlace ) {
		$.each(
			{
				// Plain numbers
				"num": function ( d ) {
					return __numericReplace( d, decimalPlace );
				},
	
				// Formatted numbers
				"num-fmt": function ( d ) {
					return __numericReplace( d, decimalPlace, _re_formatted_numeric );
				},
	
				// HTML numeric
				"html-num": function ( d ) {
					return __numericReplace( d, decimalPlace, _re_html );
				},
	
				// HTML numeric, formatted
				"html-num-fmt": function ( d ) {
					return __numericReplace( d, decimalPlace, _re_html, _re_formatted_numeric );
				}
			},
			function ( key, fn ) {
				// Add the ordering method
				_ext.type.order[ key+decimalPlace+'-pre' ] = fn;
	
				// For HTML types add a search formatter that will strip the HTML
				if ( key.match(/^html\-/) ) {
					_ext.type.search[ key+decimalPlace ] = _ext.type.search.html;
				}
			}
		);
	}
	
	
	// Default sort methods
	$.extend( _ext.type.order, {
		// Dates
		"date-pre": function ( d ) {
			return Date.parse( d ) || -Infinity;
		},
	
		// html
		"html-pre": function ( a ) {
			return _empty(a) ?
				'' :
				a.replace ?
					a.replace( /<.*?>/g, "" ).toLowerCase() :
					a+'';
		},
	
		// string
		"string-pre": function ( a ) {
			// This is a little complex, but faster than always calling toString,
			// http://jsperf.com/tostring-v-check
			return _empty(a) ?
				'' :
				typeof a === 'string' ?
					a.toLowerCase() :
					! a.toString ?
						'' :
						a.toString();
		},
	
		// string-asc and -desc are retained only for compatibility with the old
		// sort methods
		"string-asc": function ( x, y ) {
			return ((x < y) ? -1 : ((x > y) ? 1 : 0));
		},
	
		"string-desc": function ( x, y ) {
			return ((x < y) ? 1 : ((x > y) ? -1 : 0));
		}
	} );
	
	
	// Numeric sorting types - order doesn't matter here
	_addNumericSort( '' );
	
	
	$.extend( true, DataTable.ext.renderer, {
		header: {
			_: function ( settings, cell, column, classes ) {
				// No additional mark-up required
				// Attach a sort listener to update on sort - note that using the
				// `DT` namespace will allow the event to be removed automatically
				// on destroy, while the `dt` namespaced event is the one we are
				// listening for
				$(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
					if ( settings !== ctx ) { // need to check this this is the host
						return;               // table, not a nested one
					}
	
					var colIdx = column.idx;
	
					cell
						.removeClass(
							column.sSortingClass +' '+
							classes.sSortAsc +' '+
							classes.sSortDesc
						)
						.addClass( columns[ colIdx ] == 'asc' ?
							classes.sSortAsc : columns[ colIdx ] == 'desc' ?
								classes.sSortDesc :
								column.sSortingClass
						);
				} );
			},
	
			jqueryui: function ( settings, cell, column, classes ) {
				$('<div/>')
					.addClass( classes.sSortJUIWrapper )
					.append( cell.contents() )
					.append( $('<span/>')
						.addClass( classes.sSortIcon+' '+column.sSortingClassJUI )
					)
					.appendTo( cell );
	
				// Attach a sort listener to update on sort
				$(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
					if ( settings !== ctx ) {
						return;
					}
	
					var colIdx = column.idx;
	
					cell
						.removeClass( classes.sSortAsc +" "+classes.sSortDesc )
						.addClass( columns[ colIdx ] == 'asc' ?
							classes.sSortAsc : columns[ colIdx ] == 'desc' ?
								classes.sSortDesc :
								column.sSortingClass
						);
	
					cell
						.find( 'span.'+classes.sSortIcon )
						.removeClass(
							classes.sSortJUIAsc +" "+
							classes.sSortJUIDesc +" "+
							classes.sSortJUI +" "+
							classes.sSortJUIAscAllowed +" "+
							classes.sSortJUIDescAllowed
						)
						.addClass( columns[ colIdx ] == 'asc' ?
							classes.sSortJUIAsc : columns[ colIdx ] == 'desc' ?
								classes.sSortJUIDesc :
								column.sSortingClassJUI
						);
				} );
			}
		}
	} );
	
	/*
	 * Public helper functions. These aren't used internally by DataTables, or
	 * called by any of the options passed into DataTables, but they can be used
	 * externally by developers working with DataTables. They are helper functions
	 * to make working with DataTables a little bit easier.
	 */
	
	var __htmlEscapeEntities = function ( d ) {
		return typeof d === 'string' ?
			d.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;') :
			d;
	};
	
	/**
	 * Helpers for `columns.render`.
	 *
	 * The options defined here can be used with the `columns.render` initialisation
	 * option to provide a display renderer. The following functions are defined:
	 *
	 * * `number` - Will format numeric data (defined by `columns.data`) for
	 *   display, retaining the original unformatted data for sorting and filtering.
	 *   It takes 5 parameters:
	 *   * `string` - Thousands grouping separator
	 *   * `string` - Decimal point indicator
	 *   * `integer` - Number of decimal points to show
	 *   * `string` (optional) - Prefix.
	 *   * `string` (optional) - Postfix (/suffix).
	 * * `text` - Escape HTML to help prevent XSS attacks. It has no optional
	 *   parameters.
	 *
	 * @example
	 *   // Column definition using the number renderer
	 *   {
	 *     data: "salary",
	 *     render: $.fn.dataTable.render.number( '\'', '.', 0, '$' )
	 *   }
	 *
	 * @namespace
	 */
	DataTable.render = {
		number: function ( thousands, decimal, precision, prefix, postfix ) {
			return {
				display: function ( d ) {
					if ( typeof d !== 'number' && typeof d !== 'string' ) {
						return d;
					}
	
					var negative = d < 0 ? '-' : '';
					var flo = parseFloat( d );
	
					// If NaN then there isn't much formatting that we can do - just
					// return immediately, escaping any HTML (this was supposed to
					// be a number after all)
					if ( isNaN( flo ) ) {
						return __htmlEscapeEntities( d );
					}
	
					flo = flo.toFixed( precision );
					d = Math.abs( flo );
	
					var intPart = parseInt( d, 10 );
					var floatPart = precision ?
						decimal+(d - intPart).toFixed( precision ).substring( 2 ):
						'';
	
					return negative + (prefix||'') +
						intPart.toString().replace(
							/\B(?=(\d{3})+(?!\d))/g, thousands
						) +
						floatPart +
						(postfix||'');
				}
			};
		},
	
		text: function () {
			return {
				display: __htmlEscapeEntities
			};
		}
	};
	
	
	/*
	 * This is really a good bit rubbish this method of exposing the internal methods
	 * publicly... - To be fixed in 2.0 using methods on the prototype
	 */
	
	
	/**
	 * Create a wrapper function for exporting an internal functions to an external API.
	 *  @param {string} fn API function name
	 *  @returns {function} wrapped function
	 *  @memberof DataTable#internal
	 */
	function _fnExternApiFunc (fn)
	{
		return function() {
			var args = [_fnSettingsFromNode( this[DataTable.ext.iApiIndex] )].concat(
				Array.prototype.slice.call(arguments)
			);
			return DataTable.ext.internal[fn].apply( this, args );
		};
	}
	
	
	/**
	 * Reference to internal functions for use by plug-in developers. Note that
	 * these methods are references to internal functions and are considered to be
	 * private. If you use these methods, be aware that they are liable to change
	 * between versions.
	 *  @namespace
	 */
	$.extend( DataTable.ext.internal, {
		_fnExternApiFunc: _fnExternApiFunc,
		_fnBuildAjax: _fnBuildAjax,
		_fnAjaxUpdate: _fnAjaxUpdate,
		_fnAjaxParameters: _fnAjaxParameters,
		_fnAjaxUpdateDraw: _fnAjaxUpdateDraw,
		_fnAjaxDataSrc: _fnAjaxDataSrc,
		_fnAddColumn: _fnAddColumn,
		_fnColumnOptions: _fnColumnOptions,
		_fnAdjustColumnSizing: _fnAdjustColumnSizing,
		_fnVisibleToColumnIndex: _fnVisibleToColumnIndex,
		_fnColumnIndexToVisible: _fnColumnIndexToVisible,
		_fnVisbleColumns: _fnVisbleColumns,
		_fnGetColumns: _fnGetColumns,
		_fnColumnTypes: _fnColumnTypes,
		_fnApplyColumnDefs: _fnApplyColumnDefs,
		_fnHungarianMap: _fnHungarianMap,
		_fnCamelToHungarian: _fnCamelToHungarian,
		_fnLanguageCompat: _fnLanguageCompat,
		_fnBrowserDetect: _fnBrowserDetect,
		_fnAddData: _fnAddData,
		_fnAddTr: _fnAddTr,
		_fnNodeToDataIndex: _fnNodeToDataIndex,
		_fnNodeToColumnIndex: _fnNodeToColumnIndex,
		_fnGetCellData: _fnGetCellData,
		_fnSetCellData: _fnSetCellData,
		_fnSplitObjNotation: _fnSplitObjNotation,
		_fnGetObjectDataFn: _fnGetObjectDataFn,
		_fnSetObjectDataFn: _fnSetObjectDataFn,
		_fnGetDataMaster: _fnGetDataMaster,
		_fnClearTable: _fnClearTable,
		_fnDeleteIndex: _fnDeleteIndex,
		_fnInvalidate: _fnInvalidate,
		_fnGetRowElements: _fnGetRowElements,
		_fnCreateTr: _fnCreateTr,
		_fnBuildHead: _fnBuildHead,
		_fnDrawHead: _fnDrawHead,
		_fnDraw: _fnDraw,
		_fnReDraw: _fnReDraw,
		_fnAddOptionsHtml: _fnAddOptionsHtml,
		_fnDetectHeader: _fnDetectHeader,
		_fnGetUniqueThs: _fnGetUniqueThs,
		_fnFeatureHtmlFilter: _fnFeatureHtmlFilter,
		_fnFilterComplete: _fnFilterComplete,
		_fnFilterCustom: _fnFilterCustom,
		_fnFilterColumn: _fnFilterColumn,
		_fnFilter: _fnFilter,
		_fnFilterCreateSearch: _fnFilterCreateSearch,
		_fnEscapeRegex: _fnEscapeRegex,
		_fnFilterData: _fnFilterData,
		_fnFeatureHtmlInfo: _fnFeatureHtmlInfo,
		_fnUpdateInfo: _fnUpdateInfo,
		_fnInfoMacros: _fnInfoMacros,
		_fnInitialise: _fnInitialise,
		_fnInitComplete: _fnInitComplete,
		_fnLengthChange: _fnLengthChange,
		_fnFeatureHtmlLength: _fnFeatureHtmlLength,
		_fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate,
		_fnPageChange: _fnPageChange,
		_fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing,
		_fnProcessingDisplay: _fnProcessingDisplay,
		_fnFeatureHtmlTable: _fnFeatureHtmlTable,
		_fnScrollDraw: _fnScrollDraw,
		_fnApplyToChildren: _fnApplyToChildren,
		_fnCalculateColumnWidths: _fnCalculateColumnWidths,
		_fnThrottle: _fnThrottle,
		_fnConvertToWidth: _fnConvertToWidth,
		_fnGetWidestNode: _fnGetWidestNode,
		_fnGetMaxLenString: _fnGetMaxLenString,
		_fnStringToCss: _fnStringToCss,
		_fnSortFlatten: _fnSortFlatten,
		_fnSort: _fnSort,
		_fnSortAria: _fnSortAria,
		_fnSortListener: _fnSortListener,
		_fnSortAttachListener: _fnSortAttachListener,
		_fnSortingClasses: _fnSortingClasses,
		_fnSortData: _fnSortData,
		_fnSaveState: _fnSaveState,
		_fnLoadState: _fnLoadState,
		_fnSettingsFromNode: _fnSettingsFromNode,
		_fnLog: _fnLog,
		_fnMap: _fnMap,
		_fnBindAction: _fnBindAction,
		_fnCallbackReg: _fnCallbackReg,
		_fnCallbackFire: _fnCallbackFire,
		_fnLengthOverflow: _fnLengthOverflow,
		_fnRenderer: _fnRenderer,
		_fnDataSource: _fnDataSource,
		_fnRowAttributes: _fnRowAttributes,
		_fnCalculateEnd: function () {} // Used by a lot of plug-ins, but redundant
		                                // in 1.10, so this dead-end function is
		                                // added to prevent errors
	} );
	

	// jQuery access
	$.fn.dataTable = DataTable;

	// Provide access to the host jQuery object (circular reference)
	DataTable.$ = $;

	// Legacy aliases
	$.fn.dataTableSettings = DataTable.settings;
	$.fn.dataTableExt = DataTable.ext;

	// With a capital `D` we return a DataTables API instance rather than a
	// jQuery object
	$.fn.DataTable = function ( opts ) {
		return $(this).dataTable( opts ).api();
	};

	// All properties that are available to $.fn.dataTable should also be
	// available on $.fn.DataTable
	$.each( DataTable, function ( prop, val ) {
		$.fn.DataTable[ prop ] = val;
	} );


	// Information about events fired by DataTables - for documentation.
	/**
	 * Draw event, fired whenever the table is redrawn on the page, at the same
	 * point as fnDrawCallback. This may be useful for binding events or
	 * performing calculations when the table is altered at all.
	 *  @name DataTable#draw.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 */

	/**
	 * Search event, fired when the searching applied to the table (using the
	 * built-in global search, or column filters) is altered.
	 *  @name DataTable#search.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 */

	/**
	 * Page change event, fired when the paging of the table is altered.
	 *  @name DataTable#page.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 */

	/**
	 * Order event, fired when the ordering applied to the table is altered.
	 *  @name DataTable#order.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 */

	/**
	 * DataTables initialisation complete event, fired when the table is fully
	 * drawn, including Ajax data loaded, if Ajax data is required.
	 *  @name DataTable#init.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} oSettings DataTables settings object
	 *  @param {object} json The JSON object request from the server - only
	 *    present if client-side Ajax sourced data is used</li></ol>
	 */

	/**
	 * State save event, fired when the table has changed state a new state save
	 * is required. This event allows modification of the state saving object
	 * prior to actually doing the save, including addition or other state
	 * properties (for plug-ins) or modification of a DataTables core property.
	 *  @name DataTable#stateSaveParams.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} oSettings DataTables settings object
	 *  @param {object} json The state information to be saved
	 */

	/**
	 * State load event, fired when the table is loading state from the stored
	 * data, but prior to the settings object being modified by the saved state
	 * - allowing modification of the saved state is required or loading of
	 * state for a plug-in.
	 *  @name DataTable#stateLoadParams.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} oSettings DataTables settings object
	 *  @param {object} json The saved state information
	 */

	/**
	 * State loaded event, fired when state has been loaded from stored data and
	 * the settings object has been modified by the loaded data.
	 *  @name DataTable#stateLoaded.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} oSettings DataTables settings object
	 *  @param {object} json The saved state information
	 */

	/**
	 * Processing event, fired when DataTables is doing some kind of processing
	 * (be it, order, searcg or anything else). It can be used to indicate to
	 * the end user that there is something happening, or that something has
	 * finished.
	 *  @name DataTable#processing.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} oSettings DataTables settings object
	 *  @param {boolean} bShow Flag for if DataTables is doing processing or not
	 */

	/**
	 * Ajax (XHR) event, fired whenever an Ajax request is completed from a
	 * request to made to the server for new data. This event is called before
	 * DataTables processed the returned data, so it can also be used to pre-
	 * process the data returned from the server, if needed.
	 *
	 * Note that this trigger is called in `fnServerData`, if you override
	 * `fnServerData` and which to use this event, you need to trigger it in you
	 * success function.
	 *  @name DataTable#xhr.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 *  @param {object} json JSON returned from the server
	 *
	 *  @example
	 *     // Use a custom property returned from the server in another DOM element
	 *     $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
	 *       $('#status').html( json.status );
	 *     } );
	 *
	 *  @example
	 *     // Pre-process the data returned from the server
	 *     $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
	 *       for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) {
	 *         json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;
	 *       }
	 *       // Note no return - manipulate the data directly in the JSON object.
	 *     } );
	 */

	/**
	 * Destroy event, fired when the DataTable is destroyed by calling fnDestroy
	 * or passing the bDestroy:true parameter in the initialisation object. This
	 * can be used to remove bound events, added DOM nodes, etc.
	 *  @name DataTable#destroy.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 */

	/**
	 * Page length change event, fired when number of records to show on each
	 * page (the length) is changed.
	 *  @name DataTable#length.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 *  @param {integer} len New length
	 */

	/**
	 * Column sizing has changed.
	 *  @name DataTable#column-sizing.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 */

	/**
	 * Column visibility has changed.
	 *  @name DataTable#column-visibility.dt
	 *  @event
	 *  @param {event} e jQuery event object
	 *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
	 *  @param {int} column Column index
	 *  @param {bool} vis `false` if column now hidden, or `true` if visible
	 */

	return $.fn.dataTable;
}));
/*!
 * Copyright 2012, Chris Wanstrath
 * Released under the MIT License
 * https://github.com/defunkt/jquery-pjax
 */


(function($){

// When called on a container with a selector, fetches the href with
// ajax into the container or with the data-pjax attribute on the link
// itself.
//
// Tries to make sure the back button and ctrl+click work the way
// you'd expect.
//
// Exported as $.fn.pjax
//
// Accepts a jQuery ajax options object that may include these
// pjax specific options:
//
//
// container - String selector for the element where to place the response body.
//      push - Whether to pushState the URL. Defaults to true (of course).
//   replace - Want to use replaceState instead? That's cool.
//
// For convenience the second parameter can be either the container or
// the options object.
//
// Returns the jQuery object
function fnPjax(selector, container, options) {
  options = optionsFor(container, options)
  return this.on('click.pjax', selector, function(event) {
    var opts = options
    if (!opts.container) {
      opts = $.extend({}, options)
      opts.container = $(this).attr('data-pjax')
    }
    handleClick(event, opts)
  })
}

// Public: pjax on click handler
//
// Exported as $.pjax.click.
//
// event   - "click" jQuery.Event
// options - pjax options
//
// Examples
//
//   $(document).on('click', 'a', $.pjax.click)
//   // is the same as
//   $(document).pjax('a')
//
// Returns nothing.
function handleClick(event, container, options) {
  options = optionsFor(container, options)

  var link = event.currentTarget
  var $link = $(link)

  if (link.tagName.toUpperCase() !== 'A')
    throw "$.fn.pjax or $.pjax.click requires an anchor element"

  // Middle click, cmd click, and ctrl click should open
  // links in a new tab as normal.
  if ( event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey )
    return

  // Ignore cross origin links
  if ( location.protocol !== link.protocol || location.hostname !== link.hostname )
    return

  // Ignore case when a hash is being tacked on the current URL
  if ( link.href.indexOf('#') > -1 && stripHash(link) == stripHash(location) )
    return

  // Ignore event with default prevented
  if (event.isDefaultPrevented())
    return

  var defaults = {
    url: link.href,
    container: $link.attr('data-pjax'),
    target: link
  }

  var opts = $.extend({}, defaults, options)
  var clickEvent = $.Event('pjax:click')
  $link.trigger(clickEvent, [opts])

  if (!clickEvent.isDefaultPrevented()) {
    pjax(opts)
    event.preventDefault()
    $link.trigger('pjax:clicked', [opts])
  }
}

// Public: pjax on form submit handler
//
// Exported as $.pjax.submit
//
// event   - "click" jQuery.Event
// options - pjax options
//
// Examples
//
//  $(document).on('submit', 'form', function(event) {
//    $.pjax.submit(event, '[data-pjax-container]')
//  })
//
// Returns nothing.
function handleSubmit(event, container, options) {
  options = optionsFor(container, options)

  var form = event.currentTarget
  var $form = $(form)

  if (form.tagName.toUpperCase() !== 'FORM')
    throw "$.pjax.submit requires a form element"

  var defaults = {
    type: ($form.attr('method') || 'GET').toUpperCase(),
    url: $form.attr('action'),
    container: $form.attr('data-pjax'),
    target: form
  }

  if (defaults.type !== 'GET' && window.FormData !== undefined) {
    defaults.data = new FormData(form)
    defaults.processData = false
    defaults.contentType = false
  } else {
    // Can't handle file uploads, exit
    if ($form.find(':file').length) {
      return
    }

    // Fallback to manually serializing the fields
    defaults.data = $form.serializeArray()
  }

  pjax($.extend({}, defaults, options))

  event.preventDefault()
}

// Loads a URL with ajax, puts the response body inside a container,
// then pushState()'s the loaded URL.
//
// Works just like $.ajax in that it accepts a jQuery ajax
// settings object (with keys like url, type, data, etc).
//
// Accepts these extra keys:
//
// container - String selector for where to stick the response body.
//      push - Whether to pushState the URL. Defaults to true (of course).
//   replace - Want to use replaceState instead? That's cool.
//
// Use it just like $.ajax:
//
//   var xhr = $.pjax({ url: this.href, container: '#main' })
//   console.log( xhr.readyState )
//
// Returns whatever $.ajax returns.
function pjax(options) {
  options = $.extend(true, {}, $.ajaxSettings, pjax.defaults, options)

  if ($.isFunction(options.url)) {
    options.url = options.url()
  }

  var hash = parseURL(options.url).hash

  var containerType = $.type(options.container)
  if (containerType !== 'string') {
    throw "expected string value for 'container' option; got " + containerType
  }
  var context = options.context = $(options.container)
  if (!context.length) {
    throw "the container selector '" + options.container + "' did not match anything"
  }

  // We want the browser to maintain two separate internal caches: one
  // for pjax'd partial page loads and one for normal page loads.
  // Without adding this secret parameter, some browsers will often
  // confuse the two.
  if (!options.data) options.data = {}
  if ($.isArray(options.data)) {
    options.data.push({name: '_pjax', value: options.container})
  } else {
    options.data._pjax = options.container
  }

  function fire(type, args, props) {
    if (!props) props = {}
    props.relatedTarget = options.target
    var event = $.Event(type, props)
    context.trigger(event, args)
    return !event.isDefaultPrevented()
  }

  var timeoutTimer

  options.beforeSend = function(xhr, settings) {
    // No timeout for non-GET requests
    // Its not safe to request the resource again with a fallback method.
    if (settings.type !== 'GET') {
      settings.timeout = 0
    }

    xhr.setRequestHeader('X-PJAX', 'true')
    xhr.setRequestHeader('X-PJAX-Container', options.container)

    if (!fire('pjax:beforeSend', [xhr, settings]))
      return false

    if (settings.timeout > 0) {
      timeoutTimer = setTimeout(function() {
        if (fire('pjax:timeout', [xhr, options]))
          xhr.abort('timeout')
      }, settings.timeout)

      // Clear timeout setting so jquerys internal timeout isn't invoked
      settings.timeout = 0
    }

    var url = parseURL(settings.url)
    if (hash) url.hash = hash
    options.requestUrl = stripInternalParams(url)
  }

  options.complete = function(xhr, textStatus) {
    if (timeoutTimer)
      clearTimeout(timeoutTimer)

    fire('pjax:complete', [xhr, textStatus, options])

    fire('pjax:end', [xhr, options])
  }

  options.error = function(xhr, textStatus, errorThrown) {
    var container = extractContainer("", xhr, options)

    var allowed = fire('pjax:error', [xhr, textStatus, errorThrown, options])
    if (options.type == 'GET' && textStatus !== 'abort' && allowed) {
      locationReplace(container.url)
    }
  }

  options.success = function(data, status, xhr) {
    var previousState = pjax.state

    // If $.pjax.defaults.version is a function, invoke it first.
    // Otherwise it can be a static string.
    var currentVersion = typeof $.pjax.defaults.version === 'function' ?
      $.pjax.defaults.version() :
      $.pjax.defaults.version

    var latestVersion = xhr.getResponseHeader('X-PJAX-Version')

    var container = extractContainer(data, xhr, options)

    var url = parseURL(container.url)
    if (hash) {
      url.hash = hash
      container.url = url.href
    }

    // If there is a layout version mismatch, hard load the new url
    if (currentVersion && latestVersion && currentVersion !== latestVersion) {
      locationReplace(container.url)
      return
    }

    // If the new response is missing a body, hard load the page
    if (!container.contents) {
      locationReplace(container.url)
      return
    }

    pjax.state = {
      id: options.id || uniqueId(),
      url: container.url,
      title: container.title,
      container: options.container,
      fragment: options.fragment,
      timeout: options.timeout
    }

    if (options.push || options.replace) {
      window.history.replaceState(pjax.state, container.title, container.url)
    }

    // Only blur the focus if the focused element is within the container.
    var blurFocus = $.contains(context, document.activeElement)

    // Clear out any focused controls before inserting new page contents.
    if (blurFocus) {
      try {
        document.activeElement.blur()
      } catch (e) { /* ignore */ }
    }

    if (container.title) document.title = container.title

    fire('pjax:beforeReplace', [container.contents, options], {
      state: pjax.state,
      previousState: previousState
    })
    context.html(container.contents)

    // FF bug: Won't autofocus fields that are inserted via JS.
    // This behavior is incorrect. So if theres no current focus, autofocus
    // the last field.
    //
    // http://www.w3.org/html/wg/drafts/html/master/forms.html
    var autofocusEl = context.find('input[autofocus], textarea[autofocus]').last()[0]
    if (autofocusEl && document.activeElement !== autofocusEl) {
      autofocusEl.focus()
    }

    executeScriptTags(container.scripts)

    var scrollTo = options.scrollTo

    // Ensure browser scrolls to the element referenced by the URL anchor
    if (hash) {
      var name = decodeURIComponent(hash.slice(1))
      var target = document.getElementById(name) || document.getElementsByName(name)[0]
      if (target) scrollTo = $(target).offset().top
    }

    if (typeof scrollTo == 'number') $(window).scrollTop(scrollTo)

    fire('pjax:success', [data, status, xhr, options])
  }


  // Initialize pjax.state for the initial page load. Assume we're
  // using the container and options of the link we're loading for the
  // back button to the initial page. This ensures good back button
  // behavior.
  if (!pjax.state) {
    pjax.state = {
      id: uniqueId(),
      url: window.location.href,
      title: document.title,
      container: options.container,
      fragment: options.fragment,
      timeout: options.timeout
    }
    window.history.replaceState(pjax.state, document.title)
  }

  // Cancel the current request if we're already pjaxing
  abortXHR(pjax.xhr)

  pjax.options = options
  var xhr = pjax.xhr = $.ajax(options)

  if (xhr.readyState > 0) {
    if (options.push && !options.replace) {
      // Cache current container element before replacing it
      cachePush(pjax.state.id, [options.container, cloneContents(context)])

      window.history.pushState(null, "", options.requestUrl)
    }

    fire('pjax:start', [xhr, options])
    fire('pjax:send', [xhr, options])
  }

  return pjax.xhr
}

// Public: Reload current page with pjax.
//
// Returns whatever $.pjax returns.
function pjaxReload(container, options) {
  var defaults = {
    url: window.location.href,
    push: false,
    replace: true,
    scrollTo: false
  }

  return pjax($.extend(defaults, optionsFor(container, options)))
}

// Internal: Hard replace current state with url.
//
// Work for around WebKit
//   https://bugs.webkit.org/show_bug.cgi?id=93506
//
// Returns nothing.
function locationReplace(url) {
  window.history.replaceState(null, "", pjax.state.url)
  window.location.replace(url)
}


var initialPop = true
var initialURL = window.location.href
var initialState = window.history.state

// Initialize $.pjax.state if possible
// Happens when reloading a page and coming forward from a different
// session history.
if (initialState && initialState.container) {
  pjax.state = initialState
}

// Non-webkit browsers don't fire an initial popstate event
if ('state' in window.history) {
  initialPop = false
}

// popstate handler takes care of the back and forward buttons
//
// You probably shouldn't use pjax on pages with other pushState
// stuff yet.
function onPjaxPopstate(event) {

  // Hitting back or forward should override any pending PJAX request.
  if (!initialPop) {
    abortXHR(pjax.xhr)
  }

  var previousState = pjax.state
  var state = event.state
  var direction

  if (state && state.container) {
    // When coming forward from a separate history session, will get an
    // initial pop with a state we are already at. Skip reloading the current
    // page.
    if (initialPop && initialURL == state.url) return

    if (previousState) {
      // If popping back to the same state, just skip.
      // Could be clicking back from hashchange rather than a pushState.
      if (previousState.id === state.id) return

      // Since state IDs always increase, we can deduce the navigation direction
      direction = previousState.id < state.id ? 'forward' : 'back'
    }

    var cache = cacheMapping[state.id] || []
    var containerSelector = cache[0] || state.container
    var container = $(containerSelector), contents = cache[1]

    if (container.length) {
      if (previousState) {
        // Cache current container before replacement and inform the
        // cache which direction the history shifted.
        cachePop(direction, previousState.id, [containerSelector, cloneContents(container)])
      }

      var popstateEvent = $.Event('pjax:popstate', {
        state: state,
        direction: direction
      })
      container.trigger(popstateEvent)

      var options = {
        id: state.id,
        url: state.url,
        container: containerSelector,
        push: false,
        fragment: state.fragment,
        timeout: state.timeout,
        scrollTo: false
      }

      if (contents) {
        container.trigger('pjax:start', [null, options])

        pjax.state = state
        if (state.title) document.title = state.title
        var beforeReplaceEvent = $.Event('pjax:beforeReplace', {
          state: state,
          previousState: previousState
        })
        container.trigger(beforeReplaceEvent, [contents, options])
        container.html(contents)

        container.trigger('pjax:end', [null, options])
      } else {
        pjax(options)
      }

      // Force reflow/relayout before the browser tries to restore the
      // scroll position.
      container[0].offsetHeight // eslint-disable-line no-unused-expressions
    } else {
      locationReplace(location.href)
    }
  }
  initialPop = false
}

// Fallback version of main pjax function for browsers that don't
// support pushState.
//
// Returns nothing since it retriggers a hard form submission.
function fallbackPjax(options) {
  var url = $.isFunction(options.url) ? options.url() : options.url,
      method = options.type ? options.type.toUpperCase() : 'GET'

  var form = $('<form>', {
    method: method === 'GET' ? 'GET' : 'POST',
    action: url,
    style: 'display:none'
  })

  if (method !== 'GET' && method !== 'POST') {
    form.append($('<input>', {
      type: 'hidden',
      name: '_method',
      value: method.toLowerCase()
    }))
  }

  var data = options.data
  if (typeof data === 'string') {
    $.each(data.split('&'), function(index, value) {
      var pair = value.split('=')
      form.append($('<input>', {type: 'hidden', name: pair[0], value: pair[1]}))
    })
  } else if ($.isArray(data)) {
    $.each(data, function(index, value) {
      form.append($('<input>', {type: 'hidden', name: value.name, value: value.value}))
    })
  } else if (typeof data === 'object') {
    var key
    for (key in data)
      form.append($('<input>', {type: 'hidden', name: key, value: data[key]}))
  }

  $(document.body).append(form)
  form.submit()
}

// Internal: Abort an XmlHttpRequest if it hasn't been completed,
// also removing its event handlers.
function abortXHR(xhr) {
  if ( xhr && xhr.readyState < 4) {
    xhr.onreadystatechange = $.noop
    xhr.abort()
  }
}

// Internal: Generate unique id for state object.
//
// Use a timestamp instead of a counter since ids should still be
// unique across page loads.
//
// Returns Number.
function uniqueId() {
  return (new Date).getTime()
}

function cloneContents(container) {
  var cloned = container.clone()
  // Unmark script tags as already being eval'd so they can get executed again
  // when restored from cache. HAXX: Uses jQuery internal method.
  cloned.find('script').each(function(){
    if (!this.src) $._data(this, 'globalEval', false)
  })
  return cloned.contents()
}

// Internal: Strip internal query params from parsed URL.
//
// Returns sanitized url.href String.
function stripInternalParams(url) {
  url.search = url.search.replace(/([?&])(_pjax|_)=[^&]*/g, '').replace(/^&/, '')
  return url.href.replace(/\?($|#)/, '$1')
}

// Internal: Parse URL components and returns a Locationish object.
//
// url - String URL
//
// Returns HTMLAnchorElement that acts like Location.
function parseURL(url) {
  var a = document.createElement('a')
  a.href = url
  return a
}

// Internal: Return the `href` component of given URL object with the hash
// portion removed.
//
// location - Location or HTMLAnchorElement
//
// Returns String
function stripHash(location) {
  return location.href.replace(/#.*/, '')
}

// Internal: Build options Object for arguments.
//
// For convenience the first parameter can be either the container or
// the options object.
//
// Examples
//
//   optionsFor('#container')
//   // => {container: '#container'}
//
//   optionsFor('#container', {push: true})
//   // => {container: '#container', push: true}
//
//   optionsFor({container: '#container', push: true})
//   // => {container: '#container', push: true}
//
// Returns options Object.
function optionsFor(container, options) {
  if (container && options) {
    options = $.extend({}, options)
    options.container = container
    return options
  } else if ($.isPlainObject(container)) {
    return container
  } else {
    return {container: container}
  }
}

// Internal: Filter and find all elements matching the selector.
//
// Where $.fn.find only matches descendants, findAll will test all the
// top level elements in the jQuery object as well.
//
// elems    - jQuery object of Elements
// selector - String selector to match
//
// Returns a jQuery object.
function findAll(elems, selector) {
  return elems.filter(selector).add(elems.find(selector))
}

function parseHTML(html) {
  return $.parseHTML(html, document, true)
}

// Internal: Extracts container and metadata from response.
//
// 1. Extracts X-PJAX-URL header if set
// 2. Extracts inline <title> tags
// 3. Builds response Element and extracts fragment if set
//
// data    - String response data
// xhr     - XHR response
// options - pjax options Object
//
// Returns an Object with url, title, and contents keys.
function extractContainer(data, xhr, options) {
  var obj = {}, fullDocument = /<html/i.test(data)

  // Prefer X-PJAX-URL header if it was set, otherwise fallback to
  // using the original requested url.
  var serverUrl = xhr.getResponseHeader('X-PJAX-URL')
  obj.url = serverUrl ? stripInternalParams(parseURL(serverUrl)) : options.requestUrl

  var $head, $body
  // Attempt to parse response html into elements
  if (fullDocument) {
    $body = $(parseHTML(data.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0]))
    var head = data.match(/<head[^>]*>([\s\S.]*)<\/head>/i)
    $head = head != null ? $(parseHTML(head[0])) : $body
  } else {
    $head = $body = $(parseHTML(data))
  }

  // If response data is empty, return fast
  if ($body.length === 0)
    return obj

  // If there's a <title> tag in the header, use it as
  // the page's title.
  obj.title = findAll($head, 'title').last().text()

  if (options.fragment) {
    var $fragment = $body
    // If they specified a fragment, look for it in the response
    // and pull it out.
    if (options.fragment !== 'body') {
      $fragment = findAll($fragment, options.fragment).first()
    }

    if ($fragment.length) {
      obj.contents = options.fragment === 'body' ? $fragment : $fragment.contents()

      // If there's no title, look for data-title and title attributes
      // on the fragment
      if (!obj.title)
        obj.title = $fragment.attr('title') || $fragment.data('title')
    }

  } else if (!fullDocument) {
    obj.contents = $body
  }

  // Clean up any <title> tags
  if (obj.contents) {
    // Remove any parent title elements
    obj.contents = obj.contents.not(function() { return $(this).is('title') })

    // Then scrub any titles from their descendants
    obj.contents.find('title').remove()

    // Gather all script[src] elements
    obj.scripts = findAll(obj.contents, 'script[src]').remove()
    obj.contents = obj.contents.not(obj.scripts)
  }

  // Trim any whitespace off the title
  if (obj.title) obj.title = $.trim(obj.title)

  return obj
}

// Load an execute scripts using standard script request.
//
// Avoids jQuery's traditional $.getScript which does a XHR request and
// globalEval.
//
// scripts - jQuery object of script Elements
//
// Returns nothing.
function executeScriptTags(scripts) {
  if (!scripts) return

  var existingScripts = $('script[src]')

  scripts.each(function() {
    var src = this.src
    var matchedScripts = existingScripts.filter(function() {
      return this.src === src
    })
    if (matchedScripts.length) return

    var script = document.createElement('script')
    var type = $(this).attr('type')
    if (type) script.type = type
    script.src = $(this).attr('src')
    document.head.appendChild(script)
  })
}

// Internal: History DOM caching class.
var cacheMapping      = {}
var cacheForwardStack = []
var cacheBackStack    = []

// Push previous state id and container contents into the history
// cache. Should be called in conjunction with `pushState` to save the
// previous container contents.
//
// id    - State ID Number
// value - DOM Element to cache
//
// Returns nothing.
function cachePush(id, value) {
  cacheMapping[id] = value
  cacheBackStack.push(id)

  // Remove all entries in forward history stack after pushing a new page.
  trimCacheStack(cacheForwardStack, 0)

  // Trim back history stack to max cache length.
  trimCacheStack(cacheBackStack, pjax.defaults.maxCacheLength)
}

// Shifts cache from directional history cache. Should be
// called on `popstate` with the previous state id and container
// contents.
//
// direction - "forward" or "back" String
// id        - State ID Number
// value     - DOM Element to cache
//
// Returns nothing.
function cachePop(direction, id, value) {
  var pushStack, popStack
  cacheMapping[id] = value

  if (direction === 'forward') {
    pushStack = cacheBackStack
    popStack  = cacheForwardStack
  } else {
    pushStack = cacheForwardStack
    popStack  = cacheBackStack
  }

  pushStack.push(id)
  id = popStack.pop()
  if (id) delete cacheMapping[id]

  // Trim whichever stack we just pushed to to max cache length.
  trimCacheStack(pushStack, pjax.defaults.maxCacheLength)
}

// Trim a cache stack (either cacheBackStack or cacheForwardStack) to be no
// longer than the specified length, deleting cached DOM elements as necessary.
//
// stack  - Array of state IDs
// length - Maximum length to trim to
//
// Returns nothing.
function trimCacheStack(stack, length) {
  while (stack.length > length)
    delete cacheMapping[stack.shift()]
}

// Public: Find version identifier for the initial page load.
//
// Returns String version or undefined.
function findVersion() {
  return $('meta').filter(function() {
    var name = $(this).attr('http-equiv')
    return name && name.toUpperCase() === 'X-PJAX-VERSION'
  }).attr('content')
}

// Install pjax functions on $.pjax to enable pushState behavior.
//
// Does nothing if already enabled.
//
// Examples
//
//     $.pjax.enable()
//
// Returns nothing.
function enable() {
  $.fn.pjax = fnPjax
  $.pjax = pjax
  $.pjax.enable = $.noop
  $.pjax.disable = disable
  $.pjax.click = handleClick
  $.pjax.submit = handleSubmit
  $.pjax.reload = pjaxReload
  $.pjax.defaults = {
    timeout: 650,
    push: true,
    replace: false,
    type: 'GET',
    dataType: 'html',
    scrollTo: 0,
    maxCacheLength: 20,
    version: findVersion
  }
  $(window).on('popstate.pjax', onPjaxPopstate)
}

// Disable pushState behavior.
//
// This is the case when a browser doesn't support pushState. It is
// sometimes useful to disable pushState for debugging on a modern
// browser.
//
// Examples
//
//     $.pjax.disable()
//
// Returns nothing.
function disable() {
  $.fn.pjax = function() { return this }
  $.pjax = fallbackPjax
  $.pjax.enable = enable
  $.pjax.disable = $.noop
  $.pjax.click = $.noop
  $.pjax.submit = $.noop
  $.pjax.reload = function() { window.location.reload() }

  $(window).off('popstate.pjax', onPjaxPopstate)
}


// Add the state property to jQuery's event object so we can use it in
// $(window).bind('popstate')
if ($.event.props && $.inArray('state', $.event.props) < 0) {
  $.event.props.push('state')
} else if (!('state' in $.Event.prototype)) {
  $.event.addProp('state')
}

// Is pjax supported by this browser?
$.support.pjax =
  window.history && window.history.pushState && window.history.replaceState &&
  // pushState isn't reliable on iOS until 5.
  !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/)

if ($.support.pjax) {
  enable()
} else {
  disable()
}

})(jQuery)
;
//! moment.js
//! version : 2.9.0
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com

(function (undefined) {
    /************************************
        Constants
    ************************************/

    var moment,
        VERSION = '2.9.0',
        // the global-scope this is NOT the global object in Node.js
        globalScope = (typeof global !== 'undefined' && (typeof window === 'undefined' || window === global.window)) ? global : this,
        oldGlobalMoment,
        round = Math.round,
        hasOwnProperty = Object.prototype.hasOwnProperty,
        i,

        YEAR = 0,
        MONTH = 1,
        DATE = 2,
        HOUR = 3,
        MINUTE = 4,
        SECOND = 5,
        MILLISECOND = 6,

        // internal storage for locale config files
        locales = {},

        // extra moment internal properties (plugins register props here)
        momentProperties = [],

        // check for nodeJS
        hasModule = (typeof module !== 'undefined' && module && module.exports),

        // ASP.NET json date format regex
        aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
        aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,

        // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
        // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
        isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,

        // format tokens
        formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,
        localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,

        // parsing token regexes
        parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
        parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
        parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
        parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
        parseTokenDigits = /\d+/, // nonzero number of digits
        parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic.
        parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
        parseTokenT = /T/i, // T (ISO separator)
        parseTokenOffsetMs = /[\+\-]?\d+/, // 1234567890123
        parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123

        //strict parsing regexes
        parseTokenOneDigit = /\d/, // 0 - 9
        parseTokenTwoDigits = /\d\d/, // 00 - 99
        parseTokenThreeDigits = /\d{3}/, // 000 - 999
        parseTokenFourDigits = /\d{4}/, // 0000 - 9999
        parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
        parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf

        // iso 8601 regex
        // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
        isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,

        isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',

        isoDates = [
            ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
            ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
            ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
            ['GGGG-[W]WW', /\d{4}-W\d{2}/],
            ['YYYY-DDD', /\d{4}-\d{3}/]
        ],

        // iso time formats and regexes
        isoTimes = [
            ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
            ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
            ['HH:mm', /(T| )\d\d:\d\d/],
            ['HH', /(T| )\d\d/]
        ],

        // timezone chunker '+10:00' > ['10', '00'] or '-1530' > ['-', '15', '30']
        parseTimezoneChunker = /([\+\-]|\d\d)/gi,

        // getter and setter names
        proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
        unitMillisecondFactors = {
            'Milliseconds' : 1,
            'Seconds' : 1e3,
            'Minutes' : 6e4,
            'Hours' : 36e5,
            'Days' : 864e5,
            'Months' : 2592e6,
            'Years' : 31536e6
        },

        unitAliases = {
            ms : 'millisecond',
            s : 'second',
            m : 'minute',
            h : 'hour',
            d : 'day',
            D : 'date',
            w : 'week',
            W : 'isoWeek',
            M : 'month',
            Q : 'quarter',
            y : 'year',
            DDD : 'dayOfYear',
            e : 'weekday',
            E : 'isoWeekday',
            gg: 'weekYear',
            GG: 'isoWeekYear'
        },

        camelFunctions = {
            dayofyear : 'dayOfYear',
            isoweekday : 'isoWeekday',
            isoweek : 'isoWeek',
            weekyear : 'weekYear',
            isoweekyear : 'isoWeekYear'
        },

        // format function strings
        formatFunctions = {},

        // default relative time thresholds
        relativeTimeThresholds = {
            s: 45,  // seconds to minute
            m: 45,  // minutes to hour
            h: 22,  // hours to day
            d: 26,  // days to month
            M: 11   // months to year
        },

        // tokens to ordinalize and pad
        ordinalizeTokens = 'DDD w W M D d'.split(' '),
        paddedTokens = 'M D H h m s w W'.split(' '),

        formatTokenFunctions = {
            M    : function () {
                return this.month() + 1;
            },
            MMM  : function (format) {
                return this.localeData().monthsShort(this, format);
            },
            MMMM : function (format) {
                return this.localeData().months(this, format);
            },
            D    : function () {
                return this.date();
            },
            DDD  : function () {
                return this.dayOfYear();
            },
            d    : function () {
                return this.day();
            },
            dd   : function (format) {
                return this.localeData().weekdaysMin(this, format);
            },
            ddd  : function (format) {
                return this.localeData().weekdaysShort(this, format);
            },
            dddd : function (format) {
                return this.localeData().weekdays(this, format);
            },
            w    : function () {
                return this.week();
            },
            W    : function () {
                return this.isoWeek();
            },
            YY   : function () {
                return leftZeroFill(this.year() % 100, 2);
            },
            YYYY : function () {
                return leftZeroFill(this.year(), 4);
            },
            YYYYY : function () {
                return leftZeroFill(this.year(), 5);
            },
            YYYYYY : function () {
                var y = this.year(), sign = y >= 0 ? '+' : '-';
                return sign + leftZeroFill(Math.abs(y), 6);
            },
            gg   : function () {
                return leftZeroFill(this.weekYear() % 100, 2);
            },
            gggg : function () {
                return leftZeroFill(this.weekYear(), 4);
            },
            ggggg : function () {
                return leftZeroFill(this.weekYear(), 5);
            },
            GG   : function () {
                return leftZeroFill(this.isoWeekYear() % 100, 2);
            },
            GGGG : function () {
                return leftZeroFill(this.isoWeekYear(), 4);
            },
            GGGGG : function () {
                return leftZeroFill(this.isoWeekYear(), 5);
            },
            e : function () {
                return this.weekday();
            },
            E : function () {
                return this.isoWeekday();
            },
            a    : function () {
                return this.localeData().meridiem(this.hours(), this.minutes(), true);
            },
            A    : function () {
                return this.localeData().meridiem(this.hours(), this.minutes(), false);
            },
            H    : function () {
                return this.hours();
            },
            h    : function () {
                return this.hours() % 12 || 12;
            },
            m    : function () {
                return this.minutes();
            },
            s    : function () {
                return this.seconds();
            },
            S    : function () {
                return toInt(this.milliseconds() / 100);
            },
            SS   : function () {
                return leftZeroFill(toInt(this.milliseconds() / 10), 2);
            },
            SSS  : function () {
                return leftZeroFill(this.milliseconds(), 3);
            },
            SSSS : function () {
                return leftZeroFill(this.milliseconds(), 3);
            },
            Z    : function () {
                var a = this.utcOffset(),
                    b = '+';
                if (a < 0) {
                    a = -a;
                    b = '-';
                }
                return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2);
            },
            ZZ   : function () {
                var a = this.utcOffset(),
                    b = '+';
                if (a < 0) {
                    a = -a;
                    b = '-';
                }
                return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
            },
            z : function () {
                return this.zoneAbbr();
            },
            zz : function () {
                return this.zoneName();
            },
            x    : function () {
                return this.valueOf();
            },
            X    : function () {
                return this.unix();
            },
            Q : function () {
                return this.quarter();
            }
        },

        deprecations = {},

        lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'],

        updateInProgress = false;

    // Pick the first defined of two or three arguments. dfl comes from
    // default.
    function dfl(a, b, c) {
        switch (arguments.length) {
            case 2: return a != null ? a : b;
            case 3: return a != null ? a : b != null ? b : c;
            default: throw new Error('Implement me');
        }
    }

    function hasOwnProp(a, b) {
        return hasOwnProperty.call(a, b);
    }

    function defaultParsingFlags() {
        // We need to deep clone this object, and es5 standard is not very
        // helpful.
        return {
            empty : false,
            unusedTokens : [],
            unusedInput : [],
            overflow : -2,
            charsLeftOver : 0,
            nullInput : false,
            invalidMonth : null,
            invalidFormat : false,
            userInvalidated : false,
            iso: false
        };
    }

    function printMsg(msg) {
        if (moment.suppressDeprecationWarnings === false &&
                typeof console !== 'undefined' && console.warn) {
            console.warn('Deprecation warning: ' + msg);
        }
    }

    function deprecate(msg, fn) {
        var firstTime = true;
        return extend(function () {
            if (firstTime) {
                printMsg(msg);
                firstTime = false;
            }
            return fn.apply(this, arguments);
        }, fn);
    }

    function deprecateSimple(name, msg) {
        if (!deprecations[name]) {
            printMsg(msg);
            deprecations[name] = true;
        }
    }

    function padToken(func, count) {
        return function (a) {
            return leftZeroFill(func.call(this, a), count);
        };
    }
    function ordinalizeToken(func, period) {
        return function (a) {
            return this.localeData().ordinal(func.call(this, a), period);
        };
    }

    function monthDiff(a, b) {
        // difference in months
        var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
            // b is in (anchor - 1 month, anchor + 1 month)
            anchor = a.clone().add(wholeMonthDiff, 'months'),
            anchor2, adjust;

        if (b - anchor < 0) {
            anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor - anchor2);
        } else {
            anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor2 - anchor);
        }

        return -(wholeMonthDiff + adjust);
    }

    while (ordinalizeTokens.length) {
        i = ordinalizeTokens.pop();
        formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
    }
    while (paddedTokens.length) {
        i = paddedTokens.pop();
        formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
    }
    formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);


    function meridiemFixWrap(locale, hour, meridiem) {
        var isPm;

        if (meridiem == null) {
            // nothing to do
            return hour;
        }
        if (locale.meridiemHour != null) {
            return locale.meridiemHour(hour, meridiem);
        } else if (locale.isPM != null) {
            // Fallback
            isPm = locale.isPM(meridiem);
            if (isPm && hour < 12) {
                hour += 12;
            }
            if (!isPm && hour === 12) {
                hour = 0;
            }
            return hour;
        } else {
            // thie is not supposed to happen
            return hour;
        }
    }

    /************************************
        Constructors
    ************************************/

    function Locale() {
    }

    // Moment prototype object
    function Moment(config, skipOverflow) {
        if (skipOverflow !== false) {
            checkOverflow(config);
        }
        copyConfig(this, config);
        this._d = new Date(+config._d);
        // Prevent infinite loop in case updateOffset creates new moment
        // objects.
        if (updateInProgress === false) {
            updateInProgress = true;
            moment.updateOffset(this);
            updateInProgress = false;
        }
    }

    // Duration Constructor
    function Duration(duration) {
        var normalizedInput = normalizeObjectUnits(duration),
            years = normalizedInput.year || 0,
            quarters = normalizedInput.quarter || 0,
            months = normalizedInput.month || 0,
            weeks = normalizedInput.week || 0,
            days = normalizedInput.day || 0,
            hours = normalizedInput.hour || 0,
            minutes = normalizedInput.minute || 0,
            seconds = normalizedInput.second || 0,
            milliseconds = normalizedInput.millisecond || 0;

        // representation for dateAddRemove
        this._milliseconds = +milliseconds +
            seconds * 1e3 + // 1000
            minutes * 6e4 + // 1000 * 60
            hours * 36e5; // 1000 * 60 * 60
        // Because of dateAddRemove treats 24 hours as different from a
        // day when working around DST, we need to store them separately
        this._days = +days +
            weeks * 7;
        // It is impossible translate months into days without knowing
        // which months you are are talking about, so we have to store
        // it separately.
        this._months = +months +
            quarters * 3 +
            years * 12;

        this._data = {};

        this._locale = moment.localeData();

        this._bubble();
    }

    /************************************
        Helpers
    ************************************/


    function extend(a, b) {
        for (var i in b) {
            if (hasOwnProp(b, i)) {
                a[i] = b[i];
            }
        }

        if (hasOwnProp(b, 'toString')) {
            a.toString = b.toString;
        }

        if (hasOwnProp(b, 'valueOf')) {
            a.valueOf = b.valueOf;
        }

        return a;
    }

    function copyConfig(to, from) {
        var i, prop, val;

        if (typeof from._isAMomentObject !== 'undefined') {
            to._isAMomentObject = from._isAMomentObject;
        }
        if (typeof from._i !== 'undefined') {
            to._i = from._i;
        }
        if (typeof from._f !== 'undefined') {
            to._f = from._f;
        }
        if (typeof from._l !== 'undefined') {
            to._l = from._l;
        }
        if (typeof from._strict !== 'undefined') {
            to._strict = from._strict;
        }
        if (typeof from._tzm !== 'undefined') {
            to._tzm = from._tzm;
        }
        if (typeof from._isUTC !== 'undefined') {
            to._isUTC = from._isUTC;
        }
        if (typeof from._offset !== 'undefined') {
            to._offset = from._offset;
        }
        if (typeof from._pf !== 'undefined') {
            to._pf = from._pf;
        }
        if (typeof from._locale !== 'undefined') {
            to._locale = from._locale;
        }

        if (momentProperties.length > 0) {
            for (i in momentProperties) {
                prop = momentProperties[i];
                val = from[prop];
                if (typeof val !== 'undefined') {
                    to[prop] = val;
                }
            }
        }

        return to;
    }

    function absRound(number) {
        if (number < 0) {
            return Math.ceil(number);
        } else {
            return Math.floor(number);
        }
    }

    // left zero fill a number
    // see http://jsperf.com/left-zero-filling for performance comparison
    function leftZeroFill(number, targetLength, forceSign) {
        var output = '' + Math.abs(number),
            sign = number >= 0;

        while (output.length < targetLength) {
            output = '0' + output;
        }
        return (sign ? (forceSign ? '+' : '') : '-') + output;
    }

    function positiveMomentsDifference(base, other) {
        var res = {milliseconds: 0, months: 0};

        res.months = other.month() - base.month() +
            (other.year() - base.year()) * 12;
        if (base.clone().add(res.months, 'M').isAfter(other)) {
            --res.months;
        }

        res.milliseconds = +other - +(base.clone().add(res.months, 'M'));

        return res;
    }

    function momentsDifference(base, other) {
        var res;
        other = makeAs(other, base);
        if (base.isBefore(other)) {
            res = positiveMomentsDifference(base, other);
        } else {
            res = positiveMomentsDifference(other, base);
            res.milliseconds = -res.milliseconds;
            res.months = -res.months;
        }

        return res;
    }

    // TODO: remove 'name' arg after deprecation is removed
    function createAdder(direction, name) {
        return function (val, period) {
            var dur, tmp;
            //invert the arguments, but complain about it
            if (period !== null && !isNaN(+period)) {
                deprecateSimple(name, 'moment().' + name  + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
                tmp = val; val = period; period = tmp;
            }

            val = typeof val === 'string' ? +val : val;
            dur = moment.duration(val, period);
            addOrSubtractDurationFromMoment(this, dur, direction);
            return this;
        };
    }

    function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
        var milliseconds = duration._milliseconds,
            days = duration._days,
            months = duration._months;
        updateOffset = updateOffset == null ? true : updateOffset;

        if (milliseconds) {
            mom._d.setTime(+mom._d + milliseconds * isAdding);
        }
        if (days) {
            rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
        }
        if (months) {
            rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
        }
        if (updateOffset) {
            moment.updateOffset(mom, days || months);
        }
    }

    // check if is an array
    function isArray(input) {
        return Object.prototype.toString.call(input) === '[object Array]';
    }

    function isDate(input) {
        return Object.prototype.toString.call(input) === '[object Date]' ||
            input instanceof Date;
    }

    // compare two arrays, return the number of differences
    function compareArrays(array1, array2, dontConvert) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if ((dontConvert && array1[i] !== array2[i]) ||
                (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    function normalizeUnits(units) {
        if (units) {
            var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
            units = unitAliases[units] || camelFunctions[lowered] || lowered;
        }
        return units;
    }

    function normalizeObjectUnits(inputObject) {
        var normalizedInput = {},
            normalizedProp,
            prop;

        for (prop in inputObject) {
            if (hasOwnProp(inputObject, prop)) {
                normalizedProp = normalizeUnits(prop);
                if (normalizedProp) {
                    normalizedInput[normalizedProp] = inputObject[prop];
                }
            }
        }

        return normalizedInput;
    }

    function makeList(field) {
        var count, setter;

        if (field.indexOf('week') === 0) {
            count = 7;
            setter = 'day';
        }
        else if (field.indexOf('month') === 0) {
            count = 12;
            setter = 'month';
        }
        else {
            return;
        }

        moment[field] = function (format, index) {
            var i, getter,
                method = moment._locale[field],
                results = [];

            if (typeof format === 'number') {
                index = format;
                format = undefined;
            }

            getter = function (i) {
                var m = moment().utc().set(setter, i);
                return method.call(moment._locale, m, format || '');
            };

            if (index != null) {
                return getter(index);
            }
            else {
                for (i = 0; i < count; i++) {
                    results.push(getter(i));
                }
                return results;
            }
        };
    }

    function toInt(argumentForCoercion) {
        var coercedNumber = +argumentForCoercion,
            value = 0;

        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
            if (coercedNumber >= 0) {
                value = Math.floor(coercedNumber);
            } else {
                value = Math.ceil(coercedNumber);
            }
        }

        return value;
    }

    function daysInMonth(year, month) {
        return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
    }

    function weeksInYear(year, dow, doy) {
        return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
    }

    function daysInYear(year) {
        return isLeapYear(year) ? 366 : 365;
    }

    function isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }

    function checkOverflow(m) {
        var overflow;
        if (m._a && m._pf.overflow === -2) {
            overflow =
                m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
                m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
                m._a[HOUR] < 0 || m._a[HOUR] > 24 ||
                    (m._a[HOUR] === 24 && (m._a[MINUTE] !== 0 ||
                                           m._a[SECOND] !== 0 ||
                                           m._a[MILLISECOND] !== 0)) ? HOUR :
                m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
                m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
                m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
                -1;

            if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
                overflow = DATE;
            }

            m._pf.overflow = overflow;
        }
    }

    function isValid(m) {
        if (m._isValid == null) {
            m._isValid = !isNaN(m._d.getTime()) &&
                m._pf.overflow < 0 &&
                !m._pf.empty &&
                !m._pf.invalidMonth &&
                !m._pf.nullInput &&
                !m._pf.invalidFormat &&
                !m._pf.userInvalidated;

            if (m._strict) {
                m._isValid = m._isValid &&
                    m._pf.charsLeftOver === 0 &&
                    m._pf.unusedTokens.length === 0 &&
                    m._pf.bigHour === undefined;
            }
        }
        return m._isValid;
    }

    function normalizeLocale(key) {
        return key ? key.toLowerCase().replace('_', '-') : key;
    }

    // pick the locale from the array
    // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
    // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
    function chooseLocale(names) {
        var i = 0, j, next, locale, split;

        while (i < names.length) {
            split = normalizeLocale(names[i]).split('-');
            j = split.length;
            next = normalizeLocale(names[i + 1]);
            next = next ? next.split('-') : null;
            while (j > 0) {
                locale = loadLocale(split.slice(0, j).join('-'));
                if (locale) {
                    return locale;
                }
                if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return null;
    }

    function loadLocale(name) {
        var oldLocale = null;
        if (!locales[name] && hasModule) {
            try {
                oldLocale = moment.locale();
                require('./locale/' + name);
                // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales
                moment.locale(oldLocale);
            } catch (e) { }
        }
        return locales[name];
    }

    // Return a moment from input, that is local/utc/utcOffset equivalent to
    // model.
    function makeAs(input, model) {
        var res, diff;
        if (model._isUTC) {
            res = model.clone();
            diff = (moment.isMoment(input) || isDate(input) ?
                    +input : +moment(input)) - (+res);
            // Use low-level api, because this fn is low-level api.
            res._d.setTime(+res._d + diff);
            moment.updateOffset(res, false);
            return res;
        } else {
            return moment(input).local();
        }
    }

    /************************************
        Locale
    ************************************/


    extend(Locale.prototype, {

        set : function (config) {
            var prop, i;
            for (i in config) {
                prop = config[i];
                if (typeof prop === 'function') {
                    this[i] = prop;
                } else {
                    this['_' + i] = prop;
                }
            }
            // Lenient ordinal parsing accepts just a number in addition to
            // number + (possibly) stuff coming from _ordinalParseLenient.
            this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source);
        },

        _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        months : function (m) {
            return this._months[m.month()];
        },

        _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        monthsShort : function (m) {
            return this._monthsShort[m.month()];
        },

        monthsParse : function (monthName, format, strict) {
            var i, mom, regex;

            if (!this._monthsParse) {
                this._monthsParse = [];
                this._longMonthsParse = [];
                this._shortMonthsParse = [];
            }

            for (i = 0; i < 12; i++) {
                // make the regex if we don't have it already
                mom = moment.utc([2000, i]);
                if (strict && !this._longMonthsParse[i]) {
                    this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
                    this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
                }
                if (!strict && !this._monthsParse[i]) {
                    regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
                    this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
                }
                // test the regex
                if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
                    return i;
                } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
                    return i;
                } else if (!strict && this._monthsParse[i].test(monthName)) {
                    return i;
                }
            }
        },

        _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdays : function (m) {
            return this._weekdays[m.day()];
        },

        _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysShort : function (m) {
            return this._weekdaysShort[m.day()];
        },

        _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        weekdaysMin : function (m) {
            return this._weekdaysMin[m.day()];
        },

        weekdaysParse : function (weekdayName) {
            var i, mom, regex;

            if (!this._weekdaysParse) {
                this._weekdaysParse = [];
            }

            for (i = 0; i < 7; i++) {
                // make the regex if we don't have it already
                if (!this._weekdaysParse[i]) {
                    mom = moment([2000, 1]).day(i);
                    regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
                    this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
                }
                // test the regex
                if (this._weekdaysParse[i].test(weekdayName)) {
                    return i;
                }
            }
        },

        _longDateFormat : {
            LTS : 'h:mm:ss A',
            LT : 'h:mm A',
            L : 'MM/DD/YYYY',
            LL : 'MMMM D, YYYY',
            LLL : 'MMMM D, YYYY LT',
            LLLL : 'dddd, MMMM D, YYYY LT'
        },
        longDateFormat : function (key) {
            var output = this._longDateFormat[key];
            if (!output && this._longDateFormat[key.toUpperCase()]) {
                output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
                    return val.slice(1);
                });
                this._longDateFormat[key] = output;
            }
            return output;
        },

        isPM : function (input) {
            // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
            // Using charAt should be more compatible.
            return ((input + '').toLowerCase().charAt(0) === 'p');
        },

        _meridiemParse : /[ap]\.?m?\.?/i,
        meridiem : function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'pm' : 'PM';
            } else {
                return isLower ? 'am' : 'AM';
            }
        },


        _calendar : {
            sameDay : '[Today at] LT',
            nextDay : '[Tomorrow at] LT',
            nextWeek : 'dddd [at] LT',
            lastDay : '[Yesterday at] LT',
            lastWeek : '[Last] dddd [at] LT',
            sameElse : 'L'
        },
        calendar : function (key, mom, now) {
            var output = this._calendar[key];
            return typeof output === 'function' ? output.apply(mom, [now]) : output;
        },

        _relativeTime : {
            future : 'in %s',
            past : '%s ago',
            s : 'a few seconds',
            m : 'a minute',
            mm : '%d minutes',
            h : 'an hour',
            hh : '%d hours',
            d : 'a day',
            dd : '%d days',
            M : 'a month',
            MM : '%d months',
            y : 'a year',
            yy : '%d years'
        },

        relativeTime : function (number, withoutSuffix, string, isFuture) {
            var output = this._relativeTime[string];
            return (typeof output === 'function') ?
                output(number, withoutSuffix, string, isFuture) :
                output.replace(/%d/i, number);
        },

        pastFuture : function (diff, output) {
            var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
            return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
        },

        ordinal : function (number) {
            return this._ordinal.replace('%d', number);
        },
        _ordinal : '%d',
        _ordinalParse : /\d{1,2}/,

        preparse : function (string) {
            return string;
        },

        postformat : function (string) {
            return string;
        },

        week : function (mom) {
            return weekOfYear(mom, this._week.dow, this._week.doy).week;
        },

        _week : {
            dow : 0, // Sunday is the first day of the week.
            doy : 6  // The week that contains Jan 1st is the first week of the year.
        },

        firstDayOfWeek : function () {
            return this._week.dow;
        },

        firstDayOfYear : function () {
            return this._week.doy;
        },

        _invalidDate: 'Invalid date',
        invalidDate: function () {
            return this._invalidDate;
        }
    });

    /************************************
        Formatting
    ************************************/


    function removeFormattingTokens(input) {
        if (input.match(/\[[\s\S]/)) {
            return input.replace(/^\[|\]$/g, '');
        }
        return input.replace(/\\/g, '');
    }

    function makeFormatFunction(format) {
        var array = format.match(formattingTokens), i, length;

        for (i = 0, length = array.length; i < length; i++) {
            if (formatTokenFunctions[array[i]]) {
                array[i] = formatTokenFunctions[array[i]];
            } else {
                array[i] = removeFormattingTokens(array[i]);
            }
        }

        return function (mom) {
            var output = '';
            for (i = 0; i < length; i++) {
                output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
            }
            return output;
        };
    }

    // format date using native date object
    function formatMoment(m, format) {
        if (!m.isValid()) {
            return m.localeData().invalidDate();
        }

        format = expandFormat(format, m.localeData());

        if (!formatFunctions[format]) {
            formatFunctions[format] = makeFormatFunction(format);
        }

        return formatFunctions[format](m);
    }

    function expandFormat(format, locale) {
        var i = 5;

        function replaceLongDateFormatTokens(input) {
            return locale.longDateFormat(input) || input;
        }

        localFormattingTokens.lastIndex = 0;
        while (i >= 0 && localFormattingTokens.test(format)) {
            format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
            localFormattingTokens.lastIndex = 0;
            i -= 1;
        }

        return format;
    }


    /************************************
        Parsing
    ************************************/


    // get the regex to find the next token
    function getParseRegexForToken(token, config) {
        var a, strict = config._strict;
        switch (token) {
        case 'Q':
            return parseTokenOneDigit;
        case 'DDDD':
            return parseTokenThreeDigits;
        case 'YYYY':
        case 'GGGG':
        case 'gggg':
            return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
        case 'Y':
        case 'G':
        case 'g':
            return parseTokenSignedNumber;
        case 'YYYYYY':
        case 'YYYYY':
        case 'GGGGG':
        case 'ggggg':
            return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
        case 'S':
            if (strict) {
                return parseTokenOneDigit;
            }
            /* falls through */
        case 'SS':
            if (strict) {
                return parseTokenTwoDigits;
            }
            /* falls through */
        case 'SSS':
            if (strict) {
                return parseTokenThreeDigits;
            }
            /* falls through */
        case 'DDD':
            return parseTokenOneToThreeDigits;
        case 'MMM':
        case 'MMMM':
        case 'dd':
        case 'ddd':
        case 'dddd':
            return parseTokenWord;
        case 'a':
        case 'A':
            return config._locale._meridiemParse;
        case 'x':
            return parseTokenOffsetMs;
        case 'X':
            return parseTokenTimestampMs;
        case 'Z':
        case 'ZZ':
            return parseTokenTimezone;
        case 'T':
            return parseTokenT;
        case 'SSSS':
            return parseTokenDigits;
        case 'MM':
        case 'DD':
        case 'YY':
        case 'GG':
        case 'gg':
        case 'HH':
        case 'hh':
        case 'mm':
        case 'ss':
        case 'ww':
        case 'WW':
            return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
        case 'M':
        case 'D':
        case 'd':
        case 'H':
        case 'h':
        case 'm':
        case 's':
        case 'w':
        case 'W':
        case 'e':
        case 'E':
            return parseTokenOneOrTwoDigits;
        case 'Do':
            return strict ? config._locale._ordinalParse : config._locale._ordinalParseLenient;
        default :
            a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i'));
            return a;
        }
    }

    function utcOffsetFromString(string) {
        string = string || '';
        var possibleTzMatches = (string.match(parseTokenTimezone) || []),
            tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
            parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
            minutes = +(parts[1] * 60) + toInt(parts[2]);

        return parts[0] === '+' ? minutes : -minutes;
    }

    // function to convert string input to date
    function addTimeToArrayFromToken(token, input, config) {
        var a, datePartArray = config._a;

        switch (token) {
        // QUARTER
        case 'Q':
            if (input != null) {
                datePartArray[MONTH] = (toInt(input) - 1) * 3;
            }
            break;
        // MONTH
        case 'M' : // fall through to MM
        case 'MM' :
            if (input != null) {
                datePartArray[MONTH] = toInt(input) - 1;
            }
            break;
        case 'MMM' : // fall through to MMMM
        case 'MMMM' :
            a = config._locale.monthsParse(input, token, config._strict);
            // if we didn't find a month name, mark the date as invalid.
            if (a != null) {
                datePartArray[MONTH] = a;
            } else {
                config._pf.invalidMonth = input;
            }
            break;
        // DAY OF MONTH
        case 'D' : // fall through to DD
        case 'DD' :
            if (input != null) {
                datePartArray[DATE] = toInt(input);
            }
            break;
        case 'Do' :
            if (input != null) {
                datePartArray[DATE] = toInt(parseInt(
                            input.match(/\d{1,2}/)[0], 10));
            }
            break;
        // DAY OF YEAR
        case 'DDD' : // fall through to DDDD
        case 'DDDD' :
            if (input != null) {
                config._dayOfYear = toInt(input);
            }

            break;
        // YEAR
        case 'YY' :
            datePartArray[YEAR] = moment.parseTwoDigitYear(input);
            break;
        case 'YYYY' :
        case 'YYYYY' :
        case 'YYYYYY' :
            datePartArray[YEAR] = toInt(input);
            break;
        // AM / PM
        case 'a' : // fall through to A
        case 'A' :
            config._meridiem = input;
            // config._isPm = config._locale.isPM(input);
            break;
        // HOUR
        case 'h' : // fall through to hh
        case 'hh' :
            config._pf.bigHour = true;
            /* falls through */
        case 'H' : // fall through to HH
        case 'HH' :
            datePartArray[HOUR] = toInt(input);
            break;
        // MINUTE
        case 'm' : // fall through to mm
        case 'mm' :
            datePartArray[MINUTE] = toInt(input);
            break;
        // SECOND
        case 's' : // fall through to ss
        case 'ss' :
            datePartArray[SECOND] = toInt(input);
            break;
        // MILLISECOND
        case 'S' :
        case 'SS' :
        case 'SSS' :
        case 'SSSS' :
            datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
            break;
        // UNIX OFFSET (MILLISECONDS)
        case 'x':
            config._d = new Date(toInt(input));
            break;
        // UNIX TIMESTAMP WITH MS
        case 'X':
            config._d = new Date(parseFloat(input) * 1000);
            break;
        // TIMEZONE
        case 'Z' : // fall through to ZZ
        case 'ZZ' :
            config._useUTC = true;
            config._tzm = utcOffsetFromString(input);
            break;
        // WEEKDAY - human
        case 'dd':
        case 'ddd':
        case 'dddd':
            a = config._locale.weekdaysParse(input);
            // if we didn't get a weekday name, mark the date as invalid
            if (a != null) {
                config._w = config._w || {};
                config._w['d'] = a;
            } else {
                config._pf.invalidWeekday = input;
            }
            break;
        // WEEK, WEEK DAY - numeric
        case 'w':
        case 'ww':
        case 'W':
        case 'WW':
        case 'd':
        case 'e':
        case 'E':
            token = token.substr(0, 1);
            /* falls through */
        case 'gggg':
        case 'GGGG':
        case 'GGGGG':
            token = token.substr(0, 2);
            if (input) {
                config._w = config._w || {};
                config._w[token] = toInt(input);
            }
            break;
        case 'gg':
        case 'GG':
            config._w = config._w || {};
            config._w[token] = moment.parseTwoDigitYear(input);
        }
    }

    function dayOfYearFromWeekInfo(config) {
        var w, weekYear, week, weekday, dow, doy, temp;

        w = config._w;
        if (w.GG != null || w.W != null || w.E != null) {
            dow = 1;
            doy = 4;

            // TODO: We need to take the current isoWeekYear, but that depends on
            // how we interpret now (local, utc, fixed offset). So create
            // a now version of current config (take local/utc/offset flags, and
            // create now).
            weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year);
            week = dfl(w.W, 1);
            weekday = dfl(w.E, 1);
        } else {
            dow = config._locale._week.dow;
            doy = config._locale._week.doy;

            weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year);
            week = dfl(w.w, 1);

            if (w.d != null) {
                // weekday -- low day numbers are considered next week
                weekday = w.d;
                if (weekday < dow) {
                    ++week;
                }
            } else if (w.e != null) {
                // local weekday -- counting starts from begining of week
                weekday = w.e + dow;
            } else {
                // default to begining of week
                weekday = dow;
            }
        }
        temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);

        config._a[YEAR] = temp.year;
        config._dayOfYear = temp.dayOfYear;
    }

    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function dateFromConfig(config) {
        var i, date, input = [], currentDate, yearToUse;

        if (config._d) {
            return;
        }

        currentDate = currentDateArray(config);

        //compute day of the year from weeks and weekdays
        if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
            dayOfYearFromWeekInfo(config);
        }

        //if the day of the year is set, figure out what it is
        if (config._dayOfYear) {
            yearToUse = dfl(config._a[YEAR], currentDate[YEAR]);

            if (config._dayOfYear > daysInYear(yearToUse)) {
                config._pf._overflowDayOfYear = true;
            }

            date = makeUTCDate(yearToUse, 0, config._dayOfYear);
            config._a[MONTH] = date.getUTCMonth();
            config._a[DATE] = date.getUTCDate();
        }

        // Default to current date.
        // * if no year, month, day of month are given, default to today
        // * if day of month is given, default month and year
        // * if month is given, default only year
        // * if year is given, don't default anything
        for (i = 0; i < 3 && config._a[i] == null; ++i) {
            config._a[i] = input[i] = currentDate[i];
        }

        // Zero out whatever was not defaulted, including time
        for (; i < 7; i++) {
            config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
        }

        // Check for 24:00:00.000
        if (config._a[HOUR] === 24 &&
                config._a[MINUTE] === 0 &&
                config._a[SECOND] === 0 &&
                config._a[MILLISECOND] === 0) {
            config._nextDay = true;
            config._a[HOUR] = 0;
        }

        config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
        // Apply timezone offset from input. The actual utcOffset can be changed
        // with parseZone.
        if (config._tzm != null) {
            config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
        }

        if (config._nextDay) {
            config._a[HOUR] = 24;
        }
    }

    function dateFromObject(config) {
        var normalizedInput;

        if (config._d) {
            return;
        }

        normalizedInput = normalizeObjectUnits(config._i);
        config._a = [
            normalizedInput.year,
            normalizedInput.month,
            normalizedInput.day || normalizedInput.date,
            normalizedInput.hour,
            normalizedInput.minute,
            normalizedInput.second,
            normalizedInput.millisecond
        ];

        dateFromConfig(config);
    }

    function currentDateArray(config) {
        var now = new Date();
        if (config._useUTC) {
            return [
                now.getUTCFullYear(),
                now.getUTCMonth(),
                now.getUTCDate()
            ];
        } else {
            return [now.getFullYear(), now.getMonth(), now.getDate()];
        }
    }

    // date from string and format string
    function makeDateFromStringAndFormat(config) {
        if (config._f === moment.ISO_8601) {
            parseISO(config);
            return;
        }

        config._a = [];
        config._pf.empty = true;

        // This array is used to make a Date, either with `new Date` or `Date.UTC`
        var string = '' + config._i,
            i, parsedInput, tokens, token, skipped,
            stringLength = string.length,
            totalParsedInputLength = 0;

        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            if (parsedInput) {
                skipped = string.substr(0, string.indexOf(parsedInput));
                if (skipped.length > 0) {
                    config._pf.unusedInput.push(skipped);
                }
                string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
                totalParsedInputLength += parsedInput.length;
            }
            // don't parse if it's not a known token
            if (formatTokenFunctions[token]) {
                if (parsedInput) {
                    config._pf.empty = false;
                }
                else {
                    config._pf.unusedTokens.push(token);
                }
                addTimeToArrayFromToken(token, parsedInput, config);
            }
            else if (config._strict && !parsedInput) {
                config._pf.unusedTokens.push(token);
            }
        }

        // add remaining unparsed input length to the string
        config._pf.charsLeftOver = stringLength - totalParsedInputLength;
        if (string.length > 0) {
            config._pf.unusedInput.push(string);
        }

        // clear _12h flag if hour is <= 12
        if (config._pf.bigHour === true && config._a[HOUR] <= 12) {
            config._pf.bigHour = undefined;
        }
        // handle meridiem
        config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR],
                config._meridiem);
        dateFromConfig(config);
        checkOverflow(config);
    }

    function unescapeFormat(s) {
        return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
            return p1 || p2 || p3 || p4;
        });
    }

    // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    function regexpEscape(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }

    // date from string and array of format strings
    function makeDateFromStringAndArray(config) {
        var tempConfig,
            bestMoment,

            scoreToBeat,
            i,
            currentScore;

        if (config._f.length === 0) {
            config._pf.invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }

        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = copyConfig({}, config);
            if (config._useUTC != null) {
                tempConfig._useUTC = config._useUTC;
            }
            tempConfig._pf = defaultParsingFlags();
            tempConfig._f = config._f[i];
            makeDateFromStringAndFormat(tempConfig);

            if (!isValid(tempConfig)) {
                continue;
            }

            // if there is any input that was not parsed add a penalty for that format
            currentScore += tempConfig._pf.charsLeftOver;

            //or tokens
            currentScore += tempConfig._pf.unusedTokens.length * 10;

            tempConfig._pf.score = currentScore;

            if (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }

        extend(config, bestMoment || tempConfig);
    }

    // date from iso format
    function parseISO(config) {
        var i, l,
            string = config._i,
            match = isoRegex.exec(string);

        if (match) {
            config._pf.iso = true;
            for (i = 0, l = isoDates.length; i < l; i++) {
                if (isoDates[i][1].exec(string)) {
                    // match[5] should be 'T' or undefined
                    config._f = isoDates[i][0] + (match[6] || ' ');
                    break;
                }
            }
            for (i = 0, l = isoTimes.length; i < l; i++) {
                if (isoTimes[i][1].exec(string)) {
                    config._f += isoTimes[i][0];
                    break;
                }
            }
            if (string.match(parseTokenTimezone)) {
                config._f += 'Z';
            }
            makeDateFromStringAndFormat(config);
        } else {
            config._isValid = false;
        }
    }

    // date from iso format or fallback
    function makeDateFromString(config) {
        parseISO(config);
        if (config._isValid === false) {
            delete config._isValid;
            moment.createFromInputFallback(config);
        }
    }

    function map(arr, fn) {
        var res = [], i;
        for (i = 0; i < arr.length; ++i) {
            res.push(fn(arr[i], i));
        }
        return res;
    }

    function makeDateFromInput(config) {
        var input = config._i, matched;
        if (input === undefined) {
            config._d = new Date();
        } else if (isDate(input)) {
            config._d = new Date(+input);
        } else if ((matched = aspNetJsonRegex.exec(input)) !== null) {
            config._d = new Date(+matched[1]);
        } else if (typeof input === 'string') {
            makeDateFromString(config);
        } else if (isArray(input)) {
            config._a = map(input.slice(0), function (obj) {
                return parseInt(obj, 10);
            });
            dateFromConfig(config);
        } else if (typeof(input) === 'object') {
            dateFromObject(config);
        } else if (typeof(input) === 'number') {
            // from milliseconds
            config._d = new Date(input);
        } else {
            moment.createFromInputFallback(config);
        }
    }

    function makeDate(y, m, d, h, M, s, ms) {
        //can't just apply() to create a date:
        //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
        var date = new Date(y, m, d, h, M, s, ms);

        //the date constructor doesn't accept years < 1970
        if (y < 1970) {
            date.setFullYear(y);
        }
        return date;
    }

    function makeUTCDate(y) {
        var date = new Date(Date.UTC.apply(null, arguments));
        if (y < 1970) {
            date.setUTCFullYear(y);
        }
        return date;
    }

    function parseWeekday(input, locale) {
        if (typeof input === 'string') {
            if (!isNaN(input)) {
                input = parseInt(input, 10);
            }
            else {
                input = locale.weekdaysParse(input);
                if (typeof input !== 'number') {
                    return null;
                }
            }
        }
        return input;
    }

    /************************************
        Relative Time
    ************************************/


    // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
    function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
        return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
    }

    function relativeTime(posNegDuration, withoutSuffix, locale) {
        var duration = moment.duration(posNegDuration).abs(),
            seconds = round(duration.as('s')),
            minutes = round(duration.as('m')),
            hours = round(duration.as('h')),
            days = round(duration.as('d')),
            months = round(duration.as('M')),
            years = round(duration.as('y')),

            args = seconds < relativeTimeThresholds.s && ['s', seconds] ||
                minutes === 1 && ['m'] ||
                minutes < relativeTimeThresholds.m && ['mm', minutes] ||
                hours === 1 && ['h'] ||
                hours < relativeTimeThresholds.h && ['hh', hours] ||
                days === 1 && ['d'] ||
                days < relativeTimeThresholds.d && ['dd', days] ||
                months === 1 && ['M'] ||
                months < relativeTimeThresholds.M && ['MM', months] ||
                years === 1 && ['y'] || ['yy', years];

        args[2] = withoutSuffix;
        args[3] = +posNegDuration > 0;
        args[4] = locale;
        return substituteTimeAgo.apply({}, args);
    }


    /************************************
        Week of Year
    ************************************/


    // firstDayOfWeek       0 = sun, 6 = sat
    //                      the day of the week that starts the week
    //                      (usually sunday or monday)
    // firstDayOfWeekOfYear 0 = sun, 6 = sat
    //                      the first week is the week that contains the first
    //                      of this day of the week
    //                      (eg. ISO weeks use thursday (4))
    function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
        var end = firstDayOfWeekOfYear - firstDayOfWeek,
            daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
            adjustedMoment;


        if (daysToDayOfWeek > end) {
            daysToDayOfWeek -= 7;
        }

        if (daysToDayOfWeek < end - 7) {
            daysToDayOfWeek += 7;
        }

        adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd');
        return {
            week: Math.ceil(adjustedMoment.dayOfYear() / 7),
            year: adjustedMoment.year()
        };
    }

    //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
    function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
        var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;

        d = d === 0 ? 7 : d;
        weekday = weekday != null ? weekday : firstDayOfWeek;
        daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
        dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;

        return {
            year: dayOfYear > 0 ? year : year - 1,
            dayOfYear: dayOfYear > 0 ?  dayOfYear : daysInYear(year - 1) + dayOfYear
        };
    }

    /************************************
        Top Level Functions
    ************************************/

    function makeMoment(config) {
        var input = config._i,
            format = config._f,
            res;

        config._locale = config._locale || moment.localeData(config._l);

        if (input === null || (format === undefined && input === '')) {
            return moment.invalid({nullInput: true});
        }

        if (typeof input === 'string') {
            config._i = input = config._locale.preparse(input);
        }

        if (moment.isMoment(input)) {
            return new Moment(input, true);
        } else if (format) {
            if (isArray(format)) {
                makeDateFromStringAndArray(config);
            } else {
                makeDateFromStringAndFormat(config);
            }
        } else {
            makeDateFromInput(config);
        }

        res = new Moment(config);
        if (res._nextDay) {
            // Adding is smart enough around DST
            res.add(1, 'd');
            res._nextDay = undefined;
        }

        return res;
    }

    moment = function (input, format, locale, strict) {
        var c;

        if (typeof(locale) === 'boolean') {
            strict = locale;
            locale = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c = {};
        c._isAMomentObject = true;
        c._i = input;
        c._f = format;
        c._l = locale;
        c._strict = strict;
        c._isUTC = false;
        c._pf = defaultParsingFlags();

        return makeMoment(c);
    };

    moment.suppressDeprecationWarnings = false;

    moment.createFromInputFallback = deprecate(
        'moment construction falls back to js Date. This is ' +
        'discouraged and will be removed in upcoming major ' +
        'release. Please refer to ' +
        'https://github.com/moment/moment/issues/1407 for more info.',
        function (config) {
            config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
        }
    );

    // Pick a moment m from moments so that m[fn](other) is true for all
    // other. This relies on the function fn to be transitive.
    //
    // moments should either be an array of moment objects or an array, whose
    // first element is an array of moment objects.
    function pickBy(fn, moments) {
        var res, i;
        if (moments.length === 1 && isArray(moments[0])) {
            moments = moments[0];
        }
        if (!moments.length) {
            return moment();
        }
        res = moments[0];
        for (i = 1; i < moments.length; ++i) {
            if (moments[i][fn](res)) {
                res = moments[i];
            }
        }
        return res;
    }

    moment.min = function () {
        var args = [].slice.call(arguments, 0);

        return pickBy('isBefore', args);
    };

    moment.max = function () {
        var args = [].slice.call(arguments, 0);

        return pickBy('isAfter', args);
    };

    // creating with utc
    moment.utc = function (input, format, locale, strict) {
        var c;

        if (typeof(locale) === 'boolean') {
            strict = locale;
            locale = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c = {};
        c._isAMomentObject = true;
        c._useUTC = true;
        c._isUTC = true;
        c._l = locale;
        c._i = input;
        c._f = format;
        c._strict = strict;
        c._pf = defaultParsingFlags();

        return makeMoment(c).utc();
    };

    // creating with unix timestamp (in seconds)
    moment.unix = function (input) {
        return moment(input * 1000);
    };

    // duration
    moment.duration = function (input, key) {
        var duration = input,
            // matching against regexp is expensive, do it on demand
            match = null,
            sign,
            ret,
            parseIso,
            diffRes;

        if (moment.isDuration(input)) {
            duration = {
                ms: input._milliseconds,
                d: input._days,
                M: input._months
            };
        } else if (typeof input === 'number') {
            duration = {};
            if (key) {
                duration[key] = input;
            } else {
                duration.milliseconds = input;
            }
        } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y: 0,
                d: toInt(match[DATE]) * sign,
                h: toInt(match[HOUR]) * sign,
                m: toInt(match[MINUTE]) * sign,
                s: toInt(match[SECOND]) * sign,
                ms: toInt(match[MILLISECOND]) * sign
            };
        } else if (!!(match = isoDurationRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            parseIso = function (inp) {
                // We'd normally use ~~inp for this, but unfortunately it also
                // converts floats to ints.
                // inp may be undefined, so careful calling replace on it.
                var res = inp && parseFloat(inp.replace(',', '.'));
                // apply sign while we're at it
                return (isNaN(res) ? 0 : res) * sign;
            };
            duration = {
                y: parseIso(match[2]),
                M: parseIso(match[3]),
                d: parseIso(match[4]),
                h: parseIso(match[5]),
                m: parseIso(match[6]),
                s: parseIso(match[7]),
                w: parseIso(match[8])
            };
        } else if (duration == null) {// checks for null or undefined
            duration = {};
        } else if (typeof duration === 'object' &&
                ('from' in duration || 'to' in duration)) {
            diffRes = momentsDifference(moment(duration.from), moment(duration.to));

            duration = {};
            duration.ms = diffRes.milliseconds;
            duration.M = diffRes.months;
        }

        ret = new Duration(duration);

        if (moment.isDuration(input) && hasOwnProp(input, '_locale')) {
            ret._locale = input._locale;
        }

        return ret;
    };

    // version number
    moment.version = VERSION;

    // default format
    moment.defaultFormat = isoFormat;

    // constant that refers to the ISO standard
    moment.ISO_8601 = function () {};

    // Plugins that add properties should also add the key here (null value),
    // so we can properly clone ourselves.
    moment.momentProperties = momentProperties;

    // This function will be called whenever a moment is mutated.
    // It is intended to keep the offset in sync with the timezone.
    moment.updateOffset = function () {};

    // This function allows you to set a threshold for relative time strings
    moment.relativeTimeThreshold = function (threshold, limit) {
        if (relativeTimeThresholds[threshold] === undefined) {
            return false;
        }
        if (limit === undefined) {
            return relativeTimeThresholds[threshold];
        }
        relativeTimeThresholds[threshold] = limit;
        return true;
    };

    moment.lang = deprecate(
        'moment.lang is deprecated. Use moment.locale instead.',
        function (key, value) {
            return moment.locale(key, value);
        }
    );

    // This function will load locale and then set the global locale.  If
    // no arguments are passed in, it will simply return the current global
    // locale key.
    moment.locale = function (key, values) {
        var data;
        if (key) {
            if (typeof(values) !== 'undefined') {
                data = moment.defineLocale(key, values);
            }
            else {
                data = moment.localeData(key);
            }

            if (data) {
                moment.duration._locale = moment._locale = data;
            }
        }

        return moment._locale._abbr;
    };

    moment.defineLocale = function (name, values) {
        if (values !== null) {
            values.abbr = name;
            if (!locales[name]) {
                locales[name] = new Locale();
            }
            locales[name].set(values);

            // backwards compat for now: also set the locale
            moment.locale(name);

            return locales[name];
        } else {
            // useful for testing
            delete locales[name];
            return null;
        }
    };

    moment.langData = deprecate(
        'moment.langData is deprecated. Use moment.localeData instead.',
        function (key) {
            return moment.localeData(key);
        }
    );

    // returns locale data
    moment.localeData = function (key) {
        var locale;

        if (key && key._locale && key._locale._abbr) {
            key = key._locale._abbr;
        }

        if (!key) {
            return moment._locale;
        }

        if (!isArray(key)) {
            //short-circuit everything else
            locale = loadLocale(key);
            if (locale) {
                return locale;
            }
            key = [key];
        }

        return chooseLocale(key);
    };

    // compare moment object
    moment.isMoment = function (obj) {
        return obj instanceof Moment ||
            (obj != null && hasOwnProp(obj, '_isAMomentObject'));
    };

    // for typechecking Duration objects
    moment.isDuration = function (obj) {
        return obj instanceof Duration;
    };

    for (i = lists.length - 1; i >= 0; --i) {
        makeList(lists[i]);
    }

    moment.normalizeUnits = function (units) {
        return normalizeUnits(units);
    };

    moment.invalid = function (flags) {
        var m = moment.utc(NaN);
        if (flags != null) {
            extend(m._pf, flags);
        }
        else {
            m._pf.userInvalidated = true;
        }

        return m;
    };

    moment.parseZone = function () {
        return moment.apply(null, arguments).parseZone();
    };

    moment.parseTwoDigitYear = function (input) {
        return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
    };

    moment.isDate = isDate;

    /************************************
        Moment Prototype
    ************************************/


    extend(moment.fn = Moment.prototype, {

        clone : function () {
            return moment(this);
        },

        valueOf : function () {
            return +this._d - ((this._offset || 0) * 60000);
        },

        unix : function () {
            return Math.floor(+this / 1000);
        },

        toString : function () {
            return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
        },

        toDate : function () {
            return this._offset ? new Date(+this) : this._d;
        },

        toISOString : function () {
            var m = moment(this).utc();
            if (0 < m.year() && m.year() <= 9999) {
                if ('function' === typeof Date.prototype.toISOString) {
                    // native implementation is ~50x faster, use it when we can
                    return this.toDate().toISOString();
                } else {
                    return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
                }
            } else {
                return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
            }
        },

        toArray : function () {
            var m = this;
            return [
                m.year(),
                m.month(),
                m.date(),
                m.hours(),
                m.minutes(),
                m.seconds(),
                m.milliseconds()
            ];
        },

        isValid : function () {
            return isValid(this);
        },

        isDSTShifted : function () {
            if (this._a) {
                return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
            }

            return false;
        },

        parsingFlags : function () {
            return extend({}, this._pf);
        },

        invalidAt: function () {
            return this._pf.overflow;
        },

        utc : function (keepLocalTime) {
            return this.utcOffset(0, keepLocalTime);
        },

        local : function (keepLocalTime) {
            if (this._isUTC) {
                this.utcOffset(0, keepLocalTime);
                this._isUTC = false;

                if (keepLocalTime) {
                    this.subtract(this._dateUtcOffset(), 'm');
                }
            }
            return this;
        },

        format : function (inputString) {
            var output = formatMoment(this, inputString || moment.defaultFormat);
            return this.localeData().postformat(output);
        },

        add : createAdder(1, 'add'),

        subtract : createAdder(-1, 'subtract'),

        diff : function (input, units, asFloat) {
            var that = makeAs(input, this),
                zoneDiff = (that.utcOffset() - this.utcOffset()) * 6e4,
                anchor, diff, output, daysAdjust;

            units = normalizeUnits(units);

            if (units === 'year' || units === 'month' || units === 'quarter') {
                output = monthDiff(this, that);
                if (units === 'quarter') {
                    output = output / 3;
                } else if (units === 'year') {
                    output = output / 12;
                }
            } else {
                diff = this - that;
                output = units === 'second' ? diff / 1e3 : // 1000
                    units === 'minute' ? diff / 6e4 : // 1000 * 60
                    units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
                    units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
                    units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
                    diff;
            }
            return asFloat ? output : absRound(output);
        },

        from : function (time, withoutSuffix) {
            return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
        },

        fromNow : function (withoutSuffix) {
            return this.from(moment(), withoutSuffix);
        },

        calendar : function (time) {
            // We want to compare the start of today, vs this.
            // Getting start-of-today depends on whether we're locat/utc/offset
            // or not.
            var now = time || moment(),
                sod = makeAs(now, this).startOf('day'),
                diff = this.diff(sod, 'days', true),
                format = diff < -6 ? 'sameElse' :
                    diff < -1 ? 'lastWeek' :
                    diff < 0 ? 'lastDay' :
                    diff < 1 ? 'sameDay' :
                    diff < 2 ? 'nextDay' :
                    diff < 7 ? 'nextWeek' : 'sameElse';
            return this.format(this.localeData().calendar(format, this, moment(now)));
        },

        isLeapYear : function () {
            return isLeapYear(this.year());
        },

        isDST : function () {
            return (this.utcOffset() > this.clone().month(0).utcOffset() ||
                this.utcOffset() > this.clone().month(5).utcOffset());
        },

        day : function (input) {
            var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
            if (input != null) {
                input = parseWeekday(input, this.localeData());
                return this.add(input - day, 'd');
            } else {
                return day;
            }
        },

        month : makeAccessor('Month', true),

        startOf : function (units) {
            units = normalizeUnits(units);
            // the following switch intentionally omits break keywords
            // to utilize falling through the cases.
            switch (units) {
            case 'year':
                this.month(0);
                /* falls through */
            case 'quarter':
            case 'month':
                this.date(1);
                /* falls through */
            case 'week':
            case 'isoWeek':
            case 'day':
                this.hours(0);
                /* falls through */
            case 'hour':
                this.minutes(0);
                /* falls through */
            case 'minute':
                this.seconds(0);
                /* falls through */
            case 'second':
                this.milliseconds(0);
                /* falls through */
            }

            // weeks are a special case
            if (units === 'week') {
                this.weekday(0);
            } else if (units === 'isoWeek') {
                this.isoWeekday(1);
            }

            // quarters are also special
            if (units === 'quarter') {
                this.month(Math.floor(this.month() / 3) * 3);
            }

            return this;
        },

        endOf: function (units) {
            units = normalizeUnits(units);
            if (units === undefined || units === 'millisecond') {
                return this;
            }
            return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
        },

        isAfter: function (input, units) {
            var inputMs;
            units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
            if (units === 'millisecond') {
                input = moment.isMoment(input) ? input : moment(input);
                return +this > +input;
            } else {
                inputMs = moment.isMoment(input) ? +input : +moment(input);
                return inputMs < +this.clone().startOf(units);
            }
        },

        isBefore: function (input, units) {
            var inputMs;
            units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
            if (units === 'millisecond') {
                input = moment.isMoment(input) ? input : moment(input);
                return +this < +input;
            } else {
                inputMs = moment.isMoment(input) ? +input : +moment(input);
                return +this.clone().endOf(units) < inputMs;
            }
        },

        isBetween: function (from, to, units) {
            return this.isAfter(from, units) && this.isBefore(to, units);
        },

        isSame: function (input, units) {
            var inputMs;
            units = normalizeUnits(units || 'millisecond');
            if (units === 'millisecond') {
                input = moment.isMoment(input) ? input : moment(input);
                return +this === +input;
            } else {
                inputMs = +moment(input);
                return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units));
            }
        },

        min: deprecate(
                 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
                 function (other) {
                     other = moment.apply(null, arguments);
                     return other < this ? this : other;
                 }
         ),

        max: deprecate(
                'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
                function (other) {
                    other = moment.apply(null, arguments);
                    return other > this ? this : other;
                }
        ),

        zone : deprecate(
                'moment().zone is deprecated, use moment().utcOffset instead. ' +
                'https://github.com/moment/moment/issues/1779',
                function (input, keepLocalTime) {
                    if (input != null) {
                        if (typeof input !== 'string') {
                            input = -input;
                        }

                        this.utcOffset(input, keepLocalTime);

                        return this;
                    } else {
                        return -this.utcOffset();
                    }
                }
        ),

        // keepLocalTime = true means only change the timezone, without
        // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
        // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
        // +0200, so we adjust the time as needed, to be valid.
        //
        // Keeping the time actually adds/subtracts (one hour)
        // from the actual represented time. That is why we call updateOffset
        // a second time. In case it wants us to change the offset again
        // _changeInProgress == true case, then we have to adjust, because
        // there is no such time in the given timezone.
        utcOffset : function (input, keepLocalTime) {
            var offset = this._offset || 0,
                localAdjust;
            if (input != null) {
                if (typeof input === 'string') {
                    input = utcOffsetFromString(input);
                }
                if (Math.abs(input) < 16) {
                    input = input * 60;
                }
                if (!this._isUTC && keepLocalTime) {
                    localAdjust = this._dateUtcOffset();
                }
                this._offset = input;
                this._isUTC = true;
                if (localAdjust != null) {
                    this.add(localAdjust, 'm');
                }
                if (offset !== input) {
                    if (!keepLocalTime || this._changeInProgress) {
                        addOrSubtractDurationFromMoment(this,
                                moment.duration(input - offset, 'm'), 1, false);
                    } else if (!this._changeInProgress) {
                        this._changeInProgress = true;
                        moment.updateOffset(this, true);
                        this._changeInProgress = null;
                    }
                }

                return this;
            } else {
                return this._isUTC ? offset : this._dateUtcOffset();
            }
        },

        isLocal : function () {
            return !this._isUTC;
        },

        isUtcOffset : function () {
            return this._isUTC;
        },

        isUtc : function () {
            return this._isUTC && this._offset === 0;
        },

        zoneAbbr : function () {
            return this._isUTC ? 'UTC' : '';
        },

        zoneName : function () {
            return this._isUTC ? 'Coordinated Universal Time' : '';
        },

        parseZone : function () {
            if (this._tzm) {
                this.utcOffset(this._tzm);
            } else if (typeof this._i === 'string') {
                this.utcOffset(utcOffsetFromString(this._i));
            }
            return this;
        },

        hasAlignedHourOffset : function (input) {
            if (!input) {
                input = 0;
            }
            else {
                input = moment(input).utcOffset();
            }

            return (this.utcOffset() - input) % 60 === 0;
        },

        daysInMonth : function () {
            return daysInMonth(this.year(), this.month());
        },

        dayOfYear : function (input) {
            var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
            return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
        },

        quarter : function (input) {
            return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
        },

        weekYear : function (input) {
            var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
            return input == null ? year : this.add((input - year), 'y');
        },

        isoWeekYear : function (input) {
            var year = weekOfYear(this, 1, 4).year;
            return input == null ? year : this.add((input - year), 'y');
        },

        week : function (input) {
            var week = this.localeData().week(this);
            return input == null ? week : this.add((input - week) * 7, 'd');
        },

        isoWeek : function (input) {
            var week = weekOfYear(this, 1, 4).week;
            return input == null ? week : this.add((input - week) * 7, 'd');
        },

        weekday : function (input) {
            var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
            return input == null ? weekday : this.add(input - weekday, 'd');
        },

        isoWeekday : function (input) {
            // behaves the same as moment#day except
            // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
            // as a setter, sunday should belong to the previous week.
            return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
        },

        isoWeeksInYear : function () {
            return weeksInYear(this.year(), 1, 4);
        },

        weeksInYear : function () {
            var weekInfo = this.localeData()._week;
            return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
        },

        get : function (units) {
            units = normalizeUnits(units);
            return this[units]();
        },

        set : function (units, value) {
            var unit;
            if (typeof units === 'object') {
                for (unit in units) {
                    this.set(unit, units[unit]);
                }
            }
            else {
                units = normalizeUnits(units);
                if (typeof this[units] === 'function') {
                    this[units](value);
                }
            }
            return this;
        },

        // If passed a locale key, it will set the locale for this
        // instance.  Otherwise, it will return the locale configuration
        // variables for this instance.
        locale : function (key) {
            var newLocaleData;

            if (key === undefined) {
                return this._locale._abbr;
            } else {
                newLocaleData = moment.localeData(key);
                if (newLocaleData != null) {
                    this._locale = newLocaleData;
                }
                return this;
            }
        },

        lang : deprecate(
            'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
            function (key) {
                if (key === undefined) {
                    return this.localeData();
                } else {
                    return this.locale(key);
                }
            }
        ),

        localeData : function () {
            return this._locale;
        },

        _dateUtcOffset : function () {
            // On Firefox.24 Date#getTimezoneOffset returns a floating point.
            // https://github.com/moment/moment/pull/1871
            return -Math.round(this._d.getTimezoneOffset() / 15) * 15;
        }

    });

    function rawMonthSetter(mom, value) {
        var dayOfMonth;

        // TODO: Move this out of here!
        if (typeof value === 'string') {
            value = mom.localeData().monthsParse(value);
            // TODO: Another silent failure?
            if (typeof value !== 'number') {
                return mom;
            }
        }

        dayOfMonth = Math.min(mom.date(),
                daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        return mom;
    }

    function rawGetter(mom, unit) {
        return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
    }

    function rawSetter(mom, unit, value) {
        if (unit === 'Month') {
            return rawMonthSetter(mom, value);
        } else {
            return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
        }
    }

    function makeAccessor(unit, keepTime) {
        return function (value) {
            if (value != null) {
                rawSetter(this, unit, value);
                moment.updateOffset(this, keepTime);
                return this;
            } else {
                return rawGetter(this, unit);
            }
        };
    }

    moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
    moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
    moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
    // Setting the hour should keep the time, because the user explicitly
    // specified which hour he wants. So trying to maintain the same hour (in
    // a new timezone) makes sense. Adding/subtracting hours does not follow
    // this rule.
    moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
    // moment.fn.month is defined separately
    moment.fn.date = makeAccessor('Date', true);
    moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true));
    moment.fn.year = makeAccessor('FullYear', true);
    moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true));

    // add plural methods
    moment.fn.days = moment.fn.day;
    moment.fn.months = moment.fn.month;
    moment.fn.weeks = moment.fn.week;
    moment.fn.isoWeeks = moment.fn.isoWeek;
    moment.fn.quarters = moment.fn.quarter;

    // add aliased format methods
    moment.fn.toJSON = moment.fn.toISOString;

    // alias isUtc for dev-friendliness
    moment.fn.isUTC = moment.fn.isUtc;

    /************************************
        Duration Prototype
    ************************************/


    function daysToYears (days) {
        // 400 years have 146097 days (taking into account leap year rules)
        return days * 400 / 146097;
    }

    function yearsToDays (years) {
        // years * 365 + absRound(years / 4) -
        //     absRound(years / 100) + absRound(years / 400);
        return years * 146097 / 400;
    }

    extend(moment.duration.fn = Duration.prototype, {

        _bubble : function () {
            var milliseconds = this._milliseconds,
                days = this._days,
                months = this._months,
                data = this._data,
                seconds, minutes, hours, years = 0;

            // The following code bubbles up values, see the tests for
            // examples of what that means.
            data.milliseconds = milliseconds % 1000;

            seconds = absRound(milliseconds / 1000);
            data.seconds = seconds % 60;

            minutes = absRound(seconds / 60);
            data.minutes = minutes % 60;

            hours = absRound(minutes / 60);
            data.hours = hours % 24;

            days += absRound(hours / 24);

            // Accurately convert days to years, assume start from year 0.
            years = absRound(daysToYears(days));
            days -= absRound(yearsToDays(years));

            // 30 days to a month
            // TODO (iskren): Use anchor date (like 1st Jan) to compute this.
            months += absRound(days / 30);
            days %= 30;

            // 12 months -> 1 year
            years += absRound(months / 12);
            months %= 12;

            data.days = days;
            data.months = months;
            data.years = years;
        },

        abs : function () {
            this._milliseconds = Math.abs(this._milliseconds);
            this._days = Math.abs(this._days);
            this._months = Math.abs(this._months);

            this._data.milliseconds = Math.abs(this._data.milliseconds);
            this._data.seconds = Math.abs(this._data.seconds);
            this._data.minutes = Math.abs(this._data.minutes);
            this._data.hours = Math.abs(this._data.hours);
            this._data.months = Math.abs(this._data.months);
            this._data.years = Math.abs(this._data.years);

            return this;
        },

        weeks : function () {
            return absRound(this.days() / 7);
        },

        valueOf : function () {
            return this._milliseconds +
              this._days * 864e5 +
              (this._months % 12) * 2592e6 +
              toInt(this._months / 12) * 31536e6;
        },

        humanize : function (withSuffix) {
            var output = relativeTime(this, !withSuffix, this.localeData());

            if (withSuffix) {
                output = this.localeData().pastFuture(+this, output);
            }

            return this.localeData().postformat(output);
        },

        add : function (input, val) {
            // supports only 2.0-style add(1, 's') or add(moment)
            var dur = moment.duration(input, val);

            this._milliseconds += dur._milliseconds;
            this._days += dur._days;
            this._months += dur._months;

            this._bubble();

            return this;
        },

        subtract : function (input, val) {
            var dur = moment.duration(input, val);

            this._milliseconds -= dur._milliseconds;
            this._days -= dur._days;
            this._months -= dur._months;

            this._bubble();

            return this;
        },

        get : function (units) {
            units = normalizeUnits(units);
            return this[units.toLowerCase() + 's']();
        },

        as : function (units) {
            var days, months;
            units = normalizeUnits(units);

            if (units === 'month' || units === 'year') {
                days = this._days + this._milliseconds / 864e5;
                months = this._months + daysToYears(days) * 12;
                return units === 'month' ? months : months / 12;
            } else {
                // handle milliseconds separately because of floating point math errors (issue #1867)
                days = this._days + Math.round(yearsToDays(this._months / 12));
                switch (units) {
                    case 'week': return days / 7 + this._milliseconds / 6048e5;
                    case 'day': return days + this._milliseconds / 864e5;
                    case 'hour': return days * 24 + this._milliseconds / 36e5;
                    case 'minute': return days * 24 * 60 + this._milliseconds / 6e4;
                    case 'second': return days * 24 * 60 * 60 + this._milliseconds / 1000;
                    // Math.floor prevents floating point math errors here
                    case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + this._milliseconds;
                    default: throw new Error('Unknown unit ' + units);
                }
            }
        },

        lang : moment.fn.lang,
        locale : moment.fn.locale,

        toIsoString : deprecate(
            'toIsoString() is deprecated. Please use toISOString() instead ' +
            '(notice the capitals)',
            function () {
                return this.toISOString();
            }
        ),

        toISOString : function () {
            // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
            var years = Math.abs(this.years()),
                months = Math.abs(this.months()),
                days = Math.abs(this.days()),
                hours = Math.abs(this.hours()),
                minutes = Math.abs(this.minutes()),
                seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);

            if (!this.asSeconds()) {
                // this is the same as C#'s (Noda) and python (isodate)...
                // but not other JS (goog.date)
                return 'P0D';
            }

            return (this.asSeconds() < 0 ? '-' : '') +
                'P' +
                (years ? years + 'Y' : '') +
                (months ? months + 'M' : '') +
                (days ? days + 'D' : '') +
                ((hours || minutes || seconds) ? 'T' : '') +
                (hours ? hours + 'H' : '') +
                (minutes ? minutes + 'M' : '') +
                (seconds ? seconds + 'S' : '');
        },

        localeData : function () {
            return this._locale;
        },

        toJSON : function () {
            return this.toISOString();
        }
    });

    moment.duration.fn.toString = moment.duration.fn.toISOString;

    function makeDurationGetter(name) {
        moment.duration.fn[name] = function () {
            return this._data[name];
        };
    }

    for (i in unitMillisecondFactors) {
        if (hasOwnProp(unitMillisecondFactors, i)) {
            makeDurationGetter(i.toLowerCase());
        }
    }

    moment.duration.fn.asMilliseconds = function () {
        return this.as('ms');
    };
    moment.duration.fn.asSeconds = function () {
        return this.as('s');
    };
    moment.duration.fn.asMinutes = function () {
        return this.as('m');
    };
    moment.duration.fn.asHours = function () {
        return this.as('h');
    };
    moment.duration.fn.asDays = function () {
        return this.as('d');
    };
    moment.duration.fn.asWeeks = function () {
        return this.as('weeks');
    };
    moment.duration.fn.asMonths = function () {
        return this.as('M');
    };
    moment.duration.fn.asYears = function () {
        return this.as('y');
    };

    /************************************
        Default Locale
    ************************************/


    // Set default locale, other locale will inherit from English.
    moment.locale('en', {
        ordinalParse: /\d{1,2}(th|st|nd|rd)/,
        ordinal : function (number) {
            var b = number % 10,
                output = (toInt(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });

    /* EMBED_LOCALES */

    /************************************
        Exposing Moment
    ************************************/

    function makeGlobal(shouldDeprecate) {
        /*global ender:false */
        if (typeof ender !== 'undefined') {
            return;
        }
        oldGlobalMoment = globalScope.moment;
        if (shouldDeprecate) {
            globalScope.moment = deprecate(
                    'Accessing Moment through the global scope is ' +
                    'deprecated, and will be removed in an upcoming ' +
                    'release.',
                    moment);
        } else {
            globalScope.moment = moment;
        }
    }

    // CommonJS module is defined
    if (hasModule) {
        module.exports = moment;
    } else if (typeof define === 'function' && define.amd) {
        define(function (require, exports, module) {
            if (module.config && module.config() && module.config().noGlobal === true) {
                // release the global variable
                globalScope.moment = oldGlobalMoment;
            }

            return moment;
        });
        makeGlobal(true);
    } else {
        makeGlobal();
    }
}).call(this);
(function() {
  $j(function() {
    return $j(document).on('page:change', function() {
      if (window.ga != null) {
        ga('set', 'location', location.href.split('#')[0]);
        return ga('send', 'pageview', {
          "title": document.title
        });
      }
    });
  });

}).call(this);
/*!
 * jQuery blockUI plugin
 * Version 2.56.0-2013.01.31
 * @requires jQuery v1.7 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2013 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */


;(function() {
"use strict";

	function setup($) {
		$.fn._fadeIn = $.fn.fadeIn;

		var noOp = $.noop || function() {};

		// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
		// retarded userAgent strings on Vista)
		var msie = /MSIE/.test(navigator.userAgent);
		var ie6  = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent);
		var mode = document.documentMode || 0;
		// var setExpr = msie && (($.browser.version < 8 && !mode) || mode < 8);
		var setExpr = $.isFunction( document.createElement('div').style.setExpression );

		// global $ methods for blocking/unblocking the entire page
		$.blockUI   = function(opts) { install(window, opts); };
		$.unblockUI = function(opts) { remove(window, opts); };

		// convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
		$.growlUI = function(title, message, timeout, onClose) {
			var $m = $('<div class="growlUI"></div>');
			if (title) $m.append('<h1>'+title+'</h1>');
			if (message) $m.append('<h2>'+message+'</h2>');
			if (timeout === undefined) timeout = 3000;
			$.blockUI({
				message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
				timeout: timeout, showOverlay: false,
				onUnblock: onClose,
				css: $.blockUI.defaults.growlCSS
			});
		};

		// plugin method for blocking element content
		$.fn.block = function(opts) {
			var fullOpts = $.extend({}, $.blockUI.defaults, opts || {});
			this.each(function() {
				var $el = $(this);
				if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked'))
					return;
				$el.unblock({ fadeOut: 0 });
			});

			return this.each(function() {
				if ($.css(this,'position') == 'static') {
					this.style.position = 'relative';
					$(this).data('blockUI.static', true);
				}
				this.style.zoom = 1; // force 'hasLayout' in ie
				install(this, opts);
			});
		};

		// plugin method for unblocking element content
		$.fn.unblock = function(opts) {
			return this.each(function() {
				remove(this, opts);
			});
		};

		$.blockUI.version = 2.56; // 2nd generation blocking at no extra cost!

		// override these in your code to change the default behavior and style
		$.blockUI.defaults = {
			// message displayed when blocking (use null for no message)
			message:  '<h1>Please wait...</h1>',

			title: null,		// title string; only used when theme == true
			draggable: true,	// only used when theme == true (requires jquery-ui.js to be loaded)

			theme: false, // set to true to use with jQuery UI themes

			// styles for the message when blocking; if you wish to disable
			// these and use an external stylesheet then do this in your code:
			// $.blockUI.defaults.css = {};
			css: {
				padding:	0,
				margin:		0,
				width:		'30%',
				top:		'40%',
				left:		'35%',
				textAlign:	'center',
				color:		'#000',
				border:		'3px solid #aaa',
				backgroundColor:'#fff',
				cursor:		'wait'
			},

			// minimal style set used when themes are used
			themedCSS: {
				width:	'30%',
				top:	'40%',
				left:	'35%'
			},

			// styles for the overlay
			overlayCSS:  {
				backgroundColor:	'#000',
				opacity:			0.6,
				cursor:				'wait'
			},

			// style to replace wait cursor before unblocking to correct issue
			// of lingering wait cursor
			cursorReset: 'default',

			// styles applied when using $.growlUI
			growlCSS: {
				width:		'350px',
				top:		'10px',
				left:		'',
				right:		'10px',
				border:		'none',
				padding:	'5px',
				opacity:	0.6,
				cursor:		'default',
				color:		'#fff',
				backgroundColor: '#000',
				'-webkit-border-radius':'10px',
				'-moz-border-radius':	'10px',
				'border-radius':		'10px'
			},

			// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
			// (hat tip to Jorge H. N. de Vasconcelos)
			/*jshint scripturl:true */
			iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',

			// force usage of iframe in non-IE browsers (handy for blocking applets)
			forceIframe: false,

			// z-index for the blocking overlay
			baseZ: 1000,

			// set these to true to have the message automatically centered
			centerX: true, // <-- only effects element blocking (page block controlled via css above)
			centerY: true,

			// allow body element to be stetched in ie6; this makes blocking look better
			// on "short" pages.  disable if you wish to prevent changes to the body height
			allowBodyStretch: true,

			// enable if you want key and mouse events to be disabled for content that is blocked
			bindEvents: true,

			// be default blockUI will supress tab navigation from leaving blocking content
			// (if bindEvents is true)
			constrainTabKey: true,

			// fadeIn time in millis; set to 0 to disable fadeIn on block
			fadeIn:  200,

			// fadeOut time in millis; set to 0 to disable fadeOut on unblock
			fadeOut:  400,

			// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
			timeout: 0,

			// disable if you don't want to show the overlay
			showOverlay: true,

			// if true, focus will be placed in the first available input field when
			// page blocking
			focusInput: true,

			// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
			// no longer needed in 2012
			// applyPlatformOpacityRules: true,

			// callback method invoked when fadeIn has completed and blocking message is visible
			onBlock: null,

			// callback method invoked when unblocking has completed; the callback is
			// passed the element that has been unblocked (which is the window object for page
			// blocks) and the options that were passed to the unblock call:
			//	onUnblock(element, options)
			onUnblock: null,

			// callback method invoked when the overlay area is clicked.
			// setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used.
			onOverlayClick: null,

			// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
			quirksmodeOffsetHack: 4,

			// class name of the message block
			blockMsgClass: 'blockMsg',

			// if it is already blocked, then ignore it (don't unblock and reblock)
			ignoreIfBlocked: false
		};

		// private data and functions follow...

		var pageBlock = null;
		var pageBlockEls = [];

		function install(el, opts) {
			var css, themedCSS;
			var full = (el == window);
			var msg = (opts && opts.message !== undefined ? opts.message : undefined);
			opts = $.extend({}, $.blockUI.defaults, opts || {});

			if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked'))
				return;

			opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
			css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
			if (opts.onOverlayClick)
				opts.overlayCSS.cursor = 'pointer';

			themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
			msg = msg === undefined ? opts.message : msg;

			// remove the current block (if there is one)
			if (full && pageBlock)
				remove(window, {fadeOut:0});

			// if an existing element is being used as the blocking content then we capture
			// its current place in the DOM (and current display style) so we can restore
			// it when we unblock
			if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
				var node = msg.jquery ? msg[0] : msg;
				var data = {};
				$(el).data('blockUI.history', data);
				data.el = node;
				data.parent = node.parentNode;
				data.display = node.style.display;
				data.position = node.style.position;
				if (data.parent)
					data.parent.removeChild(node);
			}

			$(el).data('blockUI.onUnblock', opts.onUnblock);
			var z = opts.baseZ;

			// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
			// layer1 is the iframe layer which is used to supress bleed through of underlying content
			// layer2 is the overlay layer which has opacity and a wait cursor (by default)
			// layer3 is the message content that is displayed while blocking
			var lyr1, lyr2, lyr3, s;
			if (msie || opts.forceIframe)
				lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>');
			else
				lyr1 = $('<div class="blockUI" style="display:none"></div>');

			if (opts.theme)
				lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>');
			else
				lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');

			if (opts.theme && full) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">';
				if ( opts.title ) {
					s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
				}
				s += '<div class="ui-widget-content ui-dialog-content"></div>';
				s += '</div>';
			}
			else if (opts.theme) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">';
				if ( opts.title ) {
					s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
				}  
				s += '<div class="ui-widget-content ui-dialog-content"></div>';
				s += '</div>';
			}
			else if (full) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>';
			}
			else {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>';
			}
			lyr3 = $(s);

			// if we have a message, style it
			if (msg) {
				if (opts.theme) {
					lyr3.css(themedCSS);
					lyr3.addClass('ui-widget-content');
				}
				else
					lyr3.css(css);
			}

			// style the overlay
			if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/)
				lyr2.css(opts.overlayCSS);
			lyr2.css('position', full ? 'fixed' : 'absolute');

			// make iframe layer transparent in IE
			if (msie || opts.forceIframe)
				lyr1.css('opacity',0.0);

			//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
			var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
			$.each(layers, function() {
				this.appendTo($par);
			});

			if (opts.theme && opts.draggable && $.fn.draggable) {
				lyr3.draggable({
					handle: '.ui-dialog-titlebar',
					cancel: 'li'
				});
			}

			// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
			var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0);
			if (ie6 || expr) {
				// give body 100% height
				if (full && opts.allowBodyStretch && $.support.boxModel)
					$('html,body').css('height','100%');

				// fix ie6 issue when blocked element has a border width
				if ((ie6 || !$.support.boxModel) && !full) {
					var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
					var fixT = t ? '(0 - '+t+')' : 0;
					var fixL = l ? '(0 - '+l+')' : 0;
				}

				// simulate fixed position
				$.each(layers, function(i,o) {
					var s = o[0].style;
					s.position = 'absolute';
					if (i < 2) {
						if (full)
							s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"');
						else
							s.setExpression('height','this.parentNode.offsetHeight + "px"');
						if (full)
							s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"');
						else
							s.setExpression('width','this.parentNode.offsetWidth + "px"');
						if (fixL) s.setExpression('left', fixL);
						if (fixT) s.setExpression('top', fixT);
					}
					else if (opts.centerY) {
						if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
						s.marginTop = 0;
					}
					else if (!opts.centerY && full) {
						var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0;
						var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
						s.setExpression('top',expression);
					}
				});
			}

			// show the message
			if (msg) {
				if (opts.theme)
					lyr3.find('.ui-widget-content').append(msg);
				else
					lyr3.append(msg);
				if (msg.jquery || msg.nodeType)
					$(msg).show();
			}

			if ((msie || opts.forceIframe) && opts.showOverlay)
				lyr1.show(); // opacity is zero
			if (opts.fadeIn) {
				var cb = opts.onBlock ? opts.onBlock : noOp;
				var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
				var cb2 = msg ? cb : noOp;
				if (opts.showOverlay)
					lyr2._fadeIn(opts.fadeIn, cb1);
				if (msg)
					lyr3._fadeIn(opts.fadeIn, cb2);
			}
			else {
				if (opts.showOverlay)
					lyr2.show();
				if (msg)
					lyr3.show();
				if (opts.onBlock)
					opts.onBlock();
			}

			// bind key and mouse events
			bind(1, el, opts);

			if (full) {
				pageBlock = lyr3[0];
				pageBlockEls = $(':input:enabled:visible',pageBlock);
				if (opts.focusInput)
					setTimeout(focus, 20);
			}
			else
				center(lyr3[0], opts.centerX, opts.centerY);

			if (opts.timeout) {
				// auto-unblock
				var to = setTimeout(function() {
					if (full)
						$.unblockUI(opts);
					else
						$(el).unblock(opts);
				}, opts.timeout);
				$(el).data('blockUI.timeout', to);
			}
		}

		// remove the block
		function remove(el, opts) {
			var full = (el == window);
			var $el = $(el);
			var data = $el.data('blockUI.history');
			var to = $el.data('blockUI.timeout');
			if (to) {
				clearTimeout(to);
				$el.removeData('blockUI.timeout');
			}
			opts = $.extend({}, $.blockUI.defaults, opts || {});
			bind(0, el, opts); // unbind events

			if (opts.onUnblock === null) {
				opts.onUnblock = $el.data('blockUI.onUnblock');
				$el.removeData('blockUI.onUnblock');
			}

			var els;
			if (full) // crazy selector to handle odd field errors in ie6/7
				els = $('body').children().filter('.blockUI').add('body > .blockUI');
			else
				els = $el.find('>.blockUI');

			// fix cursor issue
			if ( opts.cursorReset ) {
				if ( els.length > 1 )
					els[1].style.cursor = opts.cursorReset;
				if ( els.length > 2 )
					els[2].style.cursor = opts.cursorReset;
			}

			if (full)
				pageBlock = pageBlockEls = null;

			if (opts.fadeOut) {
				els.fadeOut(opts.fadeOut);
				setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
			}
			else
				reset(els, data, opts, el);
		}

		// move blocking element back into the DOM where it started
		function reset(els,data,opts,el) {
			var $el = $(el);
			els.each(function(i,o) {
				// remove via DOM calls so we don't lose event handlers
				if (this.parentNode)
					this.parentNode.removeChild(this);
			});

			if (data && data.el) {
				data.el.style.display = data.display;
				data.el.style.position = data.position;
				if (data.parent)
					data.parent.appendChild(data.el);
				$el.removeData('blockUI.history');
			}

			if ($el.data('blockUI.static')) {
				$el.css('position', 'static'); // #22
			}

			if (typeof opts.onUnblock == 'function')
				opts.onUnblock(el,opts);

			// fix issue in Safari 6 where block artifacts remain until reflow
			var body = $(document.body), w = body.width(), cssW = body[0].style.width;
			body.width(w-1).width(w);
			body[0].style.width = cssW;
		}

		// bind/unbind the handler
		function bind(b, el, opts) {
			var full = el == window, $el = $(el);

			// don't bother unbinding if there is nothing to unbind
			if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
				return;

			$el.data('blockUI.isBlocked', b);

			// don't bind events when overlay is not in use or if bindEvents is false
			if (!opts.bindEvents || (b && !opts.showOverlay))
				return;

			// bind anchors and inputs for mouse and key events
			var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove';
			if (b)
				$(document).bind(events, opts, handler);
			else
				$(document).unbind(events, handler);

		// former impl...
		//		var $e = $('a,:input');
		//		b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
		}

		// event handler to suppress keyboard/mouse events when blocking
		function handler(e) {
			// allow tab navigation (conditionally)
			if (e.keyCode && e.keyCode == 9) {
				if (pageBlock && e.data.constrainTabKey) {
					var els = pageBlockEls;
					var fwd = !e.shiftKey && e.target === els[els.length-1];
					var back = e.shiftKey && e.target === els[0];
					if (fwd || back) {
						setTimeout(function(){focus(back);},10);
						return false;
					}
				}
			}
			var opts = e.data;
			var target = $(e.target);
			if (target.hasClass('blockOverlay') && opts.onOverlayClick)
				opts.onOverlayClick();

			// allow events within the message content
			if (target.parents('div.' + opts.blockMsgClass).length > 0)
				return true;

			// allow events for content that is not being blocked
			return target.parents().children().filter('div.blockUI').length === 0;
		}

		function focus(back) {
			if (!pageBlockEls)
				return;
			var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
			if (e)
				e.focus();
		}

		function center(el, x, y) {
			var p = el.parentNode, s = el.style;
			var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
			var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
			if (x) s.left = l > 0 ? (l+'px') : '0';
			if (y) s.top  = t > 0 ? (t+'px') : '0';
		}

		function sz(el, p) {
			return parseInt($.css(el,p),10)||0;
		}

	}


	/*global define:true */
	if (typeof define === 'function' && define.amd && define.amd.jQuery) {
		define(['jquery'], setup);
	} else {
		setup(jQuery);
	}

})();
(function() {
  window.block_payment_info = function(payment_info_div_id) {
    var payment_info_div;
    payment_info_div = $j('#' + payment_info_div_id);
    payment_info_div.block();
    return payment_info_div.attr('original-title', "The payment information cannot be updated because charges have been processed in the institution's financial system or this feature has been disabled for your role.");
  };

  if ($j.blockUI !== void 0) {
    $j.blockUI.defaults.overlayCSS.opacity = 0.07;
    $j.blockUI.defaults.overlayCSS.cursor = 'default';
    $j.blockUI.defaults.message = null;
  }

}).call(this);
(function() {
  var clear_chart_field_errors_js, startTimer, tipsy_tip_delay_in, tipsy_tip_delay_out;

  Array.prototype.unique = function() {
    var j, key, output, ref;
    output = {};
    for (key = j = 0, ref = this.length; 0 <= ref ? j < ref : j > ref; key = 0 <= ref ? ++j : --j) {
      output[this[key]] = this[key];
    }
    return Object.keys(output);
  };

  Date.prototype.strftime = (function() {
    var strftime, zeroPad;
    strftime = function(format) {
      var date;
      date = this;
      return (format + "").replace(/%([a-zA-Z])/g, function(m, f) {
        var formatter;
        formatter = Date.formats && Date.formats[f];
        if (typeof formatter === "function") {
          return formatter.call(Date.formats, date);
        } else if (typeof formatter === "string") {
          return date.strftime(formatter);
        }
        return f;
      });
    };
    zeroPad = function(num) {
      return (+num < 10 ? "0" : "") + num;
    };
    Date.formats = {
      d: function(date) {
        return zeroPad(date.getDate());
      },
      m: function(date) {
        return zeroPad(date.getMonth() + 1);
      },
      y: function(date) {
        return zeroPad(date.getYear() % 100);
      },
      Y: function(date) {
        return date.getFullYear();
      },
      F: "%d-%m-%Y",
      D: "%m/%d/%y"
    };
    return strftime;
  })();

  tipsy_tip_delay_in = 500;

  tipsy_tip_delay_out = 0;

  $j(function() {
    var default_search_text, no_access_message, selector, show_magnific_popup;
    $j(document).on('focusin', function(e) {
      if ($j(e.target).closest('.mce-window').length) {
        e.stopImmediatePropagation();
      }
      return true;
    });
    $j('input.live_search_pi').livequery(function() {
      var url;
      url = $j('.live_search_pi').data('url');
      return $j(this).select2({
        placeholder: "Start typing a name...",
        minimumInputLength: 2,
        width: 'element',
        ajax: {
          url: url,
          type: 'GET',
          dataType: "json",
          data: function(term) {
            return {
              term: term
            };
          },
          results: function(data) {
            return {
              results: data
            };
          }
        },
        escapeMarkup: function(m) {
          return m;
        },
        dropdownAutoWidth: true
      });
    });
    $j('.reservation_service_item_select').livequery('change', function() {
      var items, link, new_url, requests_label, service_event_id, service_item_id;
      link = $j('#event_view_service_project_link');
      service_item_id = $j(this).val();
      service_event_id = $j(this).data('service_event_id');
      if (service_item_id > 0) {
        link.toggleClass('hidden', false);
        items = $j('#service_project_id').data('items');
        if (items['animal_requests'] && items['animal_requests'].indexOf(service_item_id) > -1) {
          requests_label = 'animal_requests';
        } else {
          requests_label = 'requests';
        }
        new_url = link.data('company_url') + '?tab=' + requests_label + '&sid=' + service_item_id;
        link.attr('href', new_url);
        showSpinner($j('#split_form_wrapper span.spinner'));
        return $j.ajax('/service_event/assign_to_ongoing_project', {
          type: 'POST',
          data: {
            service_project_id: service_item_id,
            service_event_id: service_event_id
          },
          complete: function() {
            return $j('#split_form_wrapper').load("/split_payment/render_split_form", {
              klass: 'ServiceReservation',
              id: service_event_id
            });
          }
        });
      } else {
        return link.toggleClass('hidden', true);
      }
    });
    $j.extend($j.expr[":"], {
      "containsIN": function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
      }
    });
    $j(' .tags_input').livequery(function() {
      return $j(this).tagit({
        availableTags: $j(this).data('available_tags'),
        afterTagRemoved: (function(_this) {
          return function(event, tag) {
            return $j.ajax($j(_this).data('url'), {
              type: 'POST',
              data: {
                tag: tag.tagLabel,
                type: 'remove_tag'
              }
            });
          };
        })(this),
        afterTagAdded: (function(_this) {
          return function(event, tag) {
            if (!tag.duringInitialization) {
              return $j.ajax($j(_this).data('url'), {
                type: 'POST',
                data: {
                  tag: tag.tagLabel,
                  type: 'add_tag'
                }
              });
            }
          };
        })(this)
      });
    });
    $j.fn.vals = function() {
      var val;
      val = $j(this).map(function() {
        return $j(this).val();
      });
      return val.get();
    };
    ({
      cutHex: function(h) {
        if (h.charAt(0) === "#") {
          return h.substring(1, 7);
        } else {
          return h;
        }
      },
      getFontColor: function(background_color) {
        var b, brightness, g, r, ref;
        g = parseInt((cutHex(background_color)).substring(0, 2), 16);
        r = parseInt((cutHex(background_color)).substring(2, 4), 16);
        b = parseInt((cutHex(background_color)).substring(4, 6), 16);
        brightness = (0.2126 * r) + (0.7152 * g) + (0.0722 * b);
        return (ref = brightness > 100) != null ? ref : {
          "#000000": "#FFFFFF"
        };
      }
    });
    $j('input[data-select2_ajax]').livequery(function() {
      var $this;
      $this = $j(this);
      return $this.select2({
        placeholder: $this.data('placeholder'),
        minimumInputLength: 2,
        initSelection: function(element, callback) {
          return callback({
            id: $this.val(),
            text: $this.data('val')
          });
        },
        ajax: {
          url: $this.data('url'),
          dataType: 'json',
          data: function(term) {
            return {
              term: term
            };
          },
          results: function(data) {
            return {
              results: data
            };
          }
        }
      });
    });
    $j('.j-dropdown').livequery(function() {
      var $this;
      $this = $j(this);
      return $this.on('click', function(event) {
        var $menu;
        $menu = $this.find('.j-menu');
        $menu.css('left', '1805px');
        $menu.css('top', $this.position().top + parseInt($this.css('height').replace('px', '')) + (parseInt($this.css('padding').replace('px', '')) * 2) + 2);
        return $menu.toggleClass('hidden');
      });
    });
    $j('select.j-select2').livequery(function() {
      var $this, data;
      $this = $j(this);
      data = $this.data();
      data.matcher = function(term, optText, els) {
        var allText;
        allText = optText + els[0].parentNode.getAttribute("label") || "";
        return ("" + allText).toUpperCase().indexOf(("" + term).toUpperCase()) >= 0;
      };
      return $this.select2(data);
    });
    $j("a[remote=true]").live("click", function(event) {
      var self;
      event.preventDefault();
      self = $j(this);
      return $j.ajax(self.prop("href"), {
        type: "GET",
        dataType: "script"
      });
    });
    $j(' .best_in_place').livequery(function() {
      if ($j(this).html().length === 0) {
        return $j(this).html('click to edit');
      }
    });
    $j('textarea[data-tinymce]').livequery(function() {
      var skip;
      skip = Boolean($j(this).data('skip-tinymce-live-update'));
      if (!skip) {
        return resetTextareaToTinyMCE($j(this).prop('id'));
      }
    });
    $j(' .toggleable_header').livequery('click', function(ev) {
      $j(this).next().slideToggle('slow');
      $j(this).toggleClass('expanded');
      return ev.preventDefault();
    });
    $j('input[data-toggle]').live('change', function(event) {
      var $target, $this;
      $this = $j(this);
      $target = $j("#" + $this.data("target"));
      if ($this.attr("checked")) {
        return $target.removeClass("hidden");
      } else {
        return $target.addClass("hidden");
      }
    });
    $j("input[data-maxvalue]").live('input propertychange', function(event) {
      var $this, maxvalue, value;
      $this = $j(this);
      value = Number($this.val());
      maxvalue = Number($this.data("maxvalue"));
      if (maxvalue > 0 && value > maxvalue) {
        return $this.val(maxvalue);
      }
    });
    $j('input.date').livequery(function() {
      var $this, options;
      $this = $j(this);
      options = {
        scrollInput: false
      };
      if ($this.data('change_year_and_month')) {
        options['changeMonth'] = true;
        options['changeYear'] = true;
      }
      if ($this.data('maxdate')) {
        options['maxDate'] = Date.parse($this.data('maxdate'));
      }
      if ($this.data('format')) {
        options['dateFormat'] = $this.data('format');
      }
      if ($this.hasClass('notime')) {
        options.timepicker = false;
        options.format = $this.data('format') || 'F d, Y';
      }
      options['yearRange'] = "-100:+100";
      options.onSelect = function(dateText) {
        return $this.trigger('change');
      };
      return $this.datetimepicker(options);
    });
    $j('input.time').livequery(function() {
      var opts, self;
      self = $j(this);
      opts = {
        scrollInput: false,
        showDuration: true,
        scrollDefaultNow: true,
        timeFormat: self.data("format") || "H:i",
        step: self.data("step") || 10,
        forceRoundTime: self.data("round") || false,
        closeOnWindowScroll: self.data('onscroll') || true
      };
      return self.datetimepicker(opts);
    });
    $j('.date_toggle').livequery('click', function(ev) {
      var input;
      ev.preventDefault();
      input = $j(this).prevAll('input.date').first();
      if (input.datetimepicker('widget').is(':visible')) {
        return input.datetimepicker('hide');
      } else {
        return input.datetimepicker('show');
      }
    });
    $j('#service_event_form .timepart:not(.editable)').livequery(function() {
      return $j(this).keydown(function(event) {
        return event.preventDefault();
      });
    });
    $j('.datepair').livequery(function() {
      var container, e_date, e_time, s_date, s_time;
      container = $j(this);
      s_date = container.find('.start.datepart');
      s_time = container.find('.start.timepart');
      e_date = container.find('.end.datepart');
      e_time = container.find('.end.timepart');
      return $j(this).datepair({
        dateClass: 'datepart',
        timeClass: 'timepart',
        updateTime: function(input, v) {
          var end_moment, start_moment;
          start_moment = moment((s_date.val()) + " " + (s_time.val()));
          end_moment = moment((e_date.val()) + " " + (e_time.val()));
          if ($j(input).hasClass('end')) {
            if (end_moment.isSame(start_moment, 'day')) {
              return input.value = moment(v).format('LT');
            }
          } else {
            return input.value = moment(v).format('LT');
          }
        },
        parseDate: function(input) {
          var val;
          val = $j(input).val();
          if (!val) {
            return null;
          }
          return moment.utc(val).toDate();
        },
        updateDate: function(input, v) {
          var end_moment, start_moment;
          start_moment = moment((s_date.val()) + " " + (s_time.val()));
          end_moment = moment((e_date.val()) + " " + (e_time.val()));
          if (start_moment.isSame(end_moment, 'day') || start_moment.isAfter(end_moment)) {
            return $j(input).val(moment.utc(v).format('ll'));
          }
        }
      });
    });
    $j("body").on('mouseenter', '.best_in_place', function() {
      if (!$j(this).data('best_in_placed')) {
        $j(this).best_in_place();
        return $j(this).data('best_in_placed', true);
      }
    });
    $j('form.spinnable').live('ajax:beforeSend', function() {
      var submit_el;
      submit_el = $j(this).find('input[type=submit], input[type=image]');
      return showSpinner(submit_el);
    });
    $j('body').on('best_in_place:activate', function() {
      return Tipped.refresh('*');
    });
    $j('body').on('best_in_place:deactivate', function() {
      return Tipped.refresh('*');
    });
    $j('body').on('best_in_place:error', '.best_in_place_alert_on_error', function(event, request, error) {
      var o;
      event.stopImmediatePropagation();
      o = (function() {
        try {
          return JSON.parse(request.responseText);
        } catch (error1) {}
      })();
      if (Array.isArray(o)) {
        return alert(o.join("\n"));
      } else {
        return alert('Unable to make the change.');
      }
    });
    $j('form.spinnable').live('ajax:complete', function() {
      var submit_el;
      submit_el = $j(this).find('input[type=submit], input[type=image]');
      return hideSpinner(submit_el);
    });
    $j(' a.spinnable').live('ajax:beforeSend', function() {
      return showSpinner($j(this));
    });
    $j(' a.spinnable').live('ajax:complete', function() {
      return hideSpinner($j(this));
    });
    $j('[data-ajax-target]').data('type', 'html').live('ajax:success', function(event, data) {
      return $j('#' + $j(this).data('ajax-target')).html(data);
    });
    $j('form.tiny-mce').live('submit', function() {
      var self;
      self = $j(this);
      tinyMCE.triggerSave(true, true);
      return unsetTextareaToTinyMCE(self.find('textarea[data-tinymce]'));
    });
    $j('form.tiny-mce').live('ajax:beforeSend', function() {
      var self;
      self = $j(this);
      tinyMCE.triggerSave(true, true);
      return unsetTextareaToTinyMCE(self.find('textarea[data-tinymce]'));
    });
    $j('button.submit_form_button').live('click', function(event) {
      var $target, $this;
      event.preventDefault();
      $this = $j(this);
      $target = $j("#" + ($this.data('target')));
      return $j.ajax($target.attr('action'), {
        dataType: 'script',
        type: $target.attr('method') || 'POST',
        data: $target.serialize(),
        beforeSend: function() {
          return showSpinner($this);
        },
        complete: function() {
          return hideSpinner($this);
        }
      });
    });
    $j(' .link_to_remote').live('click', function() {
      return $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function(xhr, settings) {
            $j(_this).trigger("ajax:beforeSend", [xhr, settings]);
            return showSpinner(_this);
          };
        })(this),
        complete: (function(_this) {
          return function(xhr, status) {
            $j(_this).trigger("ajax:complete", [xhr, status]);
            return hideSpinner(_this);
          };
        })(this),
        success: (function(_this) {
          return function(data, status, xhr) {
            return $j(_this).trigger("ajax:success", [data, status, xhr]);
          };
        })(this),
        error: (function(_this) {
          return function(xhr, status, error) {
            return $j(_this).trigger("ajax:error", [xhr, status, error]);
          };
        })(this)
      });
    });
    $j.fn.scrollTo = function() {
      $j('body').animate({
        scrollTop: $j(this).offset().top
      });
      return true;
    };
    $j.fn.reset = function() {
      $j(this).each(function() {
        return this.reset();
      });
      return this;
    };
    default_search_text = "Search cores and services...";
    $j("#search_box .search_text").val(default_search_text);
    $j("#search_box .search_text").focus(function() {
      $j(this).removeClass("highlighted");
      if ($j(this).val() === default_search_text) {
        return $j(this).val("");
      }
    });
    $j("#search_box .search_text").blur(function() {
      if ($j.trim($j(this).val()).length === 0) {
        $j(this).val(default_search_text);
        return $j(this).addClass("highlighted");
      }
    });
    $j("#search_box").submit(function() {
      var text_field;
      text_field = $j(this).find(".search_text");
      if ($j.trim(text_field.val()) === "Search...") {
        return text_field.val("");
      }
    });
    window.loadExpansion = function(obj, completed_cb) {
      var targetExpandable;
      targetExpandable = $j("#" + (obj.data("expandable")));
      if (obj.hasClass("expanded") && !obj.hasClass("folded")) {
        targetExpandable.hide();
        obj.addClass("folded");
        if (completed_cb) {
          return completed_cb(this);
        }
      } else if (obj.hasClass("folded")) {
        targetExpandable.show();
        obj.removeClass("folded");
        if (completed_cb) {
          return completed_cb(this);
        }
      } else {
        return $j.ajax(obj.attr("href"), {
          beforeSend: (function(_this) {
            return function() {
              return obj.find(".spinner").show();
            };
          })(this),
          complete: (function(_this) {
            return function(data) {
              var text;
              text = data.responseText || data;
              obj.addClass("expanded");
              targetExpandable.html(text).show();
              if (completed_cb) {
                completed_cb(_this);
              }
              return obj.find(".spinner").hide();
            };
          })(this)
        });
      }
    };
    $j("a.expandable").live("click", function() {
      loadExpansion($j(this));
      Tipped.refresh('*');
      return false;
    });
    $j(" .tipsy_tip").tipsy({
      gravity: $j.fn.tipsy.autoWE,
      live: true,
      html: true,
      opacity: 0.8,
      delayIn: tipsy_tip_delay_in,
      delayOut: tipsy_tip_delay_out,
      gcInterval: 1500
    });
    $j(" .tipsy_tip_NS").tipsy({
      gravity: $j.fn.tipsy.autoNS,
      live: true,
      html: true,
      opacity: 0.8,
      delayIn: tipsy_tip_delay_in,
      delayOut: tipsy_tip_delay_out,
      gcInterval: 1500
    });
    $j(" .tipsy_tip_east").tipsy({
      gravity: 'e',
      live: true,
      html: true,
      opacity: 0.8,
      delayIn: tipsy_tip_delay_in,
      delayOut: tipsy_tip_delay_out,
      gcInterval: 1500
    });
    $j(" .tipsy_tip_nohtml").tipsy({
      gravity: 'sw',
      live: true,
      html: true,
      opacity: 0.8,
      delayIn: tipsy_tip_delay_in,
      delayOut: tipsy_tip_delay_out,
      gcInterval: 1500
    });
    $j(" .jaccordion").livequery(function() {
      var $this, active;
      $this = $j(this);
      active = $this.data('active') || 0;
      $this.jaccordion({
        active: active,
        heightStyle: '100%',
        collapsible: true,
        activate: function(event, ui) {
          return Tipped.refresh('*');
        }
      });
      return Tipped.refresh("*");
    }, function() {
      if ($j(this).data('uiJaccordion')) {
        return $j(this).jaccordion("destroy");
      }
    });
    $j(" .datepicker_link").livequery(function() {
      return $j(this).datetimepicker({
        defaultDate: $j(this).data('default'),
        dateFormat: $j(this).data('date-format'),
        scrollInput: false
      });
    }, function() {
      return $j(this).datetimepicker("destroy");
    });
    window.temp_mce_id = 1;
    $j(" .email_body_disabled").livequery(function() {
      $j(this).attr('id', 'mce_editor_' + window.temp_mce_id);
      tinymce.execCommand('mceAddEditor', false, $j(this).attr('id'));
      tinyMCE.execCommand('mceFocus', false, $j(this).attr('id'));
      return window.temp_mce_id += 2;
    }, function() {
      tinyMCE.execCommand('mceFocus', false, $j(this).attr('id'));
      return tinymce.execCommand('mceRemoveEditor', false, $j(this).attr('id'));
    });
    $j(" .tabbed").livequery(function() {
      return $j(this).tabs({
        create: function() {
          return Tipped.refresh("*");
        },
        show: function() {
          return Tipped.refresh("*");
        }
      });
    }, function() {
      return $j(this).tabs("destroy");
    });
    if (window.TippedForIlab !== void 0) {
      TippedForIlab.initTipped();
    }
    $j('div.jquery_ajax_pagination a').live('click', function(event) {
      var data, submit_el, target, update_el;
      showSpinner($j(this));
      update_el = $j(this).parent().data('update');
      submit_el = $j(this).parent().data('submit');
      data = $j('#' + submit_el + ' :input').serializeArray();
      target = $j('#' + update_el);
      target.load($j(this).attr('href'), data, function() {
        return hideSpinner($j(this));
      });
      event.preventDefault();
      return false;
    });
    $j(' .left_menu_flyout').each(function() {
      return Tipped.create($j(this).uniqueId(), $j(this).data('flyoutUrl'), {
        ajax: true,
        hideOn: [
          {
            element: 'tooltip',
            event: 'mouseleave'
          }, {
            element: 'self',
            event: 'mouseleave'
          }
        ],
        hook: {
          target: 'rightmiddle',
          tooltip: 'leftbottom'
        }
      });
    });
    $j(" .prototip_link").live("click", function() {
      return false;
    });
    $j(" .simple_submit").live("click", function() {
      var data, form;
      if ($j(this).attr('disabled')) {
        return false;
      } else {
        form = $j(this).parents('form');
        data = form.serialize().replace(/\&_method=\w*/, '');
        $j.ajax(form.attr('action'), {
          type: 'POST',
          data: data,
          beforeSend: (function(_this) {
            return function(xhr) {
              xhr.setRequestHeader("Accept", "text/javascript");
              $j(_this).next().show();
              $j(_this).hide();
              if ($j(_this).data('api_validation_enabled')) {
                return window.blockPageOnExternalValidation();
              }
            };
          })(this),
          complete: (function(_this) {
            return function(response) {
              $j(_this).next().hide();
              return $j(_this).show();
            };
          })(this)
        });
        return false;
      }
    });
    $j(" .simple_close").live("click", function() {
      if ($j(this).attr('disabled')) {
        return false;
      } else {
        Tipped.hide('#service_item_' + $j(this).attr('id') + ' .tipped_target.spinnable');
        return false;
      }
    });
    $j(' .data_table').livequery(function() {
      var colWidths, columns, grid_settings, headers, settings, source, types;
      headers = $j(this).attr('headers').split(',');
      grid_settings = $j(this).attr('grid_settings');
      columns = [];
      if (grid_settings && (grid_settings !== "null" && grid_settings !== "{}" && grid_settings !== '""')) {
        settings = JSON.parse(grid_settings);
        types = settings.types;
        source = settings.options;
        colWidths = settings.col_widths;
        for (var i=0; i< source.length; i++ ){
         var type = types[i]
         if (type.match(/}/)){
           renderer = eval( type )
           columns.push({ renderer: renderer, source: source[i].split(','), options: { items: 30 } })
         } else if (type == 'date') {
           columns.push({ type: type,  dateFormat: 'MM/DD/YYYY', source: source[i].split(','), options: { items: 30 } })
         } else {
           columns.push({ type: type, source: source[i].split(','), options: { items: 30 } })
         }
       };
      } else {
        columns = [];
        for (var i=0; i< headers.length; i++ ){
         if (headers[i].match(/location/i))
           columns.push({ renderer: locationRenderer })
         else {
           type = 'text'
           columns.push({ type: type })
         }
       };
      }
      return $j(this).data('handsontable', new Handsontable(this, {
        minRows: 10,
        minCols: headers.length,
        maxCols: headers.length,
        startCols: headers.length,
        minSpareRows: 1,
        columns: columns,
        colWidths: colWidths,
        colHeaders: headers,
        rowHeaders: true,
        contextMenu: ["row_above", "row_below", "remove_row"],
        outsideClickDeselects: false,
        onchange: (function(_this) {
          return function() {
            return Tipped.refresh(_this);
          };
        })(this)
      }));
    });
    $j('.file_upload').livequery(function() {
      var $this, $title, uploader;
      $this = $j(this);
      $title = $this.attr('data-title');
      $title || ($title = "Upload a file");
      $j('.qq-upload-button:first', $this).css('width', '200px');
      $j('.qq-upload-button:first', $this).each(function() {
        return this.textContent = this.textContent.replace('Upload a file', $title);
      });
      uploader = new qq.FileUploader({
        element: this,
        action: $j(this).attr('action'),
        onComplete: (function(_this) {
          return function(id, file_name, responceJSON) {
            eval($j(_this).attr('callback'));
            return Tipped.refresh('*');
          };
        })(this)
      });
      return $j(this).data('file-upload-object', uploader);
    });
    true;
    $j('body').on('click', '.toggle:not(.ui)', function() {
      $j(this).parent().parent().next().slideToggle();
      return $j(this).toggleClass('expanded');
    });
    $j('body').on('click', '.bill_err_toggle', function() {
      $j(this).parent().next().slideToggle();
      return $j(this).toggleClass('expanded');
    });
    $j('body').on('click', '.simple_toggle', function() {
      $j(this).parent().next().toggle();
      $j(this).prev().toggleClass('expanded');
      Tipped.refresh(this);
      return false;
    });
    $j('body').on('click', '.slide_toggle', function(ev) {
      var input, inputSelector, link, link_text, target, target_selector, was_visible, which_text;
      ev.preventDefault();
      link = $j(this);
      target_selector = link.data('slideToggleTarget');
      if (target_selector) {
        target = $j(target_selector);
      } else {
        target = link.next();
        if (!target.length) {
          target = link.parent().next();
        }
      }
      was_visible = target.is(':visible');
      which_text = was_visible ? 'slideToggleHiddenText' : 'slideToggleVisibleText';
      link_text = link.data(which_text);
      if (link_text) {
        link.html(link_text);
      }
      if (link.data('slideToggleNoSlide')) {
        target.toggle();
      } else {
        target.slideToggle();
      }
      inputSelector = link.data('slideToggleInputSelector');
      if (input = target.find(inputSelector)) {
        return input.val(was_visible ? 0 : 1);
      }
    });
    $j('body').on('click', '.toggle_wrapper', function() {
      $j(this).next().toggle();
      $j(this).find('.toggle_filter').toggleClass('expanded');
      Tipped.refresh(this);
      return false;
    });
    $j(' .simple_remote').live('click', function() {
      var data;
      data = $j("#" + ($j(this).attr('submit')) + " input, #" + ($j(this).attr('submit')) + " textarea").serialize();
      $j.ajax($j(this).attr('url'), {
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            $j(_this).hide();
            return $j(_this).closest('div').find('img').first().closest('span').show();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            var error_wrapper, message_wrapper, result;
            $j(_this).closest('div').find('img').first().closest('span').hide();
            $j(_this).show();
            result = eval("(" + response.responseText + ")");
            error_wrapper = $j(_this).closest('.content_wrapper').find('.alert_message');
            message_wrapper = $j(_this).closest('.content_wrapper').find('.success_message');
            error_wrapper.html('');
            message_wrapper.html('');
            if (result.error) {
              error_wrapper.html(result.error);
            } else {
              message_wrapper.html(result.message);
            }
            return Tipped.refresh(_this);
          };
        })(this)
      });
      return false;
    });
    $j(" .spt_service_quantity_input").on('change', function() {
      var el, row, val;
      el = $j(this);
      val = el.val();
      row = el.attr('id').split('_').pop();
      $j('#price_obj_' + row).attr('q', val);
      updateSPTPrices();
      return false;
    });
    $j(' .add-attachment-link').live('click', function() {
      var att, last, template;
      template = $j(" .attachment-template").first();
      att = template.clone();
      att.attr('class', 'attachment-item');
      last = $j(this).parent().find('.attachment-item').last();
      last.after(att);
      att.show();
      return false;
    });
    $j(" .supplier_name").livequery(function() {
      var el, target;
      el = $j(this);
      target = $j('#' + el.data('target_id'));
      el.autocomplete({
        select: (function(_this) {
          return function(event, ui) {
            var custom_html;
            custom_html = '<span class="erp_valid" title="Valid ERP Vendor present">valid</span>';
            el.val(ui.item.label.replace(custom_html, ' (valid)'));
            target.val(ui.item.value);
            return false;
          };
        })(this)
      }).data("ui-autocomplete")._renderItem = function(ul, item) {
        return $j("<li>").append("<a class='tipsy_tip' title='" + item.info + "'>" + item.label + "</a>").appendTo(ul);
      };
      return false;
    });
    $j(" .live_search_company").livequery(function() {
      var el, target_id, tick;
      el = $j(this);
      target_id = el.data('target_id');
      tick = $j(this).parent().find('img');
      el.autocomplete({
        select: (function(_this) {
          return function(event, ui) {
            var company_name_field_selector, custom_html;
            if (ui.item.value === 'new') {
              el.val($j(ui.item.label).text());
              $j(' .tipsy:last').hide();
              company_name_field_selector = '#' + target_id.replace(/_id/, '_name');
              Tipped.create(company_name_field_selector, "/companies/render_new_form?change_field=" + target_id, {
                ajax: true,
                hook: {
                  target: "rightmiddle",
                  tooltip: 'lefttop'
                },
                showOn: false,
                hideOn: {
                  element: "self",
                  event: "click"
                },
                closeButton: true,
                closeButtonSkin: "light",
                offset: {
                  x: 25
                }
              });
              Tipped.show(company_name_field_selector);
              tick.hide();
            } else {
              if (/supplier/.test(target_id)) {
                custom_html = '<span class="erp_valid" title="Valid ERP Vendor present">valid</span>';
                el.val(ui.item.label.replace(custom_html, ' (valid)'));
              } else {
                el.val(ui.item.label);
              }
              tick.show();
            }
            $j('#' + target_id).val(ui.item.value);
            eval(el.data('on_select'));
            return false;
          };
        })(this)
      }).data("ui-autocomplete")._renderItem = function(ul, item) {
        return $j("<li>").append("<a class='tipsy_tip' title='" + item.info + "'>" + item.label + "</a>").appendTo(ul);
      };
      return false;
    });
    $j(' .form_no_submit').live('keypress keydown keyup', function(event) {
      if (event.which === 13) {
        return event.preventDefault();
      }
    });
    $j(' .fixed_position').livequery(function() {
      var obj, wrapper_id;
      wrapper_id = $j(this).data('wrapper');
      $j(this).css('float', 'right');
      $j(this).css('right', '15px');
      $j(this).css('position', 'absolute');
      $j(this).css('z-index', '10000');
      obj = $j(this);
      $j(window).scroll(function() {
        var final_offset, max_offset, min_offset, wrapper;
        wrapper = $j('#' + wrapper_id);
        if (wrapper !== void 0) {
          return true;
        }
        max_offset = wrapper.height() + wrapper.offset().top;
        min_offset = wrapper.offset().top;
        final_offset = Math.max(min_offset, Math.min($j(window).scrollTop(), max_offset)) + obj.height();
        return obj.offset({
          top: final_offset
        });
      });
      return true;
    });
    $j("a.add_simple_comment").livequery("click", function() {
      $j('#' + $j(this).data('el_to_toggle')).toggle().effect('highlight', {}, 3000);
      return false;
    });
    $j('a.cancel_simple_comment').livequery('click', function() {
      $j('#' + $j(this).data('target')).hide();
      $j(this).parents('form').parent().find('.error_explanation').hide();
      return false;
    });
    $j(' .add_simple_comment_form').livequery('submit', function() {
      if ($j(this).find('textarea').val() === '') {
        $j(this).parent().find('.error_explanation').html('Please enter a comment').show();
      } else {
        $j.ajax($j(this).attr('action'), {
          type: 'POST',
          data: $j(this).serialize(),
          dataType: 'script',
          beforeSend: (function(_this) {
            return function() {
              return showSpinner($j(_this).find('input:submit'));
            };
          })(this),
          complete: (function(_this) {
            return function() {
              return hideSpinner($j(_this).find('input:submit'));
            };
          })(this)
        });
      }
      return false;
    });
    $j('form.send_communication_form').livequery('submit', function(event) {
      var no_additional_recipients, no_selected_recipients;
      event.preventDefault();
      no_selected_recipients = $j('#recipients_wrapper').find('input:checkbox:checked').length === 0;
      no_additional_recipients = $j.trim($j('#send_to_emails_to_be_checked').val()).length === 0;
      if (no_selected_recipients && no_additional_recipients) {
        alert('You need to choose at least one recipient.');
        return false;
      } else {
        tinymce.triggerSave();
        unsetTextareaToTinyMCE($j(this).find('.tiny_mce').attr('id'));
        tinymce.triggerSave();
        $j(this).find(':submit').attr('disabled', 'disabled');
        return $j.ajax($j(this).attr('action'), {
          type: 'POST',
          data: $j(this).serialize(),
          dataType: 'script',
          success: (function(_this) {
            return function() {
              return $j(_this).find(':submit').removeAttr('disabled');
            };
          })(this)
        });
      }
    });
    $j('input.with_enforced_limits').livequery('keyup', function() {
      var max_value;
      max_value = $j(this).attr('max');
      if (parseInt(this.value) > max_value) {
        alert("You can not set it to more than " + max_value + ".");
        return this.value = max_value;
      }
    });
    $j(' .tab_reloader a').live('click', function() {
      $j('#' + $j(this).data('tab')).html('');
      changeTab($j(this).data('tab'), {
        reload: true
      });
      return false;
    });
    no_access_message = 'Unable to perform the indicated action.';
    $j(' .j-tabbed-button').live('click', function(event) {
      return window.location = $j(this).data('location');
    });
    $j('.j-popup-close').live('click', function(event) {
      event.preventDefault();
      return $j.magnificPopup.close();
    });
    show_magnific_popup = function(src, extra_opts) {
      var opts;
      if (extra_opts == null) {
        extra_opts = {};
      }
      opts = {
        items: {
          src: src
        },
        closeOnBgClick: false,
        closeOnContentClick: false,
        fixedBgPos: false,
        close: function() {
          return $j('body').trigger('magnific_popup:close');
        }
      };
      $j.extend(opts, extra_opts);
      return $j.magnificPopup.open(opts);
    };
    selector = '.magnific_popup_inline, ' + '.magnific_popup_link, ' + '.magnific_popup_link_with_close, ' + '.magnific_popup_link_with_close_outside, ' + '.magnific_popup_link_with_close_inside';
    $j('body').on('click', selector, function(ev) {
      var elem, src, xhr;
      ev.preventDefault();
      elem = $j(ev.target).closest(selector);
      if (elem.hasClass('magnific_popup_inline')) {
        src = elem.data('src');
        $j(src).show();
        show_magnific_popup(src);
        return;
      }
      showSpinner(elem);
      xhr = $j.ajax({
        url: elem.attr('href'),
        type: elem.data('method') || 'GET',
        dataType: 'html',
        headers: {
          'X-Partial-Request': true
        }
      });
      xhr.always(function() {
        return hideSpinner(elem);
      });
      xhr.fail(function() {
        return alert(no_access_message);
      });
      xhr.done(function(data) {
        var opts;
        opts = elem.hasClass('magnific_popup_link') ? {} : elem.hasClass('magnific_popup_link_with_close') ? {
          showCloseBtn: true
        } : elem.hasClass('magnific_popup_link_with_close_outside') ? {
          showCloseBtn: true,
          closeBtnInside: false
        } : elem.hasClass('magnific_popup_link_with_close_inside') ? {
          showCloseBtn: true,
          closeBtnInside: true
        } : void 0;
        return show_magnific_popup(data, opts);
      });
    });
    $j('.tooltip_help').livequery(function() {
      var element, id;
      id = $j(this).attr('id').split('_')[1];
      element = $j('#' + id);
      element.addClass('tipped_target');
      element.addClass('inline');
      element.data('tipped', $j(this).attr('id'));
      return true;
    });
    $j(' .account_number_element').livequery('keyup', function() {
      var account_number;
      account_number = $j.map($j(" .account_number_element"), function(element) {
        return $j(element).val();
      }).join("-");
      return $j('#resulting_account_number').val(account_number);
    });
    $j('#equipment-select-all').livequery('click', function() {
      $j('.equipment-checkbox, .group-checkbox').prop('checked', true);
      return $j(" .equipment-checkbox").each(function() {
        var eq_id;
        eq_id = $j(this).val();
        return toggle_equipment(this, eq_id);
      });
    });
    $j('#equipment-select-none').livequery('click', function() {
      $j('.equipment-checkbox, .group-checkbox').prop('checked', false);
      return $j(" .equipment-checkbox").each(function() {
        var eq_id;
        eq_id = $j(this).val();
        return toggle_equipment(this, eq_id);
      });
    });
    $j(' .j-tabbed-button').live('click', function(event) {
      return window.location = $j(this).data('location');
    });
    $j('textarea[data-tinymce]').livequery(function() {
      return resetTextareaToTinyMCE($j(this).prop('id'));
    });
    $j('a[data-popup-close]').live('click', function(event) {
      event.preventDefault();
      return $j.magnificPopup.close();
    });
    $j('.simple_in_place').livequery(function() {
      var cancelLink, changeLink, container, dataType, form, hideForm, html, saveLink, showForm;
      container = $j(this);
      html = container.find('.simple_in_place_html');
      form = container.find('.simple_in_place_form');
      changeLink = container.find('.simple_in_place_change');
      saveLink = container.find('.simple_in_place_save');
      cancelLink = container.find('.simple_in_place_cancel');
      dataType = container.data('dataType') || 'text';
      showForm = function() {
        form.show();
        html.hide();
        changeLink.hide();
        saveLink.show();
        return cancelLink.show();
      };
      hideForm = function() {
        form.hide();
        html.show();
        changeLink.show();
        saveLink.hide();
        return cancelLink.hide();
      };
      changeLink.on('click', function(ev) {
        ev.preventDefault();
        return showForm();
      });
      cancelLink.on('click', function(ev) {
        ev.preventDefault();
        return hideForm();
      });
      return saveLink.on('click', function(ev) {
        var xhr;
        showSpinner(saveLink);
        xhr = $j.ajax({
          url: container.data('url'),
          method: container.data('method'),
          data: form.find(':input').serialize(),
          dataType: dataType
        });
        xhr.always(function() {
          return hideSpinner(saveLink);
        });
        xhr.fail(function() {
          return alert('Unable to save changes.');
        });
        xhr.done(function(data, textStatus, xhr) {
          if (xhr.status !== 200) {
            alert('Unable to save changes.');
            return;
          }
          if (dataType === 'text') {
            html.html(data);
          } else {
            html.html(xhr.getResponseHeader('Result') || '');
          }
          return hideForm();
        });
        return ev.preventDefault();
      });
    });
    $j('body').on('click', '.toggle_date_picker', function() {
      var container, input;
      container = $j(this).closest('.date_picker_container');
      input = $j(this).prevAll('input.date:last');
      if (!input.length) {
        input = $j(this).closest('.date_picker_container').find('input.date:last');
      }
      if (input.data('xdsoft_datetimepicker').is(':visible')) {
        input.datetimepicker('hide');
      } else {
        input.datetimepicker('show');
      }
      return false;
    });
    return true;
  });

  window.toggle_equipment = function(el, eq_id) {
    var equipment, j, len;
    $j(" .eq-" + eq_id + ":not(.equipment-checkbox)").toggle(el.checked);
    for (j = 0, len = equipment_list.length; j < len; j++) {
      equipment = equipment_list[j];
      if (equipment.id === eq_id) {
        equipment.checked = el.checked;
      }
    }
    $j("#last_page_table").fixedHeaderTable("show");
    return $j('#last_page_table tr:first th:first').height($j('.fht-table tr:first th:first').height());
  };

  window.showSpinner = function(jQselector) {
    var element;
    element = $j(jQselector);
    if (element.hasClass('ui button')) {
      return element.addClass('loading');
    } else {
      return element.each(function() {
        var display, elem, height, paddingBottom, paddingLeft, paddingRight, paddingTop, size, spinner, width;
        elem = $j(this);
        if (elem.data('hasSpinner')) {
          return;
        }
        width = elem.outerWidth();
        height = elem.outerHeight();
        size = 14;
        if ((width - size) % 2 === 0) {
          paddingLeft = (width - size) / 2;
          paddingRight = paddingLeft;
        } else {
          paddingLeft = (width - size - 1) / 2;
          paddingRight = paddingLeft - 1;
        }
        if ((height - size) % 2 === 0) {
          paddingTop = (height - size) / 2;
          paddingBottom = paddingTop;
        } else {
          paddingTop = (height - size - 1) / 2;
          paddingBottom = paddingTop - 1;
        }
        display = elem.css('display') === 'table' ? 'block' : elem.css('display');
        spinner = $j('<div style="width:' + size + 'px;' + 'height:' + size + 'px;' + 'float:' + elem.css('float') + ';' + 'display:' + display + ';' + 'clear:' + elem.css('clear') + ';' + 'position:' + elem.css('position') + ';' + 'top:' + elem.css('top') + ';' + 'right:' + elem.css('right') + ';' + 'bottom:' + elem.css('bottom') + ';' + 'left:' + elem.css('left') + ';' + 'margin: 0;' + 'border: none;' + 'padding: ' + paddingTop + 'px ' + paddingRight + 'px ' + paddingBottom + 'px ' + paddingLeft + 'px;" ' + 'class="in_place_spinner"></div>');
        elem.hide().after(spinner);
        elem.data('hasSpinner', true);
        return Spinners.create($j(spinner), {
          radius: 2,
          dashes: 15,
          width: 1,
          height: 4,
          opacity: 0.9,
          padding: 0,
          rotation: 800,
          color: '#33f'
        }).play();
      });
    }
  };

  window.hideSpinner = function(jQselector) {
    var element;
    element = $j(jQselector);
    if (element.hasClass('loading')) {
      return element.removeClass('loading');
    } else {
      return element.each(function() {
        var elem, spinner;
        elem = $j(this);
        spinner = elem.next('.in_place_spinner');
        Spinners.get(spinner);
        spinner.remove();
        elem.show();
        return elem.data('hasSpinner', false);
      });
    }
  };

  window.print_update_status_js = function(success, options) {
    var elem;
    if (options == null) {
      options = {};
    }
    elem = $j('#update_all_li_status');
    elem.html('');
    if (options.message) {
      elem.append(options.message);
    }
    if (options.count_message) {
      elem.append(options.count_message);
    }
    if (options.summary) {
      elem.append(options.summary);
    }
    if (success) {
      elem.removeClass('error_explanation');
      elem.addClass('success_explanation');
    } else {
      elem.addClass('error_explanation');
      elem.removeClass('success_explanation');
    }
    if (options.css_class) {
      elem.removeClass('error_explanation');
      elem.removeClass('success_explanation');
      elem.addClass(options.css_class);
    }
    if (options.countdown_message) {
      elem.append('<span class="countdown_message">' + options.countdown_message + '</span> ' + '<span class="timer"></span>');
      startTimer(15);
    }
    elem.show();
    return $j('.refresh_requests').livequery('click', function() {
      $j('#reset_filters').click();
      $j('#update_all_li_status').html('');
      return $j('#update_all_li_status').hide();
    });
  };

  startTimer = function(counter) {
    var element;
    if (counter !== 0) {
      element = $j('timer');
      $j('.timer').text(counter + ' seconds');
      return setTimeout((function() {
        startTimer(counter - 1);
      }), 1000);
    } else {
      $j('.countdown_message').text('');
      return $j('.timer').html('<a class="refresh_requests">Refresh requests</a>');
    }
  };

  clear_chart_field_errors_js = function() {
    return $j(' .error_chart_fields_text').remove();
  };

  window.table_search = function(base, table) {
    var header, j_base, j_table, old_text, search;
    header = $j("<button onclick='return false;' class='clear_btn' style='margin-left: 10px;'>Clear</button> <span class='result_span'></span>");
    j_base = $j(base);
    j_table = $j(table);
    j_base.parent().find('.clear_btn, .result_span').remove();
    j_base.after(header);
    old_text = (j_base.val() || '').replace(/^\s+|\s+$/g, "");
    search = function(e, override) {
      var shown, text, total, tr_inputs, tr_text, trs;
      if (override == null) {
        override = false;
      }
      text = j_base.val().replace(/^\s+|\s+$/g, "");
      if ((old_text === text) && !override) {
        return;
      }
      old_text = text;
      if (text !== "") {
        total = j_table.find("tbody>tr").hide().length;
        tr_text = j_table.find("tr:contains-ci('" + text + "')");
        tr_inputs = j_table.find("tr input[value]").filter(function() {
          return this.value.toLowerCase().indexOf(text.toLowerCase()) >= 0;
        });
        trs = tr_text.add(tr_inputs.parentsUntil(j_table, 'tr'));
        shown = trs.show().length;
      } else {
        shown = j_table.find("tbody>tr").show().length;
        total = shown;
      }
      if (shown === 0) {
        header.filter('span').html("No results");
      } else {
        header.filter('span').html("");
      }
      return j_table.effect("highlight", {}, 1500);
    };
    header.filter('button').click(function() {
      return j_base.val('').change();
    });
    j_table.on('rows_changed', debounce((function() {
      return search(null, true);
    }), 300));
    return j_base.on('change keyup input paste', debounce(search, 400));
  };

  window.cores_table_search = function(base, table) {
    var header, j_base, j_table, old_text, search;
    header = $j("<button onclick='return false;' style='margin-left: 10px;'>Clear</button> <span></span>");
    j_base = $j(base);
    j_table = $j(table);
    j_base.after(header);
    old_text = (j_base.val() || '').replace(/^\s+|\s+$/g, "");
    search = function(e, override) {
      var links, shown, text, total;
      if (override == null) {
        override = false;
      }
      text = j_base.val().replace(/^\s+|\s+$/g, "");
      if ((old_text === text) && !override) {
        return;
      }
      old_text = text;
      if (text !== "") {
        j_table.find("div").hide();
        j_table.find("h3").removeClass("expanded");
        total = j_table.find("tbody>tr").hide().length;
        links = j_table.find("tr a").filter(function() {
          return $j(this).text().toLowerCase().indexOf(text.toLowerCase()) >= 0;
        });
        links.parentsUntil(j_table, 'tr').show();
        links.parentsUntil(j_table, 'div').find("h3.toggleable_header").addClass("expanded");
        links.parentsUntil(j_table, 'div').show();
        shown = links.length;
      } else {
        j_table.find("div").show();
        j_table.find("h3").addClass("expanded");
        shown = j_table.find("tbody>tr").show().length;
        total = shown;
      }
      if (shown === 0) {
        header.filter('span').html("No results");
      } else {
        header.filter('span').html("");
      }
      return j_table.effect("highlight", {}, 1500);
    };
    header.filter('button').click(function() {
      return j_base.val('').change();
    });
    j_table.on('rows_changed', debounce((function() {
      return search(nil, true);
    }), 300));
    return j_base.on('change keyup input paste', debounce(search, 400));
  };

  window.debounce = function(func, threshold) {
    var timeout;
    timeout = void 0;
    return function() {
      var args, delay, o;
      delay = function() {
        var timout;
        func.apply(o, args);
        return timout = null;
      };
      o = this;
      args = arguments;
      if (timeout) {
        clearTimeout(timeout);
      }
      return timeout = setTimeout(delay, threshold);
    };
  };

  $j.extend($j.expr[":"], {
    "contains-ci": function(elem, i, match, array) {
      return (elem.textContent || elem.innerText || $j(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
  });

  window.left_pad = function(original_string, times, pad_char) {
    var pad;
    pad_char = (typeof pad_char !== "undefined" ? pad_char : "0");
    pad = new Array(1 + times).join(pad_char);
    return (pad + original_string).slice(-pad.length);
  };

  window.selectLocation = function(el, child_id, current_location_path) {
    var current_location, emptycolor, fullcolor, previously_selected;
    if ($j(el).hasClass('sample_cell_used')) {
      return false;
    }
    current_location = current_location_path.substr(current_location_path.lastIndexOf('>') + 2);
    if ((current_location_path.match(/>/g).length + 1) === $j(el).closest('form').find('.location_path').children().length) {
      $j(el).closest('form').find('.location_path').append("><a href='#' class='filter_locations' url='/location/select/" + child_id + "'>" + current_location + "</a>");
    } else {
      $j(el).closest('form').find('.location_path').children().last().html(current_location);
      $j(el).closest('form').find('.location_path').children().last().attr('url', "/location/select/" + child_id);
    }
    emptycolor = '#cccccc';
    fullcolor = '#c50d17';
    $j(el).parents('.select_instance_location_wrapper').find('form input[name=location_radio]').attr('value', child_id);
    previously_selected = $j(el).closest('table').find('td.selected');
    if (previously_selected.length > 0) {
      $j(previously_selected).removeClass('selected');
      $j(previously_selected).css('background-color', emptycolor);
    }
    $j(el).addClass('selected');
    $j(el).css('background-color', fullcolor);
    Tipped.refresh(el);
    return false;
  };

  $j(function() {
    var init_institution_location_select, select_a_location;
    select_a_location = function(location_id, dialog) {
      var custom_data, dialog_link;
      if (location_id) {
        custom_data = {};
        dialog.find('input[name^=custom\\[]').each(function() {
          var name;
          name = $j(this).attr('name').replace(/^custom\[/, '').replace(/\]$/, '');
          return custom_data[name] = $j(this).val();
        });
        dialog_link = $j(Tipped.findElement(dialog.get(0)));
        dialog_link.trigger('institution_location_picked', {
          location_id: location_id,
          service_center_id: dialog.find('input[name=service_center_id]').val(),
          group_id: dialog.find('input[name=group_id]').val(),
          save_as_customer_default: dialog.find('input[name=save_as_customer_default]').is(':checked'),
          user_type: dialog.find('input[name=user_type]').val(),
          custom: custom_data
        });
        return Tipped.hide(dialog_link);
      }
    };
    init_institution_location_select = function(select_parent) {
      var container, dialog, group_id, on_change_handler, parent_can_create_children, parent_is_selectable, parent_location_id, select, service_center_id, user_type;
      dialog = select_parent.closest('.select_location_dialog');
      user_type = dialog.find('input[name=user_type]').val();
      service_center_id = dialog.find('input[name=service_center_id]').val();
      group_id = dialog.find('input[name=group_id]').val();
      parent_location_id = select_parent.find('input[name=parent_location_id]').val();
      parent_is_selectable = select_parent.find('input[name=parent_is_selectable]').val();
      parent_can_create_children = select_parent.find('input[name=parent_can_create_children]').val();
      container = select_parent.closest('.institution_location_select_container');
      select = select_parent.find('input.institution_location_input');
      select.select2({
        placeholder: select.data('placeholderText'),
        width: 'element',
        query: function(options) {
          var data;
          data = {
            user_type: user_type,
            service_center_id: service_center_id,
            group_id: group_id,
            term: options.term.toLowerCase(),
            page: options.page
          };
          return $j.get('/locations/' + parent_location_id + '/live_search_node_children', data, null, 'json').done(function(data) {
            var results;
            results = {
              results: data.child_nodes,
              more: data.more
            };
            return options.callback(results);
          });
        },
        initSelection: function(element, callback) {
          return callback(JSON.parse(element.val()));
        }
      });
      on_change_handler = function(ev) {
        var data, selected_id, spinner;
        select_parent.nextAll().remove();
        spinner = select_parent.find('.institution_location_select_spinner');
        showSpinner(spinner);
        selected_id = ev.val;
        data = {
          user_type: user_type,
          service_center_id: service_center_id,
          group_id: group_id
        };
        return $j.get('/locations/' + selected_id + '/nested_select_node', data, null, 'html').always(function() {
          hideSpinner(spinner);
          return spinner.hide();
        }).done(function(data) {
          var data_elem;
          data = $j(data);
          data_elem = data;
          data_elem.appendTo(container);
          init_institution_location_select(data_elem);
          return Tipped.refresh('*');
        });
      };
      select.on('change', on_change_handler);
      select.data('change_handler', on_change_handler);
      select.select2('focus');
      if (parent_can_create_children === '1') {
        select_parent.prev().find('.institution_location_new_link').show();
      }
      if (parent_is_selectable === '1') {
        select_parent.prev().find('.institution_location_choose_link').show();
      }
      select_parent.find('.institution_location_new_link').click(function() {
        var div;
        $j('.institution_location_create_new').each(function() {
          $j(this).find('input[name=name]').val('');
          return $j(this).hide();
        });
        div = select_parent.find('.institution_location_create_new');
        div.show();
        div.find('input[name=name]').focus();
        Tipped.refresh('*');
        return false;
      });
      select_parent.find('.institution_location_new_cancel_link').click(function() {
        var elem;
        elem = $j(this).closest('.institution_location_create_new');
        elem.find('input[name=name]').val('');
        elem.slideUp().promise().done(function() {
          return Tipped.refresh('*');
        });
        return false;
      });
      select_parent.find('.institution_location_create_link').click(function() {
        var data, elem, spinner;
        elem = $j(this).closest('.institution_location_create_new');
        data = {
          service_center_id: service_center_id,
          group_id: group_id,
          user_type: user_type,
          name: elem.find('input[name=name]').val(),
          category: elem.find('input[name=category]').val()
        };
        spinner = $j(this);
        showSpinner(spinner);
        $j.post('/locations/' + parent_location_id + '/create_child_for_product_cores', data, null, 'json').fail(function() {
          return hideSpinner(spinner);
        }).done(function(data) {
          var msg_elem, prev_parent, prev_select;
          msg_elem = dialog.find('.select_location_success_message');
          msg_elem.text('Location created!').show().effect('highlight', 3000).promise().done(function() {
            return msg_elem.slideUp();
          });
          prev_parent = select_parent.prev();
          prev_select = prev_parent.find('input.institution_location_input');
          prev_select.data('change_handler')({
            val: prev_select.val()
          });
          return setTimeout((function() {
            var new_parent, new_select;
            new_parent = prev_parent.next();
            new_select = new_parent.find('input.institution_location_input');
            new_select.select2('val', JSON.stringify({
              id: data.new_product_id,
              text: data.new_product_name
            }));
            new_select.data('change_handler')({
              val: new_select.val()
            });
            return Tipped.refresh('*');
          }), 500);
        });
        return false;
      });
      return select_parent.find('.institution_location_choose_link').click(function() {
        var location_id;
        location_id = select.select2('val');
        select_a_location(location_id, dialog);
        return false;
      });
    };
    $j('.institution_location_select_container').livequery(function() {
      return $j.each($j(this).find('.institution_location_select'), function() {
        return init_institution_location_select($j(this));
      });
    });
    $j('.select_location_dialog').livequery(function() {
      return $j(this).on('click', '.select_location_cancel_link', function() {
        Tipped.hide(Tipped.findElement(this));
        return false;
      });
    });
    $j('.false_form_submit').live('click', function() {
      var $form;
      $form = $j(this).closest('.form');
      $j.ajax($form.data('action'), {
        type: $form.data('method') || 'POST',
        data: $form.find('input, select, textarea').serializeArray(),
        beforeSend: (function(_this) {
          return function() {
            return showSpinner(_this);
          };
        })(this),
        complete: (function(_this) {
          return function() {
            return hideSpinner(_this);
          };
        })(this)
      });
      return false;
    });
    return $j.magnificPopup.instance._onFocusIn = function(e) {
      if ($j(e.target).hasClass('select2-input')) {
        return true;
      }
      if ($j(e.target).closest('.t_Tooltip').length) {
        return true;
      }
      return $j.magnificPopup.proto._onFocusIn.call(this, e);
    };
  });

  window.uploadCustomFormAttachmentForStudies = function(upload_btn) {
    var formData, popupContainer;
    upload_btn = $j(upload_btn);
    popupContainer = upload_btn.parents('div#add_custom_form_attachment');
    if (popupContainer.find('form').length === 0) {
      formData = new FormData();
      popupContainer.find('input[type="hidden"], input[type="text"]').each(function(el) {
        return formData.append($j(this).attr('name'), $j(this).val());
      });
      formData.append("attachment[uploaded_data]", popupContainer.find('input[name="attachment[uploaded_data]"]')[0].files[0]);
      formData.append('fromajax', true);
      $j.ajax({
        url: popupContainer.data('path'),
        type: "POST",
        data: formData,
        processData: false,
        contentType: false
      });
    }
    return true;
  };

}).call(this);
(function() {
  $j(function() {
    $j('span.select_all_line_items a').livequery('click', function() {
      var items;
      items = $j(' .line_item');
      if ($j(this).text() === 'all') {
        items.addClass('selected').find('input:checkbox').attr('checked', true).last().trigger('change');
        $j(this).text('none');
      } else {
        items.removeClass('selected').find('input:checkbox').attr('checked', false).last().trigger('change');
        $j(this).text('all');
      }
      return false;
    });
    $j('a.reset_splits_link').on('click', function() {
      $j(' .split_row').not('.first_split').remove();
      $j('tr.split_row.first_split input.split_percentage').val('100').trigger('change');
      return false;
    });
    $j('a.mr_process_lis_link').on('click', function() {
      var data;
      if (confirmSaveLineItems()) {
        data = $j('#process :input, #line_items :input:not(.split_form :input)').serializeArray();
        if ($j(this).data('erp_id') !== void 0) {
          data.push({
            name: 'erp_id',
            value: $j(this).data('erp_id')
          });
        }
        if ($j(this).data('id') !== void 0) {
          data.push({
            name: 'id',
            value: $j(this).data('id')
          });
        }
        if ($j(this).data('requisition_order_number') !== void 0) {
          data.push({
            name: 'requisition_order_number',
            value: $j(this).data('requisition_order_number')
          });
        }
        $j.ajax('/requisition/enter_into_purchasing', {
          type: 'POST',
          data: data,
          async: true,
          beforeSend: (function(_this) {
            return function() {
              showSpinner($j(_this));
              return $j(_this).next().show();
            };
          })(this),
          complete: (function(_this) {
            return function() {
              hideSpinner($j(_this));
              return $j(_this).next().hide();
            };
          })(this)
        });
      }
      return false;
    });
    $j('#bulk_chart_fields_form').live('ajax:before', function(event) {
      var check_data, data, form;
      form = $j(this);
      check_data = $j('#line_items input:checkbox').serialize();
      data = form.serialize();
      if (check_data.length > 0) {
        data += '&' + check_data;
      }
      $j.ajax(form.data('url'), {
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            return showSpinner($j(_this).find('input:submit'));
          };
        })(this),
        success: (function(_this) {
          return function(response) {
            return hideSpinner($j(_this).find('input:submit'));
          };
        })(this)
      });
      return false;
    });
    $j('a.product_li_add_split').live('click', function() {
      var data, li_id, total_price;
      li_id = $j(this).data('li_id');
      total_price = $j("#chart_line_item_" + li_id + " input.split_percentage").first().data('total_price');
      data = $j("#chart_line_item_" + li_id + " :input").serializeArray();
      data.push({
        name: 'total_price',
        value: total_price
      });
      data.push({
        name: 'lid',
        value: li_id
      });
      $j.ajax({
        url: '/line_item/add_split',
        data: data,
        dataType: 'html',
        beforeSend: (function(_this) {
          return function() {
            return showSpinner($j(_this));
          };
        })(this),
        success: (function(_this) {
          return function(response) {
            $j("#line_item_" + li_id + "_totals_row").before("" + response);
            calculateSplitsTotal(li_id, total_price);
            return hideSpinner($j(_this));
          };
        })(this)
      });
      return false;
    });
    $j('a.service_li_add_split').live('click', function() {
      var data, li_id, total_price;
      li_id = $j(this).data('li_id');
      total_price = $j(this).data('total_price');
      data = $j("#split_form_for_" + li_id + " :input").serializeArray();
      data.push({
        name: 'lid',
        value: li_id
      });
      $j.ajax({
        url: '/line_item/add_split',
        data: data,
        dataType: 'html',
        beforeSend: (function(_this) {
          return function() {
            return showSpinner($j(_this));
          };
        })(this),
        success: (function(_this) {
          return function(response) {
            $j("#split_form_for_" + li_id + "_spacer_row").before("" + response);
            calculateSplitsTotal(li_id, total_price);
            hideSpinner($j(_this));
            return Tipped.refresh("#line_item_" + li_id + "_split_link");
          };
        })(this)
      });
      return false;
    });
    $j(' .simple_split_form a.add_split').live('click', function() {
      var data, item_id, tbody, total_price;
      item_id = $j(this).data('item_id');
      tbody = $j("#simple_split_form_" + item_id + " table tbody.split_rows");
      total_price = $j(this).data('total_price');
      data = $j("#simple_split_form_" + item_id + " :input").serializeArray();
      data.push({
        name: 'id',
        value: item_id
      });
      data.push({
        name: 'klass',
        value: $j(this).data('item_class')
      });
      $j.ajax('/split_payment/add_split', {
        type: 'GET',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            return showSpinner($j(_this));
          };
        })(this),
        complete: (function(_this) {
          return function() {
            hideSpinner($j(_this));
            if (tbody.find('tr.max_splits_reached').length > 0) {
              return $j(_this).detach();
            }
          };
        })(this)
      }).done(function(html) {
        tbody.append(html);
        setTimeout(function() {
          return Tipped.refresh('*');
        }, 10);
        simpleCalculateSplitsTotal(item_id, total_price);
        return false;
      });
      return false;
    });
    $j('a.service_request_save_payment_info').live('click', function() {
      var data, inv_id, si_id;
      si_id = $j(this).data('si_id');
      inv_id = $j(this).data('inv_id');
      data = $j("#update_payment_information_for_service_item_" + si_id).find(':input:not(:disabled)').serialize();
      $j.ajax({
        url: "/service_item/update_financial_information/" + si_id + "?invoice_id=" + inv_id,
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            return showSpinner($j(_this));
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            hideSpinner($j(_this));
            return Tipped.refresh("#payment_info_icon_" + si_id);
          };
        })(this)
      });
      return false;
    });
    $j(' .simple_split_form a.save_payment_info').live('click', function() {
      var data, item_id;
      if ($j(this).data('billing_file_unchangeable')) {
        if (!confirm("You are updating payment information on charges that have already been sent to your institution financial system. Updating the charge will not be reflected in the institution financial system automatically.")) {
          return false;
        }
      }
      if ($j(this).attr('disabled')) {
        return false;
      } else {
        item_id = $j(this).data('item_id');
        data = $j("#simple_split_form_" + item_id + " :input").serializeArray();
        data.push({
          name: 'id',
          value: item_id
        });
        data.push({
          name: 'klass',
          value: $j(this).data('item_class')
        });
        $j.ajax({
          url: "/split_payment/save_payment_info/",
          type: 'POST',
          data: data,
          beforeSend: (function(_this) {
            return function() {
              return showSpinner($j(_this));
            };
          })(this),
          success: (function(_this) {
            return function(response) {
              return hideSpinner($j(_this));
            };
          })(this)
        });
        return false;
      }
    });
    $j(' .group_change_form a.save_group_change').live('click', function(e) {
      return window.saveGroupChange(e);
    });
    $j('input.bulk_splittable').livequery('change', function() {
      var total_price;
      total_price = totalPriceSelected();
      return $j('#bulk_chart_fields_form input.split_percentage, #bulk_chart_fields_form input.split_amount').data('total_price', total_price).trigger('change');
    });
    $j('input.simple_split_percentage, input.split_percentage, input.split_amount, input.simple_split_amount').livequery('change', function() {
      var value;
      value = $j(this).val();
      if (value.length === 0) {
        value = 0;
      }
      value = Math.abs(parseFloat(value).toFixed(3));
      return $j(this).val(value);
    });
    $j(' .split_form input').livequery('change', function() {
      return $j(this).data('unsaved', true);
    });
    $j('input.split_percentage ').livequery('change', function() {
      var amount, lid, price, split_id;
      lid = $j(this).data('lid');
      split_id = $j(this).data('split_id');
      price = parseFloat($j(this).data('total_price')).toFixed(2);
      amount = (($j(this).val() / 100) * price).toFixed(2);
      $j('#cost_allocation_' + split_id + '_amount').val(amount);
      return calculateSplitsTotal(lid, price);
    });
    $j('input.split_amount ').livequery('change', function() {
      var lid, percent, price, split_id;
      lid = $j(this).data('lid');
      split_id = $j(this).data('split_id');
      price = parseFloat($j(this).data('total_price')).toFixed(2);
      percent = (($j(this).val() / price) * 100).toFixed(3);
      if (isNaN(percent)) {
        percent = 0;
      }
      $j('#cost_allocation_' + split_id + '_percentage').val(percent);
      return calculateSplitsTotal(lid, price);
    });
    $j('input.simple_split_percentage ').livequery('change', function() {
      var amount, item_id, price, split_id;
      item_id = $j(this).data('item_id');
      split_id = $j(this).data('split_id');
      price = parseFloat($j(this).data('total_price')).toFixed(2);
      amount = (($j(this).val() / 100) * price).toFixed(2);
      $j("#cost_allocation_" + split_id + "_amount").val(amount);
      return simpleCalculateSplitsTotal(item_id, price);
    });
    return $j('input.simple_split_amount ').livequery('change', function() {
      var item_id, percent, price, split_id;
      item_id = $j(this).data('item_id');
      split_id = $j(this).data('split_id');
      price = parseFloat($j(this).data('total_price')).toFixed(2);
      percent = (($j(this).val() / price) * 100).toFixed(3);
      if (isNaN(percent)) {
        percent = 0;
      }
      $j('#cost_allocation_' + split_id + '_percentage').val(percent);
      return simpleCalculateSplitsTotal(item_id, price);
    });
  });

  window.saveGroupChange = function(e) {
    var data, item_id, link;
    link = $j(e.target);
    item_id = link.data('item_id');
    data = $j("#group_change_form_" + item_id + " :input").serializeArray();
    data.push({
      name: 'id',
      value: item_id
    });
    data.push({
      name: 'klass',
      value: link.data('item_class')
    });
    $j.ajax({
      url: '/split_payment/save_group_change/',
      type: 'POST',
      data: data,
      beforeSend: (function(_this) {
        return function() {
          return showSpinner(link);
        };
      })(this),
      success: (function(_this) {
        return function(response) {
          return hideSpinner(link);
        };
      })(this)
    });
    return false;
  };

  window.confirmSaveLineItems = function() {
    var inputs;
    inputs = $j('#line_items .split_form input').map(function() {
      return $j(this).data('unsaved');
    });
    if (jQuery.inArray(true, inputs) === -1) {
      return true;
    } else {
      return confirm('You may have unsaved splits/financial details in expanded items which cannot be saved with this tool. Please save individually instead before processing to avoid losing data. Do you want to continue?');
    }
  };

  window.simpleCalculateSplitsTotal = function(item_id, price) {
    var diff, form, last, total_amount, total_el, total_percentage, total_price;
    form = $j('#simple_split_form_' + item_id);
    total_el = $j(' .item_' + item_id + '_total_percentage_row');
    total_percentage = calculateSplitsTotalPercentage(form);
    total_amount = calculateSplitsTotalAmount(form);
    total_price = parseFloat(price);
    if (total_amount === total_price && total_percentage !== 100) {
      diff = 100 - total_percentage;
      last = form.find('.simple_split_percentage').last();
      last.val((parseFloat(last.val()) + diff).toFixed(3));
      total_percentage = calculateSplitsTotalPercentage(form);
    }
    if (total_percentage === 100 && total_amount !== total_price) {
      diff = total_price - total_amount;
      last = form.find('.simple_split_amount').last();
      last.val((parseFloat(last.val()) + diff).toFixed(2));
      total_amount = calculateSplitsTotalAmount(form);
    }
    total_el.find('span.total_percentage').text((total_percentage.toString()) + '%');
    total_el.find('span.total_amount').text(total_amount.toString());
    if (parseFloat(total_percentage) !== 100) {
      total_el.removeClass('green_text').addClass('red_text');
      $j('#item_' + item_id + '_save').attr('disabled', true).addClass('disabled');
    } else {
      total_el.addClass('green_text').removeClass('red_text');
      $j('#item_' + item_id + '_save').attr('disabled', false).removeClass('disabled');
    }
    return total_percentage;
  };

  window.calculateSplitsTotal = function(lid, price) {
    var diff, form, last, total_amount, total_percentage, total_price;
    form = $j('#split_form_for_' + lid);
    total_percentage = window.calculateSplitsTotalPercentage(form);
    total_amount = window.calculateSplitsTotalAmount(form);
    total_price = parseFloat(price);
    if (total_amount === total_price && total_percentage !== 100) {
      diff = 100 - total_percentage;
      last = form.find('.split_percentage').last();
      last.val((parseFloat(last.val()) + diff).toFixed(3));
      total_percentage = window.calculateSplitsTotalPercentage(form);
    }
    if (total_percentage === 100 && total_amount !== total_price) {
      diff = total_price - total_amount;
      last = form.find('.split_amount').last();
      last.val((parseFloat(last.val()) + diff).toFixed(2));
      total_amount = calculateSplitsTotalAmount(form);
    }
    $j('#line_item_' + lid + '_total_percentage').text((total_percentage.toString()) + '%');
    $j('#line_item_' + lid + '_total_amount').text(total_amount.toString());
    if (parseFloat(total_percentage) !== 100) {
      $j('#line_item_' + lid + '_totals_row').removeClass('green_text').addClass('red_text');
      $j('#split_form_for_' + lid + '_save').attr('disabled', true).addClass('disabled');
    } else {
      $j('#line_item_' + lid + '_totals_row').addClass('green_text').removeClass('red_text');
      $j('#split_form_for_' + lid + '_save').attr('disabled', false).removeClass('disabled');
    }
    return total_percentage;
  };

  window.calculateSplitsTotalPercentage = function(form) {
    var total;
    total = 0;
    form.find('.split_percentage, .simple_split_percentage').each(function() {
      return total += parseFloat(this.value);
    });
    return Number(parseFloat(total).toFixed(3));
  };

  window.calculateSplitsTotalAmount = function(form) {
    var total;
    total = 0;
    form.find('.split_amount, .simple_split_amount').each(function() {
      return total += parseFloat(this.value);
    });
    return Number(parseFloat(total).toFixed(2));
  };

  window.totalPriceSelected = function() {
    var total;
    total = 0;
    $j('input.bulk_splittable:checked').each(function() {
      return total += parseFloat($j(this).data('total_price'));
    });
    return Number(parseFloat(total).toFixed(2));
  };

  window.refresh_payment_status_icons = function(options) {
    var BATCH_SIZE, all_icons_to_refresh, icons_to_refresh_this_time, ids;
    all_icons_to_refresh = $j('.payment_status_not_checked');
    if (all_icons_to_refresh.length === 0) {
      return;
    }
    BATCH_SIZE = 25;
    ids = [];
    icons_to_refresh_this_time = all_icons_to_refresh.slice(0, BATCH_SIZE);
    icons_to_refresh_this_time.each(function() {
      return ids.push(this.id.split('_').slice(-1)[0]);
    });
    $j.ajax({
      url: "/line_item/refresh_payment_status_icon/",
      type: 'GET',
      data: Object.assign(options, {
        ids: ids
      }),
      dataType: 'script'
    }).done(function() {
      return setTimeout(refresh_payment_status_icons, 0, options);
    });
    return null;
  };

}).call(this);
(function() {
  $j(function() {
    var get_identifier_info, show_custom_form_error, validate_identifiers_and_show_if;
    $j(' .change_instance_grid_settings').live('change', function() {
      var id;
      id = $j(this).find('option:selected').val();
      $j.ajax("/custom_form/instance_grid_settings/" + id, {
        type: 'GET',
        beforeSend: (function(_this) {
          return function() {
            return showSpinner(_this);
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            var clone, colWidths, columns, headers, settings, source, text, types, wrapper;
            hideSpinner(_this);
            text = response.responseText || response;
            wrapper = $j(_this).closest('div').next();
            wrapper.html('');
            clone = wrapper.clone();
            clone.attr('grid_settings', text);
            wrapper.replaceWith(clone);
            headers = clone.attr('headers').split(',');
            columns = [];
            settings = JSON.parse(text);
            types = settings.types;
            source = settings.options;
            colWidths = settings.col_widths;
            for (var i=0; i< source.length; i++ ){
           var type = types[i]
           if (type.match(/}/)){
             renderer = eval( type )
             columns.push({ renderer: renderer, source: source[i].split(','), options: { items: 30 } })
           }else{
             columns.push({ type: type, source: source[i].split(','), options: { items: 30 } })
           }
         };
            clone.data('handsontable', new Handsontable(clone, {
              asyncRendering: false,
              minRows: 10,
              minSpareRows: 1,
              minCols: headers.length,
              maxCols: headers.length,
              startCols: headers.length,
              columns: columns,
              colWidths: colWidths,
              colHeaders: headers,
              afterGetColHeader: updateChargesHeader,
              rowHeaders: true,
              contextMenu: ["row_above", "row_below", "remove_row"],
              outsideClickDeselects: false
            }));
            return Tipped.refresh(clone);
          };
        })(this)
      });
      return true;
    });
    $j(' .save_grid_settings').live('click', function() {
      var data;
      showSpinner(this);
      data = $j(this).closest('td').prev().find('input, select, textarea').serializeObject();
      $j(Tipped.findElement(this)).closest('tr').find('input.grid_settings').val($j.param(data));
      setTimeout(function() {
        return hideSpinner(' .save_grid_settings');
      }, 1000);
      return false;
    });
    $j(' .configure_grid_link').live('click', function() {
      var data;
      data = $j(this).closest('tr').find('input, select, textarea').serialize();
      $j(this).data('tipped-object', Tipped.create(this, '/custom_form/grid_settings', {
        ajax: {
          data: data,
          type: 'POST',
          cache: false
        },
        hook: "topright",
        closeButtonSkin: 'light',
        target: $j(this),
        showOn: 'click',
        closeButton: true,
        hideOn: false
      }));
      Tipped.show(this);
      return false;
    });
    $j('#custom_form_edit_fields ul>li').livequery(function() {
      var custom_form_id, id;
      if ($j('#custom_form_template_id').length > 0) {
        id = $j('#custom_form_template_id').find('option:selected').val();
        custom_form_id = $j('#custom_form_template_id').closest('form').attr('action').match(/\d+/)[0];
        Tipped.hide('#custom_form_template_id');
        Tipped.remove('#custom_form_template_id');
        $j(this).data('tipped-object', Tipped.create('#custom_form_template_id', {
          ajax: {
            data: {
              id: id
            },
            type: 'GET',
            async: false,
            cache: false
          },
          hook: "topright",
          closeButtonSkin: 'light',
          target: $j('#custom_form_template_id').closest('div')
        }));
        return $j.ajax("/custom_form/template_settings/" + id + "?update_settings=1&event=added", {
          type: 'POST',
          async: false,
          cache: false,
          data: $j('#custom_form_template_id').closest('form').serialize() + '&' + $j.param({
            custom_form_id: custom_form_id
          })
        });
      }
    }, function() {
      var custom_form_id, id;
      if ($j('#custom_form_template_id').length > 0) {
        id = $j('#custom_form_template_id').find('option:selected').val();
        custom_form_id = $j('#custom_form_template_id').closest('form').attr('action').match(/\d+/)[0];
        Tipped.hide('#custom_form_template_id');
        Tipped.remove('#custom_form_template_id');
        $j(this).data('tipped-object', Tipped.create('#custom_form_template_id', {
          ajax: {
            data: {
              id: id
            },
            type: 'GET',
            async: false,
            cache: false
          },
          hook: "topright",
          closeButtonSkin: 'light',
          target: $j('#custom_form_template_id').closest('div')
        }));
        return $j.ajax("/custom_form/template_settings/" + id + "?update_settings=1&event=removed", {
          type: 'POST',
          async: false,
          cache: false,
          data: $j('#custom_form_template_id').closest('form').serialize() + '&' + $j.param({
            custom_form_id: custom_form_id
          })
        });
      }
    });
    $j(' .respond_to_changes').live('change', function() {
      var params;
      params = $j(this).attr('id').match(/^cf_(\d+)_tf_(\d+)_/i);
      $j("#" + params[1] + "_" + params[2] + "__processing_link").find('a').effect('highlight', {
        duration: 5000
      });
      return true;
    });
    $j(' .process_custom_form_service_charges').live('click', function() {
      var data, form, id;
      form = $j(this).closest('.asset_fields');
      data = {
        instances: JSON.stringify(form.find('.handsontable').data('handsontable').getData()),
        asset_template_id: form.find('input').first().attr('id').match(/\d+/)[0]
      };
      id = $j(this).closest('.open').attr('id').match(/\d+/)[0];
      $j.ajax("/service_item/process_charges/" + id, {
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            $j(_this).prev().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            var prev_ui;
            prev_ui = form.find('.form_wrapper');
            if (prev_ui.length) {
              prev_ui.remove();
            }
            form.append(("<tr><td colspan=3 class='new_asset_info_wrapper form_wrapper' id=" + id + "'>") + response.responseText + '</td></tr>');
            $j(_this).prev().hide();
            return $j(_this).show();
          };
        })(this)
      });
      return false;
    });
    $j(' .service_header').livequery(function() {
      return $j(this).tipsy({
        title: function() {
          return $j(this).find('span').text() + ' service quantity';
        },
        gravity: 'se'
      });
    });
    $j(" .asset_fields .add_charges").livequery(function() {
      var ref, ref1;
      $j(this).data('tipped-object', Tipped.create(this, {
        ajax: {
          type: 'GET',
          cache: false
        },
        hook: (ref = $j(this).data("tipped-hook")) != null ? ref : "bottomright",
        showOn: (ref1 = $j(this).data("tipped-showon")) != null ? ref1 : 'click',
        hideOn: {
          element: 'self',
          event: 'click'
        },
        closeButton: true,
        closeButtonSkin: 'light',
        target: $j(this).closest('div')
      }));
      return $j(this).click(function() {
        return false;
      });
    }, function() {
      Tipped.hide(this);
      return Tipped.remove(this);
    });
    $j(' .data_table_custom_form').livequery(function() {
      var colWidths, columns, data, grid_settings, headers, settings, source, types;
      headers = $j(this).attr('headers').split(',,');
      grid_settings = $j(this).attr('grid_settings');
      columns = [];
      if (grid_settings && (grid_settings !== "null" && grid_settings !== "{}" && grid_settings !== '""')) {
        settings = JSON.parse(grid_settings);
        types = settings.types;
        source = settings.options;
        colWidths = settings.col_widths;
        for (var i=0; i< source.length; i++ ){
         var type = types[i]
         if (type.match(/}/)){
           renderer = eval( type )
           columns.push({ renderer: renderer, source: source[i].split(','), options: { items: 30 } })
         }else{
             if (type == 'date'){
                 columns.push({ type: type,  dateFormat: 'MM/DD/YYYY', source: source[i].split(','), options: { items: 30 } })
             }else{
                 columns.push({ type: type, source: source[i].split(','), options: { items: 30 } })
             }
         }
       };
      } else {
        for (var i=0; i< headers.length; i++ ){
         if (headers[i].match(/&nbsp;/))
           columns.push({ renderer: serviceRenderer, source: [], options: { items: 30 } })
         else
           if (headers[i].match(/location/i))
             columns.push({ renderer: locationRenderer, source: [], options: { items: 30 } })
           else
             columns.push({ type: 'text', source: [], options: { items: 30 } })
       };
      }
      $j(this).data('handsontable', new Handsontable(this, {
        asyncRendering: false,
        minRows: $j(this).data('rows') || 10,
        minSpareRows: 1,
        minCols: headers.length,
        maxCols: headers.length,
        startCols: headers.length,
        columns: columns,
        colWidths: colWidths,
        colHeaders: headers,
        afterGetColHeader: updateChargesHeader,
        rowHeaders: true,
        contextMenu: ["row_above", "row_below", "remove_row"],
        outsideClickDeselects: false,
        scrollV: 'auto',
        scrollH: 'auto',
        width: $j(this).closest('tr.handson_table_tr').width()
      }));
      data = eval($j(this).closest('.tr').find('.handsontable_value').val());
      if (!(0 === data.length)) {
        $j(this).data('handsontable').loadData(data);
      }
      $j(this).data('handsontable').updateSettings({
        afterChange: (function(_this) {
          return function(change, source) {
            data = JSON.stringify($j(_this).data('handsontable').getData());
            return $j(_this).closest('.tr').find('.handsontable_value').val(data);
          };
        })(this),
        afterRemoveRow: (function(_this) {
          return function(change, source) {
            data = JSON.stringify($j(_this).data('handsontable').getData());
            return $j(_this).closest('.tr').find('.handsontable_value').val(data);
          };
        })(this)
      });
      return true;
    });
    $j(' .select_asset_template').live('change', function() {
      var asset_template_id;
      asset_template_id = $j(this).find(':selected').val();
      return $j.ajax("/custom_form/asset_template/" + asset_template_id, {
        method: 'GET',
        complete: (function(_this) {
          return function(response) {
            $j(_this).parents('.header').next().find('.asset_fields').html(response.responseText);
            return Tipped.refresh('*');
          };
        })(this)
      });
    });
    $j(' .simple_asset_toggle').live('click', function() {
      $j(this).closest('tbody').next().toggle();
      $j(this).prev().toggleClass('expanded');
      return false;
    });
    $j(' .add_instances_in_service_item_link').live('click', function() {
      var data, url;
      url = $j(this).attr('action');
      data = {
        instances: JSON.stringify($j(this).parent().prev().prev().data('handsontable').getData())
      };
      $j.ajax(url, {
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            return $j(_this).next().show();
          };
        })(this),
        complete: (function(_this) {
          return function() {
            $j(_this).next().hide();
            return Tipped.hide(_this);
          };
        })(this)
      });
      return false;
    });
    $j("#custom_form_template_id").livequery(function() {
      var custom_form_id, id;
      id = $j(this).find('option:selected').val();
      custom_form_id = $j(this).closest('form').attr('action').match(/\d+/)[0];
      $j(this).data('tipped-object', Tipped.create(this, {
        ajax: {
          data: {
            id: id
          },
          type: 'GET',
          cache: false
        },
        hook: "topright",
        closeButtonSkin: 'light',
        target: $j(this).closest('div')
      }));
      $j.ajax("/custom_form/template_settings/" + id, {
        type: 'GET',
        data: {
          custom_form_id: custom_form_id
        }
      });
      return true;
    }, function() {
      Tipped.hide(this);
      return Tipped.remove(this);
    });
    $j("#custom_form_template_id").change(function() {
      var custom_form_id, id;
      id = $j(this).find('option:selected').val();
      custom_form_id = $j(this).closest('form').attr('action').match(/\d+/)[0];
      Tipped.hide(this);
      Tipped.remove(this);
      $j(this).data('tipped-object', Tipped.create(this, {
        ajax: {
          data: {
            id: id
          },
          type: 'GET',
          cache: false
        },
        hook: "topright",
        closeButtonSkin: 'light',
        target: $j(this).closest('div')
      }));
      $j.ajax("/custom_form/template_settings/" + id, {
        type: 'GET',
        data: $j(this).closest('form').serialize() + '&' + $j.param({
          custom_form_id: custom_form_id
        })
      });
      return true;
    });
    $j(" .email_pdf_button").live('click', function() {
      var url;
      url = $j(this).attr('href');
      $j.ajax(url, {
        type: 'POST',
        success: (function(_this) {
          return function() {
            $j(_this).parent().parent().html('Email will be sent shortly');
            return $j(_this).next().hide();
          };
        })(this)
      });
      return false;
    });
    get_identifier_info = function() {
      var identifiers;
      identifiers = {};
      $j('#template_fields_table .template_fields_identifier').each(function() {
        var elem, value;
        elem = $j(this);
        value = elem.val();
        if (elem.data('templateType') === 'include_asset') {
          return;
        }
        if (identifiers[value] == null) {
          identifiers[value] = [];
        }
        return identifiers[value].push(elem);
      });
      return identifiers;
    };
    show_custom_form_error = function(elem, message) {
      elem = $j(elem);
      elem.addClass('error');
      return elem.after('<div class="simple_error">' + message + '</div>');
    };
    validate_identifiers_and_show_if = function() {
      var identifiers, valid;
      $j('#template_fields_table .simple_error').remove();
      $j('#template_fields_table .template_fields_identifier').removeClass('error');
      $j('#template_fields_table .template_fields_show_if').removeClass('error');
      valid = true;
      identifiers = get_identifier_info();
      $j.each(identifiers, function(identifier, elements) {
        var ok;
        ok = false;
        if (identifier === '') {
          $j.each(elements, function(index, elem) {
            return show_custom_form_error(elem, 'Please enter a unique ID');
          });
        } else if (identifier.match(/[^a-z0-9_]/gi)) {
          $j.each(elements, function(index, elem) {
            return show_custom_form_error(elem, 'Must be alphanumeric or "_"');
          });
        } else if (elements.length > 1 && identifier !== '') {
          $j.each(elements, function(index, elem) {
            return show_custom_form_error(elem, 'Duplicate unique ID');
          });
        } else {
          ok = true;
        }
        if (!ok) {
          valid = false;
        }
        return true;
      });
      $j('#template_fields_table .template_fields_show_if').each(function() {
        var assignments, elem, show_if;
        elem = $j(this);
        show_if = elem.val();
        if (show_if !== '') {
          assignments = show_if.replace(/\|\|/g, '&&').split('&&');
          return $j.each(assignments, function(index, assignment) {
            var ok, pieces, ref;
            ok = false;
            pieces = assignment.split('=');
            if (pieces.length < 2) {
              show_custom_form_error(elem, 'You are missing an "="');
            } else if (pieces.length > 2) {
              show_custom_form_error(elem, 'You have too many "="');
            } else if (((ref = identifiers[pieces[0]]) != null ? ref : []).length === 0) {
              show_custom_form_error(elem, 'Unknown unique ID');
            } else {
              ok = true;
            }
            if (!ok) {
              valid = false;
            }
            return true;
          });
        }
      });
      return valid;
    };
    $j('#template_fields_table').stickyTableHeaders({
      fixedOffset: $j('#top_nav_menu')
    });
    $j('#template_fields_table').on('blur', '.template_fields_identifier, .template_fields_show_if', function() {
      validate_identifiers_and_show_if();
      return true;
    });
    $j('#template_fields_table').on('blur', '.template_fields_label', function(ev) {
      var base, corresponding_identifier, identifiers, label, label_val, new_identifier, ref, suffix;
      label = $j(ev.target);
      label_val = label.val();
      corresponding_identifier = label.closest('tr').find('.template_fields_identifier');
      if (corresponding_identifier.val() === '') {
        identifiers = get_identifier_info();
        suffix = 1;
        new_identifier = base = label_val.replace(/[^a-z0-9_]/gi, '_');
        while (((ref = identifiers[new_identifier]) != null ? ref : []).length > 0) {
          new_identifier = base + '_' + suffix;
          suffix += 1;
        }
        corresponding_identifier.val(new_identifier);
        validate_identifiers_and_show_if();
      }
      return true;
    });
    $j('#custom_form_form').on('ajax:before', function() {
      if (validate_identifiers_and_show_if()) {
        showSpinner($j(this).find('input[type=submit]'));
        return true;
      } else {
        alert('Please correct the fields highlighted in red before modifying or saving the form.');
        return false;
      }
    });
    $j('#custom_form_form').on('ajax:complete', function() {
      return hideSpinner($j(this).find('input[type=submit]'));
    });
    $j.fn.inputFilter = function(options) {
      var currentElement, elements, previousElement, previousValue, settings;
      settings = $j.extend({
        input: 'some_input_name',
        parent: ''
      }, options);
      elements = void 0;
      previousElement = -1;
      currentElement = 0;
      previousValue = '';
      return this.each(function(index) {
        var buttonID, placeholder, self;
        self = this;
        placeholder = $j(this).attr('placeholder') || 'Search...';
        buttonID = "input_filter_" + index + "_button";
        $j(this).after('<a href="javascript:;" id="' + buttonID + '" class="input_filter_buttons"><img src="/images/fff_silk/magnifier.png"></a>');
        $j(this).attr("placeholder", placeholder);
        $j(self).keydown(function(event) {
          if (event.keyCode === 13) {
            return $j("#" + buttonID).trigger('click');
          }
        });
        return $j("#" + buttonID).on('click', function() {
          var element, value;
          value = self.value.toLowerCase();
          if (value.length > 2) {
            if (previousValue !== value) {
              currentElement = 0;
              previousElement = -1;
            }
            elements = $j(settings.input + ":input").filter(function() {
              return this.value.toLowerCase().match("" + value);
            });
            if (settings.parent.length > 0) {
              elements = elements.parents(settings.parent);
            }
            elements = $j(elements.get().reverse());
            if (elements.length <= 0) {
              alert("No matches found!");
              return;
            }
            if (previousElement === currentElement && previousElement < elements.length - 1) {
              currentElement += 1;
            } else if (previousElement >= elements.length - 1) {
              currentElement = 0;
            }
            element = elements.eq(currentElement);
            $j('html, body').animate({
              scrollTop: element.offset().top - 200
            });
            element.clearQueue();
            element.stop(true, true);
            element.effect("highlight", {}, 3000);
            previousElement = currentElement;
            return previousValue = value;
          }
        });
      });
    };
    $j('#label_filter').livequery(function() {
      return $j(this).inputFilter({
        input: '.template_fields_label',
        parent: 'tr'
      });
    });
    $j('#custom_form_print_toggle_all_checkboxes').live('click', function() {
      if ($j(this).prop('checked')) {
        $j(this).closest('table').find('input[type=checkbox]').attr('checked', 'checked');
      } else {
        $j(this).closest('table').find('input[type=checkbox]').attr('checked', false);
      }
      return true;
    });
    return true;
  });

  window.populateInstancesGridForCustomForm = function(id) {
    var url;
    url = "/custom_form/load_generated_instances/" + id;
    return $j.ajax(url, {
      asynchronous: true,
      evalScripts: true,
      complete: (function(_this) {
        return function(response) {
          var data, grid_length;
          data = eval(response.responseText.replace(/\w'\w/, function(text) {
            return text.replace(/\'/, "\\'");
          }));
          if (0 === data.length) {
            data = [[]];
            grid_length = $j("#generate_instances_for_custom_form_grid_" + id).data('handsontable').countCols();
            for (var i=0; i< grid_length; i++ ){
          data[0].push(null)};
          }
          return $j("#generate_instances_for_custom_form_grid_" + id).data('handsontable').loadData(data);
        };
      })(this)
    });
  };

  window.populateGridForCustomForm = function(id, field_number) {
    var url;
    url = "/custom_form/load_generated_instances/" + id;
    return $j.ajax(url, {
      asynchronous: true,
      evalScripts: true,
      complete: (function(_this) {
        return function(response) {
          var data, grid_length;
          data = eval(response.responseText.replace(/\w'\w/, function(text) {
            return text.replace(/\'/, "\\'");
          }));
          if (0 === data.length) {
            data = [[]];
            grid_length = $j("#generate_instances_for_custom_form_grid_" + id + "_" + field_number).data('handsontable').countCols();
            for (var i=0; i< grid_length; i++ ){
          data[0].push(null)};
          }
          $j("#generate_instances_for_custom_form_grid_" + id + "_" + field_number).data('handsontable').loadData(data);
          return true;
        };
      })(this)
    });
  };

  window.fixFormServiceordering = (function(_this) {
    return function(id) {
      return $j(id).find('li input:last-child').each(function(index, el) {
        return $j(el).val(index);
      });
    };
  })(this);

  window.locationRenderer = function(instance, td, row, col, prop, value, cellProperties) {
    var id_name, set_location_link;
    if (value && (id_name = value.split(',')).length > 1) {
      set_location_link = "<a class='tipped_target tipsy_tip' style='cursor:pointer' data-tipped='/location/select/" + id_name[0] + "' location_id='" + id_name[0] + "' original-title='" + id_name[1] + "'>change</a>";
    } else {
      set_location_link = '<a class="tipped_target" style="cursor:pointer" data-tipped="/location/select">set</a>';
    }
    $j(td).html(set_location_link);
    return td;
  };

  window.serviceRenderer = function(instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.TextRenderer.apply(this, arguments);
    return td;
  };

  window.updateChargesHeader = function(col, th) {
    var service_indicators;
    service_indicators = this.getSettings().columns.map(function(el) {
      return el.renderer && el.renderer === serviceRenderer;
    });
    if (col >= service_indicators.indexOf(true) && service_indicators.indexOf(true) > 0) {
      $j(th).css('color', 'green');
      $j(th).tipsy({
        title: function() {
          return $j(this).find('span').text() + ' service quantity';
        },
        gravity: 'se'
      });
    } else {
      $j(th).css('color', '');
      $j(th).replaceWith($j(th).clone());
    }
    return th;
  };

  $j.fn.serializeObject = function() {
    var json, patterns, push_counters;
    json = {};
    push_counters = {};
    patterns = {
      validate: /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
      key: /[a-zA-Z0-9_]+|(?=\[\])/g,
      push: /^$/,
      fixed: /^\d+$/,
      named: /^[a-zA-Z0-9_]+$/
    };
    this.build = function(base, key, value) {
      base[key] = value;
      return base;
    };
    this.push_counter = function(key) {
      if (push_counters[key] === void 0) {
        push_counters[key] = 0;
      }
      return push_counters[key]++;
    };
    $j.each($j(this).serializeArray(), (function(_this) {
      return function(i, elem) {
        var k, keys, merge, re, reverse_key;
        if (!patterns.validate.test(elem.name)) {
          return;
        }
        keys = elem.name.match(patterns.key);
        merge = elem.value;
        reverse_key = elem.name;
        while ((k = keys.pop()) !== void 0) {
          if (patterns.push.test(k)) {
            re = new RegExp("\\[" + k + "\\]$");
            reverse_key = reverse_key.replace(re, '');
            merge = _this.build([], _this.push_counter(reverse_key), merge);
          } else if (patterns.fixed.test(k)) {
            merge = _this.build([], k, merge);
          } else if (patterns.named.test(k)) {
            merge = _this.build({}, k, merge);
          }
        }
        return json = $j.extend(true, json, merge);
      };
    })(this));
    return json;
  };

  window.SerializedFormObserver = (function() {
    function SerializedFormObserver(observed_element, interval) {
      this.observed_element = observed_element;
      this.interval = interval;
    }

    SerializedFormObserver.prototype.observe = function(callback_func) {
      var timeout_func;
      timeout_func = (function(_this) {
        return function() {
          var serializedValue;
          serializedValue = _this.getSerializedValue();
          if (serializedValue !== _this.lastSerializedValue) {
            _this.lastSerializedValue = serializedValue;
            return callback_func(serializedValue);
          }
        };
      })(this);
      this.lastSerializedValue = this.getSerializedValue();
      return this.intervalID = setInterval(timeout_func, this.interval);
    };

    SerializedFormObserver.prototype.halt = function() {
      if (this.intervalID != null) {
        return clearInterval(this.intervalID);
      }
    };

    SerializedFormObserver.prototype.getSerializedValue = function() {
      var form_elements, serialized;
      serialized = '';
      form_elements = this.observed_element.find(':input');
      if (form_elements.length > 0) {
        serialized = form_elements.serialize();
      }
      return serialized;
    };

    return SerializedFormObserver;

  })();

}).call(this);
(function() {
  var combine_params;

  combine_params = function(element, payload) {
    if (element.data("params") !== void 0) {
      return (element.data("params")) + "&" + ($j.param(payload.serializeArray()));
    } else {
      return $j.param(payload.serializeArray());
    }
  };

  $j("a[data-submit]").live("ajax:before", function(event) {
    var $payload, $this;
    $this = $j(this);
    $payload = $j("#" + ($this.data("submit")) + " :input");
    $this.data("params", combine_params($this, $payload));
    return true;
  });

  $j("a[data-with]").live('ajax:before', function(event) {
    var $payload, $this;
    $this = $j(this);
    $payload = $j($this.data("with"));
    if ($payload.length > 0) {
      $this.data("params", combine_params($this, $payload));
    }
    return true;
  });

  $j("a[data-submit], a[data-with]").live("ajax:complete", function(event, xhr, status) {
    return $j(this).removeData("params");
  });

  $j("a[data-update]").live('ajax:success', function(event, data, status, xhr) {
    var target;
    target = "#" + ($j(this).data("update"));
    return $j(target).html(data).show();
  });

  $j("button[data-path]").live("click", function(event) {
    var $this, form;
    event.preventDefault();
    $this = $j(this);
    if ($this.data("submit")) {
      form = $this.closest("form");
      if ($this.data("path").toString() !== "") {
        form.attr("action", $this.data("path"));
      }
      if ($this.data("method").toString() !== "") {
        form.attr("method", $this.data("method"));
      }
      return form.submit();
    } else {
      if (($this.data("method") || "GET") === "GET") {
        return window.location.replace($this.data("path"));
      } else {
        return $j.ajax({
          url: $this.data("path"),
          type: $this.data("method")
        });
      }
    }
  });

}).call(this);
(function() {
  $j(function() {
    $j(' .select_ecs.external').livequery(function() {
      $j(this).next().text($j(this).find('option:selected').data('label'));
      if (parseInt($j(this).find('option:selected').data('permission')) < 0) {
        $j(this).next().next().attr('disabled', 'disabled');
      }
      if ($j(this).find('option:selected').data('show')) {
        $j(this).next().show();
        return $j(this).next().next().show();
      } else {
        $j(this).next().hide();
        return $j(this).next().next().hide();
      }
    });
    $j(' .select_ecs.external').live('change', function() {
      $j(this).next().text($j(this).find('option:selected').data('label'));
      if (parseInt($j(this).find('option:selected').data('permission')) < 0) {
        $j(this).next().next().attr('disabled', 'disabled');
      }
      if ($j(this).find('option:selected').data('show')) {
        $j(this).next().show();
        $j(this).next().next().show();
      } else {
        $j(this).next().hide();
        $j(this).next().next().hide();
      }
      return Tipped.refresh('*');
    });
    $j("select.cshl_payment").livequery('change', function() {
      var ecs, item_id;
      ecs = $j(this).find('option:selected');
      item_id = $j(this).data('item_id');
      $j("#accounting_unit_" + item_id).val(ecs.data('accounting_unit'));
      $j("#account_number_" + item_id).val(ecs.data('account_number'));
      return $j("#account_category_" + item_id).val(ecs.data('account_category'));
    });
    window.aggregate_asu_payment = function(id) {
      var v, v1, v2, v3;
      v1 = $j('#department_reporting_roll_options_' + id).attr('value');
      v2 = $j('#department_reporting_options_' + id).attr('value');
      v3 = $j('#audit_reporting_options_' + id).attr('value');
      v = v1 + "|" + v2 + "|" + v3;
      $j('#cost_allocation_' + id + '_payment_user_field').val(v);
      return false;
    };
    window.show_fund_ecs_update = function(obj) {
      var show;
      show = $j(':selected', obj).data('show_fund') != null;
      $j('+ .extra', obj).toggle(show);
      $j('+ .extra input', obj).prop('disabled', !show);
      return Tipped.refresh('*');
    };
    $j('input.user_field_dropdown').livequery(function() {
      return $j(this).select2({
        allowClear: true,
        placeholder: 'Search for a ' + $j(this).data('user_field'),
        minimumInputLength: 3,
        width: '80%',
        ajax: {
          url: this.dataset.url,
          dataType: 'json',
          quietMillis: 250,
          results: function(data) {
            return data;
          },
          data: function(term, page) {
            return {
              q: term,
              page: page
            };
          }
        },
        initSelection: function(element, callback) {
          callback(element.data('data'));
          return Tipped.refresh('*');
        }
      }).select2('val', []);
    });
    return false;
  });

}).call(this);
(function() {
  $j(function() {
    $j(' .apply_addon_justification').livequery('click', function(event) {
      var form, justification, li_id;
      event.preventDefault();
      form = $j(this).closest('form');
      if (form.find('#justification').val() === '') {
        alert('Please specify the justification.');
        return false;
      }
      li_id = form.find('.line_item_id').val();
      justification = form.find('.justification').val();
      no_charge_addon(true, li_id, justification);
      $j('#no_charge_check_box_' + li_id).prop('checked', true);
      Tipped.hide('#no_charge_check_box_' + li_id);
      return false;
    });
    true;
    $j(' .apply_event_justification').livequery('click', function(event) {
      var event_id, form, justification;
      event.preventDefault();
      form = $j(this).closest('form');
      if (form.find('#justification').val() === '') {
        alert('Please specify the justification.');
        return false;
      }
      event_id = form.find('.event_id').val();
      justification = form.find('.justification').val();
      updateNoCharge(true, event_id, justification);
      $j('#nocharge_yes_no_' + event_id).prop('checked', true);
      Tipped.hideAll('*');
      return false;
    });
    $j(' .apply_line_item_justification').livequery('click', function() {
      var form;
      form = $j(this).closest('form');
      if (form.find('#justification').val() === '') {
        alert('Please specify the justification.');
        return false;
      }
      $j.ajax(form.attr('url'), {
        type: 'POST',
        data: form.serialize(),
        dataType: 'script',
        beforeSend: (function(_this) {
          return function() {
            return showSpinner(_this);
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            eval(response.responseText);
            hideSpinner(_this);
            return Tipped.hideAll("*");
          };
        })(this)
      });
      return false;
    });
    return true;
  });

  window.beforeUpdateNoCharge = function(me, event_id) {
    var old_value;
    if ($j(me).data('require_justification') === true && $j(me).prop('checked')) {
      Tipped.setDefaultSkin("light");
      old_value = $j(me).data('value');
      $j(me).prop('checked', !$j(me).prop('checked'));
      $j(me).data('tipped-object', Tipped.create(me, '/service_event/charge_justification_options?event_id=' + event_id, {
        ajax: {
          async: false,
          cache: false,
          data: {
            tipped_ajax_request: true
          }
        },
        hideOn: false,
        showOn: false,
        closeButton: true,
        closeButtonSkin: 'light',
        containment: '#wrapper_main',
        onShow: function(content, element) {
          eval($j(element).data('callback'));
          return setTimeout(function() {
            return Tipped.refresh(element);
          }, 1000);
        },
        onHide: (function(_this) {
          return function(content, element) {
            return eval($j(element).data('hide-callback'));
          };
        })(this)
      }));
      Tipped.show(me);
      return false;
    } else {
      Tipped.remove(me);
      $j(me).prop('checked');
      return updateNoCharge($j(me).prop('checked'), event_id, null);
    }
  };

  window.updateNoCharge = function(checked, event_id, justification) {
    var data;
    data = {
      event_id: event_id,
      no_charge: checked,
      justification: justification
    };
    $j('#availabilities_' + event_id).html('');
    $j.ajax("/service_event/save_no_charge", {
      beforeSend: function() {
        $j('#summary_spinner_wrapper_short_' + event_id + ', #summary_spinner_short_' + event_id).show();
        return $j('#times_summary_wrapper_short_' + event_id).html('');
      },
      success: function() {
        return $j('#summary_spinner_wrapper_short_' + event_id + ', #summary_spinner_short_' + event_id).hide();
      },
      data: data
    });
    return true;
  };

}).call(this);
(function() {
  $j(function() {
    var datepickerHandler;
    datepickerHandler = function(context) {
      var handler, handlerClass, parentHandler;
      handlerClass = 'datepicker_handler';
      handler = $j(context).next('.datepicker_handler');
      parentHandler = $j(context).parent().next('.datepicker_handler');
      if (handler.length > 0) {
        return handler;
      }
      if ($j(context).parent().hasClass('field_with_errors') && (parentHandler.length > 0)) {
        return parentHandler;
      }
      return null;
    };
    return $j('.ilab_datepicker').livequery(function() {
      if ($j(this).data('attribute') === 'time_only') {
        $j(this).datetimepicker({
          datepicker: false,
          scrollInput: false,
          step: 5,
          format: 'H:i'
        });
      } else if ($j(this).data('attribute') === 'time') {
        $j(this).datetimepicker({
          format: 'M d, Y H:i',
          scrollInput: false
        });
      } else if ($j(this).data('attribute') === 'popup' || $j(this).hasClass('no_time')) {
        $j(this).datetimepicker({
          format: 'M d, Y',
          timepicker: false,
          maxDate: $j(this).data('maxdate'),
          minDate: $j(this).data('mindate'),
          scrollInput: false
        });
      }
      if (!$j(this).hasClass('no_calendar_icon')) {
        if ($j(this).data('attribute') !== 'time_only') {
          if (!datepickerHandler(this)) {
            $j(this).after("<img class='datepicker_handler' style='margin-left: 2px;' src='/images/calendar.gif'/>");
          }
          return datepickerHandler(this).click((function(_this) {
            return function() {
              return $j(_this).datetimepicker('show');
            };
          })(this));
        }
      }
    });
  });

}).call(this);
/*!
 * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2015
 * @version 1.3.3
 *
 * Date formatter utility library that allows formatting date/time variables or Date objects using PHP DateTime format.
 * @see http://php.net/manual/en/function.date.php
 *
 * For more JQuery plugins visit http://plugins.krajee.com
 * For more Yii related demos visit http://demos.krajee.com
 */

var DateFormatter;
(function () {
    "use strict";

    var _compare, _lpad, _extend, defaultSettings, DAY, HOUR;
    DAY = 1000 * 60 * 60 * 24;
    HOUR = 3600;

    _compare = function (str1, str2) {
        return typeof(str1) === 'string' && typeof(str2) === 'string' && str1.toLowerCase() === str2.toLowerCase();
    };
    _lpad = function (value, length, char) {
        var chr = char || '0', val = value.toString();
        return val.length < length ? _lpad(chr + val, length) : val;
    };
    _extend = function (out) {
        var i, obj;
        out = out || {};
        for (i = 1; i < arguments.length; i++) {
            obj = arguments[i];
            if (!obj) {
                continue;
            }
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (typeof obj[key] === 'object') {
                        _extend(out[key], obj[key]);
                    } else {
                        out[key] = obj[key];
                    }
                }
            }
        }
        return out;
    };
    defaultSettings = {
        dateSettings: {
            days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            months: [
                'January', 'February', 'March', 'April', 'May', 'June', 'July',
                'August', 'September', 'October', 'November', 'December'
            ],
            monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            meridiem: ['AM', 'PM'],
            ordinal: function (number) {
                var n = number % 10, suffixes = {1: 'st', 2: 'nd', 3: 'rd'};
                return Math.floor(number % 100 / 10) === 1 || !suffixes[n] ? 'th' : suffixes[n];
            }
        },
        separators: /[ \-+\/\.T:@]/g,
        validParts: /[dDjlNSwzWFmMntLoYyaABgGhHisueTIOPZcrU]/g,
        intParts: /[djwNzmnyYhHgGis]/g,
        tzParts: /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        tzClip: /[^-+\dA-Z]/g
    };

    DateFormatter = function (options) {
        var self = this, config = _extend(defaultSettings, options);
        self.dateSettings = config.dateSettings;
        self.separators = config.separators;
        self.validParts = config.validParts;
        self.intParts = config.intParts;
        self.tzParts = config.tzParts;
        self.tzClip = config.tzClip;
    };

    DateFormatter.prototype = {
        constructor: DateFormatter,
        parseDate: function (vDate, vFormat) {
            var self = this, vFormatParts, vDateParts, i, vDateFlag = false, vTimeFlag = false, vDatePart, iDatePart,
                vSettings = self.dateSettings, vMonth, vMeriIndex, vMeriOffset, len, mer,
                out = {date: null, year: null, month: null, day: null, hour: 0, min: 0, sec: 0};
            if (!vDate) {
                return undefined;
            }
            if (vDate instanceof Date) {
                return vDate;
            }
            if (typeof vDate === 'number') {
                return new Date(vDate);
            }
            if (vFormat === 'U') {
                i = parseInt(vDate);
                return i ? new Date(i * 1000) : vDate;
            }
            if (typeof vDate !== 'string') {
                return '';
            }
            vFormatParts = vFormat.match(self.validParts);
            if (!vFormatParts || vFormatParts.length === 0) {
                throw new Error("Invalid date format definition.");
            }
            vDateParts = vDate.replace(self.separators, '\0').split('\0');
            for (i = 0; i < vDateParts.length; i++) {
                vDatePart = vDateParts[i];
                iDatePart = parseInt(vDatePart);
                switch (vFormatParts[i]) {
                    case 'y':
                    case 'Y':
                        len = vDatePart.length;
                        if (len === 2) {
                            out.year = parseInt((iDatePart < 70 ? '20' : '19') + vDatePart);
                        } else if (len === 4) {
                            out.year = iDatePart;
                        }
                        vDateFlag = true;
                        break;
                    case 'm':
                    case 'n':
                    case 'M':
                    case 'F':
                        if (isNaN(vDatePart)) {
                            vMonth = vSettings.monthsShort.indexOf(vDatePart);
                            if (vMonth > -1) {
                                out.month = vMonth + 1;
                            }
                            vMonth = vSettings.months.indexOf(vDatePart);
                            if (vMonth > -1) {
                                out.month = vMonth + 1;
                            }
                        } else {
                            if (iDatePart >= 1 && iDatePart <= 12) {
                                out.month = iDatePart;
                            }
                        }
                        vDateFlag = true;
                        break;
                    case 'd':
                    case 'j':
                        if (iDatePart >= 1 && iDatePart <= 31) {
                            out.day = iDatePart;
                        }
                        vDateFlag = true;
                        break;
                    case 'g':
                    case 'h':
                        vMeriIndex = (vFormatParts.indexOf('a') > -1) ? vFormatParts.indexOf('a') :
                            (vFormatParts.indexOf('A') > -1) ? vFormatParts.indexOf('A') : -1;
                        mer = vDateParts[vMeriIndex];
                        if (vMeriIndex > -1) {
                            vMeriOffset = _compare(mer, vSettings.meridiem[0]) ? 0 :
                                (_compare(mer, vSettings.meridiem[1]) ? 12 : -1);
                            if (iDatePart >= 1 && iDatePart <= 12 && vMeriOffset > -1) {
                                out.hour = iDatePart + vMeriOffset;
                            } else if (iDatePart >= 0 && iDatePart <= 23) {
                                out.hour = iDatePart;
                            }
                        } else if (iDatePart >= 0 && iDatePart <= 23) {
                            out.hour = iDatePart;
                        }
                        vTimeFlag = true;
                        break;
                    case 'G':
                    case 'H':
                        if (iDatePart >= 0 && iDatePart <= 23) {
                            out.hour = iDatePart;
                        }
                        vTimeFlag = true;
                        break;
                    case 'i':
                        if (iDatePart >= 0 && iDatePart <= 59) {
                            out.min = iDatePart;
                        }
                        vTimeFlag = true;
                        break;
                    case 's':
                        if (iDatePart >= 0 && iDatePart <= 59) {
                            out.sec = iDatePart;
                        }
                        vTimeFlag = true;
                        break;
                }
            }
            if (vDateFlag === true && out.year && out.month && out.day) {
                out.date = new Date(out.year, out.month - 1, out.day, out.hour, out.min, out.sec, 0);
            } else {
                if (vTimeFlag !== true) {
                    return false;
                }
                out.date = new Date(0, 0, 0, out.hour, out.min, out.sec, 0);
            }
            return out.date;
        },
        guessDate: function (vDateStr, vFormat) {
            if (typeof vDateStr !== 'string') {
                return vDateStr;
            }
            var self = this, vParts = vDateStr.replace(self.separators, '\0').split('\0'), vPattern = /^[djmn]/g,
                vFormatParts = vFormat.match(self.validParts), vDate = new Date(), vDigit = 0, vYear, i, iPart, iSec;

            if (!vPattern.test(vFormatParts[0])) {
                return vDateStr;
            }

            for (i = 0; i < vParts.length; i++) {
                vDigit = 2;
                iPart = vParts[i];
                iSec = parseInt(iPart.substr(0, 2));
                switch (i) {
                    case 0:
                        if (vFormatParts[0] === 'm' || vFormatParts[0] === 'n') {
                            vDate.setMonth(iSec - 1);
                        } else {
                            vDate.setDate(iSec);
                        }
                        break;
                    case 1:
                        if (vFormatParts[0] === 'm' || vFormatParts[0] === 'n') {
                            vDate.setDate(iSec);
                        } else {
                            vDate.setMonth(iSec - 1);
                        }
                        break;
                    case 2:
                        vYear = vDate.getFullYear();
                        if (iPart.length < 4) {
                            vDate.setFullYear(parseInt(vYear.toString().substr(0, 4 - iPart.length) + iPart));
                            vDigit = iPart.length;
                        } else {
                            vDate.setFullYear = parseInt(iPart.substr(0, 4));
                            vDigit = 4;
                        }
                        break;
                    case 3:
                        vDate.setHours(iSec);
                        break;
                    case 4:
                        vDate.setMinutes(iSec);
                        break;
                    case 5:
                        vDate.setSeconds(iSec);
                        break;
                }
                if (iPart.substr(vDigit).length > 0) {
                    vParts.splice(i + 1, 0, iPart.substr(vDigit));
                }
            }
            return vDate;
        },
        parseFormat: function (vChar, vDate) {
            var self = this, vSettings = self.dateSettings, fmt, backspace = /\\?(.?)/gi, doFormat = function (t, s) {
                return fmt[t] ? fmt[t]() : s;
            };
            fmt = {
                /////////
                // DAY //
                /////////
                /**
                 * Day of month with leading 0: `01..31`
                 * @return {string}
                 */
                d: function () {
                    return _lpad(fmt.j(), 2);
                },
                /**
                 * Shorthand day name: `Mon...Sun`
                 * @return {string}
                 */
                D: function () {
                    return vSettings.daysShort[fmt.w()];
                },
                /**
                 * Day of month: `1..31`
                 * @return {number}
                 */
                j: function () {
                    return vDate.getDate();
                },
                /**
                 * Full day name: `Monday...Sunday`
                 * @return {number}
                 */
                l: function () {
                    return vSettings.days[fmt.w()];
                },
                /**
                 * ISO-8601 day of week: `1[Mon]..7[Sun]`
                 * @return {number}
                 */
                N: function () {
                    return fmt.w() || 7;
                },
                /**
                 * Day of week: `0[Sun]..6[Sat]`
                 * @return {number}
                 */
                w: function () {
                    return vDate.getDay();
                },
                /**
                 * Day of year: `0..365`
                 * @return {number}
                 */
                z: function () {
                    var a = new Date(fmt.Y(), fmt.n() - 1, fmt.j()), b = new Date(fmt.Y(), 0, 1);
                    return Math.round((a - b) / DAY);
                },

                //////////
                // WEEK //
                //////////
                /**
                 * ISO-8601 week number
                 * @return {number}
                 */
                W: function () {
                    var a = new Date(fmt.Y(), fmt.n() - 1, fmt.j() - fmt.N() + 3), b = new Date(a.getFullYear(), 0, 4);
                    return _lpad(1 + Math.round((a - b) / DAY / 7), 2);
                },

                ///////////
                // MONTH //
                ///////////
                /**
                 * Full month name: `January...December`
                 * @return {string}
                 */
                F: function () {
                    return vSettings.months[vDate.getMonth()];
                },
                /**
                 * Month w/leading 0: `01..12`
                 * @return {string}
                 */
                m: function () {
                    return _lpad(fmt.n(), 2);
                },
                /**
                 * Shorthand month name; `Jan...Dec`
                 * @return {string}
                 */
                M: function () {
                    return vSettings.monthsShort[vDate.getMonth()];
                },
                /**
                 * Month: `1...12`
                 * @return {number}
                 */
                n: function () {
                    return vDate.getMonth() + 1;
                },
                /**
                 * Days in month: `28...31`
                 * @return {number}
                 */
                t: function () {
                    return (new Date(fmt.Y(), fmt.n(), 0)).getDate();
                },

                //////////
                // YEAR //
                //////////
                /**
                 * Is leap year? `0 or 1`
                 * @return {number}
                 */
                L: function () {
                    var Y = fmt.Y();
                    return (Y % 4 === 0 && Y % 100 !== 0 || Y % 400 === 0) ? 1 : 0;
                },
                /**
                 * ISO-8601 year
                 * @return {number}
                 */
                o: function () {
                    var n = fmt.n(), W = fmt.W(), Y = fmt.Y();
                    return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0);
                },
                /**
                 * Full year: `e.g. 1980...2010`
                 * @return {number}
                 */
                Y: function () {
                    return vDate.getFullYear();
                },
                /**
                 * Last two digits of year: `00...99`
                 * @return {string}
                 */
                y: function () {
                    return fmt.Y().toString().slice(-2);
                },

                //////////
                // TIME //
                //////////
                /**
                 * Meridian lower: `am or pm`
                 * @return {string}
                 */
                a: function () {
                    return fmt.A().toLowerCase();
                },
                /**
                 * Meridian upper: `AM or PM`
                 * @return {string}
                 */
                A: function () {
                    var n = fmt.G() < 12 ? 0 : 1;
                    return vSettings.meridiem[n];
                },
                /**
                 * Swatch Internet time: `000..999`
                 * @return {string}
                 */
                B: function () {
                    var H = vDate.getUTCHours() * HOUR, i = vDate.getUTCMinutes() * 60, s = vDate.getUTCSeconds();
                    return _lpad(Math.floor((H + i + s + HOUR) / 86.4) % 1000, 3);
                },
                /**
                 * 12-Hours: `1..12`
                 * @return {number}
                 */
                g: function () {
                    return fmt.G() % 12 || 12;
                },
                /**
                 * 24-Hours: `0..23`
                 * @return {number}
                 */
                G: function () {
                    return vDate.getHours();
                },
                /**
                 * 12-Hours with leading 0: `01..12`
                 * @return {string}
                 */
                h: function () {
                    return _lpad(fmt.g(), 2);
                },
                /**
                 * 24-Hours w/leading 0: `00..23`
                 * @return {string}
                 */
                H: function () {
                    return _lpad(fmt.G(), 2);
                },
                /**
                 * Minutes w/leading 0: `00..59`
                 * @return {string}
                 */
                i: function () {
                    return _lpad(vDate.getMinutes(), 2);
                },
                /**
                 * Seconds w/leading 0: `00..59`
                 * @return {string}
                 */
                s: function () {
                    return _lpad(vDate.getSeconds(), 2);
                },
                /**
                 * Microseconds: `000000-999000`
                 * @return {string}
                 */
                u: function () {
                    return _lpad(vDate.getMilliseconds() * 1000, 6);
                },

                //////////////
                // TIMEZONE //
                //////////////
                /**
                 * Timezone identifier: `e.g. Atlantic/Azores, ...`
                 * @return {string}
                 */
                e: function () {
                    var str = /\((.*)\)/.exec(String(vDate))[1];
                    return str || 'Coordinated Universal Time';
                },
                /**
                 * Timezone abbreviation: `e.g. EST, MDT, ...`
                 * @return {string}
                 */
                T: function () {
                    var str = (String(vDate).match(self.tzParts) || [""]).pop().replace(self.tzClip, "");
                    return str || 'UTC';
                },
                /**
                 * DST observed? `0 or 1`
                 * @return {number}
                 */
                I: function () {
                    var a = new Date(fmt.Y(), 0), c = Date.UTC(fmt.Y(), 0),
                        b = new Date(fmt.Y(), 6), d = Date.UTC(fmt.Y(), 6);
                    return ((a - c) !== (b - d)) ? 1 : 0;
                },
                /**
                 * Difference to GMT in hour format: `e.g. +0200`
                 * @return {string}
                 */
                O: function () {
                    var tzo = vDate.getTimezoneOffset(), a = Math.abs(tzo);
                    return (tzo > 0 ? '-' : '+') + _lpad(Math.floor(a / 60) * 100 + a % 60, 4);
                },
                /**
                 * Difference to GMT with colon: `e.g. +02:00`
                 * @return {string}
                 */
                P: function () {
                    var O = fmt.O();
                    return (O.substr(0, 3) + ':' + O.substr(3, 2));
                },
                /**
                 * Timezone offset in seconds: `-43200...50400`
                 * @return {number}
                 */
                Z: function () {
                    return -vDate.getTimezoneOffset() * 60;
                },

                ////////////////////
                // FULL DATE TIME //
                ////////////////////
                /**
                 * ISO-8601 date
                 * @return {string}
                 */
                c: function () {
                    return 'Y-m-d\\TH:i:sP'.replace(backspace, doFormat);
                },
                /**
                 * RFC 2822 date
                 * @return {string}
                 */
                r: function () {
                    return 'D, d M Y H:i:s O'.replace(backspace, doFormat);
                },
                /**
                 * Seconds since UNIX epoch
                 * @return {number}
                 */
                U: function () {
                    return vDate.getTime() / 1000 || 0;
                }
            };
            return doFormat(vChar, vChar);
        },
        formatDate: function (vDate, vFormat) {
            var self = this, i, n, len, str, vChar, vDateStr = '';
            if (typeof vDate === 'string') {
                vDate = self.parseDate(vDate, vFormat);
                if (vDate === false) {
                    return false;
                }
            }
            if (vDate instanceof Date) {
                len = vFormat.length;
                for (i = 0; i < len; i++) {
                    vChar = vFormat.charAt(i);
                    if (vChar === 'S') {
                        continue;
                    }
                    str = self.parseFormat(vChar, vDate);
                    if (i !== (len - 1) && self.intParts.test(vChar) && vFormat.charAt(i + 1) === 'S') {
                        n = parseInt(str);
                        str += self.dateSettings.ordinal(n);
                    }
                    vDateStr += str;
                }
                return vDateStr;
            }
            return '';
        }
    };
})();/**
 * @preserve jQuery DateTimePicker plugin v2.5.4
 * @homepage http://xdsoft.net/jqplugins/datetimepicker/
 * @author Chupurnov Valeriy (<chupurnov@gmail.com>)
 */
/*global DateFormatter, document,window,jQuery,setTimeout,clearTimeout,HighlightedDate,getCurrentValue*/
;(function (factory) {
	if ( typeof define === 'function' && define.amd ) {
		// AMD. Register as an anonymous module.
		define(['jquery', 'jquery-mousewheel'], factory);
	} else if (typeof exports === 'object') {
		// Node/CommonJS style for Browserify
		module.exports = factory;
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {
	'use strict';
	
	var currentlyScrollingTimeDiv = false;
	
	var default_options  = {
		i18n: {
			ar: { // Arabic
				months: [
					"كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"
				],
				dayOfWeekShort: [
					"ن", "ث", "ع", "خ", "ج", "س", "ح"
				],
				dayOfWeek: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"]
			},
			ro: { // Romanian
				months: [
					"Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"
				],
				dayOfWeekShort: [
					"Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ"
				],
				dayOfWeek: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă"]
			},
			id: { // Indonesian
				months: [
					"Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
				],
				dayOfWeekShort: [
					"Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"
				],
				dayOfWeek: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
			},
			is: { // Icelandic
				months: [
					"Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"
				],
				dayOfWeekShort: [
					"Sun", "Mán", "Þrið", "Mið", "Fim", "Fös", "Lau"
				],
				dayOfWeek: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"]
			},
			bg: { // Bulgarian
				months: [
					"Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
				],
				dayOfWeekShort: [
					"Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
				],
				dayOfWeek: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"]
			},
			fa: { // Persian/Farsi
				months: [
					'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
				],
				dayOfWeekShort: [
					'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
				],
				dayOfWeek: ["یک‌شنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنج‌شنبه", "جمعه", "شنبه", "یک‌شنبه"]
			},
			ru: { // Russian
				months: [
					'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
				],
				dayOfWeekShort: [
					"Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
				],
				dayOfWeek: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"]
			},
			uk: { // Ukrainian
				months: [
					'Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'
				],
				dayOfWeekShort: [
					"Ндл", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Сбт"
				],
				dayOfWeek: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"]
			},
			en: { // English
				months: [
					"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
				],
				dayOfWeekShort: [
					"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
				],
				dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
			},
			el: { // Ελληνικά
				months: [
					"Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
				],
				dayOfWeekShort: [
					"Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
				],
				dayOfWeek: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο"]
			},
			de: { // German
				months: [
					'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'
				],
				dayOfWeekShort: [
					"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
				],
				dayOfWeek: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]
			},
			nl: { // Dutch
				months: [
					"januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
				],
				dayOfWeekShort: [
					"zo", "ma", "di", "wo", "do", "vr", "za"
				],
				dayOfWeek: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]
			},
			tr: { // Turkish
				months: [
					"Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
				],
				dayOfWeekShort: [
					"Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
				],
				dayOfWeek: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"]
			},
			fr: { //French
				months: [
					"Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
				],
				dayOfWeekShort: [
					"Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
				],
				dayOfWeek: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]
			},
			es: { // Spanish
				months: [
					"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
				],
				dayOfWeekShort: [
					"Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
				],
				dayOfWeek: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"]
			},
			th: { // Thai
				months: [
					'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
				],
				dayOfWeekShort: [
					'อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'
				],
				dayOfWeek: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"]
			},
			pl: { // Polish
				months: [
					"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
				],
				dayOfWeekShort: [
					"nd", "pn", "wt", "śr", "cz", "pt", "sb"
				],
				dayOfWeek: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"]
			},
			pt: { // Portuguese
				months: [
					"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
				],
				dayOfWeekShort: [
					"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
				],
				dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
			},
			ch: { // Simplified Chinese
				months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
				],
				dayOfWeekShort: [
					"日", "一", "二", "三", "四", "五", "六"
				]
			},
			se: { // Swedish
				months: [
					"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September",  "Oktober", "November", "December"
				],
				dayOfWeekShort: [
					"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
				]
			},
			kr: { // Korean
				months: [
					"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
				],
				dayOfWeekShort: [
					"일", "월", "화", "수", "목", "금", "토"
				],
				dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
			},
			it: { // Italian
				months: [
					"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
				],
				dayOfWeekShort: [
					"Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
				],
				dayOfWeek: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"]
			},
			da: { // Dansk
				months: [
					"January", "Februar", "Marts", "April", "Maj", "Juni", "July", "August", "September", "Oktober", "November", "December"
				],
				dayOfWeekShort: [
					"Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
				],
				dayOfWeek: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"]
			},
			no: { // Norwegian
				months: [
					"Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"
				],
				dayOfWeekShort: [
					"Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
				],
				dayOfWeek: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag']
			},
			ja: { // Japanese
				months: [
					"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
				],
				dayOfWeekShort: [
					"日", "月", "火", "水", "木", "金", "土"
				],
				dayOfWeek: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜"]
			},
			vi: { // Vietnamese
				months: [
					"Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
				],
				dayOfWeekShort: [
					"CN", "T2", "T3", "T4", "T5", "T6", "T7"
				],
				dayOfWeek: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"]
			},
			sl: { // Slovenščina
				months: [
					"Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
				],
				dayOfWeekShort: [
					"Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
				],
				dayOfWeek: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"]
			},
			cs: { // Čeština
				months: [
					"Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"
				],
				dayOfWeekShort: [
					"Ne", "Po", "Út", "St", "Čt", "Pá", "So"
				]
			},
			hu: { // Hungarian
				months: [
					"Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"
				],
				dayOfWeekShort: [
					"Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo"
				],
				dayOfWeek: ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"]
			},
			az: { //Azerbaijanian (Azeri)
				months: [
					"Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr"
				],
				dayOfWeekShort: [
					"B", "Be", "Ça", "Ç", "Ca", "C", "Ş"
				],
				dayOfWeek: ["Bazar", "Bazar ertəsi", "Çərşənbə axşamı", "Çərşənbə", "Cümə axşamı", "Cümə", "Şənbə"]
			},
			bs: { //Bosanski
				months: [
					"Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
				],
				dayOfWeekShort: [
					"Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
				],
				dayOfWeek: ["Nedjelja","Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
			},
			ca: { //Català
				months: [
					"Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"
				],
				dayOfWeekShort: [
					"Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"
				],
				dayOfWeek: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"]
			},
			'en-GB': { //English (British)
				months: [
					"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
				],
				dayOfWeekShort: [
					"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
				],
				dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
			},
			et: { //"Eesti"
				months: [
					"Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"
				],
				dayOfWeekShort: [
					"P", "E", "T", "K", "N", "R", "L"
				],
				dayOfWeek: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"]
			},
			eu: { //Euskara
				months: [
					"Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua"
				],
				dayOfWeekShort: [
					"Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La."
				],
				dayOfWeek: ['Igandea', 'Astelehena', 'Asteartea', 'Asteazkena', 'Osteguna', 'Ostirala', 'Larunbata']
			},
			fi: { //Finnish (Suomi)
				months: [
					"Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu"
				],
				dayOfWeekShort: [
					"Su", "Ma", "Ti", "Ke", "To", "Pe", "La"
				],
				dayOfWeek: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"]
			},
			gl: { //Galego
				months: [
					"Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec"
				],
				dayOfWeekShort: [
					"Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab"
				],
				dayOfWeek: ["Domingo", "Luns", "Martes", "Mércores", "Xoves", "Venres", "Sábado"]
			},
			hr: { //Hrvatski
				months: [
					"Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"
				],
				dayOfWeekShort: [
					"Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
				],
				dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
			},
			ko: { //Korean (한국어)
				months: [
					"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
				],
				dayOfWeekShort: [
					"일", "월", "화", "수", "목", "금", "토"
				],
				dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
			},
			lt: { //Lithuanian (lietuvių)
				months: [
					"Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio"
				],
				dayOfWeekShort: [
					"Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš"
				],
				dayOfWeek: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"]
			},
			lv: { //Latvian (Latviešu)
				months: [
					"Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"
				],
				dayOfWeekShort: [
					"Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St"
				],
				dayOfWeek: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena"]
			},
			mk: { //Macedonian (Македонски)
				months: [
					"јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"
				],
				dayOfWeekShort: [
					"нед", "пон", "вто", "сре", "чет", "пет", "саб"
				],
				dayOfWeek: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"]
			},
			mn: { //Mongolian (Монгол)
				months: [
					"1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар"
				],
				dayOfWeekShort: [
					"Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням"
				],
				dayOfWeek: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"]
			},
			'pt-BR': { //Português(Brasil)
				months: [
					"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
				],
				dayOfWeekShort: [
					"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"
				],
				dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
			},
			sk: { //Slovenčina
				months: [
					"Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"
				],
				dayOfWeekShort: [
					"Ne", "Po", "Ut", "St", "Št", "Pi", "So"
				],
				dayOfWeek: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota"]
			},
			sq: { //Albanian (Shqip)
				months: [
					"Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"
				],
				dayOfWeekShort: [
					"Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu"
				],
				dayOfWeek: ["E Diel", "E Hënë", "E Martē", "E Mërkurë", "E Enjte", "E Premte", "E Shtunë"]
			},
			'sr-YU': { //Serbian (Srpski)
				months: [
					"Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
				],
				dayOfWeekShort: [
					"Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub"
				],
				dayOfWeek: ["Nedelja","Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota"]
			},
			sr: { //Serbian Cyrillic (Српски)
				months: [
					"јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар"
				],
				dayOfWeekShort: [
					"нед", "пон", "уто", "сре", "чет", "пет", "суб"
				],
				dayOfWeek: ["Недеља","Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"]
			},
			sv: { //Svenska
				months: [
					"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
				],
				dayOfWeekShort: [
					"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
				],
				dayOfWeek: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"]
			},
			'zh-TW': { //Traditional Chinese (繁體中文)
				months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
				],
				dayOfWeekShort: [
					"日", "一", "二", "三", "四", "五", "六"
				],
				dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
			},
			zh: { //Simplified Chinese (简体中文)
				months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
				],
				dayOfWeekShort: [
					"日", "一", "二", "三", "四", "五", "六"
				],
				dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
			},
			he: { //Hebrew (עברית)
				months: [
					'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
				],
				dayOfWeekShort: [
					'א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'
				],
				dayOfWeek: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"]
			},
			hy: { // Armenian
				months: [
					"Հունվար", "Փետրվար", "Մարտ", "Ապրիլ", "Մայիս", "Հունիս", "Հուլիս", "Օգոստոս", "Սեպտեմբեր", "Հոկտեմբեր", "Նոյեմբեր", "Դեկտեմբեր"
				],
				dayOfWeekShort: [
					"Կի", "Երկ", "Երք", "Չոր", "Հնգ", "Ուրբ", "Շբթ"
				],
				dayOfWeek: ["Կիրակի", "Երկուշաբթի", "Երեքշաբթի", "Չորեքշաբթի", "Հինգշաբթի", "Ուրբաթ", "Շաբաթ"]
			},
			kg: { // Kyrgyz
				months: [
					'Үчтүн айы', 'Бирдин айы', 'Жалган Куран', 'Чын Куран', 'Бугу', 'Кулжа', 'Теке', 'Баш Оона', 'Аяк Оона', 'Тогуздун айы', 'Жетинин айы', 'Бештин айы'
				],
				dayOfWeekShort: [
					"Жек", "Дүй", "Шей", "Шар", "Бей", "Жум", "Ише"
				],
				dayOfWeek: [
					"Жекшемб", "Дүйшөмб", "Шейшемб", "Шаршемб", "Бейшемби", "Жума", "Ишенб"
				]
			},
			rm: { // Romansh
				months: [
					"Schaner", "Favrer", "Mars", "Avrigl", "Matg", "Zercladur", "Fanadur", "Avust", "Settember", "October", "November", "December"
				],
				dayOfWeekShort: [
					"Du", "Gli", "Ma", "Me", "Gie", "Ve", "So"
				],
				dayOfWeek: [
					"Dumengia", "Glindesdi", "Mardi", "Mesemna", "Gievgia", "Venderdi", "Sonda"
				]
			},
			ka: { // Georgian
				months: [
					'იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი'
				],
				dayOfWeekShort: [
					"კვ", "ორშ", "სამშ", "ოთხ", "ხუთ", "პარ", "შაბ"
				],
				dayOfWeek: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი"]
			},
		},
		value: '',
		rtl: false,

		format:	'Y/m/d H:i',
		formatTime:	'H:i',
		formatDate:	'Y/m/d',

		startDate:	false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
		step: 60,
		monthChangeSpinner: true,

		closeOnDateSelect: false,
		closeOnTimeSelect: true,
		closeOnWithoutClick: true,
		closeOnInputClick: true,

		timepicker: true,
		datepicker: true,
		weeks: false,

		defaultTime: false,	// use formatTime format (ex. '10:00' for formatTime:	'H:i')
		defaultDate: false,	// use formatDate format (ex new Date() or '1986/12/08' or '-1970/01/05' or '-1970/01/05')

		minDate: false,
		maxDate: false,
		minTime: false,
		maxTime: false,
		disabledMinTime: false,
		disabledMaxTime: false,

		allowTimes: [],
		opened: false,
		initTime: true,
		inline: false,
		theme: '',

		onSelectDate: function () {},
		onSelectTime: function () {},
		onChangeMonth: function () {},
		onGetWeekOfYear: function () {},
		onChangeYear: function () {},
		onChangeDateTime: function () {},
		onShow: function () {},
		onClose: function () {},
		onGenerate: function () {},

		withoutCopyright: true,
		inverseButton: false,
		hours12: false,
		next: 'xdsoft_next',
		prev : 'xdsoft_prev',
		dayOfWeekStart: 0,
		parentID: 'body',
		timeHeightInTimePicker: 25,
		timepickerScrollbar: true,
		todayButton: true,
		prevButton: true,
		nextButton: true,
		defaultSelect: true,

		scrollMonth: true,
		scrollTime: true,
		scrollInput: true,

		lazyInit: false,
		mask: false,
		validateOnBlur: true,
		allowBlank: true,
		yearStart: 1950,
		yearEnd: 2050,
		monthStart: 0,
		monthEnd: 11,
		style: '',
		id: '',
		fixed: false,
		roundTime: 'round', // ceil, floor
		className: '',
		weekends: [],
		highlightedDates: [],
		highlightedPeriods: [],
		allowDates : [],
		allowDateRe : null,
		disabledDates : [],
		disabledWeekDays: [],
		yearOffset: 0,
		beforeShowDay: null,

		enterLikeTab: true,
		showApplyButton: false
	};

	var dateHelper = null,
		globalLocaleDefault = 'en',
		globalLocale = 'en';

	var dateFormatterOptionsDefault = {
		meridiem: ['AM', 'PM']
	};

	var initDateFormatter = function(){
		var locale = default_options.i18n[globalLocale],
			opts = {
				days: locale.dayOfWeek,
				daysShort: locale.dayOfWeekShort,
				months: locale.months,
				monthsShort: $.map(locale.months, function(n){ return n.substring(0, 3) }),
			};

	 	dateHelper = new DateFormatter({
			dateSettings: $.extend({}, dateFormatterOptionsDefault, opts)
		});
	};

	// for locale settings
	$.datetimepicker = {
		setLocale: function(locale){
			var newLocale = default_options.i18n[locale]?locale:globalLocaleDefault;
			if(globalLocale != newLocale){
				globalLocale = newLocale;
				// reinit date formatter
				initDateFormatter();
			}
		},
		setDateFormatter: function(dateFormatter) {
			dateHelper = dateFormatter;
		},
		RFC_2822: 'D, d M Y H:i:s O',
		ATOM: 'Y-m-d\TH:i:sP',
		ISO_8601: 'Y-m-d\TH:i:sO',
		RFC_822: 'D, d M y H:i:s O',
		RFC_850: 'l, d-M-y H:i:s T',
		RFC_1036: 'D, d M y H:i:s O',
		RFC_1123: 'D, d M Y H:i:s O',
		RSS: 'D, d M Y H:i:s O',
		W3C: 'Y-m-d\TH:i:sP'
	};

	// first init date formatter
	initDateFormatter();

	// fix for ie8
	if (!window.getComputedStyle) {
		window.getComputedStyle = function (el, pseudo) {
			this.el = el;
			this.getPropertyValue = function (prop) {
				var re = /(\-([a-z]){1})/g;
				if (prop === 'float') {
					prop = 'styleFloat';
				}
				if (re.test(prop)) {
					prop = prop.replace(re, function (a, b, c) {
						return c.toUpperCase();
					});
				}
				return el.currentStyle[prop] || null;
			};
			return this;
		};
	}
	if (!Array.prototype.indexOf) {
		Array.prototype.indexOf = function (obj, start) {
			var i, j;
			for (i = (start || 0), j = this.length; i < j; i += 1) {
				if (this[i] === obj) { return i; }
			}
			return -1;
		};
	}
	Date.prototype.countDaysInMonth = function () {
		return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
	};
	$.fn.xdsoftScroller = function (percent) {
		return this.each(function () {
			var timeboxparent = $(this),
				pointerEventToXY = function (e) {
					var out = {x: 0, y: 0},
						touch;
					if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
						touch  = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
						out.x = touch.clientX;
						out.y = touch.clientY;
					} else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
						out.x = e.clientX;
						out.y = e.clientY;
					}
					return out;
				},
				timebox,
				parentHeight,
				height,
				scrollbar,
				scroller,
				maximumOffset = 100,
				start = false,
				startY = 0,
				startTop = 0,
				h1 = 0,
				touchStart = false,
				startTopScroll = 0,
				calcOffset = function () {};
			if (percent === 'hide') {
				timeboxparent.find('.xdsoft_scrollbar').hide();
				return;
			}
			if (!$(this).hasClass('xdsoft_scroller_box')) {
				timebox = timeboxparent.children().eq(0);
				parentHeight = timeboxparent[0].clientHeight;
				height = timebox[0].offsetHeight;
				scrollbar = $('<div class="xdsoft_scrollbar"></div>');
				scroller = $('<div class="xdsoft_scroller"></div>');
				scrollbar.append(scroller);

				timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar);
				calcOffset = function calcOffset(event) {
					var offset = pointerEventToXY(event).y - startY + startTopScroll;
					if (offset < 0) {
						offset = 0;
					}
					if (offset + scroller[0].offsetHeight > h1) {
						offset = h1 - scroller[0].offsetHeight;
					}
					timeboxparent.trigger('scroll_element.xdsoft_scroller', [maximumOffset ? offset / maximumOffset : 0]);
				};

				scroller
					.on('touchstart.xdsoft_scroller mousedown.xdsoft_scroller', function (event) {
						if (!parentHeight) {
							timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
						}

						startY = pointerEventToXY(event).y;
						startTopScroll = parseInt(scroller.css('margin-top'), 10);
						h1 = scrollbar[0].offsetHeight;

						if (event.type === 'mousedown' || event.type === 'touchstart') {
							if (document) {
								$(document.body).addClass('xdsoft_noselect');
							}
							$([document.body, window]).on('touchend mouseup.xdsoft_scroller', function arguments_callee() {
								$([document.body, window]).off('touchend mouseup.xdsoft_scroller', arguments_callee)
									.off('mousemove.xdsoft_scroller', calcOffset)
									.removeClass('xdsoft_noselect');
							});
							$(document.body).on('mousemove.xdsoft_scroller', calcOffset);
						} else {
							touchStart = true;
							event.stopPropagation();
							event.preventDefault();
						}
					})
					.on('touchmove', function (event) {
						if (touchStart) {
							event.preventDefault();
							calcOffset(event);
						}
					})
					.on('touchend touchcancel', function () {
						touchStart =  false;
						startTopScroll = 0;
					});

				timeboxparent
					.on('scroll_element.xdsoft_scroller', function (event, percentage) {
						if (!parentHeight) {
							timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percentage, true]);
						}
						percentage = percentage > 1 ? 1 : (percentage < 0 || isNaN(percentage)) ? 0 : percentage;

						scroller.css('margin-top', maximumOffset * percentage);

						setTimeout(function () {
							timebox.css('marginTop', -parseInt((timebox[0].offsetHeight - parentHeight) * percentage, 10));
						}, 10);
					})
					.on('resize_scroll.xdsoft_scroller', function (event, percentage, noTriggerScroll) {
						var percent, sh;
						parentHeight = timeboxparent[0].clientHeight;
						height = timebox[0].offsetHeight;
						percent = parentHeight / height;
						sh = percent * scrollbar[0].offsetHeight;
						if (percent > 1) {
							scroller.hide();
						} else {
							scroller.show();
							scroller.css('height', parseInt(sh > 10 ? sh : 10, 10));
							maximumOffset = scrollbar[0].offsetHeight - scroller[0].offsetHeight;
							if (noTriggerScroll !== true) {
								timeboxparent.trigger('scroll_element.xdsoft_scroller', [percentage || Math.abs(parseInt(timebox.css('marginTop'), 10)) / (height - parentHeight)]);
							}
						}
					});

				timeboxparent.on('mousewheel', function (event) {
					var top = Math.abs(parseInt(timebox.css('marginTop'), 10));

					top = top - (event.deltaY * 20);
					if (top < 0) {
						top = 0;
					}

					timeboxparent.trigger('scroll_element.xdsoft_scroller', [top / (height - parentHeight)]);
					event.stopPropagation();
					return false;
				});

				timeboxparent.on('touchstart', function (event) {
					start = pointerEventToXY(event);
					startTop = Math.abs(parseInt(timebox.css('marginTop'), 10));
				});

				timeboxparent.on('touchmove', function (event) {
					if (start) {
						event.preventDefault();
						var coord = pointerEventToXY(event);
						timeboxparent.trigger('scroll_element.xdsoft_scroller', [(startTop - (coord.y - start.y)) / (height - parentHeight)]);
					}
				});

				timeboxparent.on('touchend touchcancel', function () {
					start = false;
					startTop = 0;
				});
			}
			timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
		});
	};

	$.fn.datetimepicker = function (opt, opt2) {
		var result = this,
			KEY0 = 48,
			KEY9 = 57,
			_KEY0 = 96,
			_KEY9 = 105,
			CTRLKEY = 17,
			DEL = 46,
			ENTER = 13,
			ESC = 27,
			BACKSPACE = 8,
			ARROWLEFT = 37,
			ARROWUP = 38,
			ARROWRIGHT = 39,
			ARROWDOWN = 40,
			TAB = 9,
			F5 = 116,
			AKEY = 65,
			CKEY = 67,
			VKEY = 86,
			ZKEY = 90,
			YKEY = 89,
			ctrlDown	=	false,
			options = ($.isPlainObject(opt) || !opt) ? $.extend(true, {}, default_options, opt) : $.extend(true, {}, default_options),

			lazyInitTimer = 0,
			createDateTimePicker,
			destroyDateTimePicker,

			lazyInit = function (input) {
				input
					.on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function initOnActionCallback() {
						if (input.is(':disabled') || input.data('xdsoft_datetimepicker')) {
							return;
						}
						clearTimeout(lazyInitTimer);
						lazyInitTimer = setTimeout(function () {

							if (!input.data('xdsoft_datetimepicker')) {
								createDateTimePicker(input);
							}
							input
								.off('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', initOnActionCallback)
								.trigger('open.xdsoft');
						}, 100);
					});
			};

		createDateTimePicker = function (input) {
			var datetimepicker = $('<div class="xdsoft_datetimepicker xdsoft_noselect"></div>'),
				xdsoft_copyright = $('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),
				datepicker = $('<div class="xdsoft_datepicker active"></div>'),
				month_picker = $('<div class="xdsoft_monthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button>' +
					'<div class="xdsoft_label xdsoft_month"><span></span><i></i></div>' +
					'<div class="xdsoft_label xdsoft_year"><span></span><i></i></div>' +
					'<button type="button" class="xdsoft_next"></button></div>'),
				calendar = $('<div class="xdsoft_calendar"></div>'),
				timepicker = $('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),
				timeboxparent = timepicker.find('.xdsoft_time_box').eq(0),
				timebox = $('<div class="xdsoft_time_variant"></div>'),
				applyButton = $('<button type="button" class="xdsoft_save_selected blue-gradient-button">Save Selected</button>'),

				monthselect = $('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'),
				yearselect = $('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>'),
				triggerAfterOpen = false,
				XDSoft_datetime,

				xchangeTimer,
				timerclick,
				current_time_index,
				setPos,
				timer = 0,
				_xdsoft_datetime,
				forEachAncestorOf,
				throttle;

			if (options.id) {
				datetimepicker.attr('id', options.id);
			}
			if (options.style) {
				datetimepicker.attr('style', options.style);
			}
			if (options.weeks) {
				datetimepicker.addClass('xdsoft_showweeks');
			}
			if (options.rtl) {
				datetimepicker.addClass('xdsoft_rtl');
			}

			datetimepicker.addClass('xdsoft_' + options.theme);
			datetimepicker.addClass(options.className);

			month_picker
				.find('.xdsoft_month span')
					.after(monthselect);
			month_picker
				.find('.xdsoft_year span')
					.after(yearselect);

			month_picker
				.find('.xdsoft_month,.xdsoft_year')
					.on('touchstart mousedown.xdsoft', function (event) {
					var select = $(this).find('.xdsoft_select').eq(0),
						val = 0,
						top = 0,
						visible = select.is(':visible'),
						items,
						i;

					month_picker
						.find('.xdsoft_select')
							.hide();
					if (_xdsoft_datetime.currentTime) {
						val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month') ? 'getMonth' : 'getFullYear']();
					}

					select[visible ? 'hide' : 'show']();
					for (items = select.find('div.xdsoft_option'), i = 0; i < items.length; i += 1) {
						if (items.eq(i).data('value') === val) {
							break;
						} else {
							top += items[0].offsetHeight;
						}
					}

					select.xdsoftScroller(top / (select.children()[0].offsetHeight - (select[0].clientHeight)));
					event.stopPropagation();
					return false;
				});

			month_picker
				.find('.xdsoft_select')
					.xdsoftScroller()
				.on('touchstart mousedown.xdsoft', function (event) {
					event.stopPropagation();
					event.preventDefault();
				})
				.on('touchstart mousedown.xdsoft', '.xdsoft_option', function () {
					if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
						_xdsoft_datetime.currentTime = _xdsoft_datetime.now();
					}

					var year = _xdsoft_datetime.currentTime.getFullYear();
					if (_xdsoft_datetime && _xdsoft_datetime.currentTime) {
						_xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect') ? 'setMonth' : 'setFullYear']($(this).data('value'));
					}

					$(this).parent().parent().hide();

					datetimepicker.trigger('xchange.xdsoft');
					if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
						options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}

					if (year !== _xdsoft_datetime.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
						options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
				});

			datetimepicker.getValue = function () {
				return _xdsoft_datetime.getCurrentTime();
			};

			datetimepicker.setOptions = function (_options) {
				var highlightedDates = {};

				options = $.extend(true, {}, options, _options);

				if (_options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length) {
					options.allowTimes = $.extend(true, [], _options.allowTimes);
				}

				if (_options.weekends && $.isArray(_options.weekends) && _options.weekends.length) {
					options.weekends = $.extend(true, [], _options.weekends);
				}

				if (_options.allowDates && $.isArray(_options.allowDates) && _options.allowDates.length) {
					options.allowDates = $.extend(true, [], _options.allowDates);
				}

				if (_options.allowDateRe && Object.prototype.toString.call(_options.allowDateRe)==="[object String]") {
					options.allowDateRe = new RegExp(_options.allowDateRe);
				}

				if (_options.highlightedDates && $.isArray(_options.highlightedDates) && _options.highlightedDates.length) {
					$.each(_options.highlightedDates, function (index, value) {
						var splitData = $.map(value.split(','), $.trim),
							exDesc,
							hDate = new HighlightedDate(dateHelper.parseDate(splitData[0], options.formatDate), splitData[1], splitData[2]), // date, desc, style
							keyDate = dateHelper.formatDate(hDate.date, options.formatDate);
						if (highlightedDates[keyDate] !== undefined) {
							exDesc = highlightedDates[keyDate].desc;
							if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
								highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
							}
						} else {
							highlightedDates[keyDate] = hDate;
						}
					});

					options.highlightedDates = $.extend(true, [], highlightedDates);
				}

				if (_options.highlightedPeriods && $.isArray(_options.highlightedPeriods) && _options.highlightedPeriods.length) {
					highlightedDates = $.extend(true, [], options.highlightedDates);
					$.each(_options.highlightedPeriods, function (index, value) {
						var dateTest, // start date
							dateEnd,
							desc,
							hDate,
							keyDate,
							exDesc,
							style;
						if ($.isArray(value)) {
							dateTest = value[0];
							dateEnd = value[1];
							desc = value[2];
							style = value[3];
						}
						else {
							var splitData = $.map(value.split(','), $.trim);
							dateTest = dateHelper.parseDate(splitData[0], options.formatDate);
							dateEnd = dateHelper.parseDate(splitData[1], options.formatDate);
							desc = splitData[2];
							style = splitData[3];
						}

						while (dateTest <= dateEnd) {
							hDate = new HighlightedDate(dateTest, desc, style);
							keyDate = dateHelper.formatDate(dateTest, options.formatDate);
							dateTest.setDate(dateTest.getDate() + 1);
							if (highlightedDates[keyDate] !== undefined) {
								exDesc = highlightedDates[keyDate].desc;
								if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
									highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
								}
							} else {
								highlightedDates[keyDate] = hDate;
							}
						}
					});

					options.highlightedDates = $.extend(true, [], highlightedDates);
				}

				if (_options.disabledDates && $.isArray(_options.disabledDates) && _options.disabledDates.length) {
					options.disabledDates = $.extend(true, [], _options.disabledDates);
				}

				if (_options.disabledWeekDays && $.isArray(_options.disabledWeekDays) && _options.disabledWeekDays.length) {
					options.disabledWeekDays = $.extend(true, [], _options.disabledWeekDays);
				}

				if ((options.open || options.opened) && (!options.inline)) {
					input.trigger('open.xdsoft');
				}

				if (options.inline) {
					triggerAfterOpen = true;
					datetimepicker.addClass('xdsoft_inline');
					input.after(datetimepicker).hide();
				}

				if (options.inverseButton) {
					options.next = 'xdsoft_prev';
					options.prev = 'xdsoft_next';
				}

				if (options.datepicker) {
					datepicker.addClass('active');
				} else {
					datepicker.removeClass('active');
				}

				if (options.timepicker) {
					timepicker.addClass('active');
				} else {
					timepicker.removeClass('active');
				}

				if (options.value) {
					_xdsoft_datetime.setCurrentTime(options.value);
					if (input && input.val) {
						input.val(_xdsoft_datetime.str);
					}
				}

				if (isNaN(options.dayOfWeekStart)) {
					options.dayOfWeekStart = 0;
				} else {
					options.dayOfWeekStart = parseInt(options.dayOfWeekStart, 10) % 7;
				}

				if (!options.timepickerScrollbar) {
					timeboxparent.xdsoftScroller('hide');
				}

				if (options.minDate && /^[\+\-](.*)$/.test(options.minDate)) {
					options.minDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.minDate), options.formatDate);
				}

				if (options.maxDate &&  /^[\+\-](.*)$/.test(options.maxDate)) {
					options.maxDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.maxDate), options.formatDate);
				}

				applyButton.toggle(options.showApplyButton);

				month_picker
					.find('.xdsoft_today_button')
						.css('visibility', !options.todayButton ? 'hidden' : 'visible');

				month_picker
					.find('.' + options.prev)
						.css('visibility', !options.prevButton ? 'hidden' : 'visible');

				month_picker
					.find('.' + options.next)
						.css('visibility', !options.nextButton ? 'hidden' : 'visible');

				setMask(options);

				if (options.validateOnBlur) {
					input
						.off('blur.xdsoft')
						.on('blur.xdsoft', function () {
							if (options.allowBlank && (!$.trim($(this).val()).length || (typeof options.mask == "string" && $.trim($(this).val()) === options.mask.replace(/[0-9]/g, '_')))) {
								$(this).val(null);
								datetimepicker.data('xdsoft_datetime').empty();
							} else {
								var d = dateHelper.parseDate($(this).val(), options.format);
								if (d) { // parseDate() may skip some invalid parts like date or time, so make it clear for user: show parsed date/time
									$(this).val(dateHelper.formatDate(d, options.format));
								} else {
									var splittedHours   = +([$(this).val()[0], $(this).val()[1]].join('')),
										splittedMinutes = +([$(this).val()[2], $(this).val()[3]].join(''));
	
									// parse the numbers as 0312 => 03:12
									if (!options.datepicker && options.timepicker && splittedHours >= 0 && splittedHours < 24 && splittedMinutes >= 0 && splittedMinutes < 60) {
										$(this).val([splittedHours, splittedMinutes].map(function (item) {
											return item > 9 ? item : '0' + item;
										}).join(':'));
									} else {
										$(this).val(dateHelper.formatDate(_xdsoft_datetime.now(), options.format));
									}
								}
								datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
							}

							datetimepicker.trigger('changedatetime.xdsoft');
							datetimepicker.trigger('close.xdsoft');
						});
				}
				options.dayOfWeekStartPrev = (options.dayOfWeekStart === 0) ? 6 : options.dayOfWeekStart - 1;

				datetimepicker
					.trigger('xchange.xdsoft')
					.trigger('afterOpen.xdsoft');
			};

			datetimepicker
				.data('options', options)
				.on('touchstart mousedown.xdsoft', function (event) {
					event.stopPropagation();
					event.preventDefault();
					yearselect.hide();
					monthselect.hide();
					return false;
				});

			//scroll_element = timepicker.find('.xdsoft_time_box');
			timeboxparent.append(timebox);
			timeboxparent.xdsoftScroller();

			datetimepicker.on('afterOpen.xdsoft', function () {
				timeboxparent.xdsoftScroller();
			});

			datetimepicker
				.append(datepicker)
				.append(timepicker);

			if (options.withoutCopyright !== true) {
				datetimepicker
					.append(xdsoft_copyright);
			}

			datepicker
				.append(month_picker)
				.append(calendar)
				.append(applyButton);

			$(options.parentID)
				.append(datetimepicker);

			XDSoft_datetime = function () {
				var _this = this;
				_this.now = function (norecursion) {
					var d = new Date(),
						date,
						time;

					if (!norecursion && options.defaultDate) {
						date = _this.strToDateTime(options.defaultDate);
						d.setFullYear(date.getFullYear());
						d.setMonth(date.getMonth());
						d.setDate(date.getDate());
					}

					if (options.yearOffset) {
						d.setFullYear(d.getFullYear() + options.yearOffset);
					}

					if (!norecursion && options.defaultTime) {
						time = _this.strtotime(options.defaultTime);
						d.setHours(time.getHours());
						d.setMinutes(time.getMinutes());
					}
					return d;
				};

				_this.isValidDate = function (d) {
					if (Object.prototype.toString.call(d) !== "[object Date]") {
						return false;
					}
					return !isNaN(d.getTime());
				};

				_this.setCurrentTime = function (dTime, requireValidDate) {
					if (typeof dTime === 'string') {
						_this.currentTime = _this.strToDateTime(dTime);
					}
					else if (_this.isValidDate(dTime)) {
						_this.currentTime = dTime;
					}
					else if (!dTime && !requireValidDate && options.allowBlank) {
						_this.currentTime = null;
					}
					else {
						_this.currentTime = _this.now();
					}
					
					datetimepicker.trigger('xchange.xdsoft');
				};

				_this.empty = function () {
					_this.currentTime = null;
				};

				_this.getCurrentTime = function (dTime) {
					return _this.currentTime;
				};

				_this.nextMonth = function () {

					if (_this.currentTime === undefined || _this.currentTime === null) {
						_this.currentTime = _this.now();
					}

					var month = _this.currentTime.getMonth() + 1,
						year;
					if (month === 12) {
						_this.currentTime.setFullYear(_this.currentTime.getFullYear() + 1);
						month = 0;
					}

					year = _this.currentTime.getFullYear();

					_this.currentTime.setDate(
						Math.min(
							new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
							_this.currentTime.getDate()
						)
					);
					_this.currentTime.setMonth(month);

					if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
						options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}

					if (year !== _this.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
						options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}

					datetimepicker.trigger('xchange.xdsoft');
					return month;
				};

				_this.prevMonth = function () {

					if (_this.currentTime === undefined || _this.currentTime === null) {
						_this.currentTime = _this.now();
					}

					var month = _this.currentTime.getMonth() - 1;
					if (month === -1) {
						_this.currentTime.setFullYear(_this.currentTime.getFullYear() - 1);
						month = 11;
					}
					_this.currentTime.setDate(
						Math.min(
							new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
							_this.currentTime.getDate()
						)
					);
					_this.currentTime.setMonth(month);
					if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
						options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
					datetimepicker.trigger('xchange.xdsoft');
					return month;
				};

				_this.getWeekOfYear = function (datetime) {
					if (options.onGetWeekOfYear && $.isFunction(options.onGetWeekOfYear)) {
						var week = options.onGetWeekOfYear.call(datetimepicker, datetime);
						if (typeof week !== 'undefined') {
							return week;
						}
					}
					var onejan = new Date(datetime.getFullYear(), 0, 1);
					//First week of the year is th one with the first Thursday according to ISO8601
					if(onejan.getDay()!=4)
						onejan.setMonth(0, 1 + ((4 - onejan.getDay()+ 7) % 7));
					return Math.ceil((((datetime - onejan) / 86400000) + onejan.getDay() + 1) / 7);
				};

				_this.strToDateTime = function (sDateTime) {
					var tmpDate = [], timeOffset, currentTime;

					if (sDateTime && sDateTime instanceof Date && _this.isValidDate(sDateTime)) {
						return sDateTime;
					}

					tmpDate = /^(\+|\-)(.*)$/.exec(sDateTime);
					if (tmpDate) {
						tmpDate[2] = dateHelper.parseDate(tmpDate[2], options.formatDate);
					}
					if (tmpDate  && tmpDate[2]) {
						timeOffset = tmpDate[2].getTime() - (tmpDate[2].getTimezoneOffset()) * 60000;
						currentTime = new Date((_this.now(true)).getTime() + parseInt(tmpDate[1] + '1', 10) * timeOffset);
					} else {
						currentTime = sDateTime ? dateHelper.parseDate(sDateTime, options.format) : _this.now();
					}

					if (!_this.isValidDate(currentTime)) {
						currentTime = _this.now();
					}

					return currentTime;
				};

				_this.strToDate = function (sDate) {
					if (sDate && sDate instanceof Date && _this.isValidDate(sDate)) {
						return sDate;
					}

					var currentTime = sDate ? dateHelper.parseDate(sDate, options.formatDate) : _this.now(true);
					if (!_this.isValidDate(currentTime)) {
						currentTime = _this.now(true);
					}
					return currentTime;
				};

				_this.strtotime = function (sTime) {
					if (sTime && sTime instanceof Date && _this.isValidDate(sTime)) {
						return sTime;
					}
					var currentTime = sTime ? dateHelper.parseDate(sTime, options.formatTime) : _this.now(true);
					if (!_this.isValidDate(currentTime)) {
						currentTime = _this.now(true);
					}
					return currentTime;
				};

				_this.str = function () {
					return dateHelper.formatDate(_this.currentTime, options.format);
				};
				_this.currentTime = this.now();
			};

			_xdsoft_datetime = new XDSoft_datetime();

			applyButton.on('touchend click', function (e) {//pathbrite
				e.preventDefault();
				datetimepicker.data('changed', true);
				_xdsoft_datetime.setCurrentTime(getCurrentValue());
				input.val(_xdsoft_datetime.str());
				datetimepicker.trigger('close.xdsoft');
			});
			month_picker
				.find('.xdsoft_today_button')
				.on('touchend mousedown.xdsoft', function () {
					datetimepicker.data('changed', true);
					_xdsoft_datetime.setCurrentTime(0, true);
					datetimepicker.trigger('afterOpen.xdsoft');
				}).on('dblclick.xdsoft', function () {
					var currentDate = _xdsoft_datetime.getCurrentTime(), minDate, maxDate;
					currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
					minDate = _xdsoft_datetime.strToDate(options.minDate);
					minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
					if (currentDate < minDate) {
						return;
					}
					maxDate = _xdsoft_datetime.strToDate(options.maxDate);
					maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
					if (currentDate > maxDate) {
						return;
					}
					input.val(_xdsoft_datetime.str());
					input.trigger('change');
					datetimepicker.trigger('close.xdsoft');
				});
			month_picker
				.find('.xdsoft_prev,.xdsoft_next')
				.on('touchend mousedown.xdsoft', function () {
					var $this = $(this),
						timer = 0,
						stop = false;

					(function arguments_callee1(v) {
						if ($this.hasClass(options.next)) {
							_xdsoft_datetime.nextMonth();
						} else if ($this.hasClass(options.prev)) {
							_xdsoft_datetime.prevMonth();
						}
						if (options.monthChangeSpinner) {
							if (!stop) {
								timer = setTimeout(arguments_callee1, v || 100);
							}
						}
					}(500));

					$([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee2() {
						clearTimeout(timer);
						stop = true;
						$([document.body, window]).off('touchend mouseup.xdsoft', arguments_callee2);
					});
				});

			timepicker
				.find('.xdsoft_prev,.xdsoft_next')
				.on('touchend mousedown.xdsoft', function () {
					var $this = $(this),
						timer = 0,
						stop = false,
						period = 110;
					(function arguments_callee4(v) {
						var pheight = timeboxparent[0].clientHeight,
							height = timebox[0].offsetHeight,
							top = Math.abs(parseInt(timebox.css('marginTop'), 10));
						if ($this.hasClass(options.next) && (height - pheight) - options.timeHeightInTimePicker >= top) {
							timebox.css('marginTop', '-' + (top + options.timeHeightInTimePicker) + 'px');
						} else if ($this.hasClass(options.prev) && top - options.timeHeightInTimePicker >= 0) {
							timebox.css('marginTop', '-' + (top - options.timeHeightInTimePicker) + 'px');
						}
                        /**
                         * Fixed bug:
                         * When using css3 transition, it will cause a bug that you cannot scroll the timepicker list.
                         * The reason is that the transition-duration time, if you set it to 0, all things fine, otherwise, this
                         * would cause a bug when you use jquery.css method.
                         * Let's say: * { transition: all .5s ease; }
                         * jquery timebox.css('marginTop') will return the original value which is before you clicking the next/prev button,
                         * meanwhile the timebox[0].style.marginTop will return the right value which is after you clicking the
                         * next/prev button.
                         * 
                         * What we should do:
                         * Replace timebox.css('marginTop') with timebox[0].style.marginTop.
                         */
                        timeboxparent.trigger('scroll_element.xdsoft_scroller', [Math.abs(parseInt(timebox[0].style.marginTop, 10) / (height - pheight))]);
						period = (period > 10) ? 10 : period - 10;
						if (!stop) {
							timer = setTimeout(arguments_callee4, v || period);
						}
					}(500));
					$([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee5() {
						clearTimeout(timer);
						stop = true;
						$([document.body, window])
							.off('touchend mouseup.xdsoft', arguments_callee5);
					});
				});

			xchangeTimer = 0;
			// base handler - generating a calendar and timepicker
			datetimepicker
				.on('xchange.xdsoft', function (event) {
					clearTimeout(xchangeTimer);
					xchangeTimer = setTimeout(function () {

						if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
							//In case blanks are allowed, delay construction until we have a valid date 
							if (options.allowBlank)
								return;
								
							_xdsoft_datetime.currentTime = _xdsoft_datetime.now();
						}

						var table =	'',
							start = new Date(_xdsoft_datetime.currentTime.getFullYear(), _xdsoft_datetime.currentTime.getMonth(), 1, 12, 0, 0),
							i = 0,
							j,
							today = _xdsoft_datetime.now(),
							maxDate = false,
							minDate = false,
							hDate,
							day,
							d,
							y,
							m,
							w,
							classes = [],
							customDateSettings,
							newRow = true,
							time = '',
							h = '',
							line_time,
							description;

						while (start.getDay() !== options.dayOfWeekStart) {
							start.setDate(start.getDate() - 1);
						}

						table += '<table><thead><tr>';

						if (options.weeks) {
							table += '<th></th>';
						}

						for (j = 0; j < 7; j += 1) {
							table += '<th>' + options.i18n[globalLocale].dayOfWeekShort[(j + options.dayOfWeekStart) % 7] + '</th>';
						}

						table += '</tr></thead>';
						table += '<tbody>';

						if (options.maxDate !== false) {
							maxDate = _xdsoft_datetime.strToDate(options.maxDate);
							maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 23, 59, 59, 999);
						}

						if (options.minDate !== false) {
							minDate = _xdsoft_datetime.strToDate(options.minDate);
							minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
						}

						while (i < _xdsoft_datetime.currentTime.countDaysInMonth() || start.getDay() !== options.dayOfWeekStart || _xdsoft_datetime.currentTime.getMonth() === start.getMonth()) {
							classes = [];
							i += 1;

							day = start.getDay();
							d = start.getDate();
							y = start.getFullYear();
							m = start.getMonth();
							w = _xdsoft_datetime.getWeekOfYear(start);
							description = '';

							classes.push('xdsoft_date');

							if (options.beforeShowDay && $.isFunction(options.beforeShowDay.call)) {
								customDateSettings = options.beforeShowDay.call(datetimepicker, start);
							} else {
								customDateSettings = null;
							}

							if(options.allowDateRe && Object.prototype.toString.call(options.allowDateRe) === "[object RegExp]"){
								if(!options.allowDateRe.test(dateHelper.formatDate(start, options.formatDate))){
									classes.push('xdsoft_disabled');
								}
							} else if(options.allowDates && options.allowDates.length>0){
								if(options.allowDates.indexOf(dateHelper.formatDate(start, options.formatDate)) === -1){
									classes.push('xdsoft_disabled');
								}
							} else if ((maxDate !== false && start > maxDate) || (minDate !== false && start < minDate) || (customDateSettings && customDateSettings[0] === false)) {
								classes.push('xdsoft_disabled');
							} else if (options.disabledDates.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
								classes.push('xdsoft_disabled');
							} else if (options.disabledWeekDays.indexOf(day) !== -1) {
								classes.push('xdsoft_disabled');
							}else if (input.is('[readonly]')) {
								classes.push('xdsoft_disabled');
							}

							if (customDateSettings && customDateSettings[1] !== "") {
								classes.push(customDateSettings[1]);
							}

							if (_xdsoft_datetime.currentTime.getMonth() !== m) {
								classes.push('xdsoft_other_month');
							}

							if ((options.defaultSelect || datetimepicker.data('changed')) && dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
								classes.push('xdsoft_current');
							}

							if (dateHelper.formatDate(today, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
								classes.push('xdsoft_today');
							}

							if (start.getDay() === 0 || start.getDay() === 6 || options.weekends.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
								classes.push('xdsoft_weekend');
							}

							if (options.highlightedDates[dateHelper.formatDate(start, options.formatDate)] !== undefined) {
								hDate = options.highlightedDates[dateHelper.formatDate(start, options.formatDate)];
								classes.push(hDate.style === undefined ? 'xdsoft_highlighted_default' : hDate.style);
								description = hDate.desc === undefined ? '' : hDate.desc;
							}

							if (options.beforeShowDay && $.isFunction(options.beforeShowDay)) {
								classes.push(options.beforeShowDay(start));
							}

							if (newRow) {
								table += '<tr>';
								newRow = false;
								if (options.weeks) {
									table += '<th>' + w + '</th>';
								}
							}

							table += '<td data-date="' + d + '" data-month="' + m + '" data-year="' + y + '"' + ' class="xdsoft_date xdsoft_day_of_week' + start.getDay() + ' ' + classes.join(' ') + '" title="' + description + '">' +
										'<div>' + d + '</div>' +
									'</td>';

							if (start.getDay() === options.dayOfWeekStartPrev) {
								table += '</tr>';
								newRow = true;
							}

							start.setDate(d + 1);
						}
						table += '</tbody></table>';

						calendar.html(table);

						month_picker.find('.xdsoft_label span').eq(0).text(options.i18n[globalLocale].months[_xdsoft_datetime.currentTime.getMonth()]);
						month_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear());

						// generate timebox
						time = '';
						h = '';
						m = '';

						line_time = function line_time(h, m) {
							var now = _xdsoft_datetime.now(), optionDateTime, current_time,
								isALlowTimesInit = options.allowTimes && $.isArray(options.allowTimes) && options.allowTimes.length;
							now.setHours(h);
							h = parseInt(now.getHours(), 10);
							now.setMinutes(m);
							m = parseInt(now.getMinutes(), 10);
							optionDateTime = new Date(_xdsoft_datetime.currentTime);
							optionDateTime.setHours(h);
							optionDateTime.setMinutes(m);
							classes = [];			
							if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || (options.maxTime !== false && _xdsoft_datetime.strtotime(options.maxTime).getTime() < now.getTime()) || (options.minTime !== false && _xdsoft_datetime.strtotime(options.minTime).getTime() > now.getTime())) {
								classes.push('xdsoft_disabled');
							} else if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || ((options.disabledMinTime !== false && now.getTime() > _xdsoft_datetime.strtotime(options.disabledMinTime).getTime()) && (options.disabledMaxTime !== false && now.getTime() < _xdsoft_datetime.strtotime(options.disabledMaxTime).getTime()))) {
								classes.push('xdsoft_disabled');
							} else if (input.is('[readonly]')) {
								classes.push('xdsoft_disabled');
							}

							current_time = new Date(_xdsoft_datetime.currentTime);
							current_time.setHours(parseInt(_xdsoft_datetime.currentTime.getHours(), 10));

							if (!isALlowTimesInit) {
								current_time.setMinutes(Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes() / options.step) * options.step);
							}

							if ((options.initTime || options.defaultSelect || datetimepicker.data('changed')) && current_time.getHours() === parseInt(h, 10) && ((!isALlowTimesInit && options.step > 59) || current_time.getMinutes() === parseInt(m, 10))) {
								if (options.defaultSelect || datetimepicker.data('changed')) {
									classes.push('xdsoft_current');
								} else if (options.initTime) {
									classes.push('xdsoft_init_time');
								}
							}
							if (parseInt(today.getHours(), 10) === parseInt(h, 10) && parseInt(today.getMinutes(), 10) === parseInt(m, 10)) {
								classes.push('xdsoft_today');
							}
							time += '<div class="xdsoft_time ' + classes.join(' ') + '" data-hour="' + h + '" data-minute="' + m + '">' + dateHelper.formatDate(now, options.formatTime) + '</div>';
						};

						if (!options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length) {
							for (i = 0, j = 0; i < (options.hours12 ? 12 : 24); i += 1) {
								for (j = 0; j < 60; j += options.step) {
									h = (i < 10 ? '0' : '') + i;
									m = (j < 10 ? '0' : '') + j;
									line_time(h, m);
								}
							}
						} else {
							for (i = 0; i < options.allowTimes.length; i += 1) {
								h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours();
								m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
								line_time(h, m);
							}
						}

						timebox.html(time);

						opt = '';
						i = 0;

						for (i = parseInt(options.yearStart, 10) + options.yearOffset; i <= parseInt(options.yearEnd, 10) + options.yearOffset; i += 1) {
							opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getFullYear() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + i + '</div>';
						}
						yearselect.children().eq(0)
												.html(opt);

						for (i = parseInt(options.monthStart, 10), opt = ''; i <= parseInt(options.monthEnd, 10); i += 1) {
							opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getMonth() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + options.i18n[globalLocale].months[i] + '</div>';
						}
						monthselect.children().eq(0).html(opt);
						$(datetimepicker)
							.trigger('generate.xdsoft');
					}, 10);
					event.stopPropagation();
				})
				.on('afterOpen.xdsoft', function () {
					if (options.timepicker) {
						var classType, pheight, height, top;
						if (timebox.find('.xdsoft_current').length) {
							classType = '.xdsoft_current';
						} else if (timebox.find('.xdsoft_init_time').length) {
							classType = '.xdsoft_init_time';
						}
						if (classType) {
							pheight = timeboxparent[0].clientHeight;
							height = timebox[0].offsetHeight;
							top = timebox.find(classType).index() * options.timeHeightInTimePicker + 1;
							if ((height - pheight) < top) {
								top = height - pheight;
							}
							timeboxparent.trigger('scroll_element.xdsoft_scroller', [parseInt(top, 10) / (height - pheight)]);
						} else {
							timeboxparent.trigger('scroll_element.xdsoft_scroller', [0]);
						}
					}
				});

			timerclick = 0;
			calendar
				.on('touchend click.xdsoft', 'td', function (xdevent) {
					xdevent.stopPropagation();  // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
					timerclick += 1;
					var $this = $(this),
						currentTime = _xdsoft_datetime.currentTime;

					if (currentTime === undefined || currentTime === null) {
						_xdsoft_datetime.currentTime = _xdsoft_datetime.now();
						currentTime = _xdsoft_datetime.currentTime;
					}

					if ($this.hasClass('xdsoft_disabled')) {
						return false;
					}

					currentTime.setDate(1);
					currentTime.setFullYear($this.data('year'));
					currentTime.setMonth($this.data('month'));
					currentTime.setDate($this.data('date'));

					datetimepicker.trigger('select.xdsoft', [currentTime]);

					input.val(_xdsoft_datetime.str());

					if (options.onSelectDate &&	$.isFunction(options.onSelectDate)) {
						options.onSelectDate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
					}

					datetimepicker.data('changed', true);
					datetimepicker.trigger('xchange.xdsoft');
					datetimepicker.trigger('changedatetime.xdsoft');
					if ((timerclick > 1 || (options.closeOnDateSelect === true || (options.closeOnDateSelect === false && !options.timepicker))) && !options.inline) {
						datetimepicker.trigger('close.xdsoft');
					}
					setTimeout(function () {
						timerclick = 0;
					}, 200);
				});

			timebox
				.on('touchmove', 'div', function () { currentlyScrollingTimeDiv = true; })
				.on('touchend click.xdsoft', 'div', function (xdevent) {
					xdevent.stopPropagation();
					if (currentlyScrollingTimeDiv) {
				        	currentlyScrollingTimeDiv = false;
				        	return;
				    	}
					var $this = $(this),
						currentTime = _xdsoft_datetime.currentTime;

					if (currentTime === undefined || currentTime === null) {
						_xdsoft_datetime.currentTime = _xdsoft_datetime.now();
						currentTime = _xdsoft_datetime.currentTime;
					}

					if ($this.hasClass('xdsoft_disabled')) {
						return false;
					}
					currentTime.setHours($this.data('hour'));
					currentTime.setMinutes($this.data('minute'));
					datetimepicker.trigger('select.xdsoft', [currentTime]);

					datetimepicker.data('input').val(_xdsoft_datetime.str());

					if (options.onSelectTime && $.isFunction(options.onSelectTime)) {
						options.onSelectTime.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
					}
					datetimepicker.data('changed', true);
					datetimepicker.trigger('xchange.xdsoft');
					datetimepicker.trigger('changedatetime.xdsoft');
					if (options.inline !== true && options.closeOnTimeSelect === true) {
						datetimepicker.trigger('close.xdsoft');
					}
				});

			datepicker
				.on('mousewheel.xdsoft', function (event) {
					if (!options.scrollMonth) {
						return true;
					}
					if (event.deltaY < 0) {
						_xdsoft_datetime.nextMonth();
					} else {
						_xdsoft_datetime.prevMonth();
					}
					return false;
				});

			input
				.on('mousewheel.xdsoft', function (event) {
					if (!options.scrollInput) {
						return true;
					}
					if (!options.datepicker && options.timepicker) {
						current_time_index = timebox.find('.xdsoft_current').length ? timebox.find('.xdsoft_current').eq(0).index() : 0;
						if (current_time_index + event.deltaY >= 0 && current_time_index + event.deltaY < timebox.children().length) {
							current_time_index += event.deltaY;
						}
						if (timebox.children().eq(current_time_index).length) {
							timebox.children().eq(current_time_index).trigger('mousedown');
						}
						return false;
					}
					if (options.datepicker && !options.timepicker) {
						datepicker.trigger(event, [event.deltaY, event.deltaX, event.deltaY]);
						if (input.val) {
							input.val(_xdsoft_datetime.str());
						}
						datetimepicker.trigger('changedatetime.xdsoft');
						return false;
					}
				});

			datetimepicker
				.on('changedatetime.xdsoft', function (event) {
					if (options.onChangeDateTime && $.isFunction(options.onChangeDateTime)) {
						var $input = datetimepicker.data('input');
						options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input, event);
						delete options.value;
						$input.trigger('change');
					}
				})
				.on('generate.xdsoft', function () {
					if (options.onGenerate && $.isFunction(options.onGenerate)) {
						options.onGenerate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
					if (triggerAfterOpen) {
						datetimepicker.trigger('afterOpen.xdsoft');
						triggerAfterOpen = false;
					}
				})
				.on('click.xdsoft', function (xdevent) {
					xdevent.stopPropagation();
				});

			current_time_index = 0;

			/**
			 * Runs the callback for each of the specified node's ancestors.
			 *
			 * Return FALSE from the callback to stop ascending.
			 *
			 * @param {DOMNode} node
			 * @param {Function} callback
			 * @returns {undefined}
			 */
			forEachAncestorOf = function (node, callback) {
				do {
					node = node.parentNode;

					if (callback(node) === false) {
						break;
					}
				} while (node.nodeName !== 'HTML');
			};

			/**
			 * Sets the position of the picker.
			 *
			 * @returns {undefined}
			 */
			setPos = function () {
				var dateInputOffset,
					dateInputElem,
					verticalPosition,
					left,
					position,
					datetimepickerElem,
					dateInputHasFixedAncestor,
					$dateInput,
					windowWidth,
					verticalAnchorEdge,
					datetimepickerCss,
					windowHeight,
					windowScrollTop;

				$dateInput = datetimepicker.data('input');
				dateInputOffset = $dateInput.offset();
				dateInputElem = $dateInput[0];

				verticalAnchorEdge = 'top';
				verticalPosition = (dateInputOffset.top + dateInputElem.offsetHeight) - 1;
				left = dateInputOffset.left;
				position = "absolute";

				windowWidth = $(window).width();
				windowHeight = $(window).height();
				windowScrollTop = $(window).scrollTop();

				if ((document.documentElement.clientWidth - dateInputOffset.left) < datepicker.parent().outerWidth(true)) {
					var diff = datepicker.parent().outerWidth(true) - dateInputElem.offsetWidth;
					left = left - diff;
				}

				if ($dateInput.parent().css('direction') === 'rtl') {
					left -= (datetimepicker.outerWidth() - $dateInput.outerWidth());
				}

				if (options.fixed) {
					verticalPosition -= windowScrollTop;
					left -= $(window).scrollLeft();
					position = "fixed";
				} else {
					dateInputHasFixedAncestor = false;

					forEachAncestorOf(dateInputElem, function (ancestorNode) {
						if (window.getComputedStyle(ancestorNode).getPropertyValue('position') === 'fixed') {
							dateInputHasFixedAncestor = true;
							return false;
						}
					});

					if (dateInputHasFixedAncestor) {
						position = 'fixed';

						//If the picker won't fit entirely within the viewport then display it above the date input.
						if (verticalPosition + datetimepicker.outerHeight() > windowHeight + windowScrollTop) {
							verticalAnchorEdge = 'bottom';
							verticalPosition = (windowHeight + windowScrollTop) - dateInputOffset.top;
						} else {
							verticalPosition -= windowScrollTop;
						}
					} else {
						if (verticalPosition + dateInputElem.offsetHeight > windowHeight + windowScrollTop) {
							verticalPosition = dateInputOffset.top - dateInputElem.offsetHeight + 1;
						}
					}

					if (verticalPosition < 0) {
						verticalPosition = 0;
					}

					if (left + dateInputElem.offsetWidth > windowWidth) {
						left = windowWidth - dateInputElem.offsetWidth;
					}
				}

				datetimepickerElem = datetimepicker[0];

				forEachAncestorOf(datetimepickerElem, function (ancestorNode) {
					var ancestorNodePosition;

					ancestorNodePosition = window.getComputedStyle(ancestorNode).getPropertyValue('position');

					if (ancestorNodePosition === 'relative' && windowWidth >= ancestorNode.offsetWidth) {
						left = left - ((windowWidth - ancestorNode.offsetWidth) / 2);
						return false;
					}
				});

				datetimepickerCss = {
					position: position,
					left: left,
					top: '',  //Initialize to prevent previous values interfering with new ones.
					bottom: ''  //Initialize to prevent previous values interfering with new ones.
				};

				datetimepickerCss[verticalAnchorEdge] = verticalPosition;

				datetimepicker.css(datetimepickerCss);
			};

			datetimepicker
				.on('open.xdsoft', function (event) {
					var onShow = true;
					if (options.onShow && $.isFunction(options.onShow)) {
						onShow = options.onShow.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
					}
					if (onShow !== false) {
						datetimepicker.show();
						setPos();
						$(window)
							.off('resize.xdsoft', setPos)
							.on('resize.xdsoft', setPos);

						if (options.closeOnWithoutClick) {
							$([document.body, window]).on('touchstart mousedown.xdsoft', function arguments_callee6() {
								datetimepicker.trigger('close.xdsoft');
								$([document.body, window]).off('touchstart mousedown.xdsoft', arguments_callee6);
							});
						}
					}
				})
				.on('close.xdsoft', function (event) {
					var onClose = true;
					month_picker
						.find('.xdsoft_month,.xdsoft_year')
							.find('.xdsoft_select')
								.hide();
					if (options.onClose && $.isFunction(options.onClose)) {
						onClose = options.onClose.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
					}
					if (onClose !== false && !options.opened && !options.inline) {
						datetimepicker.hide();
					}
					event.stopPropagation();
				})
				.on('toggle.xdsoft', function () {
					if (datetimepicker.is(':visible')) {
						datetimepicker.trigger('close.xdsoft');
					} else {
						datetimepicker.trigger('open.xdsoft');
					}
				})
				.data('input', input);

			timer = 0;

			datetimepicker.data('xdsoft_datetime', _xdsoft_datetime);
			datetimepicker.setOptions(options);

			function getCurrentValue() {
				var ct = false, time;

				if (options.startDate) {
					ct = _xdsoft_datetime.strToDate(options.startDate);
				} else {
					ct = options.value || ((input && input.val && input.val()) ? input.val() : '');
					if (ct) {
						ct = _xdsoft_datetime.strToDateTime(ct);
					} else if (options.defaultDate) {
						ct = _xdsoft_datetime.strToDateTime(options.defaultDate);
						if (options.defaultTime) {
							time = _xdsoft_datetime.strtotime(options.defaultTime);
							ct.setHours(time.getHours());
							ct.setMinutes(time.getMinutes());
						}
					}
				}

				if (ct && _xdsoft_datetime.isValidDate(ct)) {
					datetimepicker.data('changed', true);
				} else {
					ct = '';
				}

				return ct || 0;
			}

			function setMask(options) {

				var isValidValue = function (mask, value) {
					var reg = mask
						.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, '\\$1')
						.replace(/_/g, '{digit+}')
						.replace(/([0-9]{1})/g, '{digit$1}')
						.replace(/\{digit([0-9]{1})\}/g, '[0-$1_]{1}')
						.replace(/\{digit[\+]\}/g, '[0-9_]{1}');
					return (new RegExp(reg)).test(value);
				},
				getCaretPos = function (input) {
					try {
						if (document.selection && document.selection.createRange) {
							var range = document.selection.createRange();
							return range.getBookmark().charCodeAt(2) - 2;
						}
						if (input.setSelectionRange) {
							return input.selectionStart;
						}
					} catch (e) {
						return 0;
					}
				},
				setCaretPos = function (node, pos) {
					node = (typeof node === "string" || node instanceof String) ? document.getElementById(node) : node;
					if (!node) {
						return false;
					}
					if (node.createTextRange) {
						var textRange = node.createTextRange();
						textRange.collapse(true);
						textRange.moveEnd('character', pos);
						textRange.moveStart('character', pos);
						textRange.select();
						return true;
					}
					if (node.setSelectionRange) {
						node.setSelectionRange(pos, pos);
						return true;
					}
					return false;
				};
				if(options.mask) {
					input.off('keydown.xdsoft');
				}
				if (options.mask === true) {
														if (typeof moment != 'undefined') {
																	options.mask = options.format
																			.replace(/Y{4}/g, '9999')
																			.replace(/Y{2}/g, '99')
																			.replace(/M{2}/g, '19')
																			.replace(/D{2}/g, '39')
																			.replace(/H{2}/g, '29')
																			.replace(/m{2}/g, '59')
																			.replace(/s{2}/g, '59');
														} else {
																	options.mask = options.format
																			.replace(/Y/g, '9999')
																			.replace(/F/g, '9999')
																			.replace(/m/g, '19')
																			.replace(/d/g, '39')
																			.replace(/H/g, '29')
																			.replace(/i/g, '59')
																			.replace(/s/g, '59');
														}
				}

				if ($.type(options.mask) === 'string') {
					if (!isValidValue(options.mask, input.val())) {
						input.val(options.mask.replace(/[0-9]/g, '_'));
						setCaretPos(input[0], 0);
					}

					input.on('keydown.xdsoft', function (event) {
						var val = this.value,
							key = event.which,
							pos,
							digit;

						if (((key >= KEY0 && key <= KEY9) || (key >= _KEY0 && key <= _KEY9)) || (key === BACKSPACE || key === DEL)) {
							pos = getCaretPos(this);
							digit = (key !== BACKSPACE && key !== DEL) ? String.fromCharCode((_KEY0 <= key && key <= _KEY9) ? key - KEY0 : key) : '_';

							if ((key === BACKSPACE || key === DEL) && pos) {
								pos -= 1;
								digit = '_';
							}

							while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
								pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
							}

							val = val.substr(0, pos) + digit + val.substr(pos + 1);
							if ($.trim(val) === '') {
								val = options.mask.replace(/[0-9]/g, '_');
							} else {
								if (pos === options.mask.length) {
									event.preventDefault();
									return false;
								}
							}

							pos += (key === BACKSPACE || key === DEL) ? 0 : 1;
							while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
								pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
							}

							if (isValidValue(options.mask, val)) {
								this.value = val;
								setCaretPos(this, pos);
							} else if ($.trim(val) === '') {
								this.value = options.mask.replace(/[0-9]/g, '_');
							} else {
								input.trigger('error_input.xdsoft');
							}
						} else {
							if (([AKEY, CKEY, VKEY, ZKEY, YKEY].indexOf(key) !== -1 && ctrlDown) || [ESC, ARROWUP, ARROWDOWN, ARROWLEFT, ARROWRIGHT, F5, CTRLKEY, TAB, ENTER].indexOf(key) !== -1) {
								return true;
							}
						}

						event.preventDefault();
						return false;
					});
				}
			}

			_xdsoft_datetime.setCurrentTime(getCurrentValue());

			input
				.data('xdsoft_datetimepicker', datetimepicker)
				.on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function () {
					if (input.is(':disabled') || (input.data('xdsoft_datetimepicker').is(':visible') && options.closeOnInputClick)) {
						return;
					}
					clearTimeout(timer);
					timer = setTimeout(function () {
						if (input.is(':disabled')) {
							return;
						}

						triggerAfterOpen = true;
						_xdsoft_datetime.setCurrentTime(getCurrentValue(), true);
						if(options.mask) {
							setMask(options);
						}
						datetimepicker.trigger('open.xdsoft');
					}, 100);
				})
				.on('keydown.xdsoft', function (event) {
					var elementSelector,
						key = event.which;
					if ([ENTER].indexOf(key) !== -1 && options.enterLikeTab) {
						elementSelector = $("input:visible,textarea:visible,button:visible,a:visible");
						datetimepicker.trigger('close.xdsoft');
						elementSelector.eq(elementSelector.index(this) + 1).focus();
						return false;
					}
					if ([TAB].indexOf(key) !== -1) {
						datetimepicker.trigger('close.xdsoft');
						return true;
					}
				})
				.on('blur.xdsoft', function () {
					datetimepicker.trigger('close.xdsoft');
				});
		};
		destroyDateTimePicker = function (input) {
			var datetimepicker = input.data('xdsoft_datetimepicker');
			if (datetimepicker) {
				datetimepicker.data('xdsoft_datetime', null);
				datetimepicker.remove();
				input
					.data('xdsoft_datetimepicker', null)
					.off('.xdsoft');
				$(window).off('resize.xdsoft');
				$([window, document.body]).off('mousedown.xdsoft touchstart');
				if (input.unmousewheel) {
					input.unmousewheel();
				}
			}
		};
		$(document)
			.off('keydown.xdsoftctrl keyup.xdsoftctrl')
			.on('keydown.xdsoftctrl', function (e) {
				if (e.keyCode === CTRLKEY) {
					ctrlDown = true;
				}
			})
			.on('keyup.xdsoftctrl', function (e) {
				if (e.keyCode === CTRLKEY) {
					ctrlDown = false;
				}
			});

		this.each(function () {
			var datetimepicker = $(this).data('xdsoft_datetimepicker'), $input;
			if (datetimepicker) {
				if ($.type(opt) === 'string') {
					switch (opt) {
					case 'show':
						$(this).select().focus();
						datetimepicker.trigger('open.xdsoft');
						break;
					case 'hide':
						datetimepicker.trigger('close.xdsoft');
						break;
					case 'toggle':
						datetimepicker.trigger('toggle.xdsoft');
						break;
					case 'destroy':
						destroyDateTimePicker($(this));
						break;
					case 'reset':
						this.value = this.defaultValue;
						if (!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(dateHelper.parseDate(this.value, options.format))) {
							datetimepicker.data('changed', false);
						}
						datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value);
						break;
					case 'validate':
						$input = datetimepicker.data('input');
						$input.trigger('blur.xdsoft');
						break;
					default:
						if (datetimepicker[opt] && $.isFunction(datetimepicker[opt])) {
							result = datetimepicker[opt](opt2);
						}
					}
				} else {
					datetimepicker
						.setOptions(opt);
				}
				return 0;
			}
			if ($.type(opt) !== 'string') {
				if (!options.lazyInit || options.open || options.inline) {
					createDateTimePicker($(this));
				} else {
					lazyInit($(this));
				}
			}
		});

		return result;
	};

	$.fn.datetimepicker.defaults = default_options;

	function HighlightedDate(date, desc, style) {
		"use strict";
		this.date = date;
		this.desc = desc;
		this.style = style;
	}
}));
/*!
 * jQuery Mousewheel 3.1.13
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix  = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    var special = $.event.special.mousewheel = {
        version: '3.1.12',

        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
            // Store the line height and page height for this particular element
            $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
            $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
            // Clean up the data we added to the element
            $.removeData(this, 'mousewheel-line-height');
            $.removeData(this, 'mousewheel-page-height');
        },

        getLineHeight: function(elem) {
            var $elem = $(elem),
                $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent']();
            if (!$parent.length) {
                $parent = $('body');
            }
            return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16;
        },

        getPageHeight: function(elem) {
            return $(elem).height();
        },

        settings: {
            adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
            normalizeOffset: true  // calls getBoundingClientRect for each event
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },

        unmousewheel: function(fn) {
            return this.unbind('mousewheel', fn);
        }
    });


    function handler(event) {
        var orgEvent   = event || window.event,
            args       = slice.call(arguments, 1),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0,
            offsetX    = 0,
            offsetY    = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';

        // Old school scrollwheel delta
        if ( 'detail'      in orgEvent ) { deltaY = orgEvent.detail * -1;      }
        if ( 'wheelDelta'  in orgEvent ) { deltaY = orgEvent.wheelDelta;       }
        if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY;      }
        if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ( 'deltaY' in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( 'deltaX' in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) { delta  = deltaX * -1; }
        }

        // No change actually happened, no reason to go any further
        if ( deltaY === 0 && deltaX === 0 ) { return; }

        // Need to convert lines and pages to pixels if we aren't already in pixels
        // There are three delta modes:
        //   * deltaMode 0 is by pixels, nothing to do
        //   * deltaMode 1 is by lines
        //   * deltaMode 2 is by pages
        if ( orgEvent.deltaMode === 1 ) {
            var lineHeight = $.data(this, 'mousewheel-line-height');
            delta  *= lineHeight;
            deltaY *= lineHeight;
            deltaX *= lineHeight;
        } else if ( orgEvent.deltaMode === 2 ) {
            var pageHeight = $.data(this, 'mousewheel-page-height');
            delta  *= pageHeight;
            deltaY *= pageHeight;
            deltaX *= pageHeight;
        }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );

        if ( !lowestDelta || absDelta < lowestDelta ) {
            lowestDelta = absDelta;

            // Adjust older deltas if necessary
            if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
                lowestDelta /= 40;
            }
        }

        // Adjust older deltas if necessary
        if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
            // Divide all the things by 40!
            delta  /= 40;
            deltaX /= 40;
            deltaY /= 40;
        }

        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  >= 1 ? 'floor' : 'ceil' ](delta  / lowestDelta);
        deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
        deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);

        // Normalise offsetX and offsetY properties
        if ( special.settings.normalizeOffset && this.getBoundingClientRect ) {
            var boundingRect = this.getBoundingClientRect();
            offsetX = event.clientX - boundingRect.left;
            offsetY = event.clientY - boundingRect.top;
        }

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;
        event.offsetX = offsetX;
        event.offsetY = offsetY;
        // Go ahead and set deltaMode to 0 since we converted to pixels
        // Although this is a little odd since we overwrite the deltaX/Y
        // properties with normalized deltas.
        event.deltaMode = 0;

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

    function shouldAdjustOldDeltas(orgEvent, absDelta) {
        // If this is an older event and the delta is divisable by 120,
        // then we are assuming that the browser is treating this as an
        // older mouse wheel event and that we should divide the deltas
        // by 40 to try and get a more usable deltaFactor.
        // Side note, this actually impacts the reported scroll distance
        // in older browsers and can cause scrolling to be slower than native.
        // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
        return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
    }

}));
// require application
// require best_in_place
// require best_in_place.jquery-ui
// require list.min
// require account
// require add_users
// require add_charge_entry
// require administration
// require administration/procurement_groups
// require billing_event
// require center_funds
// require centers
// require ilab_tipped

// require container_kinds



// require department
// require equipment
// require fulfillment_priority
// require group
// require institution
// require inventory
// require invoices_search
// require invoices_static
// require lab_budgets
// require lab_uploads
// require link_to_function
// require link_to_remote
// require live_search
// require location
// require observe_field
// require select2_used

// require people_search
// require person_select
// require processors
// require procurement_groups
// require products
// require product_batch_select
// require product_batches
// require products_search
// require purchase_to_resale_unit_conversion
// require recurrence
// require remote_form_for
// require requisition
// require sample_templates
// require samples
// require search
// require searcher_base
// require service_center
// require service_centers
// require service_charge_uploads
// require service_items
// require stock_request_approval_jobs
// require stock_request_creation_jobs
// require stock_transfers
// require product_cores
// require product_cores_kiosk_picking
// require product_cores_kiosk_location
// require peer_reviews
// require peer_reviews_uploads
// require protocols
// require receiving_kiosk
// require special_request_items
// require service_items_tags
// require service_reservations
// require studies
// require confirm_usage
// require settings
// require sortable
// require subscription
// require support
// require stateful_job
// require taxes
// require sc_reporting
// require user_uploads
// require hazardous
// require homepage
// require pageguide
// require scheduling
// require access_request
// require show_profile
// require usage_upload
// require equipment_user_training
// require organization

// require processor_files
// require classifications
// require tinymce/tinymce
// require tiny_mce_init


// require entrez_utilities/rate_limit_timeout_handler
// require storeroom/barcode_range_expander
// require external_generic_funds/lab_select
// require external_generic_funds/select_all
// require contacts
;
(function() {
  window.TippedForIlab || (window.TippedForIlab = {
    initTipped: function() {
      if (typeof Tipped !== 'undefined') {
        Tipped.setDefaultSkin("light");
        return $j("body").on('mouseenter', '.tipped_target', function() {
          var ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
          if ($j(this).data('tipped_initialized') === 'true') {
            return;
          } else {
            $j(this).data('tipped_initialized', 'true');
          }
          if ($j(this).hasClass('inline')) {
            $j(this).data('tipped-object', Tipped.create(this, $j(this).data('tipped'), {
              inline: true,
              hook: (ref = $j(this).data("tipped-hook")) != null ? ref : "bottomright",
              showOn: $j(this).data("tipped-showon") === 'both' ? ['click', 'mouseover'] : (ref1 = $j(this).data("tipped-showon")) != null ? ref1 : 'click',
              hideOn: $j(this).data("tipped-hideon") === 'both' ? [
                {
                  element: 'self',
                  event: 'mouseleave'
                }, {
                  element: 'self',
                  event: 'mouseleave'
                }
              ] : (ref2 = $j(this).data("tipped-hideon")) != null ? ref2 : false,
              closeButton: true,
              closeButtonSkin: 'light',
              maxWidth: (ref3 = $j(this).data("tipped-maxwidth")) != null ? ref3 : 800,
              containment: (ref4 = $j(this).data('tipped-containment')) != null ? ref4 : '#wrapper_main',
              target: $j(this).closest('div'),
              onShow: function(content, element) {
                eval($j(element).data('callback'));
                return setTimeout(function() {
                  return Tipped.refresh(element);
                }, 1000);
              },
              zIndex: (ref5 = $j(this).data("tipped-zindex")) != null ? ref5 : void 0,
              onHide: function(content, element) {
                return eval($j(element).data('hide-callback'));
              }
            }));
            Tipped.show(this);
            Tipped.hide(this);
          } else if ($j(this).hasClass('static')) {
            $j(this).data('tipped-object', Tipped.create(this, {
              ajax: {
                cache: false,
                data: {
                  tipped_ajax_request: true
                }
              },
              hook: {
                target: 'leftmiddle',
                tooltip: 'righttop'
              },
              showOn: (ref6 = $j(this).data("tipped-showon")) != null ? ref6 : 'click',
              hideOn: {
                element: 'self',
                event: 'click'
              },
              closeButton: true,
              closeButtonSkin: 'light',
              maxWidth: (ref7 = $j(this).data("tipped-maxwidth")) != null ? ref7 : 700,
              zIndex: (ref8 = $j(this).data("tipped-zindex")) != null ? ref8 : 1500000,
              containment: (ref9 = $j(this).data('tipped-containment')) != null ? ref9 : false,
              target: $j(this).closest('div'),
              onShow: function(content, element) {
                eval($j(element).data('callback'));
                return setTimeout(function() {
                  return Tipped.refresh(element);
                }, 1000);
              },
              zIndex: (ref10 = $j(this).data("tipped-zindex")) != null ? ref10 : void 0,
              onHide: function(content, element) {
                return eval($j(element).data('hide-callback'));
              }
            }));
          } else {
            $j(this).data('tipped-object', Tipped.create(this, {
              ajax: {
                cache: $j(this).hasClass('cached-tip'),
                data: {
                  tipped_ajax_request: true
                }
              },
              hook: (ref11 = $j(this).data("tipped-hook")) != null ? ref11 : "bottomright",
              showOn: (ref12 = $j(this).data("tipped-showon")) != null ? ref12 : 'click',
              hideOn: $j(this).data("tipped-hideOn") === 'mouseleave' ? [
                {
                  element: 'tooltip',
                  event: 'mouseleave'
                }, {
                  element: 'target',
                  event: 'mouseleave'
                }
              ] : {
                element: 'self',
                event: 'click'
              },
              closeButton: true,
              closeButtonSkin: 'light',
              maxWidth: (ref13 = $j(this).data("tipped-maxwidth")) != null ? ref13 : 800,
              containment: (ref14 = $j(this).data('tipped-containment')) != null ? ref14 : '#wrapper_main',
              target: $j(this).closest('div'),
              zIndex: (ref15 = $j(this).data('tipped-zindex')) != null ? ref15 : void 0,
              onShow: function(content, element) {
                eval($j(element).data('callback'));
                return setTimeout(function() {
                  return Tipped.refresh(element);
                }, 1000);
              },
              zIndex: (ref16 = $j(this).data("tipped-zindex")) != null ? ref16 : void 0,
              onHide: (function(_this) {
                return function(content, element) {
                  if ($j(_this).data("tipped-clear-onclose")) {
                    $j(content).remove();
                  }
                  tinyMCE.ui.FloatPanel.hideAll();
                  return eval($j(element).data('hide-callback'));
                };
              })(this)
            }));
          }
          if (!$j(this).data('tipped_allow_click')) {
            $j(this).click(function() {
              return false;
            });
          }
          return $j(" .tipped_target").live("click", function(event) {
            if (!$j(this).data('tipped_allow_click')) {
              return event.preventDefault();
            }
          });
        });
      }
    }
  });

}).call(this);
/*
@license
dhtmlxScheduler v.4.3.28 Professional

This software is covered by DHTMLX Commercial License. Usage without proper license is prohibited.

(c) Dinamenta, UAB.
*/

window.dhtmlXScheduler = window.scheduler = { version: "4.3.28" };

if (!window.dhtmlx) {
	dhtmlx = function(obj){
		for (var a in obj) dhtmlx[a]=obj[a];
		return dhtmlx; //simple singleton
	};
}
dhtmlx.extend_api=function(name,map,ext){
    var t = window[name];
    if (!t) return; //component not defined
    window[name]=function(obj){
        var that;

        if (obj && typeof obj == "object" && !obj.tagName){
            that = t.apply(this,(map._init?map._init(obj):arguments));
            //global settings
            for (var a in dhtmlx)
                if (map[a]) this[map[a]](dhtmlx[a]);
            //local settings
            for (var a in obj){
                if (map[a]) this[map[a]](obj[a]);
                else if (a.indexOf("on")===0){
                    this.attachEvent(a,obj[a]);
                }
            }
        } else
            that = t.apply(this,arguments);
        if (map._patch) map._patch(this);
        return that||this;
    };
    window[name].prototype=t.prototype;
    if (ext)
        dhtmlXHeir(window[name].prototype,ext);
};

dhtmlxAjax={
    get:function(url,callback){
        var t=new dtmlXMLLoaderObject(true);
        t.async=(arguments.length<3);
        t.waitCall=callback;
        t.loadXML(url);
        return t;
    },
    post:function(url,post,callback){
        var t=new dtmlXMLLoaderObject(true);
        t.async=(arguments.length<4);
        t.waitCall=callback;
        t.loadXML(url,true,post);
        return t;
    },
    getSync:function(url){
        return this.get(url,null,true);
    },
    postSync:function(url,post){
        return this.post(url,post,null,true);
    }
};

/**
 *     @desc: xmlLoader object
 *     @type: private
 *     @param: funcObject - xml parser function
 *     @param: object - jsControl object
 *     @param: async - sync/async mode (async by default)
 *     @param: rSeed - enable/disable random seed ( prevent IE caching)
 *     @topic: 0
 */
function dtmlXMLLoaderObject(funcObject, dhtmlObject, async, rSeed){
    this.xmlDoc="";

    if (typeof (async) != "undefined")
        this.async=async;
    else
        this.async=true;

    this.onloadAction=funcObject||null;
    this.mainObject=dhtmlObject||null;
    this.waitCall=null;
    this.rSeed=rSeed||false;
    return this;
}

dtmlXMLLoaderObject.count = 0;

/**
 *     @desc: xml loading handler
 *     @type: private
 *     @param: dtmlObject - xmlLoader object
 *     @topic: 0
 */
dtmlXMLLoaderObject.prototype.waitLoadFunction=function(dhtmlObject){
    var once = true;
    this.check=function (){
        if ((dhtmlObject)&&(dhtmlObject.onloadAction)){
            if ((!dhtmlObject.xmlDoc.readyState)||(dhtmlObject.xmlDoc.readyState == 4)){
                if (!once)
                    return;

                once=false; //IE 5 fix
                dtmlXMLLoaderObject.count++;
                if (typeof dhtmlObject.onloadAction == "function")
                    dhtmlObject.onloadAction(dhtmlObject.mainObject, null, null, null, dhtmlObject);

                if (dhtmlObject.waitCall){
                    dhtmlObject.waitCall.call(this,dhtmlObject);
                    dhtmlObject.waitCall=null;
                }
            }
        }
    };
    return this.check;
};

/**
 *     @desc: return XML top node
 *     @param: tagName - top XML node tag name (not used in IE, required for Safari and Mozilla)
 *     @type: private
 *     @returns: top XML node
 *     @topic: 0
 */
dtmlXMLLoaderObject.prototype.getXMLTopNode=function(tagName, oldObj){
    var z;

    if (this.xmlDoc.responseXML){
        var temp = this.xmlDoc.responseXML.getElementsByTagName(tagName);
        if(temp.length === 0 && tagName.indexOf(":")!=-1)
            var temp = this.xmlDoc.responseXML.getElementsByTagName((tagName.split(":"))[1]);
        z = temp[0];
    } else
        z = this.xmlDoc.documentElement;

    if (z){
        this._retry=false;
        return z;
    }

    if (!this._retry&&_isIE){
        this._retry=true;
        var oldObj = this.xmlDoc;
        this.loadXMLString(this.xmlDoc.responseText.replace(/^[\s]+/,""), true);
        return this.getXMLTopNode(tagName, oldObj);
    }

    dhtmlxError.throwError("LoadXML", "Incorrect XML", [
        (oldObj||this.xmlDoc),
        this.mainObject
    ]);

    return document.createElement("DIV");
};

/**
 *     @desc: load XML from string
 *     @type: private
 *     @param: xmlString - xml string
 *     @topic: 0
 */
dtmlXMLLoaderObject.prototype.loadXMLString=function(xmlString, silent){

    if (!_isIE){
        var parser = new DOMParser();
        this.xmlDoc=parser.parseFromString(xmlString, "text/xml");
    } else {
        this.xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        this.xmlDoc.async=this.async;
        this.xmlDoc.onreadystatechange = function(){};
        this.xmlDoc["loadXM"+"L"](xmlString);
    }

    if (silent)
        return;

    if (this.onloadAction)
        this.onloadAction(this.mainObject, null, null, null, this);

    if (this.waitCall){
        this.waitCall();
        this.waitCall=null;
    }
};
/**
 *     @desc: load XML
 *     @type: private
 *     @param: filePath - xml file path
 *     @param: postMode - send POST request
 *     @param: postVars - list of vars for post request
 *     @topic: 0
 */
dtmlXMLLoaderObject.prototype.loadXML=function(filePath, postMode, postVars, rpc){
    if (this.rSeed)
        filePath+=((filePath.indexOf("?") != -1) ? "&" : "?")+"a_dhx_rSeed="+(new Date()).valueOf();
    this.filePath=filePath;

    if ((!_isIE)&&(window.XMLHttpRequest))
        this.xmlDoc=new XMLHttpRequest();
    else {
        this.xmlDoc=new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (this.async)
        this.xmlDoc.onreadystatechange=new this.waitLoadFunction(this);
    if (typeof postMode == "string")
        this.xmlDoc.open(postMode, filePath, this.async);
    else
        this.xmlDoc.open(postMode ? "POST" : "GET", filePath, this.async);

    if (rpc){
        this.xmlDoc.setRequestHeader("User-Agent", "dhtmlxRPC v0.1 ("+navigator.userAgent+")");
        this.xmlDoc.setRequestHeader("Content-type", "text/xml");
    }

    else if (postMode) {
        this.xmlDoc.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        this.xmlDoc.setRequestHeader('X-CSRF-Token', jQuery('meta[name="csrf-token"]').attr('content'));
    }

    this.xmlDoc.setRequestHeader("X-Requested-With","XMLHttpRequest");
    this.xmlDoc.send(null||postVars);

    if (!this.async)
        (new this.waitLoadFunction(this))();
};
/**
 *     @desc: destructor, cleans used memory
 *     @type: private
 *     @topic: 0
 */
dtmlXMLLoaderObject.prototype.destructor=function(){
    this._filterXPath = null;
    this._getAllNamedChilds = null;
    this._retry = null;
    this.async = null;
    this.rSeed = null;
    this.filePath = null;
    this.onloadAction = null;
    this.mainObject = null;
    this.xmlDoc = null;
    this.doXPath = null;
    this.doXPathOpera = null;
    this.doXSLTransToObject = null;
    this.doXSLTransToString = null;
    this.loadXML = null;
    this.loadXMLString = null;
    // this.waitLoadFunction = null;
    this.doSerialization = null;
    this.xmlNodeToJSON = null;
    this.getXMLTopNode = null;
    this.setXSLParamValue = null;
    return null;
};

dtmlXMLLoaderObject.prototype.xmlNodeToJSON = function(node){
    var t={};
    for (var i=0; i<node.attributes.length; i++)
        t[node.attributes[i].name]=node.attributes[i].value;
    t["_tagvalue"]=node.firstChild?node.firstChild.nodeValue:"";
    for (var i=0; i<node.childNodes.length; i++){
        var name=node.childNodes[i].tagName;
        if (name){
            if (!t[name]) t[name]=[];
            t[name].push(this.xmlNodeToJSON(node.childNodes[i]));
        }
    }
    return t;
};

/**
 *     @desc: Call wrapper
 *     @type: private
 *     @param: funcObject - action handler
 *     @param: dhtmlObject - user data
 *     @returns: function handler
 *     @topic: 0
 */
function callerFunction(funcObject, dhtmlObject){
    this.handler=function(e){
        if (!e)
            e=window.event;
        funcObject(e, dhtmlObject);
        return true;
    };
    return this.handler;
}

/**
 *     @desc: Calculate absolute position of html object
 *     @type: private
 *     @param: htmlObject - html object
 *     @topic: 0
 */
function getAbsoluteLeft(htmlObject){
    return getOffset(htmlObject).left;
}
/**
 *     @desc: Calculate absolute position of html object
 *     @type: private
 *     @param: htmlObject - html object
 *     @topic: 0
 */
function getAbsoluteTop(htmlObject){
    return getOffset(htmlObject).top;
}

function getOffsetSum(elem) {
    var top=0, left=0;
    while(elem) {
        top = top + parseInt(elem.offsetTop);
        left = left + parseInt(elem.offsetLeft);
        elem = elem.offsetParent;
    }
    return {top: top, left: left};
}
function getOffsetRect(elem) {
    var box = elem.getBoundingClientRect();
    var body = document.body;
    var docElem = document.documentElement;
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
    var clientTop = docElem.clientTop || body.clientTop || 0;
    var clientLeft = docElem.clientLeft || body.clientLeft || 0;
    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;
    return { top: Math.round(top), left: Math.round(left) };
}
function getOffset(elem) {
    if (elem.getBoundingClientRect) {
        return getOffsetRect(elem);
    } else {
        return getOffsetSum(elem);
    }
}

/**
 *     @desc: Convert string to it boolean representation
 *     @type: private
 *     @param: inputString - string for covertion
 *     @topic: 0
 */
function convertStringToBoolean(inputString){
    if (typeof (inputString) == "string")
        inputString=inputString.toLowerCase();

    switch (inputString){
        case "1":
        case "true":
        case "yes":
        case "y":
        case 1:
        case true:
            return true;
        default:
            return false;
    }
}

/**
 *     @desc: find out what symbol to use as url param delimiters in further params
 *     @type: private
 *     @param: str - current url string
 *     @topic: 0
 */
function getUrlSymbol(str){
    if (str.indexOf("?") != -1)
        return "&";
    else
        return "?";
}

function dhtmlDragAndDropObject(){
    if (window.dhtmlDragAndDrop)
        return window.dhtmlDragAndDrop;

    this.lastLanding=0;
    this.dragNode=0;
    this.dragStartNode=0;
    this.dragStartObject=0;
    this.tempDOMU=null;
    this.tempDOMM=null;
    this.waitDrag=0;
    window.dhtmlDragAndDrop=this;

    return this;
}

dhtmlDragAndDropObject.prototype.removeDraggableItem=function(htmlNode){
    htmlNode.onmousedown=null;
    htmlNode.dragStarter=null;
    htmlNode.dragLanding=null;
};

dhtmlDragAndDropObject.prototype.addDraggableItem=function(htmlNode, dhtmlObject){
    htmlNode.onmousedown=this.preCreateDragCopy;
    htmlNode.dragStarter=dhtmlObject;
    this.addDragLanding(htmlNode, dhtmlObject);
};

dhtmlDragAndDropObject.prototype.addDragLanding=function(htmlNode, dhtmlObject){
    htmlNode.dragLanding=dhtmlObject;
};

dhtmlDragAndDropObject.prototype.preCreateDragCopy=function(e){
    if ((e||window.event) && (e||event).button == 2)
        return;

    if (window.dhtmlDragAndDrop.waitDrag){
        window.dhtmlDragAndDrop.waitDrag=0;
        document.body.onmouseup=window.dhtmlDragAndDrop.tempDOMU;
        document.body.onmousemove=window.dhtmlDragAndDrop.tempDOMM;
        return false;
    }

    if (window.dhtmlDragAndDrop.dragNode)
        window.dhtmlDragAndDrop.stopDrag(e);

    window.dhtmlDragAndDrop.waitDrag=1;
    window.dhtmlDragAndDrop.tempDOMU=document.body.onmouseup;
    window.dhtmlDragAndDrop.tempDOMM=document.body.onmousemove;
    window.dhtmlDragAndDrop.dragStartNode=this;
    window.dhtmlDragAndDrop.dragStartObject=this.dragStarter;
    document.body.onmouseup=window.dhtmlDragAndDrop.preCreateDragCopy;
    document.body.onmousemove=window.dhtmlDragAndDrop.callDrag;
    window.dhtmlDragAndDrop.downtime = new Date().valueOf();


    if ((e)&&(e.preventDefault)){
        e.preventDefault();
        return false;
    }
    return false;
};

dhtmlDragAndDropObject.prototype.callDrag=function(e){
    if (!e)
        e=window.event;
    var dragger=window.dhtmlDragAndDrop;
    if ((new Date()).valueOf()-dragger.downtime<100) return;

    //if ((e.button == 0)&&(_isIE))
    //	return dragger.stopDrag();

    if (!dragger.dragNode){
        if (dragger.waitDrag){
            dragger.dragNode=dragger.dragStartObject._createDragNode(dragger.dragStartNode, e);

            if (!dragger.dragNode)
                return dragger.stopDrag();

            dragger.dragNode.onselectstart=function(){return false;};
            dragger.gldragNode=dragger.dragNode;
            document.body.appendChild(dragger.dragNode);
            document.body.onmouseup=dragger.stopDrag;
            dragger.waitDrag=0;
            dragger.dragNode.pWindow=window;
            dragger.initFrameRoute();
        }
        else return dragger.stopDrag(e, true);
    }

    if (dragger.dragNode.parentNode != window.document.body && dragger.gldragNode){
        var grd = dragger.gldragNode;

        if (dragger.gldragNode.old)
            grd=dragger.gldragNode.old;

        //if (!document.all) dragger.calculateFramePosition();
        grd.parentNode.removeChild(grd);
        var oldBody = dragger.dragNode.pWindow;

        if (grd.pWindow &&	grd.pWindow.dhtmlDragAndDrop.lastLanding)
            grd.pWindow.dhtmlDragAndDrop.lastLanding.dragLanding._dragOut(grd.pWindow.dhtmlDragAndDrop.lastLanding);

        //		var oldp=dragger.dragNode.parentObject;
        if (_isIE){
            var div = document.createElement("Div");
            div.innerHTML=dragger.dragNode.outerHTML;
            dragger.dragNode=div.childNodes[0];
        } else
            dragger.dragNode=dragger.dragNode.cloneNode(true);

        dragger.dragNode.pWindow=window;
        //		dragger.dragNode.parentObject=oldp;

        dragger.gldragNode.old=dragger.dragNode;
        document.body.appendChild(dragger.dragNode);
        oldBody.dhtmlDragAndDrop.dragNode=dragger.dragNode;
    }

    dragger.dragNode.style.left=e.clientX+15 +
        (dragger.fx ? dragger.fx*(-1) : 0) +
        (document.body.scrollLeft||document.documentElement.scrollLeft)+"px";
    dragger.dragNode.style.top=e.clientY+3+
        (dragger.fy ? dragger.fy*(-1) : 0) +
        (document.body.scrollTop||document.documentElement.scrollTop)+"px";

    var z;
    if (!e.srcElement)
        z = e.target;
    else
        z=e.srcElement;
    dragger.checkLanding(z, e);
};

dhtmlDragAndDropObject.prototype.calculateFramePosition=function(n){
    //this.fx = 0, this.fy = 0;
    if (window.name){
        var el = parent.frames[window.name].frameElement.offsetParent;
        var fx = 0;
        var fy = 0;

        while (el){
            fx+=el.offsetLeft;
            fy+=el.offsetTop;
            el=el.offsetParent;
        }

        if ((parent.dhtmlDragAndDrop)){
            var ls = parent.dhtmlDragAndDrop.calculateFramePosition(1);
            fx+=ls.split('_')[0]*1;
            fy+=ls.split('_')[1]*1;
        }

        if (n)
            return fx+"_"+fy;
        else
            this.fx=fx;
        this.fy=fy;
    }
    return "0_0";
};

dhtmlDragAndDropObject.prototype.checkLanding=function(htmlObject, e){
    if ((htmlObject)&&(htmlObject.dragLanding)){
        if (this.lastLanding)
            this.lastLanding.dragLanding._dragOut(this.lastLanding);
        this.lastLanding=htmlObject;
        this.lastLanding=this.lastLanding.dragLanding._dragIn(this.lastLanding, this.dragStartNode, e.clientX,
            e.clientY, e);
        this.lastLanding_scr=(_isIE ? e.srcElement : e.target);
    } else {
        if ((htmlObject)&&(htmlObject.tagName != "BODY"))
            this.checkLanding(htmlObject.parentNode, e);
        else {
            if (this.lastLanding)
                this.lastLanding.dragLanding._dragOut(this.lastLanding, e.clientX, e.clientY, e);
            this.lastLanding=0;

            if (this._onNotFound)
                this._onNotFound();
        }
    }
};

dhtmlDragAndDropObject.prototype.stopDrag=function(e, mode){
    var dragger=window.dhtmlDragAndDrop;

    if (!mode){
        dragger.stopFrameRoute();
        var temp = dragger.lastLanding;
        dragger.lastLanding=null;

        if (temp)
            temp.dragLanding._drag(dragger.dragStartNode, dragger.dragStartObject, temp,
                (_isIE ? event.srcElement : e.target));
    }
    dragger.lastLanding=null;

    if ((dragger.dragNode)&&(dragger.dragNode.parentNode == document.body))
        dragger.dragNode.parentNode.removeChild(dragger.dragNode);
    dragger.dragNode=0;
    dragger.gldragNode=0;
    dragger.fx=0;
    dragger.fy=0;
    dragger.dragStartNode=0;
    dragger.dragStartObject=0;
    document.body.onmouseup=dragger.tempDOMU;
    document.body.onmousemove=dragger.tempDOMM;
    dragger.tempDOMU=null;
    dragger.tempDOMM=null;
    dragger.waitDrag=0;
};

dhtmlDragAndDropObject.prototype.stopFrameRoute=function(win){
    if (win)
        window.dhtmlDragAndDrop.stopDrag(1, 1);

    for (var i = 0; i < window.frames.length; i++){
        try{
            if ((window.frames[i] != win)&&(window.frames[i].dhtmlDragAndDrop))
                window.frames[i].dhtmlDragAndDrop.stopFrameRoute(window);
        } catch(e){}
    }

    try{
        if ((parent.dhtmlDragAndDrop)&&(parent != window)&&(parent != win))
            parent.dhtmlDragAndDrop.stopFrameRoute(window);
    } catch(e){}
};

dhtmlDragAndDropObject.prototype.initFrameRoute=function(win, mode){
    if (win){
        window.dhtmlDragAndDrop.preCreateDragCopy();
        window.dhtmlDragAndDrop.dragStartNode=win.dhtmlDragAndDrop.dragStartNode;
        window.dhtmlDragAndDrop.dragStartObject=win.dhtmlDragAndDrop.dragStartObject;
        window.dhtmlDragAndDrop.dragNode=win.dhtmlDragAndDrop.dragNode;
        window.dhtmlDragAndDrop.gldragNode=win.dhtmlDragAndDrop.dragNode;
        window.document.body.onmouseup=window.dhtmlDragAndDrop.stopDrag;
        window.waitDrag=0;

        if (((!_isIE)&&(mode))&&((!_isFF)||(_FFrv < 1.8)))
            window.dhtmlDragAndDrop.calculateFramePosition();
    }
    try{
        if ((parent.dhtmlDragAndDrop)&&(parent != window)&&(parent != win))
            parent.dhtmlDragAndDrop.initFrameRoute(window);
    }catch(e){}

    for (var i = 0; i < window.frames.length; i++){
        try{
            if ((window.frames[i] != win)&&(window.frames[i].dhtmlDragAndDrop))
                window.frames[i].dhtmlDragAndDrop.initFrameRoute(window, ((!win||mode) ? 1 : 0));
        } catch(e){}
    }
};

_isFF = false;
_isIE = false;
_isOpera = false;
_isKHTML = false;
_isMacOS = false;
_isChrome = false;
_FFrv = false;
_KHTMLrv = false;
_OperaRv = false;

if (navigator.userAgent.indexOf('Macintosh') != -1)
    _isMacOS=true;


if (navigator.userAgent.toLowerCase().indexOf('chrome')>-1)
    _isChrome=true;

if ((navigator.userAgent.indexOf('Safari') != -1)||(navigator.userAgent.indexOf('Konqueror') != -1)){
    _KHTMLrv = parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Safari')+7, 5));

    if (_KHTMLrv > 525){ //mimic FF behavior for Safari 3.1+
        _isFF=true;
        _FFrv = 1.9;
    } else
        _isKHTML=true;
} else if (navigator.userAgent.indexOf('Opera') != -1){
    _isOpera=true;
    _OperaRv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Opera')+6, 3));
}


else if (navigator.appName.indexOf("Microsoft") != -1){
    _isIE=true;
    if ((navigator.appVersion.indexOf("MSIE 8.0")!= -1 || navigator.appVersion.indexOf("MSIE 9.0")!= -1 || navigator.appVersion.indexOf("MSIE 10.0")!= -1 ) && document.compatMode != "BackCompat"){
        _isIE=8;
    }
} else if (navigator.appName  == 'Netscape' && navigator.userAgent.indexOf("Trident") != -1){
	//ie11
	_isIE=8;
} else {
    _isFF=true;
    _FFrv = parseFloat(navigator.userAgent.split("rv:")[1]);
}


//multibrowser Xpath processor
dtmlXMLLoaderObject.prototype.doXPath=function(xpathExp, docObj, namespace, result_type){
    if (_isKHTML || (!_isIE && !window.XPathResult))
        return this.doXPathOpera(xpathExp, docObj);

    if (_isIE){ //IE
        if (!docObj)
            if (!this.xmlDoc.nodeName)
                docObj=this.xmlDoc.responseXML;
            else
                docObj=this.xmlDoc;

        if (!docObj)
            dhtmlxError.throwError("LoadXML", "Incorrect XML", [
                (docObj||this.xmlDoc),
                this.mainObject
            ]);

        if (namespace)
            docObj.setProperty("SelectionNamespaces", "xmlns:xsl='"+namespace+"'"); //

        if (result_type == 'single'){
            return docObj.selectSingleNode(xpathExp);
        }
        else {
            return docObj.selectNodes(xpathExp)||new Array(0);
        }
    } else { //Mozilla
        var nodeObj = docObj;

        if (!docObj){
            if (!this.xmlDoc.nodeName){
                docObj=this.xmlDoc.responseXML;
            }
            else {
                docObj=this.xmlDoc;
            }
        }

        if (!docObj)
            dhtmlxError.throwError("LoadXML", "Incorrect XML", [
                (docObj||this.xmlDoc),
                this.mainObject
            ]);

        if (docObj.nodeName.indexOf("document") != -1){
            nodeObj=docObj;
        }
        else {
            nodeObj=docObj;
            docObj=docObj.ownerDocument;
        }
        var retType = XPathResult.ANY_TYPE;

        if (result_type == 'single')
            retType=XPathResult.FIRST_ORDERED_NODE_TYPE;
        var rowsCol = [];
        var col = docObj.evaluate(xpathExp, nodeObj, function(pref){
            return namespace;
        }, retType, null);

        if (retType == XPathResult.FIRST_ORDERED_NODE_TYPE){
            return col.singleNodeValue;
        }
        var thisColMemb = col.iterateNext();

        while (thisColMemb){
            rowsCol[rowsCol.length]=thisColMemb;
            thisColMemb=col.iterateNext();
        }
        return rowsCol;
    }
};

function _dhtmlxError(type, name, params){
    if (!this.catches)
        this.catches=[];

    return this;
}

_dhtmlxError.prototype.catchError=function(type, func_name){
    this.catches[type]=func_name;
};

_dhtmlxError.prototype.throwError=function(type, name, params){
    if (this.catches[type])
        return this.catches[type](type, name, params);

    if (this.catches["ALL"])
        return this.catches["ALL"](type, name, params);

    window.alert("Error type: "+arguments[0]+"\nDescription: "+arguments[1]);
    return null;
};

window.dhtmlxError=new _dhtmlxError();


//opera fake, while 9.0 not released
//multibrowser Xpath processor
dtmlXMLLoaderObject.prototype.doXPathOpera=function(xpathExp, docObj){
    //this is fake for Opera
    var z = xpathExp.replace(/[\/]+/gi, "/").split('/');
    var obj = null;
    var i = 1;

    if (!z.length)
        return [];

    if (z[0] == ".")
        obj=[docObj]; else if (z[0] === ""){
        obj=(this.xmlDoc.responseXML||this.xmlDoc).getElementsByTagName(z[i].replace(/\[[^\]]*\]/g, ""));
        i++;
    } else
        return [];

    for (i; i < z.length; i++)obj=this._getAllNamedChilds(obj, z[i]);

    if (z[i-1].indexOf("[") != -1)
        obj=this._filterXPath(obj, z[i-1]);
    return obj;
};

dtmlXMLLoaderObject.prototype._filterXPath=function(a, b){
    var c = [];
    var b = b.replace(/[^\[]*\[\@/g, "").replace(/[\[\]\@]*/g, "");

    for (var i = 0; i < a.length; i++)
        if (a[i].getAttribute(b))
            c[c.length]=a[i];

    return c;
};

dtmlXMLLoaderObject.prototype._getAllNamedChilds=function(a, b){
    var c = [];

    if (_isKHTML)
        b=b.toUpperCase();

    for (var i = 0; i < a.length; i++)for (var j = 0; j < a[i].childNodes.length; j++){
        if (_isKHTML){
            if (a[i].childNodes[j].tagName&&a[i].childNodes[j].tagName.toUpperCase() == b)
                c[c.length]=a[i].childNodes[j];
        }

        else if (a[i].childNodes[j].tagName == b)
            c[c.length]=a[i].childNodes[j];
    }

    return c;
};

function dhtmlXHeir(a, b){
    for (var c in b)
        if (typeof (b[c]) == "function")
            a[c]=b[c];
    return a;
}

if(typeof (window.dhtmlxEvent) == 'undefined'){
    window.dhtmlxEvent = function dhtmlxEvent(el, event, handler){
        if (el.addEventListener)
            el.addEventListener(event, handler, false);

        else if (el.attachEvent)
            el.attachEvent("on"+event, handler);
    };
}

//============= XSL Extension ===================================

dtmlXMLLoaderObject.prototype.xslDoc=null;
dtmlXMLLoaderObject.prototype.setXSLParamValue=function(paramName, paramValue, xslDoc){
    if (!xslDoc)
        xslDoc=this.xslDoc;

    if (xslDoc.responseXML)
        xslDoc=xslDoc.responseXML;
    var item =
        this.doXPath("/xsl:stylesheet/xsl:variable[@name='"+paramName+"']", xslDoc,
            "http:/\/www.w3.org/1999/XSL/Transform", "single");

    if (item)
        item.firstChild.nodeValue=paramValue;
};

dtmlXMLLoaderObject.prototype.doXSLTransToObject=function(xslDoc, xmlDoc){
    if (!xslDoc)
        xslDoc=this.xslDoc;

    if (xslDoc.responseXML)
        xslDoc=xslDoc.responseXML;

    if (!xmlDoc)
        xmlDoc=this.xmlDoc;

    if (xmlDoc.responseXML)
        xmlDoc=xmlDoc.responseXML;


    var result;
    //Mozilla
    if (!_isIE){
        if (!this.XSLProcessor){
            this.XSLProcessor=new XSLTProcessor();
            this.XSLProcessor.importStylesheet(xslDoc);
        }
        result = this.XSLProcessor.transformToDocument(xmlDoc);
    } else {
        result = new ActiveXObject("Msxml2.DOMDocument.3.0");
        try{
            xmlDoc.transformNodeToObject(xslDoc, result);
        }catch(e){
            result = xmlDoc.transformNode(xslDoc);
        }
    }
    return result;
};

dtmlXMLLoaderObject.prototype.doXSLTransToString=function(xslDoc, xmlDoc){
    var res = this.doXSLTransToObject(xslDoc, xmlDoc);
    if(typeof(res)=="string")
        return res;
    return this.doSerialization(res);
};

dtmlXMLLoaderObject.prototype.doSerialization=function(xmlDoc){
    if (!xmlDoc)
        xmlDoc=this.xmlDoc;
    if (xmlDoc.responseXML)
        xmlDoc=xmlDoc.responseXML;
    if (!_isIE){
        var xmlSerializer = new XMLSerializer();
        return xmlSerializer.serializeToString(xmlDoc);
    } else
        return xmlDoc.xml;
};

/**
 *   @desc:
 *   @type: private
 */
dhtmlxEventable=function(obj){
    obj.attachEvent=function(name, catcher, callObj){
        name='ev_'+name.toLowerCase();
        if (!this[name])
            this[name]=new this.eventCatcher(callObj||this);

        return(name+':'+this[name].addEvent(catcher)); //return ID (event name & event ID)
    };
    obj.callEvent=function(name, arg0){
        name='ev_'+name.toLowerCase();
        if (this[name])
            return this[name].apply(this, arg0);
        return true;
    };
    obj.checkEvent=function(name){
        return (!!this['ev_'+name.toLowerCase()]);
    };
    obj.eventCatcher=function(obj){
        var dhx_catch = [];
        var z = function(){
            var res = true;
            for (var i = 0; i < dhx_catch.length; i++){
                if (dhx_catch[i]){
                    var zr = dhx_catch[i].apply(obj, arguments);
                    res=res&&zr;
                }
            }
            return res;
        };
        z.addEvent=function(ev){
            if (typeof (ev) != "function")
                ev=eval(ev);
            if (ev)
                return dhx_catch.push(ev)-1;
            return false;
        };
        z.removeEvent=function(id){
            dhx_catch[id]=null;
        };
        return z;
    };
    obj.detachEvent=function(id){
        if (id){
            var list = id.split(':');           //get EventName and ID
            this[list[0]].removeEvent(list[1]); //remove event
        }
    };
    obj.detachAllEvents = function(){
        for (var name in this){
            if (name.indexOf("ev_")===0){
                this.detachEvent(name);
                this[name] = null;
            }
        }
    };
    obj = null;
};
if(!window.dhtmlx)
	window.dhtmlx = {};

(function(){
	var _dhx_msg_cfg = null;
	function callback(config, result){
			var usercall = config.callback;
			modality(false);
			config.box.parentNode.removeChild(config.box);
			_dhx_msg_cfg = config.box = null;
			if (usercall)
				usercall(result);
	}
	function modal_key(e){
		if (_dhx_msg_cfg){
			e = e||event;
			var code = e.which||event.keyCode;
			if (dhtmlx.message.keyboard){
				if (code == 13 || code == 32)
					callback(_dhx_msg_cfg, true);
				if (code == 27)
					callback(_dhx_msg_cfg, false);
			}
			if (e.preventDefault)
				e.preventDefault();
			return !(e.cancelBubble = true);
		}
	}
	if (document.attachEvent)
		document.attachEvent("onkeydown", modal_key);
	else
		document.addEventListener("keydown", modal_key, true);

	function modality(mode){
		if(!modality.cover){
			modality.cover = document.createElement("DIV");
			//necessary for IE only
			modality.cover.onkeydown = modal_key;
			modality.cover.className = "dhx_modal_cover";
			document.body.appendChild(modality.cover);
		}
		var height =  document.body.scrollHeight;
		modality.cover.style.display = mode?"inline-block":"none";
	}

	function button(text, result, css){
		// css - for locale-independent class name
		var className = css ? css : (text || "");
		var button_css = "dhtmlx_"+(className).toLowerCase().replace(/ /g, "_")+"_button"; // dhtmlx_ok_button, dhtmlx_click_me_button
		return "<div class='dhtmlx_popup_button "+button_css+"' result='"+result+"' ><div>"+text+"</div></div>";
	}

	function info(text){
		if (!t.area){
			t.area = document.createElement("DIV");
			t.area.className = "dhtmlx_message_area";
			t.area.style[t.position]="5px";
			document.body.appendChild(t.area);
		}

		t.hide(text.id);
		var message = document.createElement("DIV");
		message.innerHTML = "<div>"+text.text+"</div>";
		message.className = "dhtmlx-info dhtmlx-" + text.type;
		message.onclick = function(){
			t.hide(text.id);
			text = null;
		};

		if (t.position == "bottom" && t.area.firstChild)
			t.area.insertBefore(message,t.area.firstChild);
		else
			t.area.appendChild(message);

		if (text.expire > 0)
			t.timers[text.id]=window.setTimeout(function(){
				t.hide(text.id);
			}, text.expire);

		t.pull[text.id] = message;
		message = null;

		return text.id;
	}
	function _boxStructure(config, ok, cancel){
		var box = document.createElement("DIV");
		box.className = " dhtmlx_modal_box dhtmlx-"+config.type;
		box.setAttribute("dhxbox", 1);

		var inner = '';

		if (config.width)
			box.style.width = config.width;
		if (config.height)
			box.style.height = config.height;
		if (config.title)
			inner+='<div class="dhtmlx_popup_title">'+config.title+'</div>';
		inner+='<div class="dhtmlx_popup_text"><span>'+(config.content?'':config.text)+'</span></div><div  class="dhtmlx_popup_controls">';
		if (ok){
			var ok_text = (config.ok || scheduler.locale.labels.message_ok);
			//default value for compatibility with custom locales some people have
			if(ok_text === undefined) ok_text = "OK";
			inner += button(ok_text, true, "ok");
		}
		if (cancel){
			var cancel_text = (config.cancel || scheduler.locale.labels.message_cancel);
			if(cancel_text === undefined) cancel_text = "Cancel";
			inner += button(cancel_text, false, "cancel");
		}
		if (config.buttons){
			for (var i=0; i<config.buttons.length; i++)
				inner += button(config.buttons[i],i);
		}
		inner += '</div>';
		box.innerHTML = inner;

		if (config.content){
			var node = config.content;
			if (typeof node == "string")
				node = document.getElementById(node);
			if (node.style.display == 'none')
				node.style.display = "";
			box.childNodes[config.title?1:0].appendChild(node);
		}

		box.onclick = function(e){
			e = e ||event;
			var source = e.target || e.srcElement;
			if (!source.className) source = source.parentNode;
			if (source.className.split(" ")[0] == "dhtmlx_popup_button"){
				var result = source.getAttribute("result");
				result = (result == "true")||(result == "false"?false:result);
				callback(config, result);
			}
		};
		config.box = box;
		if (ok||cancel)
			_dhx_msg_cfg = config;

		return box;
	}
	function _createBox(config, ok, cancel){
		var box = config.tagName ? config : _boxStructure(config, ok, cancel);

		if (!config.hidden)
			modality(true);
		document.body.appendChild(box);
		var x = Math.abs(Math.floor(((window.innerWidth||document.documentElement.offsetWidth) - box.offsetWidth)/2));
		var y = Math.abs(Math.floor(((window.innerHeight||document.documentElement.offsetHeight) - box.offsetHeight)/2));
		if (config.position == "top")
			box.style.top = "-3px";
		else
			box.style.top = y+'px';
		box.style.left = x+'px';
		//necessary for IE only
		box.onkeydown = modal_key;

		box.focus();
		if (config.hidden)
			dhtmlx.modalbox.hide(box);

		return box;
	}

	function alertPopup(config){
		return _createBox(config, true, false);
	}
	function confirmPopup(config){
		return _createBox(config, true, true);
	}
	function boxPopup(config){
		return _createBox(config);
	}
	function box_params(text, type, callback){
		if (typeof text != "object"){
			if (typeof type == "function"){
				callback = type;
				type = "";
			}
			text = {text:text, type:type, callback:callback };
		}
		return text;
	}
	function params(text, type, expire, id){
		if (typeof text != "object")
			text = {text:text, type:type, expire:expire, id:id};
		text.id = text.id||t.uid();
		text.expire = text.expire||t.expire;
		return text;
	}
	dhtmlx.alert = function(){
		var text = box_params.apply(this, arguments);
		text.type = text.type || "confirm";
		return alertPopup(text);
	};
	dhtmlx.confirm = function(){
		var text = box_params.apply(this, arguments);
		text.type = text.type || "alert";
		return confirmPopup(text);
	};
	dhtmlx.modalbox = function(){
		var text = box_params.apply(this, arguments);
		text.type = text.type || "alert";
		return boxPopup(text);
	};
	dhtmlx.modalbox.hide = function(node){
		while (node && node.getAttribute && !node.getAttribute("dhxbox"))
			node = node.parentNode;
		if (node){
			node.parentNode.removeChild(node);
			modality(false);
		}
	};
	var t = dhtmlx.message = function(text, type, expire, id){
		text = params.apply(this, arguments);
		text.type = text.type||"info";

		var subtype = text.type.split("-")[0];
		switch (subtype){
			case "alert":
				return alertPopup(text);
			case "confirm":
				return confirmPopup(text);
			case "modalbox":
				return boxPopup(text);
			default:
				return info(text);
		}
	};

	t.seed = (new Date()).valueOf();
	t.uid = function(){return t.seed++;};
	t.expire = 4000;
	t.keyboard = true;
	t.position = "top";
	t.pull = {};
	t.timers = {};

	t.hideAll = function(){
		for (var key in t.pull)
			t.hide(key);
	};
	t.hide = function(id){
		var obj = t.pull[id];
		if (obj && obj.parentNode){
			window.setTimeout(function(){
				obj.parentNode.removeChild(obj);
				obj = null;
			},2000);
			obj.className+=" hidden";

			if(t.timers[id])
				window.clearTimeout(t.timers[id]);
			delete t.pull[id];
		}
	};
})();
/**
	* 	@desc: constructor, data processor object
	*	@param: serverProcessorURL - url used for update
	*	@type: public
	*/
function dataProcessor(serverProcessorURL){
    this.serverProcessor = serverProcessorURL;
    this.action_param="!nativeeditor_status";

	this.object = null;
	this.updatedRows = []; //ids of updated rows

	this.autoUpdate = true;
	this.updateMode = "cell";
	this._tMode="GET";
	this.post_delim = "_";

    this._waitMode=0;
    this._in_progress={};//?
    this._invalid={};
    this.mandatoryFields=[];
    this.messages=[];

    this.styles={
    	updated:"font-weight:bold;",
    	inserted:"font-weight:bold;",
    	deleted:"text-decoration : line-through;",
    	invalid:"background-color:FFE0E0;",
    	invalid_cell:"border-bottom:2px solid red;",
    	error:"color:red;",
    	clear:"font-weight:normal;text-decoration:none;"
    };

    this.enableUTFencoding(true);
    dhtmlxEventable(this);

    return this;
    }

dataProcessor.prototype={
	/**
	* 	@desc: select GET or POST transaction model
	*	@param: mode - GET/POST
	*	@param: total - true/false - send records row by row or all at once (for grid only)
	*	@type: public
	*/
	setTransactionMode:function(mode,total){
        this._tMode=mode;
		this._tSend=total;
		if (mode == "REST"){
			this._tSend = false;
			this._endnm = true;
		}
    },
    escape:function(data){
    	if (this._utf)
    		return encodeURIComponent(data);
    	else
        	return escape(data);
	},
    /**
	* 	@desc: allows to set escaping mode
	*	@param: true - utf based escaping, simple - use current page encoding
	*	@type: public
	*/
	enableUTFencoding:function(mode){
        this._utf=convertStringToBoolean(mode);
    },
    /**
	* 	@desc: allows to define, which column may trigger update
	*	@param: val - array or list of true/false values
	*	@type: public
	*/
	setDataColumns:function(val){
		this._columns=(typeof val == "string")?val.split(","):val;
    },
    /**
	* 	@desc: get state of updating
	*	@returns:   true - all in sync with server, false - some items not updated yet.
	*	@type: public
	*/
	getSyncState:function(){
		return !this.updatedRows.length;
	},
	/**
	* 	@desc: enable/disable named field for data syncing, will use column ids for grid
	*	@param:   mode - true/false
	*	@type: public
	*/
	enableDataNames:function(mode){
		this._endnm=convertStringToBoolean(mode);
	},
	/**
	* 	@desc: enable/disable mode , when only changed fields and row id send to the server side, instead of all fields in default mode
	*	@param:   mode - true/false
	*	@type: public
	*/
	enablePartialDataSend:function(mode){
		this._changed=convertStringToBoolean(mode);
	},
	/**
	* 	@desc: set if rows should be send to server automaticaly
	*	@param: mode - "row" - based on row selection changed, "cell" - based on cell editing finished, "off" - manual data sending
	*	@type: public
	*/
	setUpdateMode:function(mode,dnd){
		this.autoUpdate = (mode=="cell");
		this.updateMode = mode;
		this.dnd=dnd;
	},
	ignore:function(code,master){
		this._silent_mode=true;
		code.call(master||window);
		this._silent_mode=false;
	},
	/**
	* 	@desc: mark row as updated/normal. check mandatory fields,initiate autoupdate (if turned on)
	*	@param: rowId - id of row to set update-status for
	*	@param: state - true for "updated", false for "not updated"
	*	@param: mode - update mode name
	*	@type: public
	*/
	setUpdated:function(rowId,state,mode){
		if (this._silent_mode) return;
		var ind=this.findRow(rowId);

		mode=mode||"updated";
		var existing = this.obj.getUserData(rowId,this.action_param);
		if (existing && mode == "updated") mode=existing;
		if (state){
			this.set_invalid(rowId,false); //clear previous error flag
			this.updatedRows[ind]=rowId;
			this.obj.setUserData(rowId,this.action_param,mode);
			if (this._in_progress[rowId])
				this._in_progress[rowId]="wait";
		} else{
			if (!this.is_invalid(rowId)){
				this.updatedRows.splice(ind,1);
				this.obj.setUserData(rowId,this.action_param,"");
			}
		}

		//clear changed flag
		if (!state)
			this._clearUpdateFlag(rowId);

		this.markRow(rowId,state,mode);
		if (state && this.autoUpdate) this.sendData(rowId);
	},
	_clearUpdateFlag:function(id){},
	markRow:function(id,state,mode){
		var str="";
		var invalid=this.is_invalid(id);
		if (invalid){
        	str=this.styles[invalid];
        	state=true;
    	}
		if (this.callEvent("onRowMark",[id,state,mode,invalid])){
			//default logic
			str=this.styles[state?mode:"clear"]+str;

        	this.obj[this._methods[0]](id,str);

			if (invalid && invalid.details){
				str+=this.styles[invalid+"_cell"];
				for (var i=0; i < invalid.details.length; i++)
					if (invalid.details[i])
        				this.obj[this._methods[1]](id,i,str);
			}
		}
	},
	getState:function(id){
		return this.obj.getUserData(id,this.action_param);
	},
	is_invalid:function(id){
		return this._invalid[id];
	},
	set_invalid:function(id,mode,details){
		if (details) mode={value:mode, details:details, toString:function(){ return this.value.toString(); }};
		this._invalid[id]=mode;
	},
	/**
	* 	@desc: check mandatory fields and varify values of cells, initiate update (if specified)
	*	@param: rowId - id of row to set update-status for
	*	@type: public
	*/
	checkBeforeUpdate:function(rowId){
		return true;
	},
	/**
	* 	@desc: send row(s) values to server
	*	@param: rowId - id of row which data to send. If not specified, then all "updated" rows will be send
	*	@type: public
	*/
	sendData:function(rowId){
		if (this._waitMode && (this.obj.mytype=="tree" || this.obj._h2)) return;
		if (this.obj.editStop) this.obj.editStop();


		if(typeof rowId == "undefined" || this._tSend) return this.sendAllData();
		if (this._in_progress[rowId]) return false;

		this.messages=[];
		if (!this.checkBeforeUpdate(rowId) && this.callEvent("onValidationError",[rowId,this.messages])) return false;
		this._beforeSendData(this._getRowData(rowId),rowId);
    },
    _beforeSendData:function(data,rowId){
    	if (!this.callEvent("onBeforeUpdate",[rowId,this.getState(rowId),data])) return false;
		this._sendData(data,rowId);
    },
    serialize:function(data, id){
    	if (typeof data == "string")
    		return data;
    	if (typeof id != "undefined")
    		return this.serialize_one(data,"");
    	else{
    		var stack = [];
    		var keys = [];
    		for (var key in data)
    			if (data.hasOwnProperty(key)){
    				stack.push(this.serialize_one(data[key],key+this.post_delim));
    				keys.push(key);
				}
    		stack.push("ids="+this.escape(keys.join(",")));
    		if (dhtmlx.security_key)
				stack.push("dhx_security="+dhtmlx.security_key);
    		return stack.join("&");
    	}
    },
    serialize_one:function(data, pref){
    	if (typeof data == "string")
    		return data;
    	var stack = [];
    	for (var key in data)
    		if (data.hasOwnProperty(key)){
    			if ((key == "id" || key == this.action_param) && this._tMode == "REST") continue;
    			stack.push(this.escape((pref||"")+key)+"="+this.escape(data[key]));
    		}
		return stack.join("&");
    },
    _sendData:function(a1,rowId){
    	if (!a1) return; //nothing to send
		if (!this.callEvent("onBeforeDataSending",rowId?[rowId,this.getState(rowId),a1]:[null, null, a1])) return false;

    	if (rowId)
			this._in_progress[rowId]=(new Date()).valueOf();
		var a2=new dtmlXMLLoaderObject(function(that,b,c,d,xml){
			var ids = [];
			if (rowId)
				ids.push(rowId);
			else if (a1)
				for (var key in a1)
					ids.push(key);

			return that.afterUpdate(that,xml,ids);
		},this,true);

		var a3 = this.serverProcessor+(this._user?(getUrlSymbol(this.serverProcessor)+["dhx_user="+this._user,"dhx_version="+this.obj.getUserData(0,"version")].join("&")):"");

		if (this._tMode=="GET")
        	a2.loadXML(a3+((a3.indexOf("?")!=-1)?"&":"?")+this.serialize(a1,rowId));
		else if (this._tMode == "POST")
        	a2.loadXML(a3,true,this.serialize(a1,rowId));
        else if (this._tMode == "REST"){
        	var state = this.getState(rowId);
        	var url = a3.replace(/(\&|\?)editing\=true/,"");
        	if (state == "inserted")
        		a2.loadXML(url+rowId,"POST",this.serialize(a1,rowId));
        	else if (state == "deleted")
        		a2.loadXML(url+rowId,"DELETE","");
        	else
        		a2.loadXML(url+rowId,"PUT",this.serialize(a1,rowId));
        }

		this._waitMode++;
    },
	sendAllData:function(){
		if (!this.updatedRows.length) return;

		this.messages=[]; var valid=true;
		for (var i=0; i<this.updatedRows.length; i++)
			valid&=this.checkBeforeUpdate(this.updatedRows[i]);
		if (!valid && !this.callEvent("onValidationError",["",this.messages])) return false;

		if (this._tSend)
			this._sendData(this._getAllData());
		else
			for (var i=0; i<this.updatedRows.length; i++)
				if (!this._in_progress[this.updatedRows[i]]){
					if (this.is_invalid(this.updatedRows[i])) continue;
					this._beforeSendData(this._getRowData(this.updatedRows[i]),this.updatedRows[i]);
					if (this._waitMode && (this.obj.mytype=="tree" || this.obj._h2)) return; //block send all for tree
				}
	},








	_getAllData:function(rowId){
		var out={};
		var has_one = false;
		for(var i=0;i<this.updatedRows.length;i++){
			var id=this.updatedRows[i];
			if (this._in_progress[id] || this.is_invalid(id)) continue;
			if (!this.callEvent("onBeforeUpdate",[id,this.getState(id), this._getRowData(id)])) continue;
			out[id]=this._getRowData(id,id+this.post_delim);
			has_one = true;
			this._in_progress[id]=(new Date()).valueOf();
		}
		return has_one?out:null;
	},


	/**
	* 	@desc: specify column which value should be varified before sending to server
	*	@param: ind - column index (0 based)
	*	@param: verifFunction - function (object) which should verify cell value (if not specified, then value will be compared to empty string). Two arguments will be passed into it: value and column name
	*	@type: public
	*/
	setVerificator:function(ind,verifFunction){
		this.mandatoryFields[ind] = verifFunction||(function(value){return (value!=="");});
	},
	/**
	* 	@desc: remove column from list of those which should be verified
	*	@param: ind - column Index (0 based)
	*	@type: public
	*/
	clearVerificator:function(ind){
		this.mandatoryFields[ind] = false;
	},





	findRow:function(pattern){
		var i=0;
    	for(i=0;i<this.updatedRows.length;i++)
		    if(pattern==this.updatedRows[i]) break;
	    return i;
    },











	/**
	* 	@desc: define custom actions
	*	@param: name - name of action, same as value of action attribute
	*	@param: handler - custom function, which receives a XMl response content for action
	*	@type: private
	*/
	defineAction:function(name,handler){
        if (!this._uActions) this._uActions=[];
            this._uActions[name]=handler;
	},




	/**
*     @desc: used in combination with setOnBeforeUpdateHandler to create custom client-server transport system
*     @param: sid - id of item before update
*     @param: tid - id of item after up0ate
*     @param: action - action name
*     @type: public
*     @topic: 0
*/
	afterUpdateCallback:function(sid, tid, action, btag) {
		var marker = sid;
		var correct=(action!="error" && action!="invalid");
		if (!correct) this.set_invalid(sid,action);
		if ((this._uActions)&&(this._uActions[action])&&(!this._uActions[action](btag)))
			return (delete this._in_progress[marker]);

		if (this._in_progress[marker]!="wait")
	    	this.setUpdated(sid, false);

	    var soid = sid;

	    switch (action) {
	    case "inserted":
	    case "insert":
	        if (tid != sid) {
	            this.obj[this._methods[2]](sid, tid);
	            sid = tid;
	        }
	        break;
	    case "delete":
	    case "deleted":
	    	this.obj.setUserData(sid, this.action_param, "true_deleted");
	        this.obj[this._methods[3]](sid, tid);
	        delete this._in_progress[marker];
	        return this.callEvent("onAfterUpdate", [sid, action, tid, btag]);
	    }

	    if (this._in_progress[marker]!="wait"){
	    	if (correct) this.obj.setUserData(sid, this.action_param,'');
	    	delete this._in_progress[marker];
    	} else {
    		delete this._in_progress[marker];
    		this.setUpdated(tid,true,this.obj.getUserData(sid,this.action_param));
		}

	    this.callEvent("onAfterUpdate", [soid, action, tid, btag]);
	},

	/**
	* 	@desc: response from server
	*	@param: xml - XMLLoader object with response XML
	*	@type: private
	*/
	afterUpdate:function(that,xml,id){
		//try to use json first
		if (window.JSON){
			try{
				var tag = JSON.parse(xml.xmlDoc.responseText);
				var action = tag.action || this.getState(id) || "updated";
				var sid = tag.sid || id[0];
				var tid = tag.tid || id[0];
				that.afterUpdateCallback(sid, tid, action, tag);
				that.finalizeUpdate();
				return;
			} catch(e){
			}
		}
		//xml response
		xml.getXMLTopNode("data"); //fix incorrect content type in IE

		if (!xml.xmlDoc.responseXML){
			if(this.obj && this.obj.callEvent){
				this.obj.callEvent("onSaveError", [id, xml.xmlDoc]);
			}
			return this.cleanUpdate(id);
		}

		var atag=xml.doXPath("//data/action");
		if (!atag.length) return this.cleanUpdate(id);

		for (var i=0; i<atag.length; i++){
        	var btag=atag[i];
			var action = btag.getAttribute("type");
			var sid = btag.getAttribute("sid");
			var tid = btag.getAttribute("tid");

			that.afterUpdateCallback(sid,tid,action,btag);
		}
		that.finalizeUpdate();
	},
	cleanUpdate:function(id){
		if (id)
			for (var i = 0; i < id.length; i++)
				delete this._in_progress[id[i]];
	},
	finalizeUpdate:function(){
		if (this._waitMode) this._waitMode--;

		if ((this.obj.mytype=="tree" || this.obj._h2) && this.updatedRows.length)
			this.sendData();
		this.callEvent("onAfterUpdateFinish",[]);
		if (!this.updatedRows.length)
			this.callEvent("onFullSync",[]);
	},





	/**
	* 	@desc: initializes data-processor
	*	@param: anObj - dhtmlxGrid object to attach this data-processor to
	*	@type: public
	*/
	init:function(anObj){
		this.obj = anObj;
		if (this.obj._dp_init)
			this.obj._dp_init(this);
	},


	setOnAfterUpdate:function(ev){
		this.attachEvent("onAfterUpdate",ev);
	},
	enableDebug:function(mode){
	},
	setOnBeforeUpdateHandler:function(func){
		this.attachEvent("onBeforeDataSending",func);
	},



	/* starts autoupdate mode
		@param interval
			time interval for sending update requests
	*/
	setAutoUpdate: function(interval, user) {
		interval = interval || 2000;

		this._user = user || (new Date()).valueOf();
		this._need_update = false;
		this._loader = null;
		this._update_busy = false;

		this.attachEvent("onAfterUpdate",function(sid,action,tid,xml_node){
			this.afterAutoUpdate(sid, action, tid, xml_node);
		});
		this.attachEvent("onFullSync",function(){
			this.fullSync();
		});

		var self = this;
		window.setInterval(function(){
			self.loadUpdate();
		}, interval);
	},


	/* process updating request answer
		if status == collision version is depricated
		set flag for autoupdating immidiatly
	*/
	afterAutoUpdate: function(sid, action, tid, xml_node) {
		if (action == 'collision') {
			this._need_update = true;
			return false;
		} else {
			return true;
		}
	},


	/* callback function for onFillSync event
		call update function if it's need
	*/
	fullSync: function() {
		if (this._need_update) {
			this._need_update = false;
			this.loadUpdate();
		}
		return true;
	},


	/* sends query to the server and call callback function
	*/
	getUpdates: function(url,callback){
		if (this._update_busy)
			return false;
		else
			this._update_busy = true;

		this._loader = this._loader || new dtmlXMLLoaderObject(true);

		this._loader.async=true;
		this._loader.waitCall=callback;
		this._loader.loadXML(url);
	},


	/* returns xml node value
		@param node
			xml node
	*/
	_v: function(node) {
		if (node.firstChild) return node.firstChild.nodeValue;
		return "";
	},


	/* returns values array of xml nodes array
		@param arr
			array of xml nodes
	*/
	_a: function(arr) {
		var res = [];
		for (var i=0; i < arr.length; i++) {
			res[i]=this._v(arr[i]);
		}
		return res;
	},


	/* loads updates and processes them
	*/
	loadUpdate: function(){
		var self = this;
		var version = this.obj.getUserData(0,"version");
		var url = this.serverProcessor+getUrlSymbol(this.serverProcessor)+["dhx_user="+this._user,"dhx_version="+version].join("&");
		url = url.replace("editing=true&","");
		this.getUpdates(url, function(){
			var vers;
			try {
				vers = self._loader.doXPath("//userdata");
			}
			catch(ex) {
				self._update_busy = false;
				return;
			}

			self.obj.setUserData(0, "version", self._v(vers[0]));
			var upds = self._loader.doXPath("//update");
			if (upds.length){
				self._silent_mode = true;

				for (var i=0; i<upds.length; i++) {
					var status = upds[i].getAttribute('status');
					var id = upds[i].getAttribute('id');
					var parent = upds[i].getAttribute('parent');
					switch (status) {
						case 'inserted':
							self.callEvent("insertCallback",[upds[i], id, parent]);
							break;
						case 'updated':
							self.callEvent("updateCallback",[upds[i], id, parent]);
							break;
						case 'deleted':
							self.callEvent("deleteCallback",[upds[i], id, parent]);
							break;
					}
				}

				self._silent_mode = false;
			}

			self._update_busy = false;
			self = null;
		});
	}

};

//(c)dhtmlx ltd. www.dhtmlx.com
if (window.dataProcessor && !dataProcessor.prototype.init_original){
	dataProcessor.prototype.init_original=dataProcessor.prototype.init;
	dataProcessor.prototype.init=function(obj){
		this.init_original(obj);
		obj._dataprocessor=this;

		this.setTransactionMode("POST",true);
		this.serverProcessor+=(this.serverProcessor.indexOf("?")!=-1?"&":"?")+"editing=true";
	};
}

dhtmlxError.catchError("LoadXML", function(a, b, c){
	var message = c[0].responseText;

	switch (scheduler.config.ajax_error){
		case "alert":
			window.alert(message);
			break;
		case "console":
			window.console.log(message);
			break;
		default:
			break;
	}
});


dhtmlxEventable(scheduler);

scheduler._detachDomEvent = function(el, event, handler){
	if (el.removeEventListener){
		el.removeEventListener(event, handler, false);

	}else if (el.detachEvent){
		el.detachEvent("on"+event, handler);
	}
};

scheduler._init_once = function(){

	var oldSize = getWindowSize();
	dhtmlxEvent(window,"resize",function(){
		if(!isAttachedNode(scheduler._obj))
			return;

		var newSize = getWindowSize();

		// ie7-8 triggers "resize" when window's elements are resized, it messes container-autoresize extension
		// check if it's actually resized
		if(!equals(oldSize, newSize)){
			window.clearTimeout(scheduler._resize_timer);
			scheduler._resize_timer=window.setTimeout(function(){
				if(!isAttachedNode(scheduler._obj))
					return;

				if (scheduler.callEvent("onSchedulerResize",[]))  {
					scheduler.update_view();
					scheduler.callEvent("onAfterSchedulerResize", []);
				}
			}, 100);
		}
		oldSize = newSize;

	});

	function isAttachedNode(container){
		var root = document.body;

		while(container && container != root){
			container = container.parentNode;
		}

		return !!(root == container);
	}

	function getWindowSize(){
		return {
			w : window.innerWidth || document.documentElement.clientWidth,
			h : window.innerHeight || document.documentElement.clientHeight
		};
	}
	function equals(a,b){
		return a.w == b.w && a.h == b.h;
	}

	scheduler._init_once = function(){};
};
scheduler.init=function(id,date,mode){
	date=date||(scheduler._currentDate());
	mode=mode||"week";

	if(this._obj){
		this.unset_actions();
	}

	this._obj=(typeof id == "string")?document.getElementById(id):id;

	//hook for terrace skin
	if (this._skin_init)
		scheduler._skin_init();

	scheduler.date.init();


	this._els=[];
	this._scroll=true;
	this._quirks=(_isIE && document.compatMode == "BackCompat");
	this._quirks7=(_isIE && navigator.appVersion.indexOf("MSIE 8")==-1);

	this.get_elements();
	this.init_templates();
	this.set_actions();

	this._init_once();
	this._init_touch_events();

	this.set_sizes();
	scheduler.callEvent('onSchedulerReady', []);
	this.setCurrentView(date,mode);

};

scheduler.xy={
	min_event_height:40,
	scale_width:50,
	scroll_width:18,
	scale_height:20,
	month_scale_height:20,
	menu_width:25,
	margin_top:0,
	margin_left:0,
	editor_width:140,
	month_head_height:22
};
scheduler.keys={
	edit_save:13,
	edit_cancel:27
};
scheduler.set_sizes=function(){
	var w = this._x = this._obj.clientWidth-this.xy.margin_left;
	var h = this._y = this._obj.clientHeight-this.xy.margin_top;

	//not-table mode always has scroll - need to be fixed in future
	var scale_x=this._table_view?0:(this.xy.scale_width+this.xy.scroll_width);
	var scale_s=this._table_view?-1:this.xy.scale_width;

	this.set_xy(this._els["dhx_cal_navline"][0],w,this.xy.nav_height,0,0);
	this.set_xy(this._els["dhx_cal_header"][0],w-scale_x,this.xy.scale_height,scale_s,this.xy.nav_height+(this._quirks?-1:1));
	//to support alter-skin, we need a way to alter height directly from css
	var actual_height = this._els["dhx_cal_navline"][0].offsetHeight;
	if (actual_height > 0) this.xy.nav_height = actual_height;

	var data_y=this.xy.scale_height+this.xy.nav_height+(this._quirks?-2:0);
	this.set_xy(this._els["dhx_cal_data"][0],w,h-(data_y+2),0,data_y+2);
};
scheduler.set_xy=function(node,w,h,x,y){
	node.style.width=Math.max(0,w)+"px";
	node.style.height=Math.max(0,h)+"px";
	if (arguments.length>3){
		node.style.left=x+"px";
		node.style.top=y+"px";
	}
};
scheduler.get_elements=function(){
	//get all child elements as named hash
	var els=this._obj.getElementsByTagName("DIV");
	for (var i=0; i < els.length; i++){
		var class_name=els[i].className || "";
		var attr_value = els[i].getAttribute("name") || "";
		if (class_name) class_name = class_name.split(" ")[0];
		if (!this._els[class_name]) this._els[class_name]=[];
		this._els[class_name].push(els[i]);

		//check if name need to be changed
		var label = scheduler.locale.labels[attr_value||class_name];
		if (typeof label !== "string" && attr_value && !els[i].innerHTML)
			 label = attr_value.split("_")[0];
		if (label)
			els[i].innerHTML= label;
	}
};

scheduler.unset_actions = function(){
	for (var a in this._els)
		if (this._click[a])
			for (var i=0; i < this._els[a].length; i++)
				this._els[a][i].onclick = null;
	this._obj.onselectstart = null;
	this._obj.onmousemove = null;
	this._obj.onmousedown = null;
	this._obj.onmouseup = null;
	this._obj.ondblclick = null;
	this._obj.oncontextmenu = null;
};

scheduler.set_actions=function(){
	for (var a in this._els)
		if (this._click[a])
			for (var i=0; i < this._els[a].length; i++)
				this._els[a][i].onclick=scheduler._click[a];
	this._obj.onselectstart=function(e){ return false; };
	this._obj.onmousemove=function(e){
		if (!scheduler._temp_touch_block)
			scheduler._on_mouse_move(e||event);
	};
	this._obj.onmousedown=function(e){
		if (!scheduler._ignore_next_click)
			scheduler._on_mouse_down(e||event);
	};
	this._obj.onmouseup=function(e){
		if (!scheduler._ignore_next_click)
			scheduler._on_mouse_up(e||event);
	};
	this._obj.ondblclick=function(e){
		scheduler._on_dbl_click(e||event);
	};
	this._obj.oncontextmenu = function(e) {
		var ev = e||event;
		var src = ev.target||ev.srcElement;
		var returnValue = scheduler.callEvent("onContextMenu", [scheduler._locate_event(src), ev]);
		return returnValue;
	};
};
scheduler.select=function(id){
	if (this._select_id==id) return;
	scheduler._close_not_saved();
	this.editStop(false);
	this.unselect();
	this._select_id = id;
	this.updateEvent(id);
};
scheduler.unselect=function(id){
	if (id && id!=this._select_id) return;
	var t=this._select_id;
	this._select_id = null;
	if (t && this.getEvent(t)) this.updateEvent(t);
};
scheduler.getState=function(){
	return {
		mode: this._mode,
		date: new Date(this._date),
		min_date: new Date(this._min_date),
		max_date: new Date(this._max_date),
		editor_id: this._edit_id,
		lightbox_id: this._lightbox_id,
		new_event: this._new_event,
		select_id: this._select_id,
		expanded: this.expanded,
		drag_id: this._drag_id,
		drag_mode: this._drag_mode
	};
};
scheduler._click={
	dhx_cal_data:function(e){
		//in case of touch disable click processing
		if (scheduler._ignore_next_click){
			if (e.preventDefault)
				e.preventDefault();
			e.cancelBubble = true;
			scheduler._ignore_next_click = false;
			return false;
		}

		var trg = e?e.target:event.srcElement;
		var id = scheduler._locate_event(trg);

		e = e || event;

		if (!id) {
			scheduler.callEvent("onEmptyClick",[scheduler.getActionData(e).date, e]);
		} else {
			if ( !scheduler.callEvent("onClick",[id,e]) || scheduler.config.readonly ) return;
		}

		if (id && scheduler.config.select) {

			scheduler.select(id);
			var mask = trg.className;
			if (mask.indexOf("_icon")!=-1)
				scheduler._click.buttons[mask.split(" ")[1].replace("icon_","")](id);
		} else{
			scheduler._close_not_saved();
			if (new Date().valueOf()-(scheduler._new_event||0) > 500){
				scheduler.unselect();
			}
		}
	},
	dhx_cal_refresh_button:function(){
		// Force server request, invalidate cache
		scheduler.clearAll();

		// Set current date to the view
		scheduler.setCurrentView(scheduler.date[scheduler._mode+"_start"](scheduler._date));
	},
	dhx_cal_prev_button:function(){
		scheduler._click.dhx_cal_next_button(0,-1);
	},
	dhx_cal_next_button:function(dummy,step){
		scheduler.setCurrentView(scheduler.date.add( //next line changes scheduler._date , but seems it has not side-effects
			scheduler.date[scheduler._mode+"_start"](scheduler._date),(step||1),scheduler._mode));
	},
	dhx_cal_today_button:function(){
		if (scheduler.callEvent("onBeforeTodayDisplayed", [])) {
			scheduler.setCurrentView(scheduler._currentDate());
		}
	},
	dhx_cal_tab:function(){
		var name = this.getAttribute("name");
		var mode = name.substring(0, name.search("_tab"));
		scheduler.setCurrentView(scheduler._date,mode);
	},
	buttons:{
		"delete":function(id){
			var c = scheduler.locale.labels.confirm_deleting;
			scheduler._dhtmlx_confirm(c, scheduler.locale.labels.title_confirm_deleting, function(){ scheduler.deleteEvent(id); });
		},
		edit:function(id){ scheduler.edit(id); },
		save:function(id){ scheduler.editStop(true); },
		details:function(id){ scheduler.showLightbox(id); },
		cancel:function(id){ scheduler.editStop(false); }
	}
};
scheduler._dhtmlx_confirm = function(message, title, callback) {
	if (!message)
		return callback();
	var opts = { text: message };
	if (title)
		opts.title = title;
	if (callback) {
		opts.callback = function(result) {
			if (result)
				callback();
		};
	}
	dhtmlx.confirm(opts);
};
scheduler.addEventNow=function(start,end,e){
	var base = {};
	if (start && start.constructor.toString().match(/object/i) !== null){
		base = start;
		start = null;
	}

	var d = (this.config.event_duration||this.config.time_step)*60000;
	if (!start) start = base.start_date||Math.round((scheduler._currentDate()).valueOf()/d)*d;
	var start_date = new Date(start);
	if (!end){
		var start_hour = this.config.first_hour;
		if (start_hour > start_date.getHours()){
			start_date.setHours(start_hour);
			start = start_date.valueOf();
		}
		end = start.valueOf()+d;
	}
	var end_date = new Date(end);

	// scheduler.addEventNow(new Date(), new Date()) + collision though get_visible events defect (such event was not retrieved)
	if(start_date.valueOf() == end_date.valueOf())
		end_date.setTime(end_date.valueOf()+d);

	base.start_date = base.start_date||start_date;
	base.end_date =  base.end_date||end_date;
	base.text = base.text||this.locale.labels.new_event;
	base.id = this._drag_id = base.id || this.uid();
	this._drag_mode="new-size";

	this._loading=true;
	var eventId = this.addEvent(base);
	this.callEvent("onEventCreated",[this._drag_id,e]);
	this._loading=false;

	this._drag_event={}; //dummy , to trigger correct event updating logic
	this._on_mouse_up(e);
	return eventId;
};
scheduler._on_dbl_click=function(e,src){
	src = src||(e.target||e.srcElement);
	if (this.config.readonly) return;
	var name = (src.className||"").split(" ")[0];
	switch(name){
		case "dhx_scale_holder":
		case "dhx_scale_holder_now":
		case "dhx_month_body":
		case "dhx_wa_day_data":
			if (!scheduler.config.dblclick_create) break;
			this.addEventNow(this.getActionData(e).date,null,e);
			break;
		case "dhx_cal_event":
		case "dhx_wa_ev_body":
		case "dhx_agenda_line":
		case "dhx_grid_event":
		case "dhx_cal_event_line":
		case "dhx_cal_event_clear":
			var id = this._locate_event(src);
			if (!this.callEvent("onDblClick",[id,e])) return;
			if (this.config.details_on_dblclick || this._table_view || !this.getEvent(id)._timed || !this.config.select)
				this.showLightbox(id);
			else
				this.edit(id);
			break;
		case "dhx_time_block":
		case "dhx_cal_container":
			return;
		default:
			var t = this["dblclick_"+name];
			if (t) {
				t.call(this,e);
			}
			else {
				if (src.parentNode && src != this)
					return scheduler._on_dbl_click(e,src.parentNode);
			}
			break;
	}
};
//column index by mouse x-coordinate
scheduler._get_column_index = function(x_pos){
	var column = 0;
	if (this._cols){

		var width = 0;
		for(var i=0; i < this._cols.length && !width; i++){
			width = this._cols[i];
		}

		if(width){
			column = x_pos / width;
		}else{
			column = 0;
		}

		if (this._ignores)
			for (var i=0; i<=column; i++)
				if (this._ignores[i])
					column++;
	}
	return column;
};
//transform mouse coordinates to day-time indexes of week based view
scheduler._week_indexes_from_pos = function(pos){
	//"get position" can be invoked before columns are loaded into the units view(e.g. by onMouseMove handler in key_nav.js)
	if(!this._cols){
		return pos;
	}else{
		var column = this._get_column_index(pos.x);
		pos.x=Math.min(this._cols.length-1, Math.max(0,Math.ceil(column)-1));

		pos.y=Math.max(0,Math.ceil(pos.y*60/(this.config.time_step*this.config.hour_size_px))-1)+this.config.first_hour*(60/this.config.time_step);
		return pos;
	}
};

scheduler._mouse_coords=function(ev){
	var pos;
	var b=document.body;
	var d = document.documentElement;
	if (!_isIE && (ev.pageX || ev.pageY))
	    pos={x:ev.pageX, y:ev.pageY};
	else pos={
	    x:ev.clientX + (b.scrollLeft||d.scrollLeft||0) - b.clientLeft,
	    y:ev.clientY + (b.scrollTop||d.scrollTop||0) - b.clientTop
	};

	//apply layout
	pos.x-=getAbsoluteLeft(this._obj)+(this._table_view?0:this.xy.scale_width);
	pos.y-=getAbsoluteTop(this._obj)+this.xy.nav_height+(this._dy_shift||0)+this.xy.scale_height-this._els["dhx_cal_data"][0].scrollTop;
	pos.ev = ev;

	var handler = this["mouse_"+this._mode];
	if (handler){
		pos = handler.call(this,pos);
	}else{
		//transform to date
		if (!this._table_view) {
			pos = this._week_indexes_from_pos(pos);
		} else {
			var column = this._get_column_index(pos.x);
			if (!this._cols || !this._colsS) // agenda/map views
				return pos;
			var dy=0;
			for (dy=1; dy < this._colsS.heights.length; dy++)
				if (this._colsS.heights[dy]>pos.y) break;

			pos.y=Math.ceil( (Math.max(0, column)+Math.max(0,dy-1)*7)*24*60/this.config.time_step );

			if (scheduler._drag_mode || this._mode == "month")
				pos.y=(Math.max(0,Math.ceil(column)-1)+Math.max(0,dy-1)*7)*24*60/this.config.time_step;

			//we care about ignored days only during event moving in month view
			if (this._drag_mode == "move"){
				if (scheduler._ignores_detected && scheduler.config.preserve_length){
					pos._ignores = true;
					//get real lengtn of event
					if (!this._drag_event._event_length)
						this._drag_event._event_length = this._get_real_event_length(this._drag_event.start_date, this._drag_event.end_date, { x_step:1, x_unit:"day"});
				}
			}

			pos.x=0;
		}
	}

	pos.timestamp = +new Date();

	return pos;
};
scheduler._close_not_saved=function(){
	if (new Date().valueOf()-(scheduler._new_event||0) > 500 && scheduler._edit_id){
		var c=scheduler.locale.labels.confirm_closing;

		scheduler._dhtmlx_confirm(c, scheduler.locale.labels.title_confirm_closing, function() { scheduler.editStop(scheduler.config.positive_closing); });
		if(c){
			this._drag_id = this._drag_pos = this._drag_mode = null;
		}
	}
};
scheduler._correct_shift=function(start, back){
	return start-=((new Date(scheduler._min_date)).getTimezoneOffset()-(new Date(start)).getTimezoneOffset())*60000*(back?-1:1);
};

scheduler._is_pos_changed = function(old_pos, new_pos){
	function diff(old_val, new_val, acc){
		return !!(Math.abs(old_val - new_val) > acc);
	}

	if(!(old_pos && this._drag_pos)){
		return true;
	}
	var delay = 100,
		d_pos = 5;

	// start drag only if passed some time since mouse down, or if mouse position changed sufficiently
	return !!(this._drag_pos.has_moved || !this._drag_pos.timestamp || (new_pos.timestamp - this._drag_pos.timestamp > delay) || diff(old_pos.ev.clientX, new_pos.ev.clientX, d_pos) || diff(old_pos.ev.clientY, new_pos.ev.clientY, d_pos));
};

scheduler._correct_drag_start_date = function(start){
	var obj;
	if (scheduler.matrix)
		obj = scheduler.matrix[scheduler._mode];
	obj = obj  || { x_step:1, x_unit:"day" };

	start = new Date(start);
	var len = 1;
	if(obj._start_correction || obj._end_correction)
		len = (obj.last_hour||0)*60 - (start.getHours()*60+start.getMinutes()) || 1;

	return start*1 + (scheduler._get_fictional_event_length(start, len, obj)  - len);
};
scheduler._correct_drag_end_date = function(start, duration){
	var obj;
	if (scheduler.matrix)
		obj = scheduler.matrix[scheduler._mode];
	obj = obj  || { x_step:1, x_unit:"day" };

	var end = start*1 + scheduler._get_fictional_event_length(start, duration, obj);
	return new Date(end*1 - (scheduler._get_fictional_event_length(end, -1, obj, -1) + 1));
};

scheduler._on_mouse_move=function(e){
	if (this._drag_mode){
		var pos=this._mouse_coords(e);
		if (this._is_pos_changed(this._drag_pos, pos)){
			var start, end;
			if (this._edit_id!=this._drag_id)
				this._close_not_saved();

			if(!this._drag_mode)
				return;

			this._drag_pos=pos;
			this._drag_pos.has_moved = true;

			if (this._drag_mode=="create"){
				this._close_not_saved();
				this.unselect(this._select_id);
				this._loading=true; //will be ignored by dataprocessor

				start = this._get_date_from_pos(pos).valueOf();

				if (!this._drag_start) {
					var res = this.callEvent("onBeforeEventCreated", [e, this._drag_id]);
					if (!res){
						this._loading=false;
						return;

					}

					this._loading=false;
					this._drag_start=start;

					// Corect Offset
					if (this._mode == 'day' || this._mode == 'week')
						this._drag_start += (new Date(start).getTimezoneOffset() - scheduler._min_date.getTimezoneOffset()) * 60000;

					return;
				}

				end = start;
				if (end == this._drag_start) {
				}

				var start_date = new Date(this._drag_start);
				var end_date = new Date(end);
				if ( (this._mode == "day" || this._mode == "week") &&
					(start_date.getHours() == end_date.getHours() &&
					start_date.getMinutes() == end_date.getMinutes()) ) {
						end_date = new Date(this._drag_start+1000);
				}


				this._drag_id=this.uid();
				this.addEvent(start_date, end_date, this.locale.labels.new_event, this._drag_id, pos.fields);

				this.callEvent("onEventCreated",[this._drag_id,e]);
				this._loading=false;
				this._drag_mode="new-size";

			}


			var ev=this.getEvent(this._drag_id);
			var obj;
			if (scheduler.matrix)
				obj = scheduler.matrix[scheduler._mode];
			obj = obj  || { x_step:1, x_unit:"day" };

			if (this._drag_mode=="move"){
				start = this._min_date.valueOf()+(pos.y*this.config.time_step+pos.x*24*60 -(scheduler._move_pos_shift||0) )*60000;
				if (!pos.custom && this._table_view) start+=this.date.time_part(ev.start_date)*1000;
				start = this._correct_shift(start);

				if (pos._ignores && this.config.preserve_length && this._table_view){

					start = scheduler._correct_drag_start_date(start);
					end = scheduler._correct_drag_end_date(start,this._drag_event._event_length);

				} else
					end = ev.end_date.valueOf()-(ev.start_date.valueOf()-start);
			} else { // resize
				start = ev.start_date.valueOf();
				end = ev.end_date.valueOf();
				if (this._table_view) {
					var resize_date = this._min_date.valueOf()+pos.y*this.config.time_step*60000 + (pos.custom?0:24*60*60000);
					if (this._mode == "month") {
						resize_date = this._correct_shift(resize_date, false);
						if( this._drag_from_start ) {
							var day = 24*60*60000;
							if( resize_date <= scheduler.date.date_part(new Date(end+day-1)).valueOf() ) // to get end time as 23:59:59 and then the day start
								start = resize_date - day;
						} else {
							end = resize_date;
						}
					} else {
						if (pos.resize_from_start){
							start = scheduler._correct_drag_start_date(resize_date);
						}else{
							end = scheduler._correct_drag_end_date(resize_date, 0);
						}
					}
				} else {
					var end_day_start = this.date.date_part(new Date(ev.end_date.valueOf() - 1)).valueOf();
					var end_day_date = new Date(end_day_start);

					end = end_day_start + pos.y*this.config.time_step*60000;
					end = end + ((new Date(end)).getTimezoneOffset() - end_day_date.getTimezoneOffset()) * 60000;
					this._els["dhx_cal_data"][0].style.cursor="s-resize";
					if (this._mode == "week" || this._mode == "day")
						end = this._correct_shift(end);
				}
				if (this._drag_mode == "new-size") {
					if (end <= this._drag_start){
						var shift = pos.shift||((this._table_view && !pos.custom)?24*60*60000:0);
						start = end-(pos.shift?0:shift);
						end = this._drag_start+(shift||(this.config.time_step*60000));
					} else {
						start = this._drag_start;
					}
				} else {
					if (end<=start)
						end=start+this.config.time_step*60000;
				}
			}
			var new_end = new Date(end-1);
			var new_start = new Date(start);
			//deny drag out of visible scheduler scale in timeline view
			if(this._drag_mode=="move" && scheduler.config.limit_drag_out &&
				(+new_start < +scheduler._min_date || +end > +scheduler._max_date)){

				if(+ev.start_date < +scheduler._min_date || +ev.end_date > +scheduler._max_date){
					// not move event if it's already outside time scale
					new_start = new Date(ev.start_date);
					end = new Date(ev.end_date);
				}else{

					var duration = end - new_start;

					if(+new_start < +scheduler._min_date){
						new_start = new Date(scheduler._min_date);
						if (pos._ignores && this.config.preserve_length && this._table_view){
							new_start = new Date(scheduler._correct_drag_start_date(new_start));
							if(obj._start_correction)
								new_start = new Date(new_start.valueOf() + obj._start_correction);
							end = new Date(new_start*1 + this._get_fictional_event_length(new_start, this._drag_event._event_length, obj));
						}else{
							end = new Date(+new_start + duration);
						}
					}else{
						end = new Date(scheduler._max_date);

						if (pos._ignores && this.config.preserve_length && this._table_view){
							if(obj._end_correction)
								end = new Date(end.valueOf() - obj._end_correction);
							end = new Date(end*1 - this._get_fictional_event_length(end, 0, obj, true));
							new_start = new Date(end*1 - this._get_fictional_event_length(end, this._drag_event._event_length, obj, true));
							if(this._ignores_detected){
								new_start = scheduler.date.add(new_start, obj.x_step, obj.x_unit);
								end = new Date(end*1 - this._get_fictional_event_length(end, 0, obj, true));
								end = scheduler.date.add(end, obj.x_step, obj.x_unit);
							}

						}else{
							new_start = new Date(+end - duration);
						}

					}

				}
				var new_end = new Date(end-1);
			}



			// fix event dates when resized to bottom of the column (day/week views)
			if(!this._table_view &&
				!scheduler.config.all_timed &&
				((!scheduler._get_section_view() && pos.x != this._get_event_sday({start_date: new Date(end), end_date:new Date(end)})) || new Date(end).getHours() >= this.config.last_hour)){
				var duration = end - new_start;
				var day = this._min_date.valueOf()+(pos.x*24*60)*60000;
				end = scheduler.date.date_part(new Date(day));
				end.setHours(this.config.last_hour);
				new_end = new Date(end-1);
				if(this._drag_mode == "move"){
					new_start = new Date(+end - duration);
				}
			}

			//prevent out-of-borders situation for day|week view
			if ( this._table_view || (new_end.getDate()==new_start.getDate() && new_end.getHours()<this.config.last_hour) || scheduler._allow_dnd ){
				ev.start_date=new_start;
				ev.end_date=new Date(end);
				if (this.config.update_render){
					//fix for repaint after dnd and scroll issue, #231
					var sx = scheduler._els["dhx_cal_data"][0].scrollTop;
					this.update_view();
					scheduler._els["dhx_cal_data"][0].scrollTop = sx;
				} else
					this.updateEvent(this._drag_id);
			}
			if (this._table_view) {
				this.for_rendered(this._drag_id,function(r){
					r.className+=" dhx_in_move";
				});
			}

			this.callEvent("onEventDrag", [this._drag_id, this._drag_mode, e]);
		}
	}  else {
		if (scheduler.checkEvent("onMouseMove")){
			var id = this._locate_event(e.target||e.srcElement);
			this.callEvent("onMouseMove",[id,e]);
		}
	}
};
scheduler._on_mouse_down=function(e,src) {
	// on Mac we do not get onmouseup event when clicking right mouse button leaving us in dnd state
	// let's ignore right mouse button then
	if (e.button == 2)
		return;

	if (this.config.readonly || this._drag_mode) return;
	src = src||(e.target||e.srcElement);
	var classname = src.className && src.className.split(" ")[0];

	switch (classname) {
		case "dhx_cal_event_line":
		case "dhx_cal_event_clear":
			if (this._table_view)
				this._drag_mode="move"; //item in table mode
			break;
		case "dhx_event_move":
		case "dhx_wa_ev_body":
			this._drag_mode="move";
			break;
		case "dhx_event_resize":
			this._drag_mode="resize";
			if((src.className||"").indexOf("dhx_event_resize_end") < 0){
				scheduler._drag_from_start = true;
			}else{
				scheduler._drag_from_start = false;
			}
			break;
		case "dhx_scale_holder":
		case "dhx_scale_holder_now":
		case "dhx_month_body":
		case "dhx_matrix_cell":
		case "dhx_marked_timespan":
			this._drag_mode="create";
			break;
		case "":
			if (src.parentNode)
				return scheduler._on_mouse_down(e,src.parentNode);
			break;
		default:
			if (!scheduler.checkEvent("onMouseDown") || scheduler.callEvent("onMouseDown", [classname])) {
				if (src.parentNode && src != this && classname != "dhx_body") {
					return scheduler._on_mouse_down(e,src.parentNode);
				}
			}
			this._drag_mode=null;
			this._drag_id=null;
			break;
	}
	if (this._drag_mode){
		var id = this._locate_event(src);
		if (!this.config["drag_"+this._drag_mode] || !this.callEvent("onBeforeDrag",[id, this._drag_mode, e]))
			this._drag_mode=this._drag_id=0;
		else {
			this._drag_id= id;

			if (this._edit_id!=this._drag_id || (this._edit_id && this._drag_mode == "create"))
				this._close_not_saved();
			if(!this._drag_mode)
				return;

			this._drag_event = scheduler._lame_clone(this.getEvent(this._drag_id) || {});
			this._drag_pos = this._mouse_coords(e);
		}
	}
	this._drag_start=null;
};


scheduler._get_private_properties = function(event){
	var fields = {};
	for(var i in event){
		if(i.indexOf("_") === 0){
			fields[i] = true;
		}
	}
	return fields;
};
scheduler._clear_temporary_properties = function(clean, flagged_event){
	var initial = this._get_private_properties(clean);
	var current_state = this._get_private_properties(flagged_event);
	for(var i in current_state){
		if(!initial[i]){
			delete flagged_event[i];
		}
	}
};


scheduler._on_mouse_up=function(e){
	if (e && e.button == 2 && scheduler.config.touch) return;
	if (this._drag_mode && this._drag_id){
		this._els["dhx_cal_data"][0].style.cursor="default";
		//drop

		var drag_id = this._drag_id;
		var mode = this._drag_mode;

		var moved = !this._drag_pos || this._drag_pos.has_moved;

		var ev=this.getEvent(this._drag_id);
		if (moved && (this._drag_event._dhx_changed || !this._drag_event.start_date || ev.start_date.valueOf()!=this._drag_event.start_date.valueOf() || ev.end_date.valueOf()!=this._drag_event.end_date.valueOf())){
			var is_new=(this._drag_mode=="new-size");
			if (!this.callEvent("onBeforeEventChanged",[ev, e, is_new, this._drag_event])){
				if (is_new)
					this.deleteEvent(ev.id, true);
				else {
					this._drag_event._dhx_changed = false;
					this._clear_temporary_properties(ev, this._drag_event);
					scheduler._lame_copy(ev, this._drag_event);
					this.updateEvent(ev.id);
				}
			} else {

				this._drag_id = this._drag_mode = null;
				if (is_new && this.config.edit_on_create){
					this.unselect();
					this._new_event=new Date();//timestamp of creation
					//if selection disabled - force lightbox usage
					if (this._table_view || this.config.details_on_create || !this.config.select) {
						scheduler.callEvent("onDragEnd", [drag_id, mode, e]);
						return this.showLightbox(drag_id);
					}
					this._drag_pos = true; //set flag to trigger full redraw
					this._select_id = this._edit_id = drag_id;
				} else {
					if (!this._new_event)
						this.callEvent(is_new?"onEventAdded":"onEventChanged",[drag_id,this.getEvent(drag_id)]);
				}
			}
		}
		if (this._drag_pos && (this._drag_pos.has_moved || this._drag_pos === true)) {
			this._drag_id = this._drag_mode = null; // set null to prevent _sorder recalculation for drag event
			this.render_view_data(); //redraw even if there is no real changes - necessary for correct positioning item after drag
		}
		scheduler.callEvent("onDragEnd", [drag_id, mode, e]);
	}
	this._drag_id = null;
	this._drag_mode=null;
	this._drag_pos=null;
};

scheduler._trigger_dyn_loading = function(){
	if (this._load_mode && this._load()){
		this._render_wait = true;
		return true;
	}else{
		return false;
	}
};
scheduler.update_view=function(){
	var view = this[this._mode + "_view"];
	if(view){
		view(true);
	}else{
		this._reset_scale();
	}

	if (this._trigger_dyn_loading()){
		return true;
	}
	this.render_view_data();
};

scheduler.isViewExists = function(mode){
	return !!(scheduler[mode+ "_view"] ||
		(scheduler.date[mode+ "_start"] && scheduler.templates[mode+ "_date"] && scheduler.templates[mode+ "_scale_date"]));
};

scheduler.updateView = function(date, mode) {
	date = date || this._date;
	mode = mode || this._mode;
	var dhx_cal_data = 'dhx_cal_data';

	if (!this._mode)
		this._obj.className += " dhx_scheduler_" + mode; else {
		this._obj.className = this._obj.className.replace("dhx_scheduler_" + this._mode, "dhx_scheduler_" + mode);
	}

	var prev_scroll = (this._mode == mode && this.config.preserve_scroll) ? this._els[dhx_cal_data][0].scrollTop : false; // saving current scroll

	//hide old custom view
	if (this[this._mode + "_view"] && mode && this._mode != mode)
		this[this._mode + "_view"](false);

	this._close_not_saved();

	var dhx_multi_day = 'dhx_multi_day';
	if (this._els[dhx_multi_day]) {
		this._els[dhx_multi_day][0].parentNode.removeChild(this._els[dhx_multi_day][0]);
		this._els[dhx_multi_day] = null;
	}

	this._mode = mode;
	this._date = date;
	this._table_view = (this._mode == "month");

	this._dy_shift = 0;//correction for multiday section in week/day views

	var tabs = this._els["dhx_cal_tab"];
	if(tabs){//calendar can work without view tabs
		for (var i = 0; i < tabs.length; i++) {
			var name = tabs[i].className;
			name = name.replace(/ active/g, "");
			if (tabs[i].getAttribute("name") == this._mode + "_tab")
				name = name + " active";
			tabs[i].className = name;
		}
	}
	//show new view
	this.update_view();

	if (typeof prev_scroll == "number") // if we are updating or working with the same view scrollTop should be saved
		this._els[dhx_cal_data][0].scrollTop = prev_scroll; // restoring original scroll
};
scheduler.setCurrentView = function(date, mode) {
	if (!this.callEvent("onBeforeViewChange", [this._mode, this._date, mode || this._mode, date || this._date])) return;
	this.updateView(date, mode);
	this.callEvent("onViewChange", [this._mode, this._date]);
};
scheduler._render_x_header = function(i,left,d,h, offset_top){
	offset_top = offset_top || 0;
	//header scale
	var head=document.createElement("DIV");
	head.className = "dhx_scale_bar";

	if(this.templates[this._mode+"_scalex_class"]){
		//'_scalex_class' - timeline already have similar template, use the same name
		head.className += ' ' + this.templates[this._mode+"_scalex_class"](d);
	}

	var width = this._cols[i]-1;

	if (this._mode == "month" && i === 0 && this.config.left_border) {
		head.className += " dhx_scale_bar_border";
		left = left+1;
	}
	this.set_xy(head, width, this.xy.scale_height-2, left, offset_top);//-1 for border
	head.innerHTML=this.templates[this._mode+"_scale_date"](d,this._mode); //TODO - move in separate method
	h.appendChild(head);
};

scheduler._get_columns_num = function(from, to){
	var count = 7;
	if (!scheduler._table_view){
		var count_n = scheduler.date["get_"+scheduler._mode+"_end"];
		if (count_n) to = count_n(from);
		count = Math.round((to.valueOf()-from.valueOf())/(1000*60*60*24));
	}
	return count;
};
scheduler._get_timeunit_start = function(){
	//start date of currently displayed time unit(day, week,...)
	return this.date[this._mode+"_start"](new Date(this._date.valueOf()));
};

scheduler._get_view_end = function(){
	var dd = this._get_timeunit_start();
	var ed = scheduler.date.add(dd, 1, this._mode);
	if (!scheduler._table_view){
		var count_n = scheduler.date["get_"+scheduler._mode+"_end"];
		if (count_n) ed = count_n(dd);
	}
	return ed;
};
scheduler._calc_scale_sizes = function(width, from, to){
	//calculates number of displayed columns(days/units/month view cols) and their widths
	var summ = width; //border delta
	var count = this._get_columns_num(from, to);

	this._process_ignores(from, count, "day", 1);
	var realcount = count - this._ignores_detected;

	for (var i=0; i<count; i++){
		if (this._ignores[i]){
			this._cols[i] = 0;
			realcount++;
		} else {
			this._cols[i]=Math.floor(summ/(realcount-i));
		}
		summ-=this._cols[i];
		this._colsS[i]=(this._cols[i-1]||0)+(this._colsS[i-1]||(this._table_view?0:this.xy.scale_width+2));
	}
	this._colsS['col_length'] = count;

	this._colsS[count] = (this._cols[count-1]+this._colsS[count-1]) || 0;
};
scheduler._set_scale_col_size = function(div, width, left){
	var c = this.config;
	this.set_xy(div, width-1, c.hour_size_px*(c.last_hour-c.first_hour), left+this.xy.scale_width+1, 0);//-1 for border
};

scheduler._render_scales = function(header, data_area){
	//render columns in week/units view, or header in month view
	var sd = new Date(scheduler._min_date),
		ed = new Date(scheduler._max_date),
		today = this.date.date_part( scheduler._currentDate());

	var summ = parseInt(header.style.width,10); //border delta
	var d = new Date(this._min_date);
	var count = this._get_columns_num(sd, ed);
	this._calc_scale_sizes(summ, sd, ed);
	var left=0;

	header.innerHTML = "";
	for (var i=0; i<count; i++){
		if (!this._ignores[i]){
			this._render_x_header(i,left,d,header);
		}
		if (!this._table_view){
			var scales=document.createElement("DIV");
			var cls = "dhx_scale_holder";
			if (d.valueOf() == today.valueOf()) cls = "dhx_scale_holder_now";

			if (this._ignores_detected && this._ignores[i]){
				cls += " dhx_scale_ignore";
			}

			scales.className = cls+" "+this.templates.week_date_class(d,today);

			this._set_scale_col_size(scales, this._cols[i], left);

			data_area.appendChild(scales);
			this.callEvent("onScaleAdd",[scales, d]);
		}

		left+=this._cols[i];
		d=this.date.add(d,1,"day");
		d = this.date.day_start(d);
	}
};

scheduler._reset_scale=function(){
	//current mode doesn't support scales
	//we mustn't call reset_scale for such modes, so it just to be sure
	if (!this.templates[this._mode + "_date"]) return;

	var h = this._els["dhx_cal_header"][0];
	var data_area = this._els["dhx_cal_data"][0];
	var c = this.config;

	h.innerHTML = "";
	//data_area.scrollTop = 0; //fix flickering in FF; makes IE8 flicker instead
	data_area.innerHTML = "";

	var str = ((c.readonly || (!c.drag_resize)) ? " dhx_resize_denied" : "") + ((c.readonly || (!c.drag_move)) ? " dhx_move_denied" : "");
	data_area.className = "dhx_cal_data" + str;

	this._scales = {};
	this._cols = [];	//store for data section
	this._colsS = {height: 0};
	this._dy_shift = 0;

	this.set_sizes();

	var d,sd,today;
	var dd = this._get_timeunit_start(),
		ed = scheduler._get_view_end();

	d = sd = this._table_view ? scheduler.date.week_start(dd) : dd;


	this._min_date=d;
	this._els["dhx_cal_date"][0].innerHTML=this.templates[this._mode+"_date"](dd,ed,this._mode);

	this._max_date = ed;
	scheduler._render_scales(h, data_area);

	if (this._table_view) // month view
		this._reset_month_scale(data_area,dd,sd);
	else{
		this._reset_hours_scale(data_area,dd,sd);
		if (c.multi_day) {
			var dhx_multi_day = 'dhx_multi_day';

			if(this._els[dhx_multi_day]) {
				this._els[dhx_multi_day][0].parentNode.removeChild(this._els[dhx_multi_day][0]);
				this._els[dhx_multi_day] = null;
			}

			var navline = this._els["dhx_cal_navline"][0];
			var top = navline.offsetHeight + this._els["dhx_cal_header"][0].offsetHeight+1;

			var c1 = document.createElement("DIV");
			c1.className = dhx_multi_day;
			c1.style.visibility="hidden";
			this.set_xy(c1, Math.max(this._colsS[this._colsS.col_length]+this.xy.scroll_width - 2, 0), 0, 0, top); // 2 extra borders, dhx_header has -1 bottom margin
			data_area.parentNode.insertBefore(c1,data_area);

			var c2 = c1.cloneNode(true);
			c2.className = dhx_multi_day+"_icon";
			c2.style.visibility="hidden";
			this.set_xy(c2, this.xy.scale_width, 0, 0, top); // dhx_header has -1 bottom margin

			c1.appendChild(c2);
			this._els[dhx_multi_day]=[c1,c2];
			this._els[dhx_multi_day][0].onclick = this._click.dhx_cal_data;
		}
	}
};
scheduler._reset_hours_scale=function(b,dd,sd){
	var c=document.createElement("DIV");
	c.className="dhx_scale_holder";

	var date = new Date(1980,1,1,this.config.first_hour,0,0);
	for (var i=this.config.first_hour*1; i < this.config.last_hour; i++) {
		var cc=document.createElement("DIV");
		cc.className="dhx_scale_hour";
		cc.style.height=this.config.hour_size_px-(this._quirks?0:1)+"px";
		var width = this.xy.scale_width;
		if (this.config.left_border) {
			width = width - 1;
			cc.className += " dhx_scale_hour_border";
		}
		cc.style.width = width + "px";
		cc.innerHTML=scheduler.templates.hour_scale(date);

		c.appendChild(cc);
		date=this.date.add(date,1,"hour");
	}
	b.appendChild(c);
	if (this.config.scroll_hour)
		b.scrollTop = this.config.hour_size_px*(this.config.scroll_hour-this.config.first_hour);
};

scheduler._currentDate = function(){
	if(scheduler.config.now_date){
		return new Date(scheduler.config.now_date);
	}
	return new Date();
};

scheduler._process_ignores = function(sd, n, mode, step, preserve){
	this._ignores={};
	this._ignores_detected = 0;
	var ignore = scheduler["ignore_"+this._mode];

	if (ignore){
		var ign_date = new Date(sd);
		for (var i=0; i<n; i++){
			if (ignore(ign_date)){
				this._ignores_detected += 1;
				this._ignores[i] = true;
				if (preserve)
					n++;
			}
			ign_date = scheduler.date.add(ign_date, step, mode);
			if(scheduler.date[mode + '_start'])
				ign_date = scheduler.date[mode + '_start'](ign_date);
		}
	}
};

scheduler._render_month_scale = function(div, dd/*month start*/, sd/*view start*/ ){
	//renders month view layout

	var ed=scheduler.date.add(dd,1,"month"),
		view_start = new Date(sd);
	var cd = scheduler._currentDate();
	this.date.date_part(cd);
	this.date.date_part(sd);

	var rows=Math.ceil(Math.round((ed.valueOf()-sd.valueOf()) / (60*60*24*1000) ) / 7);
	var tdwidths=[];

	for (var i=0; i<=7; i++) {
		var cell_width = ((this._cols[i]||0)-1);
		if (i === 0 && this.config.left_border) {
			cell_width = cell_width - 1;
		}
		tdwidths[i] = cell_width + "px";
	}

	function getCellHeight(row){
		var h = scheduler._colsS.height;
		if(scheduler._colsS.heights[row + 1] !== undefined ){
			h = scheduler._colsS.heights[row + 1] - (scheduler._colsS.heights[row]||0);
		}
		return h;
	}


	var cellheight = 0;

	var table = document.createElement("table");
	table.setAttribute("cellpadding", "0");
	table.setAttribute("cellspacing", "0");

	var tableBody = document.createElement("tbody");
	table.appendChild(tableBody);

	var rendered_dates = [];
	for (var i=0; i<rows; i++){
		var row = document.createElement("tr");
		tableBody.appendChild(row);
		var row_height = Math.max(getCellHeight(i) - scheduler.xy.month_head_height, 0);
		for (var j=0; j<7; j++) {
			var cell = document.createElement("td");
			row.appendChild(cell);

			var cls = "";
			if (sd<dd)
				cls='dhx_before';
			else if (sd>=ed)
				cls='dhx_after';
			else if (sd.valueOf()==cd.valueOf())
				cls='dhx_now';

			if (this._ignores_detected && this._ignores[j]){
				cls += " dhx_scale_ignore";
			}

			cell.className = cls + " " + this.templates.month_date_class(sd, cd);

			var body_class = "dhx_month_body";
			var head_class = "dhx_month_head";
			if (j === 0 && this.config.left_border) {
				body_class += " dhx_month_body_border";
				head_class += " dhx_month_head_border";
			}
			if (!this._ignores_detected || !this._ignores[j]){
				var cellHead = document.createElement("DIV");
				cellHead.className = head_class;
				cellHead.innerHTML = this.templates.month_day(sd);
				cell.appendChild(cellHead);

				var cellBody = document.createElement("DIV");
				cellBody.className = body_class;
				cellBody.style.height = row_height + "px";
				cellBody.style.width = tdwidths[j];
				cell.appendChild(cellBody);

			} else {
				cell.appendChild(document.createElement("div"));
				cell.appendChild(document.createElement("div"));
			}
			rendered_dates.push(sd);
			var bf1 = sd.getDate();
			sd=this.date.add(sd,1,"day");
			if (sd.getDate() - bf1 > 1)
				sd = new Date(sd.getFullYear(), sd.getMonth(), bf1 + 1, 12, 0);
		}

		scheduler._colsS.heights[i] = cellheight;
		cellheight += getCellHeight(i);
	}

	this._min_date = view_start;
	this._max_date = sd;

	div.innerHTML = "";
	div.appendChild(table);

	this._scales = {};
	var divs = div.getElementsByTagName('div');
	for (var i=0; i<rendered_dates.length; i++) { // [header, body, header, body, ...]
		var div = divs[(i*2)+1];
		var date = rendered_dates[i];
		this._scales[+date] = div;
	}
	for (var i=0; i<rendered_dates.length; i++) {
		var date = rendered_dates[i];
		this.callEvent("onScaleAdd", [this._scales[+date], date]);
	}



	return this._max_date;
};

scheduler._reset_month_scale=function(b,dd,sd){
	//recalculates rows height and redraws month layout
	var ed=scheduler.date.add(dd,1,"month");

	//trim time part for comparation reasons
	var cd = scheduler._currentDate();
	this.date.date_part(cd);
	this.date.date_part(sd);

	var rows=Math.ceil(Math.round((ed.valueOf()-sd.valueOf()) / (60*60*24*1000) ) / 7);

	var height = (Math.floor(b.clientHeight/rows) - this.xy.month_head_height);

	this._colsS.height = height + this.xy.month_head_height;
	this._colsS.heights = [];

	return scheduler._render_month_scale(b, dd, sd);

};
scheduler.getLabel = function(property, key) {
	var sections = this.config.lightbox.sections;
	for (var i=0; i<sections.length; i++) {
		if(sections[i].map_to == property) {
			var options = sections[i].options;
			for (var j=0; j<options.length; j++) {
				if(options[j].key == key) {
					return options[j].label;
				}
			}
		}
	}
	return "";
};
scheduler.updateCollection = function(list_name, collection) {
	var list = scheduler.serverList(list_name);
	if (!list) return false;
	list.splice(0, list.length);
	list.push.apply(list, collection || []);
	scheduler.callEvent("onOptionsLoad", []);
	scheduler.resetLightbox();
	return true;
};
scheduler._lame_clone = function(object, cache) {
	var i, t, result; // iterator, types array, result

	cache = cache || [];

	for (i=0; i<cache.length; i+=2)
		if(object === cache[i])
			return cache[i+1];

	if (object && typeof object == "object") {
		result = {};
		t = [Array,Date,Number,String,Boolean];
		for (i=0; i<t.length; i++) {
			if (object instanceof t[i])
				result = i ? new t[i](object) : new t[i](); // first one is array
		}
		cache.push(object, result);
		for (i in object) {
			if (Object.prototype.hasOwnProperty.apply(object, [i]))
				result[i] = scheduler._lame_clone(object[i], cache);
		}
	}
	return result || object;
};
scheduler._lame_copy = function(target, source) {
	for (var key in source) {
		if (source.hasOwnProperty(key)) {
			target[key] = source[key];
		}
	}
	return target;
};
scheduler._get_date_from_pos = function(pos) {
	var start=this._min_date.valueOf()+(pos.y*this.config.time_step+(this._table_view?0:pos.x)*24*60)*60000;
	return new Date(this._correct_shift(start));
};
// n_ev - native event
scheduler.getActionData = function(n_ev) {
	var pos = this._mouse_coords(n_ev);
	return {
		date:this._get_date_from_pos(pos),
		section:pos.section
	};
};
scheduler._focus = function(node, select){
	if (node && node.focus){
		if (this.config.touch){
			window.setTimeout(function(){
				node.focus();
			},100);
		} else {
			if (select && node.select) node.select();
			node.focus();
		}
	}
};

//non-linear scales
scheduler._get_real_event_length=function(sd, fd, obj){
	var ev_length = fd -sd;
	var hours = (obj._start_correction + obj._end_correction)||0;
	var ignore = this["ignore_"+this._mode];

	var start_slot = 0,
		end_slot;
	if (obj.render){
		start_slot = this._get_date_index(obj, sd);
		end_slot = this._get_date_index(obj, fd);
	} else{
		end_slot = Math.round(ev_length/60/60/1000/24);
	}

	var last_column = true;
	while (start_slot < end_slot){
		var check = scheduler.date.add(fd, -obj.x_step, obj.x_unit);
		if (ignore && ignore(fd) && (!last_column || (last_column && ignore(check) ))){
			ev_length -= (fd-check);

		}else{
			last_column = false;
			ev_length -= hours;
		}


		fd = check;
		end_slot--;
	}
	return ev_length;
};
scheduler._get_fictional_event_length=function(end_date, ev_length, obj, back){
	var sd = new Date(end_date);
	var dir = back ? -1 : 1;

	//get difference caused by first|last hour
	if (obj._start_correction || obj._end_correction){
		var today;
		if (back)
			today = (sd.getHours()*60+sd.getMinutes()) - (obj.first_hour||0)*60;
		else
			today = (obj.last_hour||0)*60 - (sd.getHours()*60+sd.getMinutes());
		var per_day = (obj.last_hour - obj.first_hour)*60;
		var days = Math.ceil( (ev_length / (60*1000) - today ) / per_day);
		if(days < 0) days = 0;
		ev_length += days * (24*60 - per_day) * 60 * 1000;
	}

	var fd = new Date(end_date*1+ev_length*dir);
	var ignore = this["ignore_"+this._mode];

	var start_slot = 0,
		end_slot;
	if (obj.render){
		start_slot = this._get_date_index(obj, sd);
		end_slot = this._get_date_index(obj, fd);
	} else{
		end_slot = Math.round(ev_length/60/60/1000/24);
	}

	while (start_slot*dir <= end_slot*dir){
		var check = scheduler.date.add(sd, obj.x_step*dir, obj.x_unit);
		if (ignore && ignore(sd)){
			ev_length += (check-sd)*dir;
			end_slot += dir;
		}

		sd = check;
		start_slot+=dir;
	}

	return ev_length;
};

scheduler._get_section_view = function(){
	if(this.matrix && this.matrix[this._mode]){
		return this.matrix[this._mode];
	}else if(this._props && this._props[this._mode]){
		return this._props[this._mode];
	}
	return null;
};

scheduler._get_section_property = function(){
	if(this.matrix && this.matrix[this._mode]){
		return this.matrix[this._mode].y_property;
	}else if(this._props && this._props[this._mode]){
		return this._props[this._mode].map_to;
	}
	return null;
};

scheduler._is_initialized = function(){
	var state = this.getState();
	return (this._obj && state.date && state.mode);
};
scheduler._is_lightbox_open = function(){
	var state = this.getState();
	return state.lightbox_id !== null && state.lightbox_id !== undefined;
};
scheduler.date={
	init:function(){
		var s = scheduler.locale.date.month_short;
		var t = scheduler.locale.date.month_short_hash = {};
		for (var i = 0; i < s.length; i++)
			t[s[i]]=i;

		var s = scheduler.locale.date.month_full;
		var t = scheduler.locale.date.month_full_hash = {};
		for (var i = 0; i < s.length; i++)
			t[s[i]]=i;
	},
	date_part:function(date){
		var old = new Date(date);
		date.setHours(0);
		date.setMinutes(0);
		date.setSeconds(0);
		date.setMilliseconds(0);
		if (date.getHours() && //shift to yesterday on dst
			(date.getDate() < old.getDate() || date.getMonth() < old.getMonth() || date.getFullYear() < old.getFullYear()) )
			date.setTime(date.getTime() + 60 * 60 * 1000 * (24 - date.getHours()));
		return date;
	},
	time_part:function(date){
		return (date.valueOf()/1000 - date.getTimezoneOffset()*60)%86400;
	},
	week_start:function(date){
		var shift=date.getDay();
		if (scheduler.config.start_on_monday){
			if (shift===0) shift=6;
			else shift--;
		}
		return this.date_part(this.add(date,-1*shift,"day"));
	},
	month_start:function(date){
		date.setDate(1);
		return this.date_part(date);
	},
	year_start:function(date){
		date.setMonth(0);
		return this.month_start(date);
	},
	day_start:function(date){
		return this.date_part(date);
	},
	_add_days:function(date, inc){
		var ndate = new Date(date.valueOf());

		ndate.setDate(ndate.getDate() + inc);

		// Workaround for Safari/iOS timezone bug, ref:OKZ-149693
		if(inc == Math.round(inc) && inc > 0){
			var datesDiff = +ndate - +date,
				rest = datesDiff % (24*60*60*1000);
			if(rest && date.getTimezoneOffset() == ndate.getTimezoneOffset()){
				var hours = rest / (60* 60 * 1000);
				ndate.setTime(ndate.getTime() + (24 - hours) * 60 * 60 * 1000);
			}
		}

		if (inc >= 0 && (!date.getHours() && ndate.getHours()) &&//shift to yesterday on dst
			(ndate.getDate() < date.getDate() || ndate.getMonth() < date.getMonth() || ndate.getFullYear() < date.getFullYear()) )
			ndate.setTime(ndate.getTime() + 60 * 60 * 1000 * (24 - ndate.getHours()));
		return ndate;
	},
	add:function(date,inc,mode){
		var ndate=new Date(date.valueOf());
		switch(mode){
			case "day":
				ndate = scheduler.date._add_days(ndate, inc);
				break;
			case "week":
				ndate = scheduler.date._add_days(ndate, inc * 7);
				break;
			case "month": ndate.setMonth(ndate.getMonth()+inc); break;
			case "year": ndate.setYear(ndate.getFullYear()+inc); break;
			case "hour":
				/*
				 setHour(getHour() + inc) and setMinutes gives weird result when is applied on a Daylight Saving time switch
				 setTime seems working as expected
				*/
				ndate.setTime(ndate.getTime() + inc * 60 * 60 * 1000);
				break;
			case "minute":
				ndate.setTime(ndate.getTime() + inc * 60 * 1000);
				break;
			default:
				return scheduler.date["add_"+mode](date,inc,mode);
		}
		return ndate;
	},
	to_fixed:function(num){
		if (num<10)	return "0"+num;
		return num;
	},
	copy:function(date){
		return new Date(date.valueOf());
	},
	date_to_str:function(format,utc){
		format=format.replace(/%[a-zA-Z]/g,function(a){
			switch(a){
				case "%d": return "\"+scheduler.date.to_fixed(date.getDate())+\"";
				case "%m": return "\"+scheduler.date.to_fixed((date.getMonth()+1))+\"";
				case "%j": return "\"+date.getDate()+\"";
				case "%n": return "\"+(date.getMonth()+1)+\"";
				case "%y": return "\"+scheduler.date.to_fixed(date.getFullYear()%100)+\"";
				case "%Y": return "\"+date.getFullYear()+\"";
				case "%D": return "\"+scheduler.locale.date.day_short[date.getDay()]+\"";
				case "%l": return "\"+scheduler.locale.date.day_full[date.getDay()]+\"";
				case "%M": return "\"+scheduler.locale.date.month_short[date.getMonth()]+\"";
				case "%F": return "\"+scheduler.locale.date.month_full[date.getMonth()]+\"";
				case "%h": return "\"+scheduler.date.to_fixed((date.getHours()+11)%12+1)+\"";
				case "%g": return "\"+((date.getHours()+11)%12+1)+\"";
				case "%G": return "\"+date.getHours()+\"";
				case "%H": return "\"+scheduler.date.to_fixed(date.getHours())+\"";
				case "%i": return "\"+scheduler.date.to_fixed(date.getMinutes())+\"";
				case "%a": return "\"+(date.getHours()>11?\"pm\":\"am\")+\"";
				case "%A": return "\"+(date.getHours()>11?\"PM\":\"AM\")+\"";
				case "%s": return "\"+scheduler.date.to_fixed(date.getSeconds())+\"";
				case "%W": return "\"+scheduler.date.to_fixed(scheduler.date.getISOWeek(date))+\"";
				default: return a;
			}
		});
		if (utc) format=format.replace(/date\.get/g,"date.getUTC");
		return new Function("date","return \""+format+"\";");
	},
	str_to_date:function(format,utc){
		var splt="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);";
		var mask=format.match(/%[a-zA-Z]/g);
		for (var i=0; i<mask.length; i++){
			switch(mask[i]){
				case "%j":
				case "%d": splt+="set[2]=temp["+i+"]||1;";
					break;
				case "%n":
				case "%m": splt+="set[1]=(temp["+i+"]||1)-1;";
					break;
				case "%y": splt+="set[0]=temp["+i+"]*1+(temp["+i+"]>50?1900:2000);";
					break;
				case "%g":
				case "%G":
				case "%h":
				case "%H":
							splt+="set[3]=temp["+i+"]||0;";
					break;
				case "%i":
							splt+="set[4]=temp["+i+"]||0;";
					break;
				case "%Y": splt+="set[0]=temp["+i+"]||0;";
					break;
				case "%a":
				case "%A": splt+="set[3]=set[3]%12+((temp["+i+"]||'').toLowerCase()=='am'?0:12);";
					break;
				case "%s": splt+="set[5]=temp["+i+"]||0;";
					break;
				case "%M": splt+="set[1]=scheduler.locale.date.month_short_hash[temp["+i+"]]||0;";
					break;
				case "%F": splt+="set[1]=scheduler.locale.date.month_full_hash[temp["+i+"]]||0;";
					break;
				default:
					break;
			}
		}
		var code ="set[0],set[1],set[2],set[3],set[4],set[5]";
		if (utc) code =" Date.UTC("+code+")";
		return new Function("date","var set=[0,0,1,0,0,0]; "+splt+" return new Date("+code+");");
	},
	getISOWeek: function(ndate) {
		if(!ndate) return false;
		var nday = ndate.getDay();
		if (nday === 0) {
			nday = 7;
		}
		var first_thursday = new Date(ndate.valueOf());
		first_thursday.setDate(ndate.getDate() + (4 - nday));
		var year_number = first_thursday.getFullYear(); // year of the first Thursday
		var ordinal_date = Math.round( (first_thursday.getTime() - new Date(year_number, 0, 1).getTime()) / 86400000); //ordinal date of the first Thursday - 1 (so not really ordinal date)
		var week_number = 1 + Math.floor( ordinal_date / 7);
		return week_number;
	},
	getUTCISOWeek: function(ndate){
		return this.getISOWeek(this.convert_to_utc(ndate));
	},
	convert_to_utc: function(date) {
		return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
	}
};
scheduler.locale = {
	date:{
		month_full:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
		month_short:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
		day_full:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
		day_short:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
	},
	labels:{
		dhx_cal_today_button:"Today",
		day_tab:"Day",
		week_tab:"Week",
		month_tab:"Month",
		new_event:"New event",
		icon_save:"Save",
		icon_cancel:"Cancel",
		icon_details:"Details",
		icon_edit:"Edit",
		icon_delete:"Delete",
		confirm_closing:"",//Your changes will be lost, are your sure ?
		confirm_deleting:"Event will be deleted permanently, are you sure?",
		section_description:"Description",
		section_time:"Time period",
		full_day:"Full day",

		/*recurring events*/
		confirm_recurring:"Do you want to edit the whole set of repeated events?",
		section_recurring:"Repeat event",
		button_recurring:"Disabled",
		button_recurring_open:"Enabled",
		button_edit_series: "Edit series",
		button_edit_occurrence: "Edit occurrence",

		/*agenda view extension*/
		agenda_tab:"Agenda",
		date:"Date",
		description:"Description",

		/*year view extension*/
		year_tab:"Year",

		/* week agenda extension */
		week_agenda_tab: "Agenda",

		/*grid view extension*/
		grid_tab: "Grid",

		/* touch tooltip*/
		drag_to_create:"Drag to create",
		drag_to_move:"Drag to move",

		/* dhtmlx message default buttons */
		message_ok:"OK",
		message_cancel:"Cancel"
	}
};


/*
%e	Day of the month without leading zeros (01..31)
%d	Day of the month, 2 digits with leading zeros (01..31)
%j	Day of the year, 3 digits with leading zeros (001..366)
%a	A textual representation of a day, two letters
%W	A full textual representation of the day of the week

%c	Numeric representation of a month, without leading zeros (0..12)
%m	Numeric representation of a month, with leading zeros (00..12)
%b	A short textual representation of a month, three letters (Jan..Dec)
%M	A full textual representation of a month, such as January or March (January..December)

%y	A two digit representation of a year (93..03)
%Y	A full numeric representation of a year, 4 digits (1993..03)
*/

scheduler.config={
	default_date: "%M %j, %Y",
	month_date: "%F %Y",
	load_date: "%Y-%m-%d",
	week_date: "%l",
	day_date: "%D, %F %j",
	hour_date: "%H:%i",
	month_day: "%d",
	xml_date: "%m/%d/%Y %H:%i",
	api_date: "%d-%m-%Y %H:%i",
	preserve_length:true,
	time_step: 5,

	start_on_monday: 1,
	first_hour: 0,
	last_hour: 24,
	readonly: false,
	drag_resize: 1,
	drag_move: 1,
	drag_create: 1,
	dblclick_create: 1,
	edit_on_create: 1,
	details_on_create: 0,
	resize_month_events:false,
	resize_month_timed:false,

	cascade_event_display: false,
	cascade_event_count: 4,
	cascade_event_margin: 30,

	multi_day:true,
	multi_day_height_limit: 0,

	drag_lightbox: true,
	preserve_scroll: true,
	select: true,

	server_utc: false,
	touch:true,
	touch_tip:true,
	touch_drag:500,
	quick_info_detached:true,

	positive_closing: false,

	drag_highlight: true,
	limit_drag_out: false,
	icons_edit: ["icon_save", "icon_cancel"],
	icons_select: ["icon_details", "icon_edit", "icon_delete"],
	buttons_left: ["dhx_save_btn", "dhx_cancel_btn"],
	buttons_right: ["dhx_delete_btn"],
	lightbox: {
		sections: [
			{name: "description", height: 200, map_to: "text", type: "textarea", focus: true},
			{name: "time", height: 72, type: "time", map_to: "auto"}
		]
	},
	highlight_displayed_event: true,
	left_border: false,

	ajax_error: "alert",//"ignore"|"console"
	delay_render: 0,
	timeline_swap_resize:false
};
scheduler.templates={};
scheduler.init_templates=function(){
	var labels = scheduler.locale.labels;
	labels.dhx_save_btn 	= labels.icon_save;
	labels.dhx_cancel_btn 	= labels.icon_cancel;
	labels.dhx_delete_btn 	= labels.icon_delete;


	var d=scheduler.date.date_to_str;
	var c=scheduler.config;
	var f = function(a,b){
		for (var c in b)
			if (!a[c]) a[c]=b[c];
	};
	f(scheduler.templates,{
		day_date:d('%D, '+c.default_date),
		month_date:d(c.month_date),
		week_date:function(d1,d2){
			return d(c.default_date)(d1)+" &ndash; "+d(c.default_date)(scheduler.date.add(d2,-1,"day"));
		},
		day_scale_date:d(c.default_date),
		month_scale_date:d(c.week_date),
		week_scale_date:d(c.day_date),
		hour_scale:d(c.hour_date),
		time_picker:d(c.hour_date),
		event_date:d(c.hour_date),
		month_day:d(c.month_day),
		xml_date:scheduler.date.str_to_date(c.xml_date,c.server_utc),
		load_format:d(c.load_date,c.server_utc),
		xml_format:d(c.xml_date,c.server_utc),
		api_date:scheduler.date.str_to_date(c.api_date),
		event_header:function(start,end,ev){
			return scheduler.templates.event_date(start)+" - "+scheduler.templates.event_date(end);
		},
		event_text:function(start,end,ev){
			return ev.text;
		},
		event_class:function(start,end,ev){
			return "";
		},
		month_date_class:function(d){
			return "";
		},
		week_date_class:function(d){
			return "";
		},
		event_bar_date:function(start,end,ev){
			return scheduler.templates.event_date(start)+" ";
		},
		event_bar_text:function(start,end,ev){
			return ev.text;
		},
		month_events_link : function(date, count){
			return "<a>View more("+count+" events)</a>";
		},
		drag_marker_class : function(start, end, event){
			return "";
		},
		drag_marker_content : function(start, end, event){
			return "";
		}
	});
	this.callEvent("onTemplatesReady",[]);
};



scheduler.uid = function() {
	if (!this._seed) this._seed = (new Date()).valueOf();
	return this._seed++;
};
scheduler._events = {};
scheduler.clearAll = function() {
	this._events = {};
	this._loaded = {};

	this._edit_id = null;
	this._select_id = null;
	this._drag_id = null;
	this._drag_mode = null;
	this._drag_pos = null;

	this.clear_view();
	this.callEvent("onClearAll", []);
};
scheduler.addEvent = function(start_date, end_date, text, id, extra_data) {
	if (!arguments.length)
		return this.addEventNow();
	var ev = start_date;
	if (arguments.length != 1) {
		ev = extra_data || {};
		ev.start_date = start_date;
		ev.end_date = end_date;
		ev.text = text;
		ev.id = id;
	}
	ev.id = ev.id || scheduler.uid();
	ev.text = ev.text || "";

	if (typeof ev.start_date == "string")  ev.start_date = this.templates.api_date(ev.start_date);
	if (typeof ev.end_date == "string")  ev.end_date = this.templates.api_date(ev.end_date);

	var d = (this.config.event_duration || this.config.time_step) * 60000;
	if (ev.start_date.valueOf() == ev.end_date.valueOf())
		ev.end_date.setTime(ev.end_date.valueOf() + d);

	ev._timed = this.isOneDayEvent(ev);

	var is_new = !this._events[ev.id];
	this._events[ev.id] = ev;
	this.event_updated(ev);
	if (!this._loading)
		this.callEvent(is_new ? "onEventAdded" : "onEventChanged", [ev.id, ev]);
	return ev.id;
};
scheduler.deleteEvent = function(id, silent) {
	var ev = this._events[id];
	if (!silent && (!this.callEvent("onBeforeEventDelete", [id, ev]) || !this.callEvent("onConfirmedBeforeEventDelete", [id, ev])))
		return;
	if (ev) {
		this._select_id = null;
		delete this._events[id];
		this.event_updated(ev);
	}

	this.callEvent("onEventDeleted", [id, ev]);
};
scheduler.getEvent = function(id) {
	return this._events[id];
};
scheduler.setEvent = function(id, hash) {
	if(!hash.id)
		hash.id = id;

	this._events[id] = hash;
};
scheduler.for_rendered = function(id, method) {
	for (var i = this._rendered.length - 1; i >= 0; i--)
		if (this._rendered[i].getAttribute("event_id") == id)
			method(this._rendered[i], i);
};
scheduler.changeEventId = function(id, new_id) {
	if (id == new_id) return;
	var ev = this._events[id];
	if (ev) {
		ev.id = new_id;
		this._events[new_id] = ev;
		delete this._events[id];
	}
	this.for_rendered(id, function(r) {
		r.setAttribute("event_id", new_id);
	});
	if (this._select_id == id) this._select_id = new_id;
	if (this._edit_id == id) this._edit_id = new_id;
	//if (this._drag_id==id) this._drag_id=new_id;
	this.callEvent("onEventIdChange", [id, new_id]);
};

(function() {
	var attrs = ["text", "Text", "start_date", "StartDate", "end_date", "EndDate"];
	var create_getter = function(name) {
		return function(id) { return (scheduler.getEvent(id))[name]; };
	};
	var create_setter = function(name) {
		return function(id, value) {
			var ev = scheduler.getEvent(id);
			ev[name] = value;
			ev._changed = true;
			ev._timed = this.isOneDayEvent(ev);
			scheduler.event_updated(ev, true);
		};
	};
	for (var i = 0; i < attrs.length; i += 2) {
		scheduler["getEvent" + attrs[i + 1]] = create_getter(attrs[i]);
		scheduler["setEvent" + attrs[i + 1]] = create_setter(attrs[i]);
	}
})();

scheduler.event_updated = function(ev, force) {
	if (this.is_visible_events(ev))
		this.render_view_data();
	else
		this.clear_event(ev.id);
};
scheduler.is_visible_events = function(ev) {
	//if in displayed dates
	var in_visible_range = (ev.start_date < this._max_date && this._min_date < ev.end_date);

	if(in_visible_range){

		//end dates are not between last/first hours
		var evFirstHour = ev.start_date.getHours(),
			evLastHour = ev.end_date.getHours() + (ev.end_date.getMinutes()/60),
			lastHour = this.config.last_hour,
			firstHour = this.config.first_hour;

		var end_dates_visible = (this._table_view || !((evLastHour > lastHour || evLastHour < firstHour) && (evFirstHour >= lastHour || evFirstHour < firstHour)));

		if(end_dates_visible){
			return true;
		}else{

			//event is bigger than area hidden between last/first hours
			var event_duration = (ev.end_date.valueOf() - ev.start_date.valueOf()) / (1000*60*60),//hours
				hidden_duration = 24 - (this.config.last_hour - this.config.first_hour);

			return !!((event_duration > hidden_duration) || (evFirstHour < lastHour && evLastHour >= firstHour));

		}
	}else{
		return false;
	}
};
scheduler.isOneDayEvent = function(ev) {
	var delta = ev.end_date.getDate() - ev.start_date.getDate();

	if (!delta)
		return ev.start_date.getMonth() == ev.end_date.getMonth() && ev.start_date.getFullYear() == ev.end_date.getFullYear();
	else {
		if (delta < 0)  delta = Math.ceil((ev.end_date.valueOf() - ev.start_date.valueOf()) / (24 * 60 * 60 * 1000));
		return (delta == 1 && !ev.end_date.getHours() && !ev.end_date.getMinutes() && (ev.start_date.getHours() || ev.start_date.getMinutes() ));
	}

};
scheduler.get_visible_events = function(only_timed) {
	//not the best strategy for sure
	var stack = [];

	for (var id in this._events)
		if (this.is_visible_events(this._events[id]))
			if (!only_timed || this._events[id]._timed)
				if (this.filter_event(id, this._events[id]))
					stack.push(this._events[id]);

	return stack;
};
scheduler.filter_event = function(id, ev) {
	var filter = this["filter_" + this._mode];
	return (filter) ? filter(id, ev) : true;
};
scheduler._is_main_area_event = function(ev){
	return !!ev._timed;
};
scheduler.render_view_data = function(evs, hold) {
	if (!evs) {
		if (this._not_render) {
			this._render_wait = true;
			return;
		}
		this._render_wait = false;

		this.clear_view();
		evs = this.get_visible_events(!(this._table_view || this.config.multi_day));
	}
	for(var i= 0, len = evs.length; i < len; i++){
		this._recalculate_timed(evs[i]);
	}

	if (this.config.multi_day && !this._table_view) {

		var tvs = [];
		var tvd = [];
		for (var i = 0; i < evs.length; i++) {
			if (this._is_main_area_event(evs[i]))
				tvs.push(evs[i]);
			else
				tvd.push(evs[i]);
		}

		// multiday events
		this._rendered_location = this._els['dhx_multi_day'][0];
		this._table_view = true;
		this.render_data(tvd, hold);
		this._table_view = false;

		// normal events
		this._rendered_location = this._els['dhx_cal_data'][0];
		this._table_view = false;
		this.render_data(tvs, hold);

	} else {
		this._rendered_location = this._els['dhx_cal_data'][0];
		this.render_data(evs, hold);
	}
};


scheduler._view_month_day = function(e){
	var date = scheduler.getActionData(e).date;
	if(!scheduler.callEvent("onViewMoreClick", [date]))
		return;
	scheduler.setCurrentView(date, "day");
};

scheduler._render_month_link = function(ev){
	var parent = this._rendered_location;
	var toRender = this._lame_clone(ev);

	//render links in each cell of multiday events
	for(var d = ev._sday; d < ev._eday; d++){

		toRender._sday = d;
		toRender._eday = d+1;

		var date = scheduler.date;
		var curr = scheduler._min_date;
		curr = date.add(curr, toRender._sweek, "week");
		curr = date.add(curr, toRender._sday, "day");
		var count = scheduler.getEvents(curr, date.add(curr, 1, "day")).length;

		var pos = this._get_event_bar_pos(toRender);
		var widt = (pos.x2 - pos.x);

		var el = document.createElement("div");
		el.onclick = function(e){scheduler._view_month_day(e||event);};
		el.className = "dhx_month_link";
		el.style.top = pos.y + "px";
		el.style.left = pos.x + "px";
		el.style.width = widt + "px";
		el.innerHTML = scheduler.templates.month_events_link(curr, count);
		this._rendered.push(el);

		parent.appendChild(el);
	}
};

scheduler._recalculate_timed = function(id){
	if(!id) return;
	var ev;
	if(typeof(id) != "object")
		ev = this._events[id];
	else
		ev = id;
	if(!ev) return;
	ev._timed = scheduler.isOneDayEvent(ev);
};
scheduler.attachEvent("onEventChanged", scheduler._recalculate_timed);
scheduler.attachEvent("onEventAdded", scheduler._recalculate_timed);

scheduler.render_data = function(evs, hold) {
	evs = this._pre_render_events(evs, hold);

	for (var i = 0; i < evs.length; i++)
		if (this._table_view){
			if(scheduler._mode != 'month'){
				this.render_event_bar(evs[i]);//may be multiday section on other views
			}else{

				var max_evs = scheduler.config.max_month_events;
				if(max_evs !== max_evs*1 || evs[i]._sorder < max_evs){
					//of max number events per month cell is set and event can be rendered
					this.render_event_bar(evs[i]);
				}else if(max_evs !== undefined && evs[i]._sorder == max_evs){
					//render 'view more' links
					scheduler._render_month_link(evs[i]);
				}else{
					//do not render events with ordinal number > maximum events per cell
				}
			}



		}else
			this.render_event(evs[i]);
};

scheduler._get_first_visible_cell = function(cells) {
	for (var i = 0; i < cells.length; i++) {
		if ((cells[i].className || "").indexOf("dhx_scale_ignore") == -1) {
			return cells[i];
		}
	}
	// if no visible cell found, return cells[0] to be more tolerant, since it's the original logic
	return cells[0];
};

scheduler._pre_render_events = function(evs, hold) {
	var hb = this.xy.bar_height;
	var h_old = this._colsS.heights;
	var h = this._colsS.heights = [0, 0, 0, 0, 0, 0, 0];
	var data = this._els["dhx_cal_data"][0];

	if (!this._table_view)
		evs = this._pre_render_events_line(evs, hold); //ignore long events for now
	else
		evs = this._pre_render_events_table(evs, hold);

	if (this._table_view) {
		if (hold)
			this._colsS.heights = h_old;
		else {
			var evl = data.firstChild;
			if (evl.rows) {
				for (var i = 0; i < evl.rows.length; i++) {
					h[i]++;
					var cells = evl.rows[i].cells;
					var cellHeight = this._colsS.height - this.xy.month_head_height;
					if ((h[i]) * hb > cellHeight) { // 22 - height of cell's header
						//we have overflow, update heights

						var cHeight = cellHeight;
						if(this.config.max_month_events*1 !== this.config.max_month_events || h[i] <= this.config.max_month_events){
							cHeight = h[i] * hb;
						}else if( (this.config.max_month_events + 1) * hb > cellHeight){
							cHeight = (this.config.max_month_events + 1) * hb;
						}

						for (var j = 0; j < cells.length; j++) {
							cells[j].childNodes[1].style.height = cHeight + "px";
						}
					//	h[i] = (h[i - 1] || 0) + cells[0].offsetHeight;
					}

					h[i] = (h[i - 1] || 0) + scheduler._get_first_visible_cell(cells).offsetHeight;
				}
				h.unshift(0);
				if (evl.parentNode.offsetHeight < evl.parentNode.scrollHeight && !scheduler._colsS.scroll_fix && scheduler.xy.scroll_width) {

					var scale_settings = scheduler._colsS,
						sum_width = scale_settings[scale_settings.col_length],
						row_heights = scale_settings.heights.slice();

					sum_width -= (scheduler.xy.scroll_width || 0);
					this._calc_scale_sizes(sum_width, this._min_date, this._max_date);
					scheduler._colsS.heights = row_heights;

					this.set_xy(this._els["dhx_cal_header"][0], sum_width, this.xy.scale_height);
					scheduler._render_scales(this._els["dhx_cal_header"][0]);
					scheduler._render_month_scale(this._els["dhx_cal_data"][0], this._get_timeunit_start(), this._min_date);

					scale_settings.scroll_fix = true;
				}
			} else {
				if (!evs.length && this._els["dhx_multi_day"][0].style.visibility == "visible")
					h[0] = -1;
				if (evs.length || h[0] == -1) {
					//shift days to have space for multiday events
					var childs = evl.parentNode.childNodes;

					// +1 so multiday events would have 2px from top and 2px from bottom by default
					var full_multi_day_height = (h[0] + 1) * hb + 1;

					var used_multi_day_height = full_multi_day_height;
					var used_multi_day_height_css = full_multi_day_height + "px";
					if (this.config.multi_day_height_limit) {
						used_multi_day_height = Math.min(full_multi_day_height, this.config.multi_day_height_limit) ;
						used_multi_day_height_css = used_multi_day_height + "px";
					}

					data.style.top = (this._els["dhx_cal_navline"][0].offsetHeight + this._els["dhx_cal_header"][0].offsetHeight + used_multi_day_height ) + 'px';
					data.style.height = (this._obj.offsetHeight - parseInt(data.style.top, 10) - (this.xy.margin_top || 0)) + 'px';

					var multi_day_section = this._els["dhx_multi_day"][0];
					multi_day_section.style.height = used_multi_day_height_css;
					multi_day_section.style.visibility = (h[0] == -1 ? "hidden" : "visible");

					// icon
					var multi_day_icon = this._els["dhx_multi_day"][1];
					multi_day_icon.style.height = used_multi_day_height_css;
					multi_day_icon.style.visibility = (h[0] == -1 ? "hidden" : "visible");
					multi_day_icon.className = h[0] ? "dhx_multi_day_icon" : "dhx_multi_day_icon_small";
					this._dy_shift = (h[0] + 1) * hb;
					if(this.config.multi_day_height_limit){
						this._dy_shift = Math.min(this.config.multi_day_height_limit, this._dy_shift);
					}
					h[0] = 0;

					if (used_multi_day_height != full_multi_day_height) {
						data.style.top = (parseInt(data.style.top) + 2) + "px";

						multi_day_section.style.overflowY = "auto";
					//	multi_day_section.style.width = (parseInt(this._els["dhx_cal_navline"][0].style.width)) + "px";

						multi_day_icon.style.position = "fixed";
						multi_day_icon.style.top = "";
						multi_day_icon.style.left = "";
					}
				}
			}
		}
	}

	return evs;
};
scheduler._get_event_sday = function(ev) {
	// get day in current view
	// use rounding for 23 or 25 hour days on DST
	var datePart = this.date.day_start(new Date(ev.start_date));
	return Math.round((datePart.valueOf() - this._min_date.valueOf()) / (24 * 60 * 60 * 1000));
};
scheduler._get_event_mapped_end_date = function(ev) {
	var end_date = ev.end_date;
	if (this.config.separate_short_events) {
		var ev_duration = (ev.end_date - ev.start_date) / 60000; // minutes
		if (ev_duration < this._min_mapped_duration) {
			end_date = this.date.add(end_date, this._min_mapped_duration - ev_duration, "minute");
		}
	}
	return end_date;
};
scheduler._pre_render_events_line = function(evs, hold){
	evs.sort(function(a, b) {
		if (a.start_date.valueOf() == b.start_date.valueOf())
			return a.id > b.id ? 1 : -1;
		return a.start_date > b.start_date ? 1 : -1;
	});
	var days = []; //events by weeks
	var evs_originals = [];

	this._min_mapped_duration = Math.ceil(this.xy.min_event_height * 60 / this.config.hour_size_px);  // values could change along the way

	for (var i = 0; i < evs.length; i++) {
		var ev = evs[i];

		//check date overflow
		var sd = ev.start_date;
		var ed = ev.end_date;
		//check scale overflow
		var sh = sd.getHours();
		var eh = ed.getHours();

		ev._sday = this._get_event_sday(ev); // sday based on event start_date
		if (this._ignores[ev._sday]){
			//ignore event
			evs.splice(i,1);
			i--;
			continue;
		}

		if (!days[ev._sday]) days[ev._sday] = [];

		if (!hold) {
			ev._inner = false;

			var stack = days[ev._sday];

			while (stack.length) {
				var t_ev = stack[stack.length - 1];
				var t_end_date = this._get_event_mapped_end_date(t_ev);
				if (t_end_date.valueOf() <= ev.start_date.valueOf()) {
					stack.splice(stack.length - 1, 1);
				} else {
					break;
				}
			}
			var slot_index = stack.length;
			var sorderSet = false;
			for (var j = 0; j < stack.length; j++) {
				var t_ev = stack[j];
				var t_end_date = this._get_event_mapped_end_date(t_ev);
				if (t_end_date.valueOf() <= ev.start_date.valueOf()) {
					sorderSet = true;
					ev._sorder = t_ev._sorder;
					slot_index = j;
					ev._inner = true;
					break;
				}
			}

			if (stack.length)
				stack[stack.length - 1]._inner = true;

			if (!sorderSet) {
				if (stack.length) {
					if (stack.length <= stack[stack.length - 1]._sorder) {
						if (!stack[stack.length - 1]._sorder)
							ev._sorder = 0;
						else
							for (j = 0; j < stack.length; j++) {
								var _is_sorder = false;
								for (var k = 0; k < stack.length; k++) {
									if (stack[k]._sorder == j) {
										_is_sorder = true;
										break;
									}
								}
								if (!_is_sorder) {
									ev._sorder = j;
									break;
								}
							}
						ev._inner = true;
					} else {
						var _max_sorder = stack[0]._sorder;
						for (j = 1; j < stack.length; j++) {
							if (stack[j]._sorder > _max_sorder)
								_max_sorder = stack[j]._sorder;
						}
						ev._sorder = _max_sorder + 1;
						ev._inner = false;
					}

				} else
					ev._sorder = 0;
			}

			stack.splice(slot_index, slot_index == stack.length ? 0 : 1, ev);

			if (stack.length > (stack.max_count || 0)) {
				stack.max_count = stack.length;
				ev._count = stack.length;
			} else {
				ev._count = (ev._count) ? ev._count : 1;
			}
		}

		if (sh < this.config.first_hour || eh >= this.config.last_hour) {
			// Need to create copy of event as we will be changing it's start/end date
			// e.g. first_hour = 11 and event.start_date hours = 9. Need to preserve that info
			evs_originals.push(ev);
			evs[i] = ev = this._copy_event(ev);

			if (sh < this.config.first_hour) {
				ev.start_date.setHours(this.config.first_hour);
				ev.start_date.setMinutes(0);
			}
			if (eh >= this.config.last_hour) {
				ev.end_date.setMinutes(0);
				ev.end_date.setHours(this.config.last_hour);
			}

			if (ev.start_date > ev.end_date || sh == this.config.last_hour) {
				evs.splice(i, 1);
				i--;
				continue;
			}
		}
	}
	if (!hold) {
		for (var i = 0; i < evs.length; i++) {
			evs[i]._count = days[evs[i]._sday].max_count;
		}
		for (var i = 0; i < evs_originals.length; i++)
			evs_originals[i]._count = days[evs_originals[i]._sday].max_count;
	}

	return evs;
};
scheduler._time_order = function(evs) {
	evs.sort(function(a, b) {
		if (a.start_date.valueOf() == b.start_date.valueOf()) {
			if (a._timed && !b._timed) return 1;
			if (!a._timed && b._timed) return -1;
			return a.id > b.id ? 1 : -1;
		}
		return a.start_date > b.start_date ? 1 : -1;
	});
};
scheduler._pre_render_events_table = function(evs, hold) { // max - max height of week slot
	this._time_order(evs);
	var out = [];
	var weeks = [
		[],
		[],
		[],
		[],
		[],
		[],
		[]
	]; //events by weeks
	var max = this._colsS.heights;
	var start_date;
	var cols = this._cols.length;
	var chunks_info = {};

	for (var i = 0; i < evs.length; i++) {
		var ev = evs[i];
		var id = ev.id;
		if (!chunks_info[id]) {
			chunks_info[id] = {
				first_chunk: true,
				last_chunk: true
			};
		}
		var chunk_info = chunks_info[id];
		var sd = (start_date || ev.start_date);
		var ed = ev.end_date;
		//trim events which are crossing through current view
		if (sd < this._min_date) {
			chunk_info.first_chunk = false;
			sd = this._min_date;
		}
		if (ed > this._max_date) {
			chunk_info.last_chunk = false;
			ed = this._max_date;
		}

		var locate_s = this.locate_holder_day(sd, false, ev);
		ev._sday = locate_s % cols;

		//skip single day events for ignored dates
		if (this._ignores[ev._sday] && ev._timed) continue;

		var locate_e = this.locate_holder_day(ed, true, ev) || cols;
		ev._eday = (locate_e % cols) || cols; //cols used to fill full week, when event end on monday
		ev._length = locate_e - locate_s;

		//3600000 - compensate 1 hour during winter|summer time shift
		ev._sweek = Math.floor((this._correct_shift(sd.valueOf(), 1) - this._min_date.valueOf()) / (60 * 60 * 1000 * 24 * cols));

		//current slot
		var stack = weeks[ev._sweek];
		//check order position
		var stack_line;

		for (stack_line = 0; stack_line < stack.length; stack_line++)
			if (stack[stack_line]._eday <= ev._sday)
				break;

		if (!ev._sorder || !hold) {
			ev._sorder = stack_line;
		}

		if (ev._sday + ev._length <= cols) {
			start_date = null;
			out.push(ev);
			stack[stack_line] = ev;
			//get max height of slot
			max[ev._sweek] = stack.length - 1;
			ev._first_chunk = chunk_info.first_chunk;
			ev._last_chunk = chunk_info.last_chunk;
		} else { // split long event in chunks
			var copy = this._copy_event(ev);
			copy.id = ev.id;
			copy._length = cols - ev._sday;
			copy._eday = cols;
			copy._sday = ev._sday;
			copy._sweek = ev._sweek;
			copy._sorder = ev._sorder;
			copy.end_date = this.date.add(sd, copy._length, "day");
			copy._first_chunk = chunk_info.first_chunk;
			if (chunk_info.first_chunk) {
				chunk_info.first_chunk = false;
			}

			out.push(copy);
			stack[stack_line] = copy;
			start_date = copy.end_date;
			//get max height of slot
			max[ev._sweek] = stack.length - 1;
			i--;
			continue;  //repeat same step
		}
	}
	return out;
};
scheduler._copy_dummy = function() {
	var a = new Date(this.start_date);
	var b = new Date(this.end_date);
	this.start_date = a;
	this.end_date = b;
};
scheduler._copy_event = function(ev) {
	this._copy_dummy.prototype = ev;
	return new this._copy_dummy();
	//return {start_date:ev.start_date, end_date:ev.end_date, text:ev.text, id:ev.id}
};
scheduler._rendered = [];
scheduler.clear_view = function() {
	for (var i = 0; i < this._rendered.length; i++) {
		var obj = this._rendered[i];
		if (obj.parentNode) obj.parentNode.removeChild(obj);
	}
	this._rendered = [];
};
scheduler.updateEvent = function(id) {
	var ev = this.getEvent(id);
	this.clear_event(id);

	if (ev && this.is_visible_events(ev) && this.filter_event(id, ev) && (this._table_view || this.config.multi_day || ev._timed)) {
		if (this.config.update_render){
			this.render_view_data();
		}else{
			if(this.getState().mode == "month" && !this.getState().drag_id && !this.isOneDayEvent(ev)){
				this.render_view_data();
			}else{
				this.render_view_data([ev], true);
			}
		}
	}
};
scheduler.clear_event = function(id) {
	this.for_rendered(id, function(node, i) {
		if (node.parentNode)
			node.parentNode.removeChild(node);
		scheduler._rendered.splice(i, 1);
	});
};
scheduler._y_from_date = function(ev){
	var date = ev.start_date;
	var sm = date.getHours() * 60 + date.getMinutes() - this._buffer_before(ev);
	return ((Math.round((sm * 60 * 1000 - this.config.first_hour * 60 * 60 * 1000) * this.config.hour_size_px / (60 * 60 * 1000))) % (this.config.hour_size_px * 24)); //42px/hour
};
scheduler._calc_event_y = function(ev, min_height){
	min_height = min_height || 0;
	var sm = ev.start_date.getHours() * 60 + ev.start_date.getMinutes() - this._buffer_before(ev);
    if (ev.end_date.getHours() + ev.end_date.getMinutes() === 0) {
        var em = scheduler.config.last_hour * 60;
    } else {
        var em = (ev.end_date.getHours() * 60 + ev.end_date.getMinutes() + this._buffer_after(ev)) || (scheduler.config.last_hour * 60);
    }

	var top = this._y_from_date(ev);

	var height = Math.max(min_height + this._buffer_in_pixels(ev) , (em - sm) * this.config.hour_size_px / 60); //42px/hour
	return {
		top: top,
		height: height
	};
};
scheduler._minutes_to_pixels = function(minutes) {
	return ((minutes || 0) * this.config.hour_size_px) / 60;
};
scheduler._buffer_before = function(ev) {
	return ev.buffer_before || 0;
};
scheduler._buffer_after = function(ev) {
	return ev.buffer_after || 0;
};
scheduler._buffer_total = function(ev) {
	return this._buffer_before(ev) + this._buffer_after(ev);
};
scheduler._buffer_in_pixels = function(ev) {
	return this._buffer_before_in_pixels(ev) + this._buffer_after_in_pixels(ev);
};
scheduler._buffer_before_in_pixels = function(ev) {
	return this._minutes_to_pixels(this._buffer_before(ev));
};
scheduler._buffer_after_in_pixels = function(ev) {
    if (ev.end_date.getHours() + ev.end_date.getMinutes()  === 0)
        return 0;
	return this._minutes_to_pixels(this._buffer_after(ev));
};
scheduler.render_event = function(ev) {
	var menu = scheduler.xy.menu_width;
	var menu_offset = (this.config.use_select_menu_space) ? 0 : menu;
	if (ev._sday < 0) return; //can occur in case of recurring event during time shift

	var parent = scheduler.locate_holder(ev._sday);
	if (!parent) return; //attempt to render non-visible event

	var pos_y = this._calc_event_y(ev, scheduler.xy.min_event_height);
	var top = pos_y.top,
		height = pos_y.height;

	var ev_count = ev._count || 1;
	var ev_sorder = ev._sorder || 0;

	var width = Math.floor((parent.clientWidth - menu_offset) / ev_count);
	var left = ev_sorder * width + 1;
	if (!ev._inner) width = width * (ev_count - ev_sorder);
	if (this.config.cascade_event_display) {
		var limit = this.config.cascade_event_count;
		var margin = this.config.cascade_event_margin;
		left = ev_sorder % limit * margin;
		var right = (ev._inner) ? (ev_count - ev_sorder - 1) % limit * margin / 2 : 0;
		width = Math.floor(parent.clientWidth - menu_offset - left - right);
	}

	var d = this._render_v_bar(ev, menu_offset + left, top, width, height, ev._text_style, scheduler.templates.event_header(ev.start_date, ev.end_date, ev), scheduler.templates.event_text(ev.start_date, ev.end_date, ev));

	this._rendered.push(d);
	parent.appendChild(d);

	left = left + parseInt(parent.style.left, 10) + menu_offset;

	if (this._edit_id == ev.id) {

		d.style.zIndex = 1; //fix overlapping issue
		width = Math.max(width - 4, scheduler.xy.editor_width);
		d = document.createElement("DIV");
		d.setAttribute("event_id", ev.id);
		this.set_xy(d, width, height - 20, left, top + 14);
		d.className = "dhx_cal_event dhx_cal_editor";

		var tplClass = scheduler.templates.event_class(ev.start_date, ev.end_date, ev);

		if(tplClass){
			d.className += " " + tplClass;
		}
		var d2 = document.createElement("DIV");
		this.set_xy(d2, width - 6, height - 26);
		d2.style.cssText += ";margin:2px 2px 2px 2px;overflow:hidden;";

		d.appendChild(d2);
		this._els["dhx_cal_data"][0].appendChild(d);
		this._rendered.push(d);

		d2.innerHTML = "<textarea class='dhx_cal_editor'>" + ev.text + "</textarea>";
		if (this._quirks7) d2.firstChild.style.height = height - 12 + "px"; //IEFIX
		this._editor = d2.firstChild;
		this._editor.onkeydown = function(e) {
			if ((e || event).shiftKey) return true;
			var code = (e || event).keyCode;
			if (code == scheduler.keys.edit_save) scheduler.editStop(true);
			if (code == scheduler.keys.edit_cancel) scheduler.editStop(false);
		};
		this._editor.onselectstart = function (e) {
			(e || event).cancelBubble = true;
			return true;
		};
		scheduler._focus(d2.firstChild, true);
		//IE and opera can add x-scroll during focusing
		this._els["dhx_cal_data"][0].scrollLeft = 0;
	}
	if (this.xy.menu_width !== 0 && this._select_id == ev.id) {
		if (this.config.cascade_event_display && this._drag_mode)
			d.style.zIndex = 1; //fix overlapping issue for cascade view in case of dnd of selected event
		var icons = this.config["icons_" + ((this._edit_id == ev.id) ? "edit" : "select")];
		var icons_str = "";
		var bg_color = (ev.color ? ("background-color: " + ev.color + ";") : "");
		var color = (ev.textColor ? ("color: " + ev.textColor + ";") : "");
		for (var i = 0; i < icons.length; i++)
			icons_str += "<div class='dhx_menu_icon " + icons[i] + "' style='" + bg_color + "" + color + "' title='" + this.locale.labels[icons[i]] + "'></div>";
		var obj = this._render_v_bar(ev, left - menu + 1, top, menu, icons.length * 20 + 26 - 2, "", "<div style='" + bg_color + "" + color + "' class='dhx_menu_head'></div>", icons_str, true);
		obj.style.left = left - menu + 1;
		this._els["dhx_cal_data"][0].appendChild(obj);
		this._rendered.push(obj);
	}
	if(this.config.drag_highlight && this._drag_id == ev.id){
		this.highlightEventPosition(ev);
	}
};
scheduler._render_v_bar = function (ev, x, y, w, h, style, contentA, contentB, bottom) {
	var d = document.createElement("DIV");
	var id = ev.id;
	var cs = (bottom) ? "dhx_cal_event dhx_cal_select_menu" : "dhx_cal_event";
	var buffer_before_pixels = this._buffer_before_in_pixels(ev);
	var buffer_after_pixels = this._buffer_after_in_pixels(ev);

	var cse = scheduler.templates.event_class(ev.start_date, ev.end_date, ev);
	if (cse) cs = cs + " " + cse;

	var bg_color = (ev.color ? ("background:" + ev.color + ";") : "");
	var color = (ev.textColor ? ("color:" + ev.textColor + ";") : "");

	var html = '<div event_id="' + id + '" class="' + cs + '" style="position:absolute; top:' + y + 'px; left:' + x + 'px; width:' + (w - 4) + 'px; height:' + (h - 2) + 'px;' + (style || "") + '"></div>';
	d.innerHTML = html;

	var container = d.cloneNode(true).firstChild;

	h = h - this._buffer_in_pixels(ev);

	if (!bottom && scheduler.renderEvent(container, ev, w, h, contentA, contentB)) {
		return container;
	} else {
		container = d.firstChild;

		var inner_html = '<div class="dhx_event_move dhx_header" style=" width:' + (w - 6) + 'px;' + bg_color + '" >&nbsp;</div>';
		var inner_html = '';
		if (!bottom && buffer_before_pixels) {
			inner_html += '<div class="dhx_buffer_before" style=" width:' + (w - 5) + 'px; height: ' + buffer_before_pixels + 'px;" >&nbsp;</div>';
		}
		inner_html += '<div class="dhx_event_move dhx_title" style="' + bg_color + '' + color + '">' + contentA + '</div>';
		inner_html += '<div class="dhx_body" style=" width:' + (w - (this._quirks ? 4 : 14)) + 'px; height:' + (h - (this._quirks ? 20 : 30) + 1) + 'px;' + bg_color + '' + color + '">' + contentB + '</div>'; // +2 css specific, moved from render_event

		var footer_class = "dhx_event_resize dhx_footer";
		if (bottom)
			footer_class = "dhx_resize_denied " + footer_class;

		if (!bottom && buffer_after_pixels) {
			inner_html += '<div class="dhx_buffer_after" style=" width:' + (w - 5) + 'px; height: ' + (buffer_after_pixels + 1) + 'px;" >&nbsp;</div>';
		}
		inner_html += '<div class="' + footer_class + '" style=" width:' + (w - 8) + 'px;' + (bottom ? ' margin-top:-1px;' : '') + '' + bg_color + '' + color + '" ></div>';

		container.innerHTML = inner_html;
	}

	return container;
};
scheduler.renderEvent = function(){
	return false;
};
scheduler.locate_holder = function(day) {
	if (this._mode == "day") return this._els["dhx_cal_data"][0].firstChild; //dirty
	return this._els["dhx_cal_data"][0].childNodes[day];
};
scheduler.locate_holder_day = function(date, past) {
	var day = Math.floor((this._correct_shift(date, 1) - this._min_date) / (60 * 60 * 24 * 1000));
	//when locating end data of event , we need to use next day if time part was defined
	if (past && this.date.time_part(date)) day++;
	return day;
};



scheduler._get_dnd_order = function(order, ev_height, max_height){
	if(!this._drag_event)
		return order;
	if(!this._drag_event._orig_sorder)
		this._drag_event._orig_sorder = order;
	else
		order = this._drag_event._orig_sorder;

	var evTop = ev_height * order;
	while((evTop + ev_height) > max_height){
		order--;
		evTop -= ev_height;
	}
	order = Math.max(order, 0);
	return order;
};
//scheduler._get_event_bar_pos = function(sday, eday, week, drag){
scheduler._get_event_bar_pos = function(ev){
	var x = this._colsS[ev._sday];
	var x2 = this._colsS[ev._eday];
	if (x2 == x) x2 = this._colsS[ev._eday + 1];
	var hb = this.xy.bar_height;

	var order = ev._sorder;
	if(ev.id == this._drag_id){
		var cellHeight = this._colsS.heights[ev._sweek + 1] - this._colsS.heights[ev._sweek]- this.xy.month_head_height;//22 for month head height
		order = scheduler._get_dnd_order(order, hb, cellHeight);
	}
	var y_event_offset =  order * hb;
	var y = this._colsS.heights[ev._sweek] + (this._colsS.height ? (this.xy.month_scale_height + 2) : 2 ) + y_event_offset;
	return {x:x, x2:x2, y:y};
};

scheduler.render_event_bar = function (ev) {
	var parent = this._rendered_location;
	var pos = this._get_event_bar_pos(ev);

	var y = pos.y;
	var x = pos.x;
	var x2 = pos.x2;

	// resize for month mutliday events
	var resize_handle = "";

	//events in ignored dates

	if (!x2) return;

	var resizable = scheduler.config.resize_month_events && this._mode == "month" &&
		(!ev._timed || scheduler.config.resize_month_timed);

	var d = document.createElement("DIV");
	var left_chunk = (ev.hasOwnProperty("_first_chunk") && ev._first_chunk),
		right_chunk = (ev.hasOwnProperty("_last_chunk") && ev._last_chunk);

	var resize_left = resizable && (ev._timed || left_chunk);
	var resize_right = resizable && (ev._timed || right_chunk);

	var cs = "dhx_cal_event_clear";
	if (!ev._timed || resizable) {
		cs = "dhx_cal_event_line";
	}
	if(left_chunk){
		cs += " dhx_cal_event_line_start";
	}
	if(right_chunk){
		cs += " dhx_cal_event_line_end";
	}
	if(resize_left){
		resize_handle += "<div class='dhx_event_resize dhx_event_resize_start'></div>";
	}
	if(resize_right){
		resize_handle += "<div class='dhx_event_resize dhx_event_resize_end'></div>";
	}

	var cse = scheduler.templates.event_class(ev.start_date, ev.end_date, ev);
	if (cse){
		cs += " " + cse;
	}

	var bg_color = (ev.color ? ("background:" + ev.color + ";") : "");
	var color = (ev.textColor ? ("color:" + ev.textColor + ";") : "");

	var style_text = [
		"position:absolute",
		"top:" + y + "px",
		"left:" + x + "px",
		"width:" + (x2 - x - 15) + "px",
		color,
		bg_color,
		(ev._text_style || "")
	].join(";");

	var html = '<div event_id="' + ev.id + '" class="' + cs + '" style="'+style_text+'">';
	if (resizable) {
		html += resize_handle;
	}
	if(scheduler.getState().mode == "month"){
		ev = scheduler.getEvent(ev.id); // ev at this point could be a part (row in a month view) of a larger event
	}

	if (ev._timed)
		html += scheduler.templates.event_bar_date(ev.start_date, ev.end_date, ev);
	html += scheduler.templates.event_bar_text(ev.start_date, ev.end_date, ev) + '</div>';
	html += '</div>';

	d.innerHTML = html;

	this._rendered.push(d.firstChild);
	parent.appendChild(d.firstChild);
};

scheduler._locate_event = function(node) {
	var id = null;
	while (node && !id && node.getAttribute) {
		id = node.getAttribute("event_id");
		node = node.parentNode;
	}
	return id;
};

scheduler.edit = function(id) {
	if (this._edit_id == id) return;
	this.editStop(false, id);
	this._edit_id = id;
	this.updateEvent(id);
};
scheduler.editStop = function(mode, id) {
	if (id && this._edit_id == id) return;
	var ev = this.getEvent(this._edit_id);
	if (ev) {
		if (mode) ev.text = this._editor.value;
		this._edit_id = null;
		this._editor = null;
		this.updateEvent(ev.id);
		this._edit_stop_event(ev, mode);
	}
};
scheduler._edit_stop_event = function(ev, mode) {
	if (this._new_event) {
		if (!mode) {
			if (ev) // in case of custom lightbox user can already delete event
				this.deleteEvent(ev.id, true);
		} else {
			this.callEvent("onEventAdded", [ev.id, ev]);
		}
		this._new_event = null;
	} else {
		if (mode){
			this.callEvent("onEventChanged", [ev.id, ev]);
		}
	}
};

scheduler.getEvents = function(from, to) {
	var result = [];
	for (var a in this._events) {
		var ev = this._events[a];
		if (ev && ( (!from && !to) || (ev.start_date < to && ev.end_date > from) ))
			result.push(ev);
	}
	return result;
};
scheduler.getRenderedEvent = function(id) {
	if (!id)
		return;
	var rendered_events = scheduler._rendered;
	for (var i=0; i<rendered_events.length; i++) {
		var rendered_event = rendered_events[i];
		if (rendered_event.getAttribute("event_id") == id) {
			return rendered_event;
		}
	}
	return null;
};
scheduler.showEvent = function(id, mode) {
	var ev = (typeof id == "number" || typeof id == "string") ? scheduler.getEvent(id) : id;
	mode = mode||scheduler._mode;

	if (!ev || (this.checkEvent("onBeforeEventDisplay") && !this.callEvent("onBeforeEventDisplay", [ev, mode])))
		return;

	var scroll_hour = scheduler.config.scroll_hour;
	scheduler.config.scroll_hour = ev.start_date.getHours();
	var preserve_scroll = scheduler.config.preserve_scroll;
	scheduler.config.preserve_scroll = false;

	var original_color = ev.color;
	var original_text_color = ev.textColor;
	if (scheduler.config.highlight_displayed_event) {
		ev.color = scheduler.config.displayed_event_color;
		ev.textColor = scheduler.config.displayed_event_text_color;
	}

	scheduler.setCurrentView(new Date(ev.start_date), mode);

	ev.color = original_color;
	ev.textColor = original_text_color;
	scheduler.config.scroll_hour = scroll_hour;
	scheduler.config.preserve_scroll = preserve_scroll;

	if (scheduler.matrix && scheduler.matrix[mode]) {
		var rendered_event = scheduler.getRenderedEvent(ev.id);
		if(rendered_event)
			scheduler._els.dhx_cal_data[0].scrollTop = getAbsoluteTop(rendered_event) - getAbsoluteTop(scheduler._els.dhx_cal_data[0]) - 20;
	}

	scheduler.callEvent("onAfterEventDisplay", [ev, mode]);
};

scheduler._append_drag_marker = function(m){
	if(m.parentNode) return;
	var zone = scheduler._els["dhx_cal_data"][0];

	var scale = zone.lastChild;
	if(scale.className && scale.className.indexOf("dhx_scale_holder") < 0 && scale.previousSibling){
		scale = scale.previousSibling;
	}
	if (scale && scale.className.indexOf("dhx_scale_holder") === 0) {
		scale.appendChild(m);
	}
};

scheduler._update_marker_position = function(m, event){
	var size = scheduler._calc_event_y(event, 0);
	m.style.top = size.top + "px";
	m.style.height = size.height + "px";
};

scheduler.highlightEventPosition = function(event){
	var m = document.createElement("div");

	m.setAttribute("event_id", event.id);
	this._rendered.push(m);
	this._update_marker_position(m, event);

	var css = this.templates.drag_marker_class(event.start_date, event.end_date, event);
	var html = this.templates.drag_marker_content(event.start_date, event.end_date, event);
	m.className = "dhx_drag_marker";
	if(css)
		m.className += " " + css;
	if(html)
		m.innerHTML = html;
	this._append_drag_marker(m);
};
scheduler._loaded = {};
scheduler._load = function(url, from) {
	url = url || this._load_url;

	if(!url){
		//if scheduler.setLoadMode is called before scheduler.init, initial rendering will invoke data loading while url is undefined
		return;
	}

	url += (url.indexOf("?") == -1 ? "?" : "&") + "timeshift=" + (new Date()).getTimezoneOffset();
	if (this.config.prevent_cache)    url += "&uid=" + this.uid();
	var to;
	from = from || this._date;

	if (this._load_mode) {
		var lf = this.templates.load_format;

		from = this.date[this._load_mode + "_start"](new Date(from.valueOf()));
		while (from > this._min_date) from = this.date.add(from, -1, this._load_mode);
		to = from;

		var cache_line = true;
		while (to < this._max_date) {
			to = this.date.add(to, 1, this._load_mode);
			if (this._loaded[lf(from)] && cache_line)
				from = this.date.add(from, 1, this._load_mode); else cache_line = false;
		}

		var temp_to = to;
		do {
			to = temp_to;
			temp_to = this.date.add(to, -1, this._load_mode);
		} while (temp_to > from && this._loaded[lf(temp_to)]);

		if (to <= from)
			return false; //already loaded
		dhtmlxAjax.get(url + "&from=" + lf(from) + "&to=" + lf(to), function(l) {scheduler.on_load(l);});
		while (from < to) {
			this._loaded[lf(from)] = true;
			from = this.date.add(from, 1, this._load_mode);
		}
	} else
		dhtmlxAjax.get(url, function(l) {scheduler.on_load(l);});
	this.callEvent("onXLS", []);
	return true;
};
scheduler.on_load = function(loader) {
	var evs;
	var error = false;
	if (this._process && this._process != "xml") {
		try{
			evs = this[this._process].parse(loader.xmlDoc.responseText);
		}catch (e){
			error = true;
		}
	} else {
		evs = this._magic_parser(loader);
		if(!evs){
			error = true;
		}
	}

	if(error){
		this.callEvent("onLoadError", [loader.xmlDoc]);
		evs = [];
	}

	scheduler._process_loading(evs);

	this.callEvent("onXLE", []);
};
scheduler._process_loading = function(evs) {
	this._loading = true;
	this._not_render = true;
	for (var i = 0; i < evs.length; i++) {
		if (!this.callEvent("onEventLoading", [evs[i]])) continue;
		this.addEvent(evs[i]);
	}
	this._not_render = false;
	if (this._render_wait) this.render_view_data();

	this._loading = false;
	if (this._after_call) this._after_call();
	this._after_call = null;
};
scheduler._init_event = function(event) {
	event.text = (event.text || event._tagvalue) || "";
	event.start_date = scheduler._init_date(event.start_date);
	event.end_date = scheduler._init_date(event.end_date);
};

scheduler._init_date = function(date){
	if(!date)
		return null;
	if(typeof date == "string")
		return scheduler.templates.xml_date(date);
	else return new Date(date);
};

scheduler.json = {};
scheduler.json.parse = function(data) {
	if (typeof data == "string") {
		scheduler._temp = eval("(" + data + ")");
		data = (scheduler._temp) ? scheduler._temp.data || scheduler._temp.d || scheduler._temp : [];
	}

	if (data.dhx_security)
		dhtmlx.security_key = data.dhx_security;

	var collections = (scheduler._temp && scheduler._temp.collections) ? scheduler._temp.collections : {};
	var collections_loaded = false;
	for (var key in collections) {
		if (collections.hasOwnProperty(key)) {
			collections_loaded = true;
			var collection = collections[key];
			var arr = scheduler.serverList[key];
			if (!arr) continue;
			arr.splice(0, arr.length); //clear old options
			for (var j = 0; j < collection.length; j++) {
				var option = collection[j];
				var obj = { key: option.value, label: option.label }; // resulting option object
				for (var option_key in option) {
					if (option.hasOwnProperty(option_key)) {
						if (option_key == "value" || option_key == "label")
							continue;
						obj[option_key] = option[option_key]; // obj['value'] = option['value']
					}
				}
				arr.push(obj);
			}
		}
	}
	if (collections_loaded)
		scheduler.callEvent("onOptionsLoad", []);

	var evs = [];
	for (var i = 0; i < data.length; i++) {
		var event = data[i];
		scheduler._init_event(event);
		evs.push(event);
	}
	return evs;
};
scheduler.parse = function(data, type) {
	this._process = type;
	this.on_load({xmlDoc: {responseText: data}});
};
scheduler.load = function(url, call) {
	if (typeof call == "string") {
		this._process = call;
		call = arguments[2];
	}

	this._load_url = url;
	this._after_call = call;
	this._load(url, this._date);
};
//possible values - day,week,month,year,all
scheduler.setLoadMode = function(mode) {
	if (mode == "all") mode = "";
	this._load_mode = mode;
};

scheduler.serverList = function(name, array) {
	if (array) {
		this.serverList[name] = array.slice(0);
		return this.serverList[name];
	}
	this.serverList[name] = (this.serverList[name] || []);
	return this.serverList[name];
};
scheduler._userdata = {};
scheduler._magic_parser = function(loader) {
	var xml;
	if (!loader.getXMLTopNode) { //from a string
		var xml_string = loader.xmlDoc.responseText;
		loader = new dtmlXMLLoaderObject(function() {});
		loader.loadXMLString(xml_string);
	}

	xml = loader.getXMLTopNode("data");
	if (xml.tagName != "data") return null;//not an xml
	var skey = xml.getAttribute("dhx_security");
	if (skey)
		dhtmlx.security_key = skey;

	var opts = loader.doXPath("//coll_options");
	for (var i = 0; i < opts.length; i++) {
		var bind = opts[i].getAttribute("for");
		var arr = this.serverList[bind];
		if (!arr) continue;
		arr.splice(0, arr.length);	//clear old options
		var itms = loader.doXPath(".//item", opts[i]);
		for (var j = 0; j < itms.length; j++) {
			var itm = itms[j];
			var attrs = itm.attributes;
			var obj = { key: itms[j].getAttribute("value"), label: itms[j].getAttribute("label")};
			for (var k = 0; k < attrs.length; k++) {
				var attr = attrs[k];
				if (attr.nodeName == "value" || attr.nodeName == "label")
					continue;
				obj[attr.nodeName] = attr.nodeValue;
			}
			arr.push(obj);
		}
	}
	if (opts.length)
		scheduler.callEvent("onOptionsLoad", []);

	var ud = loader.doXPath("//userdata");
	for (var i = 0; i < ud.length; i++) {
		var udx = this._xmlNodeToJSON(ud[i]);
		this._userdata[udx.name] = udx.text;
	}

	var evs = [];
	xml = loader.doXPath("//event");

	for (var i = 0; i < xml.length; i++) {
		var ev = evs[i] = this._xmlNodeToJSON(xml[i]);
		scheduler._init_event(ev);
	}
	return evs;
};
scheduler._xmlNodeToJSON = function(node) {
	var t = {};
	for (var i = 0; i < node.attributes.length; i++)
		t[node.attributes[i].name] = node.attributes[i].value;

	for (var i = 0; i < node.childNodes.length; i++) {
		var child = node.childNodes[i];
		if (child.nodeType == 1)
			t[child.tagName] = child.firstChild ? child.firstChild.nodeValue : "";
	}

	if (!t.text) t.text = node.firstChild ? node.firstChild.nodeValue : "";

	return t;
};
scheduler.attachEvent("onXLS", function() {
	if (this.config.show_loading === true) {
		var t;
		t = this.config.show_loading = document.createElement("DIV");
		t.className = 'dhx_loading';
		t.style.left = Math.round((this._x - 128) / 2) + "px";
		t.style.top = Math.round((this._y - 15) / 2) + "px";
		this._obj.appendChild(t);
	}
});
scheduler.attachEvent("onXLE", function() {
	var t = this.config.show_loading;
	if (t && typeof t == "object") {
			this._obj.removeChild(t);
			this.config.show_loading = true;
		}
});

scheduler.ical={
	parse:function(str){
		var data = str.match(RegExp(this.c_start+"[^\f]*"+this.c_end,""));
		if (!data.length) return;

		//unfolding
		data[0]=data[0].replace(/[\r\n]+(?=[a-z \t])/g," ");
		//drop property
		data[0]=data[0].replace(/\;[^:\r\n]*:/g,":");


		var incoming=[];
		var match;
		var event_r = RegExp("(?:"+this.e_start+")([^\f]*?)(?:"+this.e_end+")","g");
		while ((match=event_r.exec(data)) !== null){
			var e={};
			var param;
			var param_r = /[^\r\n]+[\r\n]+/g;
			while ((param=param_r.exec(match[1])) !== null)
				this.parse_param(param.toString(),e);
			if (e.uid && !e.id) e.id = e.uid; //fallback to UID, when ID is not defined
			incoming.push(e);
		}
		return incoming;
	},
	parse_param:function(str,obj){
		var d = str.indexOf(":");
			if (d==-1) return;

		var name = str.substr(0,d).toLowerCase();
		var value = str.substr(d+1).replace(/\\\,/g,",").replace(/[\r\n]+$/,"");
		if (name=="summary")
			name="text";
		else if (name=="dtstart"){
			name = "start_date";
			value = this.parse_date(value,0,0);
		}
		else if (name=="dtend"){
			name = "end_date";
			value = this.parse_date(value,0,0);
		}
		obj[name]=value;
	},
	parse_date:function(value,dh,dm){
		var t = value.split("T");
		if (t[1]){
			dh=t[1].substr(0,2);
			dm=t[1].substr(2,2);
		}
		var dy = t[0].substr(0,4);
		var dn = parseInt(t[0].substr(4,2),10)-1;
		var dd = t[0].substr(6,2);
		if (scheduler.config.server_utc && !t[1]) { // if no hours/minutes were specified == full day event
			return new Date(Date.UTC(dy,dn,dd,dh,dm)) ;
		}
		return new Date(dy,dn,dd,dh,dm);
	},
	c_start:"BEGIN:VCALENDAR",
	e_start:"BEGIN:VEVENT",
	e_end:"END:VEVENT",
	c_end:"END:VCALENDAR"
};
scheduler._lightbox_controls = {};
scheduler.formSection = function(name){
	var config = this.config.lightbox.sections;
	var i =0;
	for (i; i < config.length; i++)
		if (config[i].name == name)
			break;
	var section = config[i];
	if (!scheduler._lightbox)
		scheduler.getLightbox();
	var header = document.getElementById(section.id);
	var node = header.nextSibling;

	var result = {
		section: section,
		header: header,
		node: node,
		getValue:function(ev){
			return scheduler.form_blocks[section.type].get_value(node, (ev||{}), section);
		},
		setValue:function(value, ev){
			return scheduler.form_blocks[section.type].set_value(node, value, (ev||{}), section);
		}
	};

	var handler = scheduler._lightbox_controls["get_"+section.type+"_control"];
	return handler?handler(result):result;
};
scheduler._lightbox_controls.get_template_control = function(result) {
	result.control = result.node;
	return result;
};
scheduler._lightbox_controls.get_select_control = function(result) {
	result.control = result.node.getElementsByTagName('select')[0];
	return result;
};
scheduler._lightbox_controls.get_textarea_control = function(result) {
	result.control = result.node.getElementsByTagName('textarea')[0];
	return result;
};
scheduler._lightbox_controls.get_time_control = function(result) {
	result.control = result.node.getElementsByTagName('select'); // array
	return result;
};
scheduler.form_blocks={
	template:{
			render: function(sns){
			var height=(sns.height||"30")+"px";
			return "<div class='dhx_cal_ltext dhx_cal_template' style='height:"+height+";'></div>";
		},
		set_value:function(node,value,ev,config){
			node.innerHTML = value||"";
		},
		get_value:function(node,ev,config){
			return node.innerHTML||"";
		},
		focus: function(node){
		}
	},
	textarea:{
		render:function(sns){
			var height=(sns.height||"130")+"px";
			return "<div class='dhx_cal_ltext' style='height:"+height+";'><textarea></textarea></div>";
		},
		set_value:function(node,value,ev){
			scheduler.form_blocks.textarea._get_input(node).value=value||"";
		},
		get_value:function(node,ev){
			return scheduler.form_blocks.textarea._get_input(node).value;
		},
		focus:function(node){
			var a = scheduler.form_blocks.textarea._get_input(node);
			scheduler._focus(a, true);
		},
		_get_input: function(node){
			return node.getElementsByTagName("textarea")[0];
		}
	},
	select:{
		render:function(sns){
			var height=(sns.height||"23")+"px";
			var html="<div class='dhx_cal_ltext' style='height:"+height+";'><select style='width:100%;'>";
			for (var i=0; i < sns.options.length; i++)
				html+="<option value='"+sns.options[i].key+"'>"+sns.options[i].label+"</option>";
			html+="</select></div>";
			return html;
		},
		set_value:function(node,value,ev,sns){
			var select = node.firstChild;
			if (!select._dhx_onchange && sns.onchange) {
				select.onchange = sns.onchange;
				select._dhx_onchange = true;
			}
			if (typeof value == "undefined")
				value = (select.options[0]||{}).value;
			select.value=value||"";
		},
		get_value:function(node,ev){
			return node.firstChild.value;
		},
		focus:function(node){
			var a=node.firstChild; scheduler._focus(a, true);
		}
	},
	time:{
		render:function(sns) {
			if (!sns.time_format) {
				// default order
				sns.time_format = ["%H:%i", "%d", "%m", "%Y"];
			}
			// map: default order => real one
			sns._time_format_order = {};
			var time_format = sns.time_format;

			var cfg = scheduler.config;
			var dt = this.date.date_part(scheduler._currentDate());
			var last = 24*60, first = 0;
			if(scheduler.config.limit_time_select){
				last = 60*cfg.last_hour+1;
				first = 60*cfg.first_hour;
				dt.setHours(cfg.first_hour);
			}
			var html = "";

			for (var p = 0; p < time_format.length; p++) {
				var time_option = time_format[p];

				// adding spaces between selects
				if (p > 0) {
					html += " ";
				}

				switch (time_option) {
					case "%Y":
						sns._time_format_order[3] = p;
						//year
						html+="<select>";
						var year = dt.getFullYear()-5; //maybe take from config?
						for (var i=0; i < 10; i++)
							html+="<option value='"+(year+i)+"'>"+(year+i)+"</option>";
						html+="</select> ";
						break;
					case "%m":
						sns._time_format_order[2] = p;
						//month
						html+="<select>";
						for (var i=0; i < 12; i++)
							html+="<option value='"+i+"'>"+this.locale.date.month_full[i]+"</option>";
						html += "</select>";
						break;
					case "%d":
						sns._time_format_order[1] = p;
						//days
						html+="<select>";
						for (var i=1; i < 32; i++)
							html+="<option value='"+i+"'>"+i+"</option>";
						html += "</select>";
						break;
					case "%H:%i":
						sns._time_format_order[0] = p;
						//hours
						html += "<select>";
						var i = first;
						var tdate = dt.getDate();
						sns._time_values = [];

						while(i<last){
							var time=this.templates.time_picker(dt);
							html+="<option value='"+i+"'>"+time+"</option>";
							sns._time_values.push(i);
							dt.setTime(dt.valueOf()+this.config.time_step*60*1000);
							var diff = (dt.getDate()!=tdate)?1:0; // moved or not to the next day
							i=diff*24*60+dt.getHours()*60+dt.getMinutes();
						}
						html += "</select>";
						break;
				}
			}

			return "<div style='height:30px;padding-top:0px;font-size:inherit;' class='dhx_section_time'>"+html+"<span style='font-weight:normal; font-size:10pt;'> &nbsp;&ndash;&nbsp; </span>"+html+"</div>";
		},
		set_value:function(node,value,ev,config){
			var cfg = scheduler.config;
			var s=node.getElementsByTagName("select");
			var map = config._time_format_order;
			var start_date, end_date;

			if(cfg.full_day) {
				if (!node._full_day){
					var html = "<label class='dhx_fullday'><input type='checkbox' name='full_day' value='true'> "+scheduler.locale.labels.full_day+"&nbsp;</label></input>";
					if (!scheduler.config.wide_form)
						html = node.previousSibling.innerHTML+html;
					node.previousSibling.innerHTML=html;
					node._full_day=true;
				}
				var input=node.previousSibling.getElementsByTagName("input")[0];
				input.checked = (scheduler.date.time_part(ev.start_date)===0 && scheduler.date.time_part(ev.end_date)===0);

				s[map[0]].disabled=input.checked;
				s[ map[0] + s.length/2 ].disabled=input.checked;

				input.onclick = function(){
					if(input.checked) {
						var obj = {};
						scheduler.form_blocks.time.get_value(node,obj,config);

						start_date = scheduler.date.date_part(obj.start_date);
						end_date = scheduler.date.date_part(obj.end_date);

						if (+end_date == +start_date || (+end_date >= +start_date && (ev.end_date.getHours() !== 0 || ev.end_date.getMinutes() !== 0)))
							end_date = scheduler.date.add(end_date, 1, "day");
					}else{
						start_date = null;
						end_date = null;
					}

					s[map[0]].disabled=input.checked;
					s[ map[0] + s.length/2 ].disabled=input.checked;

					_fill_lightbox_select(s,0,start_date||ev.start_date);
					_fill_lightbox_select(s,4,end_date||ev.end_date);
				};
			}

			if(cfg.auto_end_date && cfg.event_duration) {
				var _update_lightbox_select = function () {
					start_date = new Date(s[map[3]].value,s[map[2]].value,s[map[1]].value,0,s[map[0]].value);
					end_date = new Date(start_date.getTime() + (scheduler.config.event_duration * 60 * 1000));
					_fill_lightbox_select(s, 4, end_date);
				};
				for(var i=0; i<4; i++) {
					s[i].onchange = _update_lightbox_select;
				}
			}

			function _fill_lightbox_select(s,i,d) {
				var time_values = config._time_values;
				var direct_value = d.getHours()*60+d.getMinutes();
				var fixed_value = direct_value;
				var value_found = false;
				for (var k=0; k<time_values.length; k++) {
					var t_v = time_values[k];
					if (t_v === direct_value) {
						value_found = true;
						break;
					}
					if (t_v < direct_value)
						fixed_value = t_v;
				}

				s[i+map[0]].value=(value_found)?direct_value:fixed_value;
				if(!(value_found || fixed_value)){
					s[i+map[0]].selectedIndex = -1;//show empty select in FF
				}
				s[i+map[1]].value=d.getDate();
				s[i+map[2]].value=d.getMonth();
				s[i+map[3]].value=d.getFullYear();
			}

			_fill_lightbox_select(s,0,ev.start_date);
			_fill_lightbox_select(s,4,ev.end_date);
		},
		get_value:function(node, ev, config) {
			var s = node.getElementsByTagName("select");
			var map = config._time_format_order;

			ev.start_date=new Date(s[map[3]].value,s[map[2]].value,s[map[1]].value,0,s[map[0]].value);
			ev.end_date=new Date(s[map[3]+4].value,s[map[2]+4].value,s[map[1]+4].value,0,s[map[0]+4].value);

			if(!(s[map[3]].value && s[map[3]+4].value)){
				// use the previous date if start/end years are empty (outside lightbox range)
				var original = this.getEvent(this._lightbox_id);
				if(original){
					ev.start_date = original.start_date;
					ev.end_date = original.end_date;
				}
			}

			if (ev.end_date<=ev.start_date)
				ev.end_date=scheduler.date.add(ev.start_date,scheduler.config.time_step,"minute");
			return {
				start_date: new Date(ev.start_date),
				end_date: new Date(ev.end_date)
			};
		},
		focus:function(node){
			scheduler._focus(node.getElementsByTagName("select")[0]);
		}
	}
};
scheduler.showCover=function(box){
	if (box){
		box.style.display="block";

		var scroll_top = window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop;
		var scroll_left = window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft;

		var view_height = window.innerHeight||document.documentElement.clientHeight;

		if(scroll_top) // if vertical scroll on window
			box.style.top=Math.round(scroll_top+Math.max((view_height-box.offsetHeight)/2, 0))+"px";
		else // vertical scroll on body
			box.style.top=Math.round(Math.max(((view_height-box.offsetHeight)/2), 0) + 9)+"px"; // +9 for compatibility with auto tests

		// not quite accurate but used for compatibility reasons
		if(document.documentElement.scrollWidth > document.body.offsetWidth) // if horizontal scroll on the window
			box.style.left=Math.round(scroll_left+(document.body.offsetWidth-box.offsetWidth)/2)+"px";
		else // horizontal scroll on the body
			box.style.left=Math.round((document.body.offsetWidth-box.offsetWidth)/2)+"px";
	}
    this.show_cover();
};
scheduler.showLightbox=function(id){
	if (!id) return;
	if (!this.callEvent("onBeforeLightbox",[id])) {
		if (this._new_event)
			this._new_event = null;
		return;
	}
	var box = this.getLightbox();
	this.showCover(box);
	this._fill_lightbox(id,box);
	this.callEvent("onLightbox",[id]);
};
scheduler._fill_lightbox = function(id, box) {
	var ev = this.getEvent(id);
	var s = box.getElementsByTagName("span");
	if (scheduler.templates.lightbox_header) {
		s[1].innerHTML = "";
		s[2].innerHTML = scheduler.templates.lightbox_header(ev.start_date, ev.end_date, ev);
	} else {
		s[1].innerHTML = this.templates.event_header(ev.start_date, ev.end_date, ev);
		s[2].innerHTML = (this.templates.event_bar_text(ev.start_date, ev.end_date, ev) || "").substr(0, 70); //IE6 fix
	}

	var sns = this.config.lightbox.sections;
	for (var i = 0; i < sns.length; i++) {
		var current_sns = sns[i];
		var node = document.getElementById(current_sns.id).nextSibling;
		var block = this.form_blocks[current_sns.type];
		var value = (ev[current_sns.map_to] !== undefined) ? ev[current_sns.map_to] : current_sns.default_value;
		block.set_value.call(this, node, value, ev, current_sns);
		if (sns[i].focus)
			block.focus.call(this, node);
	}

	scheduler._lightbox_id = id;
};
scheduler._lightbox_out=function(ev){
	var sns = this.config.lightbox.sections;
	for (var i=0; i < sns.length; i++) {
		var node = document.getElementById(sns[i].id);
		node=(node?node.nextSibling:node);
		var block=this.form_blocks[sns[i].type];
		var res=block.get_value.call(this,node,ev, sns[i]);
		if (sns[i].map_to!="auto")
			ev[sns[i].map_to]=res;
	}
	return ev;
};
scheduler._empty_lightbox=function(data){
	var id=scheduler._lightbox_id;
	var ev=this.getEvent(id);
	var box=this.getLightbox();

	this._lame_copy(ev, data);

	this.setEvent(ev.id,ev);
	this._edit_stop_event(ev,true);
	this.render_view_data();
};
scheduler.hide_lightbox=function(id){
	this.hideCover(this.getLightbox());
	this._lightbox_id = null;
	this.callEvent("onAfterLightbox",[]);
};
scheduler.hideCover=function(box){
	if (box) box.style.display="none";
	this.hide_cover();
};
scheduler.hide_cover=function(){
	if (this._cover)
		this._cover.parentNode.removeChild(this._cover);
	this._cover=null;
};
scheduler.show_cover=function(){
	if(this._cover)
		return;

	this._cover=document.createElement("DIV");
	this._cover.className="dhx_cal_cover";
	var _document_height = ((document.height !== undefined) ? document.height : document.body.offsetHeight);
	var _scroll_height = ((document.documentElement) ? document.documentElement.scrollHeight : 0);
	this._cover.style.height = Math.max(_document_height, _scroll_height) + 'px';
	document.body.appendChild(this._cover);
};
scheduler.save_lightbox=function(){
	var data = this._lightbox_out({}, this._lame_copy(this.getEvent(this._lightbox_id)));
	if (this.checkEvent("onEventSave") && !this.callEvent("onEventSave",[this._lightbox_id, data, this._new_event]))
		return;
	this._empty_lightbox(data);
	this.hide_lightbox();
};
scheduler.startLightbox = function(id, box){
	this._lightbox_id = id;
	this._custom_lightbox = true;

	this._temp_lightbox = this._lightbox;
	this._lightbox = box;
	this.showCover(box);
};
scheduler.endLightbox = function(mode, box){
	this._edit_stop_event(scheduler.getEvent(this._lightbox_id),mode);
	if (mode)
		scheduler.render_view_data();
	this.hideCover(box);

	if (this._custom_lightbox){
		this._lightbox = this._temp_lightbox;
		this._custom_lightbox = false;
	}
	this._temp_lightbox = this._lightbox_id = null; // in case of custom lightbox user only calls endLightbox so we need to reset _lightbox_id
};
scheduler.resetLightbox = function(){
	if (scheduler._lightbox && !scheduler._custom_lightbox)
		scheduler._lightbox.parentNode.removeChild(scheduler._lightbox);
	scheduler._lightbox = null;
};
scheduler.cancel_lightbox=function(){
	this.callEvent("onEventCancel",[this._lightbox_id, this._new_event]);
	this.endLightbox(false);
	this.hide_lightbox();
};
scheduler._init_lightbox_events=function(){
	this.getLightbox().onclick=function(e){
		var src=e?e.target:event.srcElement;
		if (!src.className) src=src.previousSibling;
		if (src && src.className)
			switch(src.className){
				case "dhx_save_btn":
					scheduler.save_lightbox();
					break;
				case "dhx_delete_btn":
					var c=scheduler.locale.labels.confirm_deleting;

					scheduler._dhtmlx_confirm(c, scheduler.locale.labels.title_confirm_deleting, function(){
						scheduler.deleteEvent(scheduler._lightbox_id);
						scheduler._new_event = null; //clear flag, if it was unsaved event
						scheduler.hide_lightbox();
					});

					break;
				case "dhx_cancel_btn":
					scheduler.cancel_lightbox();
					break;

				default:
					if (src.getAttribute("dhx_button")) {
						scheduler.callEvent("onLightboxButton", [src.className, src, e]);
					} else {
						var index, block, sec;
						if (src.className.indexOf("dhx_custom_button") != -1) {
							if (src.className.indexOf("dhx_custom_button_") != -1) {
								index = src.parentNode.getAttribute("index");
								sec = src.parentNode.parentNode;
							} else {
								index = src.getAttribute("index");
								sec = src.parentNode;
								src = src.firstChild;
							}
						}
						if (index) {
							block = scheduler.form_blocks[scheduler.config.lightbox.sections[index].type];
							block.button_click(index, src, sec, sec.nextSibling);
						}
					}
					break;
			}
	};
	this.getLightbox().onkeydown=function(e){
		switch((e||event).keyCode){
			case scheduler.keys.edit_save:
				if ((e||event).shiftKey) return;
				scheduler.save_lightbox();
				break;
			case scheduler.keys.edit_cancel:
				scheduler.cancel_lightbox();
				break;
			default:
				break;
		}
	};
};
scheduler.setLightboxSize=function(){
	var d = this._lightbox;
	if (!d) return;

	var con = d.childNodes[1];
	con.style.height="0px";
	con.style.height=con.scrollHeight+"px";
	d.style.height=con.scrollHeight+scheduler.xy.lightbox_additional_height+"px";
	con.style.height=con.scrollHeight+"px"; //it is incredible , how ugly IE can be
};

scheduler._init_dnd_events = function(){
	dhtmlxEvent(document.body, "mousemove", scheduler._move_while_dnd);
	dhtmlxEvent(document.body, "mouseup", scheduler._finish_dnd);
	scheduler._init_dnd_events = function(){};
};
scheduler._move_while_dnd = function(e){
	if (scheduler._dnd_start_lb){
		if (!document.dhx_unselectable){
			document.body.className += " dhx_unselectable";
			document.dhx_unselectable = true;
		}
		var lb = scheduler.getLightbox();
		var now = (e&&e.target)?[e.pageX, e.pageY]:[event.clientX, event.clientY];
		lb.style.top = scheduler._lb_start[1]+now[1]-scheduler._dnd_start_lb[1]+"px";
		lb.style.left = scheduler._lb_start[0]+now[0]-scheduler._dnd_start_lb[0]+"px";
	}
};
scheduler._ready_to_dnd = function(e){
	var lb = scheduler.getLightbox();
	scheduler._lb_start = [parseInt(lb.style.left,10), parseInt(lb.style.top,10)];
	scheduler._dnd_start_lb = (e&&e.target)?[e.pageX, e.pageY]:[event.clientX, event.clientY];
};
scheduler._finish_dnd = function(){
	if (scheduler._lb_start){
		scheduler._lb_start = scheduler._dnd_start_lb = false;
		document.body.className = document.body.className.replace(" dhx_unselectable","");
		document.dhx_unselectable = false;
	}
};
scheduler.getLightbox=function(){ //scheduler.config.wide_form=true;
	if (!this._lightbox){
		var d=document.createElement("DIV");
		d.className="dhx_cal_light";
		if (scheduler.config.wide_form)
			d.className+=" dhx_cal_light_wide";
		if (scheduler.form_blocks.recurring)
			d.className+=" dhx_cal_light_rec";

		if (/msie|MSIE 6/.test(navigator.userAgent))
			d.className+=" dhx_ie6";
		d.style.visibility="hidden";
		var html = this._lightbox_template;

		var buttons = this.config.buttons_left;
		for (var i = 0; i < buttons.length; i++)
			html+="<div class='dhx_btn_set dhx_left_btn_set "+buttons[i]+"_set'><div dhx_button='1' class='"+buttons[i]+"'></div><div>"+scheduler.locale.labels[buttons[i]]+"</div></div>";

		buttons = this.config.buttons_right;
		for (var i = 0; i < buttons.length; i++)
			html+="<div class='dhx_btn_set dhx_right_btn_set "+buttons[i]+"_set' style='float:right;'><div dhx_button='1' class='"+buttons[i]+"'></div><div>"+scheduler.locale.labels[buttons[i]]+"</div></div>";

		html+="</div>";
		d.innerHTML=html;
		if (scheduler.config.drag_lightbox){
			d.firstChild.onmousedown = scheduler._ready_to_dnd;
			d.firstChild.onselectstart = function(){ return false; };
			d.firstChild.style.cursor = "pointer";
			scheduler._init_dnd_events();

		}
		document.body.insertBefore(d,document.body.firstChild);
		this._lightbox=d;

		var sns=this.config.lightbox.sections;
		html="";
		for (var i=0; i < sns.length; i++) {
			var block=this.form_blocks[sns[i].type];
			if (!block) continue; //ignore incorrect blocks
			sns[i].id="area_"+this.uid();
			var button = "";
			if (sns[i].button){
			 	button = "<div class='dhx_custom_button' index='"+i+"'><div class='dhx_custom_button_"+sns[i].button+"'></div><div>"+this.locale.labels["button_"+sns[i].button]+"</div></div>";
			 }

			if (this.config.wide_form){
				html+="<div class='dhx_wrap_section'>";
			}

			var label_name = this.locale.labels["section_"+sns[i].name];
			if(typeof label_name !== "string"){
				label_name = sns[i].name;
			}
			html+="<div id='"+sns[i].id+"' class='dhx_cal_lsection'>"+button+label_name+"</div>"+block.render.call(this,sns[i]);
			html+="</div>";
		}

		var ds=d.getElementsByTagName("div");
		for (var i=0; i<ds.length; i++) {
			var t_ds = ds[i];
			if (t_ds.className == "dhx_cal_larea") {
				t_ds.innerHTML = html;
				break;
			}
		}

		//sizes
		this.setLightboxSize();

		this._init_lightbox_events(this);
		d.style.display="none";
		d.style.visibility="visible";
	}
	return this._lightbox;
};

scheduler.attachEvent("onEventIdChange", function(old_id, new_id){
	if(this._lightbox_id == old_id)
		this._lightbox_id = new_id;
});

scheduler._lightbox_template="<div class='dhx_cal_ltitle'><span class='dhx_mark'>&nbsp;</span><span class='dhx_time'></span><span class='dhx_title'></span></div><div class='dhx_cal_larea'></div>";

scheduler._init_touch_events = function(){
	if (this.config.touch != "force")
		this.config.touch = this.config.touch  &&
			    ( (navigator.userAgent.indexOf("Mobile")!=-1)   ||
				(navigator.userAgent.indexOf("iPad")!=-1)       ||
				(navigator.userAgent.indexOf("Android")!=-1)    ||
				(navigator.userAgent.indexOf("Touch")!=-1));

	if (this.config.touch){
		this.xy.scroll_width = 0;
		if (window.navigator.msPointerEnabled){
			this._touch_events(["MSPointerMove", "MSPointerDown", "MSPointerUp"], function(ev){
				if (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE ) return null;
				return ev;
			}, function(ev){
				return (!ev || ev.pointerType == ev.MSPOINTER_TYPE_MOUSE);
			});
			this._obj.ondblclick = function(){};
		} else
			this._touch_events(["touchmove", "touchstart", "touchend"], function(ev){
				if (ev.touches && ev.touches.length > 1) return null;
				if (ev.touches[0])
					return { target:ev.target, pageX:ev.touches[0].pageX, pageY:ev.touches[0].pageY };
				else
					return ev;
			}, function(){ return false; });
	}
};

scheduler._touch_events = function(names, accessor, ignore){
	//webkit on android need to be handled separately
	var a_webkit = (navigator.userAgent.indexOf("Android")!=-1) && (navigator.userAgent.indexOf("WebKit")!=-1);
	var source, tracker, timer, drag_mode, scroll_mode, action_mode;
	var dblclicktime = 0;

	function attachTouchEvent(element, name, callback){
		//touch gestures must be disabled when ligthbox is opened
		dhtmlxEvent(element, name, function(e){
			if(scheduler._is_lightbox_open()){
				return true;
			}else{
				return callback(e);
			}
		});
	}

	function check_direction_swipe(s_ev, e_ev, step, max_dy){
		if (!s_ev || !e_ev) return;

		var t = s_ev.target;
		while(t && t != scheduler._obj){
			t = t.parentNode;
		}
		if(t != scheduler._obj){
			//swipe outside scheduler
			return;
		}

		var dy = Math.abs(s_ev.pageY - e_ev.pageY);
		var dx = Math.abs(s_ev.pageX - e_ev.pageX);
		if (dy < max_dy && dx>step && (!dy || (dx/dy > 3))){
			if (s_ev.pageX > e_ev.pageX)
				scheduler._click.dhx_cal_next_button();
			else
				scheduler._click.dhx_cal_prev_button();
		}
	}

	function doMouseMove(e){
		var dnd = scheduler.getState().drag_mode,
			timeline = scheduler.matrix ? scheduler.matrix[scheduler._mode] : false;

		var original_render = scheduler.render_view_data;
		if(dnd == 'create' && timeline){
			//suppress full redraw of timeline on creating event
			scheduler.render_view_data = function() {
				var id = scheduler.getState().drag_id;
				var ev = scheduler.getEvent(id);
				var property = timeline.y_property;

				var evs = scheduler.getEvents(ev.start_date, ev.end_date);
				for(var i = 0; i < evs.length; i++){
					if(evs[i][property] != ev[property]){
						evs.splice(i, 1);
						i--;
					}
				}
				ev._sorder = evs.length - 1;
				ev._count = evs.length;

				this.render_data([ev], scheduler.getState().mode);

			};
		}

		scheduler._on_mouse_move(e);

		if(dnd == 'create' && timeline){
			scheduler.render_view_data = original_render;
		}
	}
	attachTouchEvent(document.body, names[0], function(e){
		if (ignore(e)) return;

		if (drag_mode){
			doMouseMove(accessor(e));
			scheduler._update_global_tip();
			if (e.preventDefault)
				e.preventDefault();
			e.cancelBubble = true;
			return false;
		}

		//if (tracker && a_webkit){
		//	check_direction_swipe(tracker, accessor(e), 0);
		//}

		tracker = accessor(e);
		//ignore common and scrolling moves
		if (!action_mode) return;

		//multitouch
		if (!tracker){
			scroll_mode = true;
			return;
		}

		//target changed - probably in scroll mode

		if (source.target != tracker.target || (Math.abs(source.pageX - tracker.pageX) > 5) || (Math.abs(source.pageY - tracker.pageY) > 5)){
			scroll_mode = true;
			clearTimeout(timer);
		}

	});

	attachTouchEvent(this._els["dhx_cal_data"][0], "scroll", drag_cancel);
	attachTouchEvent(this._els["dhx_cal_data"][0], "touchcancel", drag_cancel);
	attachTouchEvent(this._els["dhx_cal_data"][0], "contextmenu", function(e){
		if (action_mode){
			if (e && e.preventDefault)
				e.preventDefault();
			(e||event).cancelBubble = true;
			return false;
		}
	});
	attachTouchEvent(this._obj, names[1], function(e){
		if (ignore(e)) return;

		var fake_event;
		drag_mode = scroll_mode = false;
		action_mode = true;
		scheduler._temp_touch_block = true;
		fake_event = tracker = accessor(e);

		if (!fake_event){
			scroll_mode = true;
			return;
		}

		//dbl click
		var now = new Date();

		if (!scroll_mode && !drag_mode && now - dblclicktime < 250){
			scheduler._click.dhx_cal_data(fake_event);
			window.setTimeout(function(){
				scheduler._on_dbl_click(fake_event);
			}, 50);

			if (e.preventDefault)
				e.preventDefault();
			e.cancelBubble = true;
			scheduler._block_next_stop = true;
			return false;
		}
		dblclicktime = now;

		//drag

		if (scroll_mode || drag_mode || !scheduler.config.touch_drag)
			return;

		var actTask = scheduler._locate_event(document.activeElement);
		var fakeTask = scheduler._locate_event(fake_event.target);
		var sourceTask = source? scheduler._locate_event(source.target) : null;

		if(actTask && fakeTask && actTask == fakeTask && actTask != sourceTask)
		{
			if(e.preventDefault) {
				e.preventDefault();
			}
			e.cancelBubble = true;
			scheduler._ignore_next_click = false;
			scheduler._click.dhx_cal_data(fake_event);
			source = fake_event;
			return false;
		}

		//there is no target
		timer = setTimeout(function(){

			drag_mode = true;
			var target = source.target;
			if (target && target.className && target.className.indexOf("dhx_body") != -1)
				target = target.previousSibling;

			scheduler._on_mouse_down(source, target);
			if (scheduler._drag_mode && scheduler._drag_mode != "create"){
				//var pos = -1;
				scheduler.for_rendered(scheduler._drag_id, function(node, i) {
				//	pos = node.getBoundingClientRect().top;
					node.style.display='none';
					scheduler._rendered.splice(i, 1);
				});
				/*if (pos>=0){
					var step = scheduler.config.time_step;
					scheduler._move_pos_shift = step* Math.round((fake_event.pageY - pos)*60/(scheduler.config.hour_size_px*step));
				}*/
			}

			if (scheduler.config.touch_tip)
				scheduler._show_global_tip();
			scheduler.updateEvent(scheduler._drag_id);
		},scheduler.config.touch_drag);

		source = fake_event;
	});
	function drag_cancel(e){
		scheduler._hide_global_tip();
		if (drag_mode){
			scheduler._on_mouse_up( accessor(e||event) );
			scheduler._temp_touch_block = false;
		}
		scheduler._drag_id = null;
		scheduler._drag_mode=null;
		scheduler._drag_pos=null;

		clearTimeout(timer);
		drag_mode = action_mode = false;
		scroll_mode = true;
	}
	attachTouchEvent(this._els["dhx_cal_data"][0], names[2], function(e){
		if (ignore(e)) return;

		if (!drag_mode)
			check_direction_swipe(source, tracker, 200, 100);

		if (drag_mode)
			scheduler._ignore_next_click = true;

		drag_cancel(e);
		if (scheduler._block_next_stop){
			scheduler._block_next_stop = false;
			if (e.preventDefault)
				e.preventDefault();
			e.cancelBubble = true;
			return false;
		}
	});

	dhtmlxEvent(document.body, names[2], drag_cancel);
};

scheduler._show_global_tip = function(){
	scheduler._hide_global_tip();

	var toptip = scheduler._global_tip = document.createElement("DIV");
	toptip.className='dhx_global_tip';

	scheduler._update_global_tip(1);

	document.body.appendChild(toptip);
};
scheduler._update_global_tip = function(init){
	var toptip = scheduler._global_tip;
	if (toptip){
		var time = "";
		if (scheduler._drag_id && !init){
			var ev = scheduler.getEvent(scheduler._drag_id);
			if (ev)
				time = "<div>" + (ev._timed ? scheduler.templates.event_header(ev.start_date, ev.end_date, ev):scheduler.templates.day_date(ev.start_date, ev.end_date, ev)) + "</div>";
		}

		if (scheduler._drag_mode == "create" || scheduler._drag_mode == "new-size")
			toptip.innerHTML = (scheduler.locale.labels.drag_to_create || "Drag to create")+time;
		else
			toptip.innerHTML = (scheduler.locale.labels.drag_to_move || "Drag to move")+time;
	}
};
scheduler._hide_global_tip = function(){
	var toptip = scheduler._global_tip;
	if (toptip && toptip.parentNode){
		toptip.parentNode.removeChild(toptip);
		scheduler._global_tip = 0;
	}
};

scheduler._dp_init=function(dp){
	dp._methods=["_set_event_text_style","","_dp_change_event_id","_dp_hook_delete"];

	this._dp_change_event_id = function(id, new_id){
		if(!scheduler.getEvent(id))
			return;

		scheduler.changeEventId(id, new_id);
	};

	this._dp_hook_delete = function(id, new_id){
		if(!scheduler.getEvent(id))
			return;

		if(id != new_id){
			if(this.getUserData(id, dp.action_param) == "true_deleted")
				this.setUserData(id, dp.action_param, "updated");

			this.changeEventId(id, new_id);
		}
		return this.deleteEvent(new_id, true);
	};
	this.attachEvent("onEventAdded",function(id){
		if (!this._loading && this._validId(id))
			dp.setUpdated(id,true,"inserted");
	});
	this.attachEvent("onConfirmedBeforeEventDelete", function(id){
		if (!this._validId(id)) return;
		var z=dp.getState(id);

		if (z=="inserted" || this._new_event) {  dp.setUpdated(id,false);		return true; }
		if (z=="deleted")  return false;
    	if (z=="true_deleted")  return true;

		dp.setUpdated(id,true,"deleted");
      	return false;
	});
	this.attachEvent("onEventChanged",function(id){
		if (!this._loading && this._validId(id))
			dp.setUpdated(id,true,"updated");
	});

	scheduler.attachEvent("onClearAll", function(){
		// clear dataprocessor state when scheduler is reset
		dp._in_progress={};
		dp._invalid={};
		dp.updatedRows = [];
		dp._waitMode = 0;
	});

	dp._objToJson = function(obj, data, prefix){
		prefix = prefix || "";
		data = data || {};

		for (var a in obj){
			if (a.indexOf("_") === 0) continue;
			if (obj[a] && obj[a].getUTCFullYear) //not very good, but will work
				data[prefix+a] = this.obj.templates.xml_format(obj[a]);
			else {
				if (obj[a] && typeof obj[a] == "object")
					dp._objToJson(obj[a], data, prefix+a+".");
				else
					data[prefix+a] = obj[a];
			}
		}

		return data;
	};
	dp._getRowData=function(id,pref){
		var ev=this.obj.getEvent(id);
		return this._objToJson(ev);
	};
	dp._clearUpdateFlag=function(){};

	dp.attachEvent("insertCallback", scheduler._update_callback);
	dp.attachEvent("updateCallback", scheduler._update_callback);
	dp.attachEvent("deleteCallback", function(upd, id) {
		if (this.obj.getEvent(id)){
			this.obj.setUserData(id, this.action_param, "true_deleted");
			this.obj.deleteEvent(id);
		} else if (this.obj._add_rec_marker)
			this.obj._update_callback(upd, id);
	});

};

scheduler._validId=function(id){
	return true;
};

scheduler.setUserData=function(id,name,value){
	if (id){
		var ev = this.getEvent(id);
		if(ev) ev[name]=value;
	}else{
		this._userdata[name]=value;
	}
};
scheduler.getUserData=function(id,name){
	if (id){
		var ev = this.getEvent(id);
		if(ev)
			return ev[name];
		else
			return null;
	}else{
		return this._userdata[name];
	}
};
scheduler._set_event_text_style=function(id,style){
	if(!scheduler.getEvent(id))
		return;

	this.for_rendered(id,function(r){
		r.style.cssText+=";"+style;
	});
	var ev = this.getEvent(id);
	ev["_text_style"]=style;
	this.event_updated(ev);
};

scheduler._update_callback = function(upd,id){
	var data		=	scheduler._xmlNodeToJSON(upd.firstChild);

	//fix for updates of recurring events
	if (data.rec_type == "none") data.rec_pattern = "none";
	data.text		=	data.text||data._tagvalue;
	data.start_date	=	scheduler.templates.xml_date(data.start_date);
	data.end_date	=	scheduler.templates.xml_date(data.end_date);

	scheduler.addEvent(data);
	if (scheduler._add_rec_marker)
		scheduler.setCurrentView();
};
scheduler._skin_settings = {
	fix_tab_position: [1,0],
	use_select_menu_space: [1,0],
	wide_form: [1,0],

	hour_size_px: [44,42],
	displayed_event_color: ["#ff4a4a", "ffc5ab"],
	displayed_event_text_color: ["#ffef80", "7e2727"]
};

scheduler._skin_xy = {
	lightbox_additional_height: [90,50],
	nav_height: [59,22],
	bar_height: [24,20]
};

scheduler._configure = function(col, data, skin){
	for (var key in data)
		if (typeof col[key] == "undefined")
			col[key] = data[key][skin];
};
scheduler._skin_init = function(){
	if (!scheduler.skin){
		var links = document.getElementsByTagName("link");
		for (var i = 0; i < links.length; i++) {
			var res = links[i].href.match("dhtmlxscheduler_([a-z]+).css");
			if (res){
				scheduler.skin = res[1];
				break;
			}
		}
	}



	var set = 0;
	if (scheduler.skin && (scheduler.skin === "classic" || scheduler.skin === "glossy")) set = 1;

	//apply skin related settings
	this._configure(scheduler.config, scheduler._skin_settings, set);
	this._configure(scheduler.xy, scheduler._skin_xy, set);

	if (scheduler.skin === "flat"){
		scheduler.xy.scale_height = 35;
		scheduler.templates.hour_scale = function(date){
			var min = date.getMinutes();
			min = min < 10 ? "0"+min : min;
			var html = "<span class='dhx_scale_h'>"+ date.getHours() +"</span>"+
				"<span class='dhx_scale_m'>&nbsp;"+ min +"</span>";
			return html;
		};
	}

	//classic skin need not any further customization
	if (set) return;


	var minic = scheduler.config.minicalendar;
	if (minic) minic.padding = 14;

	scheduler.templates.event_bar_date = function(start,end,ev) {
		return "• <b>"+scheduler.templates.event_date(start)+"</b> ";
	};

	//scheduler._lightbox_template="<div class='dhx_cal_ltitle'><span class='dhx_mark'>&nbsp;</span><span class='dhx_time'></span><span class='dhx_title'></span><div class='dhx_close_icon'></div></div><div class='dhx_cal_larea'></div>";
	scheduler.attachEvent("onTemplatesReady", function() {

		var date_to_str = scheduler.date.date_to_str("%d");
		if(!scheduler.templates._old_month_day){
			scheduler.templates._old_month_day = scheduler.templates.month_day;
		}
		var old_month_day = scheduler.templates._old_month_day;
		scheduler.templates.month_day = function(date) {
			if (this._mode == "month") {
				var label = date_to_str(date);
				if (date.getDate() == 1) {
					label = scheduler.locale.date.month_full[date.getMonth()] + " " + label;
				}
				if (+date == +scheduler.date.date_part(new Date())) {
					label = scheduler.locale.labels.dhx_cal_today_button + " " + label;
				}
				return label;
			} else {
				return old_month_day.call(this, date);
			}
		};


		if (scheduler.config.fix_tab_position){
			var navline_divs = scheduler._els["dhx_cal_navline"][0].getElementsByTagName('div');
			var minical = null;
			var tabs = [];
			var last = 211;
			for (var i=0; i<navline_divs.length; i++) {
				var div = navline_divs[i];
				var name = div.getAttribute("name");
				if (name) { // mode tab
					div.style.right = "auto";
					switch (name) {
						case "day_tab":
							div.style.left = "14px";
							div.className += " dhx_cal_tab_first";
							break;
						case "week_tab":
							div.style.left = "75px";
							break;
						case "month_tab":
							div.style.left = "136px";
							div.className += " dhx_cal_tab_last";
							break;
						default:
							div.style.left = last+"px";
							div.className += " dhx_cal_tab_standalone";
							last = last + 14 + div.offsetWidth;
							break;
					}
				}else{
					if((div.className || "").indexOf("dhx_minical_icon") === 0 &&
						div.parentNode == scheduler._els["dhx_cal_navline"][0]){
						// if default minicalendar icon
						minical = div;
					}
				}

			}

			if(minical){
				minical.style.left = last+"px";
			}
		}

	});
	scheduler._skin_init = function(){};
};


if (window.jQuery){

(function( $ ){

	var methods = [];
	$.fn.dhx_scheduler = function(config){
		if (typeof(config) === 'string') {
			if (methods[config] ) {
				return methods[config].apply(this, []);
			}else {
				$.error('Method ' +  config + ' does not exist on jQuery.dhx_scheduler');
			}
		} else {
			var views = [];
			this.each(function() {
				if (this && this.getAttribute){
					if (!this.getAttribute("dhxscheduler")){
						for (var key in config)
							if (key!="data")
								scheduler.config[key] = config[key];

						if (!this.getElementsByTagName("div").length){
							this.innerHTML = '<div class="dhx_cal_navline"><div class="dhx_cal_prev_button">&nbsp;</div><div class="dhx_cal_next_button">&nbsp;</div><div class="dhx_cal_today_button"></div><div class="dhx_cal_date"></div><div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div><div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div><div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div></div><div class="dhx_cal_header"></div><div class="dhx_cal_data"></div>';
							this.className += " dhx_cal_container";
						}
						scheduler.init(this, scheduler.config.date, scheduler.config.mode);
						if (config.data)
							scheduler.parse(config.data);

						views.push(scheduler);
					}
				}
			});

			if (views.length === 1) return views[0];
			return views;
		}
	};




})(jQuery);

}
(function(){

	var setCurrentView = scheduler.setCurrentView,
		updateView = scheduler.updateView;
	var update_view_timer = null,
		curr_view_timer = null;

	var lazy_setCurrentView = function(date, mode){
		var self = this;
		window.clearTimeout(curr_view_timer);
		window.clearTimeout(update_view_timer);

		updateFlags(this, date, mode);

		curr_view_timer = setTimeout(function(){

			if (!self.callEvent("onBeforeViewChange", [self._mode, self._date, mode || self._mode, date || self._date])) return;
			updateView.call(self, date, mode);
			self.callEvent("onViewChange", [self._mode, self._date]);

			window.clearTimeout(update_view_timer);
			curr_view_timer = 0;
		}, scheduler.config.delay_render);
	};
	var lazy_updateView = function(date, mode){
		var self = this,
			ars = arguments;

		updateFlags(this, date, mode);

		window.clearTimeout(update_view_timer);
		update_view_timer = setTimeout(function(){
			if(curr_view_timer)
				return;

			updateView.apply(self, ars);
		}, scheduler.config.delay_render);
	};
	function updateFlags(scheduler, date, mode){
		if(date)
			scheduler._date = date;
		if(mode)
			scheduler._mode = mode;

	}
	scheduler.attachEvent("onSchedulerReady", function(){
		if(scheduler.config.delay_render){
			scheduler.setCurrentView = lazy_setCurrentView;
			scheduler.updateView = lazy_updateView;
		}else{
			scheduler.setCurrentView = setCurrentView;
			scheduler.updateView = updateView;
		}
	});

})();
/*
@license
dhtmlxScheduler v.4.3.28 Professional

This software is covered by DHTMLX Commercial License. Usage without proper license is prohibited.

(c) Dinamenta, UAB.
*/

(function(){

	scheduler.config.all_timed = "short";

	var is_event_short = function (ev) {
		return 	!((ev.end_date - ev.start_date)/(1000*60*60) >= 24);
	};

	// copy of usual events and recurring instances;
	// regular copy causes problems with recurrings which have series event as a prototype
	scheduler._safe_copy = function(event){
		var proto = null,
			copy = null;
		if(event.event_pid){
			proto = scheduler.getEvent(event.event_pid);
		}

		if (proto && proto.isPrototypeOf(event)) {
			copy = scheduler._copy_event(event);
			delete copy.event_length;
			delete copy.event_pid;
			delete copy.rec_pattern;
			delete copy.rec_type;
		} else {
			copy = scheduler._lame_clone(event);
		}
		return copy;
	};

	var old_prerender_events_line = scheduler._pre_render_events_line;
	scheduler._pre_render_events_line = function(evs, hold){
		if (!this.config.all_timed)
			return old_prerender_events_line.call(this, evs, hold);

		for (var i=0; i < evs.length; i++) {
			var ev=evs[i];

			if (ev._timed)
				continue;

			if (this.config.all_timed == "short") {
				if (!is_event_short(ev)) {
					evs.splice(i--,1);
					continue;
				}
			}

			var ce = this._safe_copy(ev); // current event (event for one specific day) is copy of original with modified dates

			ce.start_date = new Date(ce.start_date); // as lame copy doesn't copy date objects

			if (!isOvernightEvent(ev)) {
				ce.end_date = new Date(ev.end_date);
			}
			else {
				ce.end_date = getNextDay(ce.start_date);
				if (this.config.last_hour != 24) { // if specific last_hour was set (e.g. 20)
					ce.end_date = setDateTime(ce.start_date, this.config.last_hour);
				}
			}

			var event_changed = false;
			if (ce.start_date < this._max_date && ce.end_date > this._min_date && ce.start_date < ce.end_date) {
				evs[i] = ce; // adding another event in collection
				event_changed = true;
			}
		//	if (ce.start_date > ce.end_date) {
		//		evs.splice(i--,1);
		//	}

			var re = this._safe_copy(ev); // remaining event, copy of original with modified start_date (making range more narrow)
			re.end_date = new Date(re.end_date);
			if (re.start_date < this._min_date)
				re.start_date = setDateTime(this._min_date, this.config.first_hour);// as we are starting only with whole hours
			else
				re.start_date = setDateTime(getNextDay(ev.start_date), this.config.first_hour);

			if (re.start_date < this._max_date && re.start_date < re.end_date) {
				if (event_changed)
					evs.splice(i+1,0,re);//insert part
				else {
					evs[i--] = re;
					continue;
				}
			}

		}
		// in case of all_timed pre_render is not applied to the original event
		// so we need to force redraw in case of dnd
		var redraw = (this._drag_mode == 'move')?false:hold;
		return old_prerender_events_line.call(this, evs, redraw);


		function isOvernightEvent(ev){
			var next_day = getNextDay(ev.start_date);
			return (+ev.end_date > +next_day);
		}
		function getNextDay(date){
			var next_day = scheduler.date.add(date, 1, "day");
			next_day = scheduler.date.date_part(next_day);
			return next_day;
		}
		function setDateTime(date, hours){
			var val = scheduler.date.date_part(new Date(date));
			val.setHours(hours);
			return val;
		}
	};
	var old_get_visible_events = scheduler.get_visible_events;
	scheduler.get_visible_events = function(only_timed){
		if (!(this.config.all_timed && this.config.multi_day))
			return old_get_visible_events.call(this, only_timed);	
		return old_get_visible_events.call(this, false); // only timed = false
	};
	scheduler.attachEvent("onBeforeViewChange", function (old_mode, old_date, mode, date) {
		scheduler._allow_dnd = (mode == "day" || mode == "week");
		return true;
	});

	scheduler._is_main_area_event = function(ev){
		return !!(ev._timed || this.config.all_timed === true || (this.config.all_timed == "short" && is_event_short(ev)) );
	};

	var oldUpdate = scheduler.updateEvent;
	scheduler.updateEvent = function(id){
		// full redraw(update_render=true) messes events order while dnd.
		// individual redraw(update_render=false) of multiday event, which happens on select/unselect, expands event to full width of the cell and can be fixes only with full redraw.
		// so for now full redraw is always enabled for not-dnd updates
		var fullRedrawNeeded = (scheduler.config.all_timed && !(scheduler.isOneDayEvent(scheduler._events[id]) || scheduler.getState().drag_id));
		var initial;
		if(fullRedrawNeeded){
			initial = scheduler.config.update_render;
			scheduler.config.update_render = true;
		}
		oldUpdate.apply(scheduler, arguments);

		if(fullRedrawNeeded){
			scheduler.config.update_render = initial;
		}
	};
})();
/*
@license
dhtmlxScheduler v.4.3.28 Professional

This software is covered by DHTMLX Commercial License. Usage without proper license is prohibited.

(c) Dinamenta, UAB.
*/

scheduler._props = {};
scheduler.createUnitsView=function(name,property,list,size,step,skip_incorrect, days){
	if (typeof name == "object"){
		list = name.list;
		property = name.property;
		size = name.size||0;
		step = name.step||1;
		skip_incorrect = name.skip_incorrect;
		days = name.days || 1;
		name = name.name;
	}

	scheduler._props[name]={map_to:property, options:list, step:step, position:0, days: days };
    if(size>scheduler._props[name].options.length){
        scheduler._props[name]._original_size = size;
        size = 0;
    }
    scheduler._props[name].size = size;
	scheduler._props[name].skip_incorrect = skip_incorrect||false;

	scheduler.date[name+"_start"]= scheduler.date.day_start;
	scheduler.templates[name+"_date"] = function(date, end_date){
		var pr = scheduler._props[name];
		if(!(pr.days > 1)){
			return scheduler.templates.day_date(date);
		}else{
			return scheduler.templates.week_date(date, end_date);
		}
	};

	scheduler._get_unit_index = function(unit_view, date) {
		var original_position = unit_view.position || 0;
		var date_position = Math.round((scheduler._correct_shift(+date, 1) - +scheduler._min_date) / (60 * 60 * 24 * 1000));

		var l = unit_view.options.length;
		if(date_position >= l) {
			date_position = date_position % l;
		}

		return original_position + date_position;
	};
	scheduler.templates[name + "_scale_text"] = function(id, label, option) {
		if (option.css) {
			return "<span class='" + option.css + "'>" + label + "</span>";
		} else {
			return label;
		}
	};
	scheduler.templates[name+"_scale_date"] = function(date) {
		var unit_view = scheduler._props[name];
		var list = unit_view.options;
		if (!list.length) return "";
		var index = scheduler._get_unit_index(unit_view, date);
		var option = list[index];
		return scheduler.templates[name + "_scale_text"](option.key, option.label, option);
	};
	scheduler.templates[name+"_second_scale_date"] = function(date) {
		return scheduler.templates.week_scale_date(date);
	};

	scheduler.date["add_"+name]=function(date,inc){
		return scheduler.date.add(date,inc * scheduler._props[name].days,"day");
	};
	scheduler.date["get_"+name+"_end"]=function(date){
		return scheduler.date.add(date,(scheduler._props[name].size||scheduler._props[name].options.length)*scheduler._props[name].days,"day");
	};

	scheduler.attachEvent("onOptionsLoad",function(){
        var pr = scheduler._props[name];
		var order = pr.order = {};
		var list = pr.options;
		for(var i=0; i<list.length;i++)
			order[list[i].key]=i;
        if(pr._original_size && pr.size===0){
            pr.size = pr._original_size;
            delete pr.original_size;
        }
		if(pr.size > list.length) {
            pr._original_size = pr.size;
            pr.size = 0;
        }
        else
            pr.size = pr._original_size||pr.size;
		if (scheduler._date && scheduler._mode == name)
			scheduler.setCurrentView(scheduler._date, scheduler._mode);
	});

	scheduler["mouse_"+ name] = function(pos){ //mouse_coord handler
		var pr = scheduler._props[this._mode];

		if (pr){
			pos = this._week_indexes_from_pos(pos);
			if(!this._drag_event) this._drag_event = {};

			if (this._drag_id && this._drag_mode){
				this._drag_event._dhx_changed = true;
			}


			if(this._drag_mode && this._drag_mode == "new-size"){
				var sday = scheduler._get_event_sday(scheduler._events[scheduler._drag_id]);
				if(Math.floor(pos.x / pr.options.length) != Math.floor(sday / pr.options.length))
					pos.x = sday;
			}

			var section_ind = pos.x % pr.options.length;
			var unit_ind = Math.min(section_ind+pr.position,pr.options.length-1);

			pos.section = (pr.options[unit_ind]||{}).key;
			pos.x = Math.floor(pos.x / pr.options.length);




			var ev = this.getEvent(this._drag_id);
			this._update_unit_section({view:pr, event:ev, pos:pos});
		}
		pos.force_redraw = true;

		return pos;
	};



	scheduler.callEvent("onOptionsLoad",[]);
};

scheduler._update_unit_section = function(action){
	var view = action.view,
		event = action.event,
		pos = action.pos;
	if(event) {
		event[view.map_to] = pos.section;
	}
};

scheduler.scrollUnit=function(step){
	var pr = scheduler._props[this._mode];
	if (pr){
		pr.position=Math.min(Math.max(0,pr.position+step),pr.options.length-pr.size);
		this.setCurrentView();
	}
};
(function(){
	var _removeIncorrectEvents = function(evs) {
		var pr = scheduler._props[scheduler._mode];
		if(pr && pr.order && pr.skip_incorrect) {
            var correct_events = [];
			for(var i=0; i<evs.length; i++) {
				if(typeof pr.order[evs[i][pr.map_to]] != "undefined") {
                    correct_events.push(evs[i]);
				}
			}
            evs.splice(0,evs.length);
			evs.push.apply(evs,correct_events);
		}
		return evs;
	};
	var old_pre_render_events_table = scheduler._pre_render_events_table;
	scheduler._pre_render_events_table=function(evs,hold) {
		evs = _removeIncorrectEvents(evs);
		return old_pre_render_events_table.apply(this, [evs, hold]);
	};
	var old_pre_render_events_line = scheduler._pre_render_events_line;
	scheduler._pre_render_events_line = function(evs,hold){
		evs = _removeIncorrectEvents(evs);
		return old_pre_render_events_line.apply(this, [evs, hold]);
	};
	var fix_und=function(pr,ev){
		if (pr && typeof pr.order[ev[pr.map_to]] == "undefined"){
			var s = scheduler;
			var dx = 24*60*60*1000;
			var ind = Math.floor((ev.end_date - s._min_date)/dx);
			//ev.end_date = new Date(s.date.time_part(ev.end_date)*1000+s._min_date.valueOf());
			//ev.start_date = new Date(s.date.time_part(ev.start_date)*1000+s._min_date.valueOf());

			if(pr.options.length)
				ev[pr.map_to] = pr.options[Math.min(ind+pr.position,pr.options.length-1)].key;
			return true;
		}
	};


	var oldive = scheduler.is_visible_events;
	scheduler.is_visible_events = function(e){
		var res = oldive.apply(this,arguments);
		if (res){
			var pr = scheduler._props[this._mode];
			if (pr && pr.size){
				var val = pr.order[e[pr.map_to]];
				if (val < pr.position || val >= pr.size+pr.position )
					return false;
			}
		}
		return res;
	};

	var old_process_ignores = scheduler._process_ignores;

	scheduler._process_ignores = function(sd, n, mode, step, preserve){
		if(!scheduler._props[this._mode]){
			old_process_ignores.call(this, sd, n, mode, step, preserve);
			return;
		}
		this._ignores={};
		this._ignores_detected = 0;
		var ignore = scheduler["ignore_"+this._mode];

		if (ignore){
			var sectionsCount = (scheduler._props && scheduler._props[this._mode] ?
				(scheduler._props[this._mode].size||scheduler._props[this._mode].options.length) : 1);
			n /= sectionsCount;

			var ign_date = new Date(sd);
			for (var i=0; i<n; i++){
				if (ignore(ign_date)){
					var sectionStart = i * sectionsCount,
						sectionEnd = (i + 1) * sectionsCount;

					for(var j = sectionStart; j < sectionEnd; j++) {
						this._ignores_detected += 1;
						this._ignores[j] = true;
						if (preserve)
							n++;
					}
				}
				ign_date = scheduler.date.add(ign_date, step, mode);
				if(scheduler.date[mode + '_start'])
					ign_date = scheduler.date[mode + '_start'](ign_date);
			}
		}
	};


	var t = scheduler._reset_scale;
	scheduler._reset_scale = function(){
		var pr = scheduler._props[this._mode];
		var ret = t.apply(this,arguments);
		if (pr){
			this._max_date = this.date.add(this._min_date,pr.days,"day");

			var d = this._els["dhx_cal_data"][0].childNodes;
			for (var i=0; i < d.length; i++)
				d[i].className = d[i].className.replace("_now",""); //clear now class

			// set background for current date
			var today = new Date();
			if(today.valueOf() >= this._min_date && today.valueOf() < this._max_date) {
				var dx = 24*60*60*1000;
				var ind = Math.floor((today - scheduler._min_date)/dx);
				var units_l = pr.options.length;
				var today_start = ind*units_l;
				var today_end = today_start + units_l;
				for (i=today_start; i<today_end; i++){
					if(d[i])
						d[i].className = d[i].className.replace("dhx_scale_holder","dhx_scale_holder_now"); //set now class
				}
			}

			if (pr.size && pr.size < pr.options.length){

				var h = this._els["dhx_cal_header"][0];
				var arrow = document.createElement("DIV");
				if (pr.position){
					arrow.className = "dhx_cal_prev_button";
					arrow.style.cssText="left:1px;top:2px;position:absolute;";
					arrow.innerHTML = "&nbsp;";
					h.firstChild.appendChild(arrow);
					arrow.onclick=function(){
						scheduler.scrollUnit(pr.step*-1);
					};
				}
				if (pr.position+pr.size<pr.options.length){
					arrow = document.createElement("DIV");
					arrow.className = "dhx_cal_next_button";
					arrow.style.cssText="left:auto; right:0px;top:2px;position:absolute;";
					arrow.innerHTML = "&nbsp;";
					h.lastChild.appendChild(arrow);
					arrow.onclick=function(){
						scheduler.scrollUnit(pr.step);
					};
				}
			}
		}
		return ret;

	};

	var _reset_scale = scheduler._reset_scale;
	scheduler._reset_scale = function(){
		var pr = scheduler._props[this._mode];
		var scale_height = scheduler.xy.scale_height;
		if (pr && pr.days > 1){
			if(!this._header_resized){
				this._header_resized = scheduler.xy.scale_height;
				scheduler.xy.scale_height = scale_height * 2;
			}
		}else{
			if(this._header_resized){
				scheduler.xy.scale_height /= 2;
				this._header_resized = false;
			}
		}
		_reset_scale.apply(this, arguments);
	};

	var _get_view_end = scheduler._get_view_end;
	scheduler._get_view_end = function(){
		var pr = scheduler._props[this._mode];
		if(pr && pr.days > 1) {
			var dd = this._get_timeunit_start();
			return scheduler.date.add(dd, pr.days, "day");
		}else{
			return _get_view_end.apply(this, arguments);
		}
	};

	var xh = scheduler._render_x_header;
	scheduler._render_x_header = function(i, left, d, h) {

		var pr = scheduler._props[this._mode];
		if(!pr || pr.days <= 1) {
			return xh.apply(this, arguments);
		}else if(pr.days > 1){

			var scale_height = scheduler.xy.scale_height;
			scheduler.xy.scale_height = Math.ceil(scale_height / 2);
			xh.call(this, i, left, d, h, Math.ceil(scheduler.xy.scale_height));

			var units_l = pr.options.length;
			// second scale
			if( (i+1)%units_l === 0 ) {
				var head = document.createElement("DIV");
				head.className = "dhx_scale_bar dhx_second_scale_bar";
				var date = this.date.add(this._min_date, Math.floor(i/units_l), "day");
				if (this.templates[this._mode + "_second_scalex_class"]) {
					head.className += ' ' + this.templates[this._mode + "_second_scalex_class"](new Date(date));
				}
				var s_left,
					s_width = this._cols[i]*units_l - 1;
				if(units_l > 1)
					s_left = this._colsS[i-(units_l-1)] - this.xy.scale_width - 2; //borders
				else
					s_left = left;
				

				this.set_xy(head, s_width, this.xy.scale_height - 2, s_left, 0); //-1 for border
				head.innerHTML = this.templates[this._mode + "_second_scale_date"](new Date(date), this._mode); //TODO - move in separate method
				h.appendChild(head);
			}

			scheduler.xy.scale_height = scale_height;
		}
	};

	var r = scheduler._get_event_sday;
	scheduler._get_event_sday=function(ev){
		var pr = scheduler._props[this._mode];
		if (pr){
			if(pr.days <= 1){
				fix_und(pr,ev);
				return this._get_section_sday(ev[pr.map_to]);
			}else{
				var dx = 24*60*60*1000;
				var ind = Math.floor(((ev.end_date.valueOf()-1 - ev.end_date.getTimezoneOffset() * 60 * 1000) -// -1 for events with 00:00 end time
					(scheduler._min_date.valueOf() - scheduler._min_date.getTimezoneOffset() * 60 * 1000))/dx);

				var units_l = pr.options.length;
				var section_index = pr.order[ev[pr.map_to]];
				return ( ind * units_l + section_index ) - pr.position;
			}

		}
		return r.call(this,ev);
	};
	scheduler._get_section_sday = function(section){
		var pr = scheduler._props[this._mode];
		return pr.order[section]-pr.position;
	};

	var l = scheduler.locate_holder_day;
	scheduler.locate_holder_day=function(a,b,ev) {
		var pr = scheduler._props[this._mode];
		if (!pr) {
			return l.apply(this, arguments);
		}
		var section;
		if (!ev) {
			ev = {
				start_date: a,
				end_date: a
			};
			section = 0;
		}
		else {
			fix_und(pr, ev);
		}
		if (pr.days <= 1) {
			return (section === undefined ? pr.order[ev[pr.map_to]] : section) * 1 + (b ? 1 : 0) - pr.position;
		} else {
			var dx = 24 * 60 * 60 * 1000;
			var ind = Math.floor((ev.start_date.valueOf() - scheduler._min_date.valueOf()) / dx); // -1 for events with 00:00 end time
			var units_l = pr.options.length;
			var section_index = section === undefined ? pr.order[ev[pr.map_to]] : section;
			return (ind * units_l + section_index * 1) + (b ? 1 : 0) - pr.position;
		}
	};

	var o = scheduler._time_order;
	scheduler._time_order = function(evs){
		var pr = scheduler._props[this._mode];
		if (pr){
			evs.sort(function(a,b){
				return pr.order[a[pr.map_to]]>pr.order[b[pr.map_to]]?1:-1;
			});
		} else
			o.apply(this,arguments);
	};


	var prerender = scheduler._pre_render_events_table;
	scheduler._pre_render_events_table = function(evs, hold){
		var pr = scheduler._props[this._mode];

		// split multiday event into several one-day parts
		if(pr && pr.days > 1 && !this.config.all_timed){
			var days = {};
			for(var i = 0; i < evs.length; i++){
				var ev = evs[i];
				if(!this.isOneDayEvent(evs[i])){

					var to = new Date(Math.min(+ev.end_date, +this._max_date)),
						from = new Date(Math.max(+ev.start_date, +this._min_date));
					evs.splice(i, 1);


					while(+from < +to){
						var chunk = this._copy_event(ev);
						chunk.start_date = from;
						chunk.end_date = getNextDay(chunk.start_date);
						from = scheduler.date.add(from, 1, 'day');

						var date = +scheduler.date.date_part(new Date(from));
						if(!days[date])
							days[date] = [];
						days[date].push(chunk);
						evs.splice(i, 0, chunk);
						i++;
					}
					i--;
				}else{
					var date = +scheduler.date.date_part(new Date(ev.start_date));
					if(!days[date])
						days[date] = [];
					days[date].push(ev);
				}

			}


			var res = [];
			for(var i in days){
				res.splice.apply(res, [res.length - 1, 0].concat(prerender.apply(this, [days[i], hold])) );
			}
			//var evs = prerender.apply(this, [evs, hold]);
			for (var i = 0; i < res.length; i++) {
				if (this._ignores[res[i]._sday]) {
					res.splice(i, 1);
					i--;
				}
				else {
					res[i]._first_chunk = res[i]._last_chunk = false;
				}
			}
			res.sort(function(a, b) {
				if (a.start_date.valueOf() == b.start_date.valueOf())
					return a.id > b.id ? 1 : -1;
				return a.start_date > b.start_date ? 1 : -1;
			});
			evs = res;
		}else{
			evs = prerender.apply(this, [evs, hold]);
		}

		function getNextDay(date){
			var next_day = scheduler.date.add(date, 1, "day");
			next_day = scheduler.date.date_part(next_day);
			return next_day;
		}
		return evs;
	};

	scheduler.attachEvent("onEventAdded",function(id,ev){
		if (this._loading) return true;
		for (var a in scheduler._props){
			var pr = scheduler._props[a];
			if (typeof ev[pr.map_to] == "undefined")
				ev[pr.map_to] = pr.options[0].key;
		}
		return true;
	});
	scheduler.attachEvent("onEventCreated",function(id,n_ev){
		var pr = scheduler._props[this._mode];
		if (pr && n_ev){
			var ev = this.getEvent(id);
			fix_und(pr,ev);
			var pos = this._mouse_coords(n_ev);
			this._update_unit_section({view:pr, event:ev, pos:pos});

			this.event_updated(ev);
		}
		return true;
	});
})();
/*
@license
dhtmlxScheduler v.4.3.28 Professional

This software is covered by DHTMLX Commercial License. Usage without proper license is prohibited.

(c) Dinamenta, UAB.
*/

window.dhtmlXTooltip = scheduler.dhtmlXTooltip = window.dhtmlxTooltip = {};

dhtmlXTooltip.config = {
	className: 'dhtmlXTooltip tooltip',
	timeout_to_display: 50,
	timeout_to_hide: 50,
	delta_x: 15,
	delta_y: -20
};

dhtmlXTooltip.tooltip = document.createElement('div');
dhtmlXTooltip.tooltip.className = dhtmlXTooltip.config.className;

dhtmlXTooltip.show = function(event, text) { //browser event, text to display
	if (scheduler.config.touch && !scheduler.config.touch_tooltip) return;
	
	var dhxTooltip = dhtmlXTooltip;
	var tooltip_div = this.tooltip;
	var tooltip_div_style = tooltip_div.style;
	dhxTooltip.tooltip.className = dhxTooltip.config.className;
	var pos = this.position(event);

	var target = event.target || event.srcElement;
	// if we are over tooltip -- do nothing, just return (so tooltip won't move)
	if (this.isTooltip(target)) {
		return;
	}

	var actual_x = pos.x + (dhxTooltip.config.delta_x || 0);
	var actual_y = pos.y - (dhxTooltip.config.delta_y || 0);

	tooltip_div_style.visibility = "hidden";

	if (tooltip_div_style.removeAttribute) {
		tooltip_div_style.removeAttribute("right");
		tooltip_div_style.removeAttribute("bottom");
	} else {
		tooltip_div_style.removeProperty("right");
		tooltip_div_style.removeProperty("bottom");
	}

	tooltip_div_style.left = "0";
	tooltip_div_style.top = "0";

	this.tooltip.innerHTML = text;
	document.body.appendChild(this.tooltip);

	var tooltip_width = this.tooltip.offsetWidth;
	var tooltip_height = this.tooltip.offsetHeight;

	if ((document.body.offsetWidth - actual_x - tooltip_width) < 0) { // tooltip is out of the right page bound
		if(tooltip_div_style.removeAttribute)
			tooltip_div_style.removeAttribute("left");
		else
			tooltip_div_style.removeProperty("left");
		tooltip_div_style.right = (document.body.offsetWidth - actual_x + 2 * (dhxTooltip.config.delta_x||0)) + "px";
	} else {
		if (actual_x < 0) {
			// tooltips is out of the left page bound
			tooltip_div_style.left = (pos.x + Math.abs(dhxTooltip.config.delta_x||0)) + "px";
		} else {
			// normal situation
			tooltip_div_style.left = actual_x + "px";
		}
	}

	if ((document.body.offsetHeight - actual_y - tooltip_height) < 0) { // tooltip is below bottom of the page
		if(tooltip_div_style.removeAttribute)
			tooltip_div_style.removeAttribute("top");
		else
			tooltip_div_style.removeProperty("top");
		tooltip_div_style.bottom = (document.body.offsetHeight - actual_y - 2 * (dhxTooltip.config.delta_y||0)) + "px";
	} else {
		if (actual_y < 0) {
			// tooltip is higher then top of the page
			tooltip_div_style.top = (pos.y + Math.abs(dhxTooltip.config.delta_y||0)) + "px";
		} else {
			// normal situation
			tooltip_div_style.top = actual_y + "px";
		}
	}

	tooltip_div_style.visibility = "visible";
	this.tooltip.onmouseleave = function(e){
		e = e || window.event;
		/*
		 A rare but reported scenario, when tooltip appears at the edge of the scheduler (e.g. left part inside cal, right part - outside).
		 User moves mouse from the scheduler into the tooltip, and then from the tooltip to the page outside the calendar.
		 As a result - tooltip freezes and no longer reacts until mouse reenters the calendar.
		*/
		var tooltip = scheduler.dhtmlXTooltip;

		var node = e.relatedTarget;
		while (node != scheduler._obj && node) {
			node = node.parentNode;
		}

		if(node != scheduler._obj)
			tooltip.delay(tooltip.hide, tooltip, [], tooltip.config.timeout_to_hide);
	};

	scheduler.callEvent("onTooltipDisplayed", [this.tooltip, this.tooltip.event_id]);
};
dhtmlXTooltip._clearTimeout = function(){
	if(this.tooltip._timeout_id) {
		window.clearTimeout(this.tooltip._timeout_id);
	}
};

dhtmlXTooltip.hide = function() {
	if (this.tooltip.parentNode) {
		var event_id = this.tooltip.event_id;
		this.tooltip.event_id = null;
		this.tooltip.onmouseleave = null;
		this.tooltip.parentNode.removeChild(this.tooltip);
		scheduler.callEvent("onAfterTooltip", [event_id]);
	}
	this._clearTimeout();
};
dhtmlXTooltip.delay = function(method, object, params, delay) {
	this._clearTimeout();
	this.tooltip._timeout_id = setTimeout(function() {
		var ret = method.apply(object, params);
		method = object = params = null;
		return ret;
	}, delay || this.config.timeout_to_display);
};

dhtmlXTooltip.isTooltip = function(node) {
	var res = false;
	if (node && (node.className.split(" ")[0] == "dhtmlXTooltip")) {
		//debugger;
	}
	while (node && !res) {
		res = (node.className == this.tooltip.className);
		node = node.parentNode;
	}
	return res;
};

dhtmlXTooltip.position = function(ev) {
	ev = ev || window.event;
	if (ev.pageX || ev.pageY) //FF, KHTML
		return {x:ev.pageX, y:ev.pageY};
	//IE
	var d = ((window._isIE) && (document.compatMode != "BackCompat")) ? document.documentElement : document.body;
	return {
		x:ev.clientX + d.scrollLeft - d.clientLeft,
		y:ev.clientY + d.scrollTop - d.clientTop
	};
};

scheduler.attachEvent("onMouseMove", function(event_id, e) { // (scheduler event_id, browser event)
	var ev = window.event || e;
	var target = ev.target || ev.srcElement;
	var dhxTooltip = dhtmlXTooltip;

	var is_tooltip = dhxTooltip.isTooltip(target);
	var is_tooltip_target = (dhxTooltip.isTooltipTarget && dhxTooltip.isTooltipTarget(target));

	// if we are over event or tooltip or custom target for tooltip
	if (event_id || is_tooltip || is_tooltip_target) {
		var text;

		if (event_id || dhxTooltip.tooltip.event_id) {
			var event = scheduler.getEvent(event_id) || scheduler.getEvent(dhxTooltip.tooltip.event_id);
			if (!event)
				return;

			dhxTooltip.tooltip.event_id = event.id;
			text = scheduler.templates.tooltip_text(event.start_date, event.end_date, event);
			if (!text)
				return dhxTooltip.hide();
		}
		if (is_tooltip_target) {
			text = "";
		}

		var evt;
		if (_isIE) {
			//make a copy of event, will be used in timed call

			evt = {'pageX':undefined,
				'pageY':undefined,
				'clientX':undefined,
				'clientY':undefined,
				'target':undefined,
				'srcElement':undefined
			};
			for(var i in evt){
				evt[i] = ev[i];
			}
		}

		if (!scheduler.callEvent("onBeforeTooltip", [event_id]) || !text)
			return;

		dhxTooltip.delay(dhxTooltip.show, dhxTooltip, [(evt || ev), text]); // showing tooltip
	} else {
		dhxTooltip.delay(dhxTooltip.hide, dhxTooltip, [], dhxTooltip.config.timeout_to_hide);
	}
});
scheduler.attachEvent("onBeforeDrag", function() {
	dhtmlXTooltip.hide();
	return true;
});
scheduler.attachEvent("onEventDeleted", function() {
	dhtmlXTooltip.hide();
	return true;
});

/* Could be redifined */
scheduler.templates.tooltip_date_format = scheduler.date.date_to_str("%Y-%m-%d %H:%i");

scheduler.templates.tooltip_text = function(start, end, event) {
	return "<b>Event:</b> " + event.text + "<br/><b>Start date:</b> " + scheduler.templates.tooltip_date_format(start) + "<br/><b>End date:</b> " + scheduler.templates.tooltip_date_format(end);
};
/*
@license
dhtmlxScheduler v.4.3.28 Professional

This software is covered by DHTMLX Commercial License. Usage without proper license is prohibited.

(c) Dinamenta, UAB.
*/

scheduler.attachEvent("onTemplatesReady", function() {
	var original_sns = scheduler.config.lightbox.sections.slice();
	var original_left_buttons = scheduler.config.buttons_left.slice();
	var original_right_buttons = scheduler.config.buttons_right.slice();


	scheduler.attachEvent("onBeforeLightbox", function(id) {
		if (this.config.readonly_form || this.getEvent(id).readonly) {
			this.config.readonly_active = true;

			for (var i = 0; i < this.config.lightbox.sections.length; i++) {
				this.config.lightbox.sections[i].focus = false;
			}
		}
		else {
			this.config.readonly_active = false;
			scheduler.config.lightbox.sections = original_sns.slice(); // restore original list of sections including recurring
			scheduler.config.buttons_left = original_left_buttons.slice();
			scheduler.config.buttons_right = original_right_buttons.slice();
		}

		var sns = this.config.lightbox.sections;
		if (this.config.readonly_active) {
			for (var i = 0; i < sns.length; i++) {
				if (sns[i].type == 'recurring') {
					if (this.config.readonly_active) {
						sns.splice(i, 1);
					}
					break;
				}
			}

			var forbidden_buttons = ["dhx_delete_btn", "dhx_save_btn"];
			var button_arrays = [scheduler.config.buttons_left, scheduler.config.buttons_right];
			for (var i = 0; i < forbidden_buttons.length; i++) {
				var forbidden_button = forbidden_buttons[i];
				for (var k = 0; k < button_arrays.length; k++) {
					var button_array = button_arrays[k];
					var index = -1;
					for (var p = 0; p < button_array.length; p++) {
						if (button_array[p] == forbidden_button) {
							index = p;
							break;
						}
					}
					if (index != -1) {
						button_array.splice(index, 1);
					}
				}
			}


		}

		this.resetLightbox();

		return true;
	});

	function txt_replace(tag, d, n, text) {
		var txts = d.getElementsByTagName(tag);
		var txtt = n.getElementsByTagName(tag);
		for (var i = txtt.length - 1; i >= 0; i--) {
			var n = txtt[i];
			if (!text){
				n.disabled = true;
				//radio and checkboxes loses state after .cloneNode in IE
				if(d.checked)
					n.checked = true;
			}else {
				var t = document.createElement("SPAN");
				t.className = "dhx_text_disabled";
				t.innerHTML = text(txts[i]);
				n.parentNode.insertBefore(t, n);
				n.parentNode.removeChild(n);
			}
		}
	}

	var old = scheduler._fill_lightbox;
	scheduler._fill_lightbox = function() {

		var lb = this.getLightbox();
		if (this.config.readonly_active) {
			lb.style.visibility = 'hidden';
			// lightbox should have actual sizes before rendering controls
			// currently only matters for dhtmlxCombo
			lb.style.display = 'block';
		}
		var res = old.apply(this, arguments);
		if (this.config.readonly_active) {
			//reset visibility and display
			lb.style.visibility = '';
			lb.style.display = 'none';
		}

		if (this.config.readonly_active) {

			var d = this.getLightbox();
			var n = this._lightbox_r = d.cloneNode(true);
			n.id = scheduler.uid();

			txt_replace("textarea", d, n, function(a) {
				return a.value;
			});
			txt_replace("input", d, n, false);
			txt_replace("select", d, n, function(a) {
				if(!a.options.length) return "";
				return a.options[Math.max((a.selectedIndex || 0), 0)].text;
			});

			d.parentNode.insertBefore(n, d);

			olds.call(this, n);
			if (scheduler._lightbox)
				scheduler._lightbox.parentNode.removeChild(scheduler._lightbox);
			this._lightbox = n;

			if (scheduler.config.drag_lightbox)
				n.firstChild.onmousedown = scheduler._ready_to_dnd;
			this.setLightboxSize();
			n.onclick = function(e) {
				var src = e ? e.target : event.srcElement;
				if (!src.className) src = src.previousSibling;
				if (src && src.className)
					switch (src.className) {
						case "dhx_cancel_btn":
							scheduler.callEvent("onEventCancel", [scheduler._lightbox_id]);
							scheduler._edit_stop_event(scheduler.getEvent(scheduler._lightbox_id), false);
							scheduler.hide_lightbox();
							break;
					}
			};
		}
		return res;
	};

	var olds = scheduler.showCover;
	scheduler.showCover = function() {
		if (!this.config.readonly_active)
			olds.apply(this, arguments);
	};

	var hold = scheduler.hide_lightbox;
	scheduler.hide_lightbox = function() {
		if (this._lightbox_r) {
			this._lightbox_r.parentNode.removeChild(this._lightbox_r);
			this._lightbox_r = this._lightbox = null;
		}

		return hold.apply(this, arguments);
	};
});
/*
@license
dhtmlxScheduler v.4.3.28 Professional

This software is covered by DHTMLX Commercial License. Usage without proper license is prohibited.

(c) Dinamenta, UAB.
*/

scheduler.config.limit_start = null;
scheduler.config.limit_end   = null;
scheduler.config.limit_view  = false;
scheduler.config.check_limits = true;
scheduler.config.mark_now = true;
scheduler.config.display_marked_timespans = true;

scheduler._temp_limit_scope = function(){
	var before = null;
	var dhx_time_block = "dhx_time_block";
	var default_timespan_type = "default";
	var fix_options = function(options, days, zones) {
		if (days instanceof Date && zones instanceof Date) {
			options.start_date = days;
			options.end_date = zones;
		} else {
			options.days = days;
			options.zones = zones;
		}	
		return options;
	};
	var get_resulting_options = function(days, zones, sections) {
		var options = (typeof days == "object") ? days : { days: days };
		options.type = dhx_time_block;
		options.css = "";
		if (zones) {
			if (sections)
				options.sections = sections;
			options = fix_options(options, days, zones);
		}
		return options;
	};
	scheduler.blockTime = function(days, zones, sections){
		var options = get_resulting_options(days, zones, sections);
		return scheduler.addMarkedTimespan(options);
	};
	scheduler.unblockTime = function(days, zones, sections) {
		zones = zones || "fullday";
		var options = get_resulting_options(days, zones, sections);
		return scheduler.deleteMarkedTimespan(options);
	};
	scheduler.attachEvent("onBeforeViewChange",function(om,od,nm,nd){

		function isBlocked(date, mode){
			var limit_start = scheduler.config.limit_start,
				limit_end = scheduler.config.limit_end,
				date_end =  scheduler.date.add(date,1,mode);

			return (date.valueOf() > limit_end.valueOf() || date_end <= limit_start.valueOf());
		}

		if (scheduler.config.limit_view){
			nd = nd||od; nm = nm||om;		
			if (isBlocked(nd, nm) && !(od.valueOf() == nd.valueOf())){
				setTimeout(function(){
					var resetDate = !isBlocked(od, nm) ? od : scheduler.config.limit_start;

					scheduler.setCurrentView(!isBlocked(resetDate, nm) ? resetDate : null, nm);
				},1);
				return false;
			}
		}
		return true;
	});
	scheduler.checkInMarkedTimespan = function(ev, timespan_type, on_overlap){
		timespan_type = timespan_type || default_timespan_type;

		var res = true;
		var temp_start_date = new Date(ev.start_date.valueOf());
		var temp_end_date = scheduler.date.add(temp_start_date, 1, "day");
		var timespans = scheduler._marked_timespans;
		for (; temp_start_date < ev.end_date; temp_start_date = scheduler.date.date_part(temp_end_date), temp_end_date = scheduler.date.add(temp_start_date, 1, "day") ) {
			var day_value = +scheduler.date.date_part( new Date(temp_start_date) ); // the first part of event not necessarily contains only date part
			var day_index = temp_start_date.getDay();

			var zones = getZones(ev, timespans, day_index, day_value, timespan_type);
			if (zones){
				for (var i = 0; i < zones.length; i+=2) {

					// they may change for new event if it passes limit zone
					var sm = scheduler._get_zone_minutes(temp_start_date);
					var em = ( ev.end_date>temp_end_date || ev.end_date.getDate() != temp_start_date.getDate() ) ? 1440 : scheduler._get_zone_minutes(ev.end_date);

					var sz = zones[i];
					var ez = zones[i+1];
					if (sz<em && ez>sm) {
						if(typeof on_overlap == "function"){
							//handler allows to cancel overlapping
							//actually needed only to keep default behavior of limits
							res = on_overlap(ev, sm, em, sz, ez);//event object, event start/end minutes in 'zones' format, zone start/end minutes
						}else{
							res = false;
						}
						if(!res)
							break;
					}
				}
			}
		}
		return !res;
	};
	var blocker = scheduler.checkLimitViolation = function(event){
		if(!event)
			return true;
		if (!scheduler.config.check_limits)
			return true;
		var s = scheduler;
		var c = s.config;
		var evs = [];
		if (event.rec_type) {
			var dates = scheduler.getRecDates(event);
			for(var i=0; i < dates.length; i++){
				var ev = scheduler._copy_event(event);
				scheduler._lame_copy(ev, dates[i]);
				evs.push(ev);
			}

		} else {
			evs = [event];
		}

		var complete_res = true;
		for (var p=0; p<evs.length; p++) {
			var res = true;
			var ev = evs[p];
			// Event could have old _timed property (e.g. we are creating event with DND on timeline view and crossed day)
			ev._timed = scheduler.isOneDayEvent(ev);

			res = (c.limit_start && c.limit_end) ? (ev.start_date.valueOf() >= c.limit_start.valueOf() && ev.end_date.valueOf() <= c.limit_end.valueOf()) : true;
			if (res){
				res = !scheduler.checkInMarkedTimespan(ev, dhx_time_block, function(ev, sm, em, sz, ez){
					//try crop event to allow placing
					var allow = true;
					if (sm<=ez && sm >=sz){
						if (ez == 24*60 || em<ez){
							allow = false;
						}
						if(ev._timed && s._drag_id && s._drag_mode == "new-size"){
							ev.start_date.setHours(0);
							ev.start_date.setMinutes(ez);
						}
						else {
							allow = false;
						}
					}
					if ((em>=sz && em<ez) || (sm < sz && em > ez)){
						if(ev._timed && s._drag_id && s._drag_mode == "new-size"){
							ev.end_date.setHours(0);
							ev.end_date.setMinutes(sz);
						}
						else {
							allow = false;
						}
					}
					return allow;
				});
			}
			if (!res) {
				res = (s.checkEvent("onLimitViolation")) ? s.callEvent("onLimitViolation",[ev.id, ev]) : res;
			}
			complete_res = complete_res && res;
		}
		if(!complete_res){
			s._drag_id = null;
			s._drag_mode = null;
		}
		return complete_res;


	};
	scheduler._get_blocked_zones = function(timespans, property, day_index, day_value, timespan_type){
		var zones =[];
		if (timespans && timespans[property]) {
			var timeline_zones = timespans[property];
			var blocked_timeline_zones = this._get_relevant_blocked_zones(day_index, day_value, timeline_zones, timespan_type);
			for (var i=0; i<blocked_timeline_zones.length; i++) {
				zones = this._add_timespan_zones(zones, blocked_timeline_zones[i].zones);
			}
		}
		return zones;
	};
	scheduler._get_relevant_blocked_zones = function(day_index, day_value, zones, timespan_type) {
		var relevant_zones = (zones[day_value] && zones[day_value][timespan_type]) ? zones[day_value][timespan_type] :
			(zones[day_index] && zones[day_index][timespan_type]) ? zones[day_index][timespan_type] : [];
		return relevant_zones;
	};
	function getZones(ev, timespans, day_index, day_value, timespan_type){
		var s = scheduler;
		//containers for 'unit' and 'timeline' views, and related 'section_id' properties
		var zones = [];
		var containers = {
			'_props':'map_to',
			'matrix':'y_property'};
		//check blocked sections in all units and timelines
		for(var container in containers){
			var property = containers[container];
			if(s[container]){
				for(var view in s[container]){
					var view_config = s[container][view];
					var linker = view_config[property];
					if(!ev[linker]) continue;
					zones =  s._add_timespan_zones(zones,
						scheduler._get_blocked_zones(timespans[view], ev[linker], day_index, day_value, timespan_type));
				}
			}
		}
		// now need to add day blocks
		zones = s._add_timespan_zones(zones, scheduler._get_blocked_zones(timespans, 'global', day_index, day_value, timespan_type));
		return zones;
	}

	scheduler.attachEvent("onMouseDown", function(classname) {
		return !(classname == dhx_time_block);
	});
	scheduler.attachEvent("onBeforeDrag",function(id){
		if (!id) return true;
		return blocker(scheduler.getEvent(id));
	});
	scheduler.attachEvent("onClick", function (event_id, native_event_object){
		return blocker(scheduler.getEvent(event_id));
    });
	scheduler.attachEvent("onBeforeLightbox",function(id){

		var ev = scheduler.getEvent(id);
		before = [ev.start_date, ev.end_date];
		return blocker(ev);
	});
	scheduler.attachEvent("onEventSave", function(id, data, is_new_event) {

		//lightbox may not have 'time' section
		if(!(data.start_date && data.end_date)){
			var ev = scheduler.getEvent(id);
			data.start_date = new Date(ev.start_date);
			data.end_date = new Date(ev.end_date);
		}

		if(data.rec_type){
			//_roll_back_dates modifies start_date of recurring event, need to check limits after modification
			// use a copy to keep original event unchanged
			var data_copy = scheduler._lame_clone(data);
			scheduler._roll_back_dates(data_copy);
			return blocker(data_copy);
		}
		return blocker(data);
	});
	scheduler.attachEvent("onEventAdded",function(id){
		if (!id) return true;
		var ev = scheduler.getEvent(id);
		if (!blocker(ev) && scheduler.config.limit_start && scheduler.config.limit_end) {
			//if newly created event is outside of limited time - crop it, leaving only allowed time
			if (ev.start_date < scheduler.config.limit_start) {
				ev.start_date = new Date(scheduler.config.limit_start);
			}
			if (ev.start_date.valueOf() >= scheduler.config.limit_end.valueOf()) {
				ev.start_date = this.date.add(scheduler.config.limit_end, -1, "day");
			}
			if (ev.end_date < scheduler.config.limit_start) {
				ev.end_date = new Date(scheduler.config.limit_start);
			}
			if (ev.end_date.valueOf() >= scheduler.config.limit_end.valueOf()) {
				ev.end_date = this.date.add(scheduler.config.limit_end, -1, "day");
			}
			if (ev.start_date.valueOf() >= ev.end_date.valueOf()) {
				ev.end_date = this.date.add(ev.start_date, (this.config.event_duration||this.config.time_step), "minute");
			}
			ev._timed=this.isOneDayEvent(ev);
		}
		return true;
	});
	scheduler.attachEvent("onEventChanged",function(id){
		if (!id) return true;
		var ev = scheduler.getEvent(id);
		if (!blocker(ev)){
			if (!before) return false;
			ev.start_date = before[0];
			ev.end_date = before[1];
			ev._timed=this.isOneDayEvent(ev);
		}
		return true;
	});
	scheduler.attachEvent("onBeforeEventChanged",function(ev, native_object, is_new){
		return blocker(ev);
	});
	scheduler.attachEvent("onBeforeEventCreated", function(ev) { // native event
		var start_date = scheduler.getActionData(ev).date;
		var event = {
			_timed: true,
			start_date: start_date,
			end_date: scheduler.date.add(start_date, scheduler.config.time_step, "minute")
		};
		return blocker(event);
	});

	scheduler.attachEvent("onViewChange", function(){
		scheduler._mark_now();
	});
	scheduler.attachEvent("onSchedulerResize", function(){
		window.setTimeout(function(){ scheduler._mark_now(); }, 1);
		return true;
	});
	scheduler.attachEvent("onTemplatesReady", function() {
		scheduler._mark_now_timer = window.setInterval(function() {
			if(!scheduler._is_initialized())
				return;
			scheduler._mark_now();
		}, 60000);
	});
	scheduler._mark_now = function(hide) {
		// day, week, units views
		var dhx_now_time = 'dhx_now_time';
		if (!this._els[dhx_now_time]) {
			this._els[dhx_now_time] = [];
		}
		var now = scheduler._currentDate();
		var cfg = this.config;
		scheduler._remove_mark_now(); // delete previous marks if they exist
		if (!hide && cfg.mark_now && now < this._max_date && now > this._min_date && now.getHours() >= cfg.first_hour && now.getHours()<cfg.last_hour) {
			var day_index = this.locate_holder_day(now);
			this._els[dhx_now_time] = scheduler._append_mark_now(day_index, now);
		}
	};
	scheduler._append_mark_now = function(day_index, now) {
		var dhx_now_time = 'dhx_now_time';
		var zone_start= scheduler._get_zone_minutes(now);
		var options = {
			zones: [zone_start, zone_start+1],
			css: dhx_now_time,
			type: dhx_now_time
		};
		if (!this._table_view) {
			if (this._props && this._props[this._mode]) { // units view
				var start_index,
					end_index;

				var view = this._props[this._mode];
				var units_l = view.size || view.options.length;
				if (view.days > 1) {
					start_index = day_index;
					end_index = day_index + units_l;
				}
				else {
					start_index = 0;
					end_index = start_index + units_l;
				}

				var r_divs = [];

				for (var i = start_index; i < end_index; i++) {
					var t_day = i; // as each unit is actually considered +1 day
					options.days = t_day;
					var t_div = scheduler._render_marked_timespan(options, null, t_day)[0];
					r_divs.push(t_div);
				}
				return r_divs;
			} else {  // day/week views
				options.days = day_index;
				return scheduler._render_marked_timespan(options, null, day_index);
			}
		} else {
			if (this._mode == "month") {
				options.days = +scheduler.date.date_part(now);
				return scheduler._render_marked_timespan(options, null, null);
			}
		}
	};
	scheduler._remove_mark_now = function() {
		var dhx_now_time = 'dhx_now_time';
		var els = this._els[dhx_now_time];
		for (var i=0; i<els.length; i++) {
			var div = els[i];
			var parent = div.parentNode;
			if (parent) {
				parent.removeChild(div);
			}
		}
		this._els[dhx_now_time] = [];
	};

	/*
	scheduler._marked_timespans = {
		"global": {
			"0": {
				"default": [
					{  // sunday
						zones: [0, 100, 500, 600],
						css: "yellow_box",
						type: "default",
						view: "global",
						day: 0
					}
				]
			}
			"112121312": {
				"my_special_type": [
					{
						zones: [600, 900],
						type: "block",
						css: "some_class",
						view: "global",
						day: 112121312
					},
					{}
				]
			}
		},
		"units": {
			"5_id": {
				"3": {
					"special_type": [ {}, {}, {} ],
					"another_type": [ {} ]
				}
			},
			"6_id": {
				"11212127": {
					...
				}
			}
		}
	}
	*/
	scheduler._marked_timespans = { global: {} };

	scheduler._get_zone_minutes = function(date) {
		return date.getHours()*60 + date.getMinutes();
	};
	scheduler._prepare_timespan_options = function(config) { // receives 1 option, returns array of options
		var r_configs = []; // resulting configs
		var temp_configs = [];

		if (config.days == "fullweek")
			config.days = [0,1,2,3,4,5,6];

		if (config.days instanceof Array) {
			var t_days = config.days.slice();
			for (var i=0; i<t_days.length; i++) {
				var cloned_config = scheduler._lame_clone(config);
				cloned_config.days = t_days[i];
				r_configs.push.apply(r_configs, scheduler._prepare_timespan_options(cloned_config));
			}
			return r_configs;
		}

		if ( !config || !((config.start_date && config.end_date && config.end_date > config.start_date) || (config.days !== undefined && config.zones)) )
			return r_configs;  // incorrect config was provided

		var min = 0;
		var max = 24*60;
		if (config.zones == "fullday")
			config.zones = [min, max];
		if (config.zones && config.invert_zones) {
			config.zones = scheduler.invertZones(config.zones);
		}

		config.id = scheduler.uid();
		config.css = config.css||"";
		config.type = config.type||default_timespan_type;

		var sections = config.sections;
		if (sections) {
			for (var view_key in sections) {
				if (sections.hasOwnProperty(view_key)) {
					var ids = sections[view_key];
					if (!(ids instanceof Array))
						ids = [ids];
					for (var i=0; i<ids.length; i++) {
						var t_config = scheduler._lame_copy({}, config);
						t_config.sections = {};
						t_config.sections[view_key] = ids[i];
						temp_configs.push(t_config);
					}
				}
			}	
		} else {
			temp_configs.push(config);
		}

		for (var k=0; k<temp_configs.length; k++) {
			var c_config = temp_configs[k]; // config to be checked

			var start_date = c_config.start_date;
			var end_date = c_config.end_date;

			if (start_date && end_date) {
				var t_sd = scheduler.date.date_part(new Date(start_date)); // e.g. 05 october
				var t_ed= scheduler.date.add(t_sd, 1, "day");  // 06 october, will both be incremented in the loop

				while (t_sd < end_date) {
					var t_config = scheduler._lame_copy({}, c_config);
					delete t_config.start_date;
					delete t_config.end_date;
					t_config.days = t_sd.valueOf();
					var zone_start = (start_date > t_sd) ? scheduler._get_zone_minutes(start_date) : min; 
					var zone_end = ( end_date>t_ed || end_date.getDate() != t_sd.getDate() ) ? max : scheduler._get_zone_minutes(end_date);
					t_config.zones = [zone_start, zone_end];
					r_configs.push(t_config);

					t_sd = t_ed;
					t_ed = scheduler.date.add(t_ed, 1, "day");
				}
			} else {
				if (c_config.days instanceof Date)
					c_config.days = (scheduler.date.date_part(c_config.days)).valueOf();
				c_config.zones = config.zones.slice();
				r_configs.push(c_config);
			}
		}
		return r_configs;
	};
	scheduler._get_dates_by_index = function(index, start, end) {
		var dates = [];
		start = scheduler.date.date_part(new Date(start||scheduler._min_date));
		end = new Date(end||scheduler._max_date);
		var start_day = start.getDay();
		var delta = (index-start_day >= 0) ? (index-start_day) : (7-start.getDay()+index);
		var t_date = scheduler.date.add(start, delta, "day");
		for (; t_date < end; t_date = scheduler.date.add(t_date, 1, "week")) {
			dates.push(t_date);
		}
		return dates;
	};
	scheduler._get_css_classes_by_config = function(config) {
		var css_classes = [];
		if (config.type == dhx_time_block) {
			css_classes.push(dhx_time_block);
			if (config.css)
				css_classes.push(dhx_time_block+"_reset");
		}
		css_classes.push("dhx_marked_timespan", config.css);
		return css_classes.join(" ");
	};
	scheduler._get_block_by_config = function(config) {
		var block  = document.createElement("DIV");
		if (config.html) {
			if (typeof config.html == "string")
				block.innerHTML = config.html;
			else
				block.appendChild(config.html);
		}
		return block;
	};
	scheduler._render_marked_timespan = function(options, area, day) {
		var blocks = []; // resulting block which will be rendered and returned
		var c = scheduler.config;
		var min_date = this._min_date;
		var max_date = this._max_date;
		var day_value = false; // if timespan for specific date should be displayed

		if (!c.display_marked_timespans)
			return blocks;

		// in case of markTimespan
		if (!day && day !== 0) {
			if (options.days < 7)
				day = options.days;
			else {
				var date_to_display = new Date(options.days);
				day_value = +date_to_display;

				// in case of markTimespan date could be not in the viewing range, need to return
				if ( !(+max_date > +date_to_display && +min_date <= +date_to_display) )
					return blocks;

				day = date_to_display.getDay();
			}

			// convert day default index (Sun - 0, Sat - 6) to index of hourscales (depends on week_start and config.start_on_monday)
			var min_day = min_date.getDay();
			if (min_day > day) {
				day = 7 - (min_day-day);
			} else {
				day = day - min_day;
			}
		}
		var zones = options.zones;
		var css_classes = scheduler._get_css_classes_by_config(options);

		if (scheduler._table_view && scheduler._mode == "month") {
			var areas = [];
			var days = [];


			if (!area) {
				days = (day_value) ? [day_value] : scheduler._get_dates_by_index(day);
				for (var i=0; i < days.length; i++) {
					areas.push( this._scales[days[i]] );
				}
			} else {
				areas.push(area);
				days.push(day);
			}

			for (var i=0; i < areas.length; i++) {
				area = areas[i];
				day = days[i];

				var sweek = Math.floor((this._correct_shift(day,1)-min_date.valueOf())/(60*60*1000*24*this._cols.length)),
					sday = this.locate_holder_day(day, false) % this._cols.length;

				if(this._ignores[sday]) continue;

				var block_proto = scheduler._get_block_by_config(options),
					height = Math.max(area.offsetHeight - 1, 0), // 1 for bottom border
					width = Math.max(area.offsetWidth - 1, 0), // 1 for left border
					left = this._colsS[sday],
					top = this._colsS.heights[sweek]+(this._colsS.height?(this.xy.month_scale_height+2):2)-1;

				block_proto.className = css_classes;
				block_proto.style.top = top + "px";
				block_proto.style.lineHeight = block_proto.style.height = height + "px";

				for (var k=0; k < zones.length; k+=2) {
					var start = zones[i];
					var end = zones[i+1];
					if (end <= start)
						return [];

					var block = block_proto.cloneNode(true);

					block.style.left = (left + Math.round( (start)/(24*60) * width)) + "px";
					block.style.width = Math.round( (end-start)/(24*60) * width) + "px";

					area.appendChild(block);
					blocks.push(block);
				}
			}
		} else {
			var index = day;

			if(this._ignores[this.locate_holder_day(day, false)]) return blocks;

			if (this._props && this._props[this._mode] && options.sections && options.sections[this._mode]) {
				var view = this._props[this._mode];
				index = view.order[options.sections[this._mode]];

				var inner_index = view.order[options.sections[this._mode]];
				if(!(view.days > 1)){
					index = inner_index;
					if (view.size && (index > view.position+view.size)) {
						index = 0;
					}
				}else{
					var units_l = view.size || view.options.length;
					index = index*units_l + inner_index;
				}
			}
			area = area ? area : scheduler.locate_holder(index);

			for (var i = 0; i < zones.length; i+=2){
				var start = Math.max(zones[i], c.first_hour*60);
				var end = Math.min(zones[i+1], c.last_hour*60);
				if (end <= start) {
					if (i+2 < zones.length)
						continue;
					else
						return [];
				}

				var block = scheduler._get_block_by_config(options);
				block.className = css_classes;

				// +1 for working with section which really takes up whole height (as % would be == 0)
				var all_hours_height = this.config.hour_size_px*24 + 1;
				var hour_ms = 60*60*1000;
				block.style.top = (Math.round((start*60*1000-this.config.first_hour*hour_ms)*this.config.hour_size_px/hour_ms) % all_hours_height) + "px";
				block.style.lineHeight = block.style.height = Math.max((Math.round(((end-start)*60*1000)*this.config.hour_size_px/hour_ms)) % all_hours_height, 1)+"px";

				area.appendChild(block);
				blocks.push(block);
			}
		}

		return blocks;
	};

	scheduler._mark_timespans = function(){
		var data = this._els["dhx_cal_data"][0];
		var divs = [];
		//manually trigger rendering of configs for each column
		var date = new Date(scheduler._min_date);
		for(var i = 0, len = data.childNodes.length; i < len; i++){
			var area = data.childNodes[i];
			if(area.firstChild && (area.firstChild.className || "").indexOf("dhx_scale_hour") > -1){
				continue;
			}

			divs.push.apply(divs, scheduler._on_scale_add_marker(area, date));
			date = scheduler.date.add(date, 1, "day");
		}
		return divs;
	};

	// just marks timespan, will be cleaned after refresh
	scheduler.markTimespan = function(configuration) {

		var rebuild_els = false;
		if(!this._els["dhx_cal_data"]){
			scheduler.get_elements();
			rebuild_els = true;
		}


		// backup regular marked timespans
		var timespans_ids = scheduler._marked_timespans_ids,
			timespan_types = scheduler._marked_timespans_types,
			timespans = scheduler._marked_timespans;

		scheduler.deleteMarkedTimespan();

		//add block to configs
		scheduler.addMarkedTimespan(configuration);

		var divs = scheduler._mark_timespans();

		if(rebuild_els)
			scheduler._els = [];

		// restore timespan config
		scheduler._marked_timespans_ids = timespans_ids;
		scheduler._marked_timespans_types = timespan_types;
		scheduler._marked_timespans = timespans;

		return divs;
	};
	scheduler.unmarkTimespan = function(divs) {
		if (!divs)
			return;
		for (var i=0; i<divs.length; i++) {
			var div = divs[i];
			// parent may no longer be present if we switched views, navigated
			if (div.parentNode) {
				div.parentNode.removeChild(div);
			}
		}
	};

	scheduler._marked_timespans_ids = {};
	// adds marked timespan to collections, persistent
	scheduler.addMarkedTimespan = function(configuration) {
		var configs = scheduler._prepare_timespan_options(configuration);
		var global = "global";

		if (!configs.length)
			return; // options are incorrect, nothing to mark

		var id = configs[0].id;
		var timespans = scheduler._marked_timespans;
		var ids = scheduler._marked_timespans_ids;
		if (!ids[id])
			ids[id] = [];

		for (var i=0; i<configs.length; i++) {
			var config = configs[i];
			var day = config.days;
			var zones = config.zones;
			var css = config.css;
			var sections = config.sections;
			var type = config.type; // default or specified
			config.id = id;

			if (sections) {
				for (var view_key in sections) {
					if (sections.hasOwnProperty(view_key)) {
						if (!timespans[view_key])
							timespans[view_key] = {};
						var unit_id = sections[view_key];
						var timespans_view = timespans[view_key];
						if (!timespans_view[unit_id])
							timespans_view[unit_id] = {};
						if (!timespans_view[unit_id][day])
							timespans_view[unit_id][day] = {};
						if (!timespans_view[unit_id][day][type]){
							timespans_view[unit_id][day][type] = [];
							if(!scheduler._marked_timespans_types)
								scheduler._marked_timespans_types = {};
							if(!scheduler._marked_timespans_types[type])
								scheduler._marked_timespans_types[type] = true;
						}
						var day_configs = timespans_view[unit_id][day][type];
						config._array = day_configs;
						day_configs.push(config);
						ids[id].push(config);
					}
				}
			} else {
				if (!timespans[global][day])
					timespans[global][day] = {};
				if (!timespans[global][day][type])
					timespans[global][day][type] = [];

				if(!scheduler._marked_timespans_types)
					scheduler._marked_timespans_types = {};
				if(!scheduler._marked_timespans_types[type])
					scheduler._marked_timespans_types[type] = true;


				var day_configs = timespans[global][day][type];
				config._array = day_configs;
				day_configs.push(config);
				ids[id].push(config);
			}
		}
		return id;
	};
	// not used for now
	scheduler._add_timespan_zones = function(current_zones, zones) {
		var resulting_zones = current_zones.slice();
		zones = zones.slice();

		if (!resulting_zones.length)
			return zones;

		for (var i=0; i<resulting_zones.length; i+=2) {
			var c_zone_start = resulting_zones[i];
			var c_zone_end = resulting_zones[i+1];
			var isLast = (i+2 == resulting_zones.length);

			for (var k=0; k<zones.length; k+=2) {
				var zone_start = zones[k];
				var zone_end = zones[k+1];
				if ((zone_end > c_zone_end && zone_start <= c_zone_end) || (zone_start < c_zone_start && zone_end >= c_zone_start)) {
					resulting_zones[i] = Math.min(c_zone_start, zone_start);
					resulting_zones[i+1] = Math.max(c_zone_end, zone_end);
					i -= 2;
				} else {
					if (!isLast) // do nothing, maybe next current zone will match or will be last
						continue;

					var offset = (c_zone_start > zone_start)?0:2;
					resulting_zones.splice(i+offset, 0, zone_start, zone_end); // last current zone, need to add another
				}
				zones.splice(k--,2); // zone was merged or added, need to exclude it
				break;
			}
		}
		return resulting_zones;
	};
	scheduler._subtract_timespan_zones = function(current_zones, zones) {
		var resulting_zones = current_zones.slice();
		for (var i=0; i<resulting_zones.length; i+=2 ) {
			var c_zone_start = resulting_zones[i];// current_zone_start
			var c_zone_end = resulting_zones[i+1];
			for (var k=0; k<zones.length; k+=2) {
				var zone_start = zones[k];
				var zone_end = zones[k+1];
				if (zone_end > c_zone_start && zone_start < c_zone_end) {
					var is_modified = false;
					if (c_zone_start >= zone_start && c_zone_end <= zone_end) {
						resulting_zones.splice(i, 2);
					}				
					if (c_zone_start < zone_start) {
						resulting_zones.splice(i, 2, c_zone_start, zone_start);
						is_modified = true;
					}
					if (c_zone_end > zone_end) {
						resulting_zones.splice( (is_modified)?(i+2):i, (is_modified)?0:2, zone_end, c_zone_end);
					}
					i -= 2;
					break;
				} else {
					continue;
				}
			}
		}
		return resulting_zones;
	};
	scheduler.invertZones = function(zones) {
		return scheduler._subtract_timespan_zones([0, 1440], zones.slice());
	};
	scheduler._delete_marked_timespan_by_id = function(id) {
		var configs = scheduler._marked_timespans_ids[id];
		if (configs) {
			for (var i=0; i<configs.length; i++) {
				var config = configs[i];
				var parent_array = config._array;
				for (var k=0; k<parent_array.length; k++) {
					if (parent_array[k] == config) {
						parent_array.splice(k, 1);
						break;
					}
				}
			}
		}
	};
	scheduler._delete_marked_timespan_by_config = function(config) {
		var timespans = scheduler._marked_timespans;
		var sections = config.sections;
		var day = config.days;
		var type = config.type||default_timespan_type;
		var day_timespans = []; // array of timespans to subtract our config
		if (sections) {
			for (var view_key in sections) {
				if (sections.hasOwnProperty(view_key) && timespans[view_key]) {
					var unit_id = sections[view_key];
					if (timespans[view_key][unit_id] && timespans[view_key][unit_id][day] && timespans[view_key][unit_id][day][type])
						day_timespans = timespans[view_key][unit_id][day][type];
				}
			}
		} else {
			if (timespans.global[day] && timespans.global[day][type])
				day_timespans = timespans.global[day][type];
		}
		for (var i=0; i<day_timespans.length; i++) {
			var d_t = day_timespans[i];
			var zones = scheduler._subtract_timespan_zones(d_t.zones, config.zones);
			if (zones.length)
				d_t.zones = zones;
			else {
				day_timespans.splice(i,1);
				i--;
				// need to update ids collection
				var related_zones = scheduler._marked_timespans_ids[d_t.id];
				for (var k=0; k<related_zones.length; k++) {
					if (related_zones[k] == d_t) {
						related_zones.splice(k, 1);
						break;
					}
				}
			}
		}

		for (var i in scheduler._marked_timespans.timeline) {
			for (var j in scheduler._marked_timespans.timeline[i]) {
				for (var k in scheduler._marked_timespans.timeline[i][j]) {
					if (k === type) {
						delete scheduler._marked_timespans.timeline[i][j][k];
					}
				}
			}
		}
	};
	scheduler.deleteMarkedTimespan = function(configuration) {
		// delete everything
		if (!arguments.length) {
			scheduler._marked_timespans = { global: {} };
			scheduler._marked_timespans_ids = {};
			scheduler._marked_timespans_types = {};
		}

		if (typeof configuration != "object") { // id was passed
			scheduler._delete_marked_timespan_by_id(configuration);
		} else { // normal configuration was passed

			if(!(configuration.start_date && configuration.end_date)){
				if(!configuration.days)
					configuration.days = "fullweek";
				if(!configuration.zones)
					configuration.zones = "fullday";
			}

			var types = [];
			if(!configuration.type){
				//if type not specified - delete timespans of all types
				for(var type in scheduler._marked_timespans_types){
					types.push(type);
				}
			}else{
				types.push(configuration.type);
			}


			var configs = scheduler._prepare_timespan_options(configuration);

			for (var i=0; i<configs.length; i++) {

				var config = configs[i];
				for( var t=0; t < types.length; t++){
					var typedConfig = scheduler._lame_clone(config);
					typedConfig.type = types[t];
					scheduler._delete_marked_timespan_by_config(typedConfig);
				}
			}

		}
	};
	scheduler._get_types_to_render = function(common, specific) {
		var types_to_render = (common) ? scheduler._lame_copy({},common) : {};
		for (var type in specific||{} ) {
			if (specific.hasOwnProperty(type)) {
				types_to_render[type] = specific[type];
			}
		}
		return types_to_render;
	};
	scheduler._get_configs_to_render = function(types) {
		var configs = [];
		for (var type in types) {
			if (types.hasOwnProperty(type)) {
				configs.push.apply(configs, types[type]);
			}
		}
		return configs;
	};

	scheduler._on_scale_add_marker = function(area, day){
		if (scheduler._table_view && scheduler._mode != "month")
			return;

		var day_index = day.getDay();
		var day_value = day.valueOf();
		var mode = this._mode;
		var timespans = scheduler._marked_timespans;
		var r_configs = [];
		var divs = [];
		if (this._props && this._props[mode]) { // we are in the units view and need to draw it's sections as well
			var view = this._props[mode]; // units view object
			var units = view.options;
			var index = scheduler._get_unit_index(view, day);
			var unit = units[index]; // key, label

			if(!(view.days > 1)){
				day = scheduler.date.date_part(new Date(this._date)); // for units view actually only 1 day is displayed yet the day variable will change, need to use this._date for all calls
			}else{
				var dx = 24*60*60*1000;
				var day_ind = Math.round((day - scheduler._min_date)/dx);

				day = scheduler.date.add(scheduler._min_date, Math.floor(day_ind/units.length), "day"); // to the "same" day for all sections
				day = scheduler.date.date_part(day);
			}
			day_index = day.getDay();
			day_value = day.valueOf();

			if (timespans[mode] && timespans[mode][unit.key]) {
				var unit_zones = timespans[mode][unit.key];
				var unit_types = scheduler._get_types_to_render(unit_zones[day_index], unit_zones[day_value]);
				r_configs.push.apply(r_configs, scheduler._get_configs_to_render(unit_types));
			}
		}

		var global_data = timespans["global"];
		var day_types = global_data[day_value]||global_data[day_index];
		r_configs.push.apply(r_configs, scheduler._get_configs_to_render(day_types));

		for (var i=0; i<r_configs.length; i++) {
			divs.push.apply(divs, (scheduler._render_marked_timespan(r_configs[i], area, day)));
		}
		return divs;
	};
	scheduler.attachEvent("onScaleAdd", function(){
		scheduler._on_scale_add_marker.apply(scheduler, arguments);
	});

	scheduler.dblclick_dhx_marked_timespan = function(e,src){
		if (!scheduler.config.dblclick_create){
			scheduler.callEvent("onScaleDblClick",[scheduler.getActionData(e).date,src,e]);
		}
		scheduler.addEventNow(scheduler.getActionData(e).date,null,e);
	};

};
scheduler._temp_limit_scope();
(function() {
  $j(function() {
    $j(' .j_link_to_remote').live('click', function(event) {
      var data, display_status, ref, submit, type;
      display_status = (function(_this) {
        return function(response, update_el) {
          var new_html, upd;
          if ($j(_this).is('.ui .button.loading')) {
            $j(_this).removeClass('loading');
          }
          hideSpinner(_this);
          if ((upd = $j(_this).attr('update') || update_el)) {
            new_html = response.responseText || response;
            $j('#' + upd).html(new_html);
            $j('#' + upd).effect('highlight');
          }
          return false;
        };
      })(this);
      if ($j(this).data('method')) {
        type = $j(this).data('method');
      } else if ($j(this).data('ajax-method')) {
        type = $j(this).data('ajax-method');
      } else {
        type = 'POST';
      }
      data = {};
      submit = $j(this).attr('submit');
      if (submit && submit.length > 0) {
        data = $j('#' + $j(this).attr('submit')).find('input, select, textarea').serialize();
      }
      $j.ajax($j(this).attr('url'), {
        type: type,
        data: data,
        async: $j(this).data('async') || false,
        dataType: (ref = $j(this).data('data_type')) != null ? ref : 'script',
        beforeSend: (function(_this) {
          return function() {
            if ($j(_this).is('.ui .button')) {
              $j(_this).addClass('loading');
            }
            return showSpinner(_this);
          };
        })(this),
        complete: display_status,
        error: (function(_this) {
          return function() {
            return display_status({
              responseText: "FAILURE!"
            }, $j(_this).data('error_notification'));
          };
        })(this)
      });
      event.preventDefault();
      return false;
    });
    $j(' .spinnable[form_to_submit]').live('ajax:before', function() {
      $j(this).data('params', $j('#' + $j(this).attr('form_to_submit')).find('input,select,textarea').serialize());
      return true;
    });
    $j(' .spinnable[loading]').live('ajax:before', function() {
      eval($j(this).attr('loading'));
      return true;
    });
    $j(' .spinnable[success]').live('ajax:complete', function() {
      eval($j(this).attr('success'));
      return true;
    });
    $j(' .customizable_form_for_inplace_display_ok_link').live('click', function() {
      var id_string;
      id_string = $j(this).attr('id_string');
      $j.ajax($j(this).attr('url'), {
        type: $j(this).attr('method'),
        data: $j("#" + id_string + "_form").serialize(),
        beforeSend: function() {
          $j("#loader_" + id_string).show();
          return $j("#" + id_string + "_form").hide();
        },
        complete: function() {
          $j("#loader_" + id_string).hide();
          return Tipped.refresh("*");
        }
      });
      return false;
    });
    $j(' .spinnable[update]').live('ajax:complete', function(event, response) {
      $j('#' + $j(this).attr('update')).html(response.responseText);
      return true;
    });
    $j(' .sort_equipment_link').live('click', function() {
      $j.ajax($j(this).attr('url'), {
        type: 'GET',
        dataType: "html",
        beforeSend: function() {
          $j('#projects_list').hide();
          $j('#equipment').append(createSpinner());
          return Tipped.hide('#equipment-more-actions');
        },
        success: function(response) {
          return $j('#equipment').html(response);
        }
      });
      return false;
    });
    $j(' .initiate_employee_training_link').live('click', function() {
      var checkChangeTabFinished;
      changeTab('services');
      alert('You will be directed to a form momentarily.');
      checkChangeTabFinished = setInterval((function(_this) {
        return function() {
          if ($j("#services_list").length) {
            $j.ajax($j(_this).attr('url'), {
              type: 'GET',
              dataType: 'script',
              beforeSend: function() {
                return showSpinner(_this);
              },
              success: function(response) {
                return hideSpinner(_this);
              }
            });
            return clearInterval(checkChangeTabFinished);
          }
        };
      })(this), 200);
      return false;
    });
    $j(' .location_show_details_link').live('click', function() {
      var star_id;
      star_id = $j(this).attr('star_id');
      $j.ajax($j(this).attr('url'), {
        type: 'GET',
        beforeSend: (function(_this) {
          return function() {
            return $j('#location_browser_spinner').show();
          };
        })(this),
        success: (function(_this) {
          return function() {
            $j('#star').remove();
            $j("#" + star_id).append("<span id='star'><img src='/images/small_right_arrow.png'></span>");
            return $j('#location_browser_spinner').hide();
          };
        })(this)
      });
      return false;
    });
    $j('#create_service_item_draft').live('click', function() {
      var data, link, service_item_id;
      link = $j(this);
      $j('.study_information :input').addClass('exclude_from_submition');
      $j('.study_information .service_row_custom_form_warn').addClass('exclude_from_submition');
      $j('.study_information .service_row_custom_form').addClass('exclude_from_submition');
      $j('#state_to').val(link.data('draft'));
      service_item_id = $j('[name="service_item_id"]').val();
      updateNewSIPrices("service_item_timeline_" + service_item_id);
      data = $j('#service_item_form_new :input').not('.exclude_from_submition').serialize().replace(/template_fields.*?=.*?&/, '');
      if ($j('#service_item_details')[0].innerHTML.trim().length > 0) {
        $j.ajax("/service_item/create", {
          dataType: "script",
          data: data,
          type: 'POST',
          beforeSend: (function(_this) {
            return function() {
              var additional_params, i, id, ids, len, results;
              process('create_service_item');
              if (link.data('employee')) {
                $j('#create_service_item_draft').addClass('disabled').prop('disabled', 'disabled');
              }
              window.canSubmitServiceItem = true;
              ids = [];
              if ($j('#service_item_details .service_row_custom_form_warn').not('.exclude_from_submition').length > 0) {
                $j('#service_item_details .service_row_custom_form_warn').not('.exclude_from_submition').each(function() {
                  return ids.push($j(this).attr('id').match(/\d+/)[0]);
                });
              }
              results = [];
              for (i = 0, len = ids.length; i < len; i++) {
                id = ids[i];
                if ($j("#view_custom_form_" + id).length > 0) {
                  additional_params = 'status=completed';
                  additional_params += '&draft_form=true';
                  if (link.data("no_warning")) {
                    additional_params += '&no_warning=true';
                  }
                  data = $j("#view_custom_form_" + id + " :input").not('.exclude_from_submition').serialize();
                  results.push($j.ajax("/custom_form/save/" + id + "?" + additional_params, {
                    type: 'POST',
                    data: data,
                    dataType: "script",
                    async: false
                  }));
                } else {
                  results.push(void 0);
                }
              }
              return results;
            };
          })(this),
          complete: (function(_this) {
            return function() {
              return unprocess('create_service_item');
            };
          })(this),
          success: (function(_this) {
            return function(data) {
              return clearInterval(new_si_interval);
            };
          })(this)
        });
      }
      return false;
    });
    $j('#delete_service_item').live('ajax:beforeSend', function(e, xhr, settings) {});
    $j('#delete_service_item').live('ajax:complete', function(xhr, status) {
      return clearInterval(new_si_interval);
    });
    $j('#new_custom_form_link').live('ajax:before', function(e, xhr, settings) {
      var elements, link;
      link = $j(this);
      elements = $j('#template_fields_table').find('tbody').add(link.closest('thead'));
      $j('.tf_fields_size').val($j('#custom_form_edit_fields tr').length);
      link.data('params', elements.find('input,select,textarea').serialize());
      return true;
    });
    $j(' .product_set_hazardous_link').live('click', function() {
      var params_yw, product_id;
      product_id = $j(this).attr('product_id');
      params_yw = $j(this).attr('params_yw');
      if ($j(this).attr('remove').length > 0) {
        return $j.ajax($j(this).attr('url'), {
          type: 'GET',
          beforeSend: (function(_this) {
            return function() {
              showSpinner(_this);
              $j('#product_' + product_id).remove();
              return decrementMaterialsToClassifyCount(params_yw);
            };
          })(this),
          success: (function(_this) {
            return function() {
              return hideSpinner(_this);
            };
          })(this)
        });
      } else {
        return $j.ajax($j(this).attr('url'), {
          type: 'GET',
          beforeSend: (function(_this) {
            return function() {
              showSpinner(_this);
              material_line_update_notify(product_id);
              return decrementMaterialsToClassifyCount(params_yw);
            };
          })(this),
          success: (function(_this) {
            return function() {
              hideSpinner(_this);
              return attachHazardousForm($j('#is_haz_button_' + product_id));
            };
          })(this)
        });
      }
    });
    $j(' .unfavorite_product_link').live('ajax:complete', function(e, xhr, settings) {
      return $j('#bookmark_wrapper_' + $j(this).attr('product_id')).removeClass('fav_on');
    });
    $j(' .favorite_product_link').live('ajax:complete', function(e, xhr, settings) {
      return $j('#bookmark_wrapper_' + $j(this).attr('product_id')).addClass('fav_on');
    });
    $j(' .reload_hazardous_material_classification').live('click', function() {
      var spinner;
      spinner = createSpinner();
      $j.ajax($j(this).attr('url'), {
        type: 'GET',
        beforeSend: (function(_this) {
          return function() {
            $j('#material_classification_content').html('');
            $j('#material_classification').append(spinner);
            return Tipped.hideAll();
          };
        })(this),
        success: function() {
          return spinner.remove();
        }
      });
      return false;
    });
    $j(' .lab_unfavorite_product_link').live('ajax:complete', function(e, xhr, settings) {
      return $j('#bookmark_wrapper_lab_' + $j(this).attr('product_id')).removeClass('fav_on');
    });
    $j(' .lab_favorite_product_link').live('ajax:complete', function(e, xhr, settings) {
      return $j('#bookmark_wrapper_lab_' + $j(this).attr('product_id')).addClass('fav_on');
    });
    $j(' .save_service_item_contact').live('ajax:before', function(e, xhr) {
      $j(this).data('params', $j('#' + $j(this).attr('form_to_submit')).find('input,select,textarea').serialize());
      return true;
    });
    $j(' .save_service_item_contact').live('ajax:before', function(e, xhr) {
      $j(this).data('params', $j('#' + $j(this).attr('form_to_submit')).find('input,select,textarea').serialize());
      return true;
    });
    $j(' .reservations_links').live('click', function(event) {
      var element_id;
      event.preventDefault();
      element_id = $j(this).attr('data-resource');
      $j.ajax($j(this).attr('href'), {
        type: 'POST',
        data: 'script',
        data: $j('#' + element_id).serialize(),
        beforeSend: function() {
          return $j("#reservations_spinner").show();
        },
        complete: function() {
          return $j("#reservations_spinner").hide();
        }
      });
      return false;
    });
    $j(' .j_link_to_remote_with_tinymce').live('click', function() {
      var data;
      tinyMCE.triggerSave(true, true);
      data = $j('#' + $j(this).attr('submit')).find('input,select,textarea').serializeArray();
      $j.ajax($j(this).attr('url'), {
        type: 'POST',
        data: data,
        dataType: 'script',
        beforeSend: (function(_this) {
          return function() {
            return showSpinner(_this);
          };
        })(this),
        complete: (function(_this) {
          return function() {
            return hideSpinner(_this);
          };
        })(this),
        error: (function(_this) {
          return function() {
            var elem, id;
            id = '#' + $j(_this).data('error_notification');
            elem = $j(id);
            elem.html('FAILURE!');
            return elem.effect('highlight');
          };
        })(this)
      });
      return false;
    });
    $j(' .save_hazardous_info_button').live('click', function() {
      var data, product_id;
      product_id = $j(this).attr('product_id');
      data = $j("#hazardous_form_" + product_id + ' input, select').serialize();
      $j.ajax($j(this).attr('url'), {
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            showSpinner(_this);
            return eval($j(_this).attr('loading_string'));
          };
        })(this),
        success: (function(_this) {
          return function() {
            hideSpinner(_this);
            return attachHazardousForm($j('#is_haz_button_' + product_id));
          };
        })(this)
      });
      return false;
    });
    $j('#edit_time_summary').live('click', function() {
      return false;
    });
    $j(' .institution_add_department_link').live('click', function() {
      var data, name;
      name = $j('#new_department_name').val().replace(/^\s+|\s+$/g, "");
      if (name === '') {
        alert('You need to add department name.');
      } else {
        if (confirm("Are you sure you would like to create a new department?")) {
          data = {
            name: name
          };
          $j.ajax($j(this).attr('url'), {
            type: 'GET',
            data: data,
            dataType: 'script',
            beforeSend: (function(_this) {
              return function() {
                return showSpinner(_this);
              };
            })(this),
            success: (function(_this) {
              return function() {
                return hideSpinner(_this);
              };
            })(this)
          });
        }
      }
      return false;
    });
    $j(' .remote_cached').live('click', function(event) {
      var data, ref, submit, type, upd;
      showSpinner($j(this).closest('.button'));
      if ($j(this).data('method')) {
        type = $j(this).data('method');
      } else if ($j(this).data('ajax-method')) {
        type = $j(this).data('ajax-method');
      } else {
        type = 'GET';
      }
      data = {};
      submit = $j(this).attr('submit');
      if (submit && submit.length > 0) {
        data = $j('#' + $j(this).attr('submit')).find('input, select, textarea').serialize();
      }
      if ($j(this).hasClass('loaded')) {
        if ((upd = $j(this).attr('update'))) {
          $j('#' + upd).toggle();
        }
        $j(this).toggleClass('expanded');
        hideSpinner($j(this).closest('.button'));
      } else {
        $j.ajax($j(this).attr('url'), {
          type: type,
          data: data,
          async: false,
          dataType: (ref = $j(this).data('data_type')) != null ? ref : 'script',
          complete: (function(_this) {
            return function(response) {
              var new_html;
              $j(_this).addClass('expanded');
              $j(_this).addClass('loaded');
              if ((upd = $j(_this).attr('update'))) {
                new_html = response.responseText || response;
                $j('#' + upd).html(new_html);
                $j('#' + upd).effect('highlight');
              }
              hideSpinner($j(_this).closest('.button'));
              return false;
            };
          })(this)
        });
      }
      event.preventDefault();
      return false;
    });
    return false;
  });

}).call(this);
 /*
 * # Semantic UI - 2.2.13
 * https://github.com/Semantic-Org/Semantic-UI
 * http://www.semantic-ui.com/
 *
 * Copyright 2014 Contributors
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */
/*!
 * # Semantic UI 2.2.13 - Site
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */


;(function ($, window, document, undefined) {

$.site = $.fn.site = function(parameters) {
  var
    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),

    settings        = ( $.isPlainObject(parameters) )
      ? $.extend(true, {}, $.site.settings, parameters)
      : $.extend({}, $.site.settings),

    namespace       = settings.namespace,
    error           = settings.error,

    eventNamespace  = '.' + namespace,
    moduleNamespace = 'module-' + namespace,

    $document       = $(document),
    $module         = $document,
    element         = this,
    instance        = $module.data(moduleNamespace),

    module,
    returnedValue
  ;
  module = {

    initialize: function() {
      module.instantiate();
    },

    instantiate: function() {
      module.verbose('Storing instance of site', module);
      instance = module;
      $module
        .data(moduleNamespace, module)
      ;
    },

    normalize: function() {
      module.fix.console();
      module.fix.requestAnimationFrame();
    },

    fix: {
      console: function() {
        module.debug('Normalizing window.console');
        if (console === undefined || console.log === undefined) {
          module.verbose('Console not available, normalizing events');
          module.disable.console();
        }
        if (typeof console.group == 'undefined' || typeof console.groupEnd == 'undefined' || typeof console.groupCollapsed == 'undefined') {
          module.verbose('Console group not available, normalizing events');
          window.console.group = function() {};
          window.console.groupEnd = function() {};
          window.console.groupCollapsed = function() {};
        }
        if (typeof console.markTimeline == 'undefined') {
          module.verbose('Mark timeline not available, normalizing events');
          window.console.markTimeline = function() {};
        }
      },
      consoleClear: function() {
        module.debug('Disabling programmatic console clearing');
        window.console.clear = function() {};
      },
      requestAnimationFrame: function() {
        module.debug('Normalizing requestAnimationFrame');
        if(window.requestAnimationFrame === undefined) {
          module.debug('RequestAnimationFrame not available, normalizing event');
          window.requestAnimationFrame = window.requestAnimationFrame
            || window.mozRequestAnimationFrame
            || window.webkitRequestAnimationFrame
            || window.msRequestAnimationFrame
            || function(callback) { setTimeout(callback, 0); }
          ;
        }
      }
    },

    moduleExists: function(name) {
      return ($.fn[name] !== undefined && $.fn[name].settings !== undefined);
    },

    enabled: {
      modules: function(modules) {
        var
          enabledModules = []
        ;
        modules = modules || settings.modules;
        $.each(modules, function(index, name) {
          if(module.moduleExists(name)) {
            enabledModules.push(name);
          }
        });
        return enabledModules;
      }
    },

    disabled: {
      modules: function(modules) {
        var
          disabledModules = []
        ;
        modules = modules || settings.modules;
        $.each(modules, function(index, name) {
          if(!module.moduleExists(name)) {
            disabledModules.push(name);
          }
        });
        return disabledModules;
      }
    },

    change: {
      setting: function(setting, value, modules, modifyExisting) {
        modules = (typeof modules === 'string')
          ? (modules === 'all')
            ? settings.modules
            : [modules]
          : modules || settings.modules
        ;
        modifyExisting = (modifyExisting !== undefined)
          ? modifyExisting
          : true
        ;
        $.each(modules, function(index, name) {
          var
            namespace = (module.moduleExists(name))
              ? $.fn[name].settings.namespace || false
              : true,
            $existingModules
          ;
          if(module.moduleExists(name)) {
            module.verbose('Changing default setting', setting, value, name);
            $.fn[name].settings[setting] = value;
            if(modifyExisting && namespace) {
              $existingModules = $(':data(module-' + namespace + ')');
              if($existingModules.length > 0) {
                module.verbose('Modifying existing settings', $existingModules);
                $existingModules[name]('setting', setting, value);
              }
            }
          }
        });
      },
      settings: function(newSettings, modules, modifyExisting) {
        modules = (typeof modules === 'string')
          ? [modules]
          : modules || settings.modules
        ;
        modifyExisting = (modifyExisting !== undefined)
          ? modifyExisting
          : true
        ;
        $.each(modules, function(index, name) {
          var
            $existingModules
          ;
          if(module.moduleExists(name)) {
            module.verbose('Changing default setting', newSettings, name);
            $.extend(true, $.fn[name].settings, newSettings);
            if(modifyExisting && namespace) {
              $existingModules = $(':data(module-' + namespace + ')');
              if($existingModules.length > 0) {
                module.verbose('Modifying existing settings', $existingModules);
                $existingModules[name]('setting', newSettings);
              }
            }
          }
        });
      }
    },

    enable: {
      console: function() {
        module.console(true);
      },
      debug: function(modules, modifyExisting) {
        modules = modules || settings.modules;
        module.debug('Enabling debug for modules', modules);
        module.change.setting('debug', true, modules, modifyExisting);
      },
      verbose: function(modules, modifyExisting) {
        modules = modules || settings.modules;
        module.debug('Enabling verbose debug for modules', modules);
        module.change.setting('verbose', true, modules, modifyExisting);
      }
    },
    disable: {
      console: function() {
        module.console(false);
      },
      debug: function(modules, modifyExisting) {
        modules = modules || settings.modules;
        module.debug('Disabling debug for modules', modules);
        module.change.setting('debug', false, modules, modifyExisting);
      },
      verbose: function(modules, modifyExisting) {
        modules = modules || settings.modules;
        module.debug('Disabling verbose debug for modules', modules);
        module.change.setting('verbose', false, modules, modifyExisting);
      }
    },

    console: function(enable) {
      if(enable) {
        if(instance.cache.console === undefined) {
          module.error(error.console);
          return;
        }
        module.debug('Restoring console function');
        window.console = instance.cache.console;
      }
      else {
        module.debug('Disabling console function');
        instance.cache.console = window.console;
        window.console = {
          clear          : function(){},
          error          : function(){},
          group          : function(){},
          groupCollapsed : function(){},
          groupEnd       : function(){},
          info           : function(){},
          log            : function(){},
          markTimeline   : function(){},
          warn           : function(){}
        };
      }
    },

    destroy: function() {
      module.verbose('Destroying previous site for', $module);
      $module
        .removeData(moduleNamespace)
      ;
    },

    cache: {},

    setting: function(name, value) {
      if( $.isPlainObject(name) ) {
        $.extend(true, settings, name);
      }
      else if(value !== undefined) {
        settings[name] = value;
      }
      else {
        return settings[name];
      }
    },
    internal: function(name, value) {
      if( $.isPlainObject(name) ) {
        $.extend(true, module, name);
      }
      else if(value !== undefined) {
        module[name] = value;
      }
      else {
        return module[name];
      }
    },
    debug: function() {
      if(settings.debug) {
        if(settings.performance) {
          module.performance.log(arguments);
        }
        else {
          module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
          module.debug.apply(console, arguments);
        }
      }
    },
    verbose: function() {
      if(settings.verbose && settings.debug) {
        if(settings.performance) {
          module.performance.log(arguments);
        }
        else {
          module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
          module.verbose.apply(console, arguments);
        }
      }
    },
    error: function() {
      module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
      module.error.apply(console, arguments);
    },
    performance: {
      log: function(message) {
        var
          currentTime,
          executionTime,
          previousTime
        ;
        if(settings.performance) {
          currentTime   = new Date().getTime();
          previousTime  = time || currentTime;
          executionTime = currentTime - previousTime;
          time          = currentTime;
          performance.push({
            'Element'        : element,
            'Name'           : message[0],
            'Arguments'      : [].slice.call(message, 1) || '',
            'Execution Time' : executionTime
          });
        }
        clearTimeout(module.performance.timer);
        module.performance.timer = setTimeout(module.performance.display, 500);
      },
      display: function() {
        var
          title = settings.name + ':',
          totalTime = 0
        ;
        time = false;
        clearTimeout(module.performance.timer);
        $.each(performance, function(index, data) {
          totalTime += data['Execution Time'];
        });
        title += ' ' + totalTime + 'ms';
        if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
          console.groupCollapsed(title);
          if(console.table) {
            console.table(performance);
          }
          else {
            $.each(performance, function(index, data) {
              console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
            });
          }
          console.groupEnd();
        }
        performance = [];
      }
    },
    invoke: function(query, passedArguments, context) {
      var
        object = instance,
        maxDepth,
        found,
        response
      ;
      passedArguments = passedArguments || queryArguments;
      context         = element         || context;
      if(typeof query == 'string' && object !== undefined) {
        query    = query.split(/[\. ]/);
        maxDepth = query.length - 1;
        $.each(query, function(depth, value) {
          var camelCaseValue = (depth != maxDepth)
            ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
            : query
          ;
          if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
            object = object[camelCaseValue];
          }
          else if( object[camelCaseValue] !== undefined ) {
            found = object[camelCaseValue];
            return false;
          }
          else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
            object = object[value];
          }
          else if( object[value] !== undefined ) {
            found = object[value];
            return false;
          }
          else {
            module.error(error.method, query);
            return false;
          }
        });
      }
      if ( $.isFunction( found ) ) {
        response = found.apply(context, passedArguments);
      }
      else if(found !== undefined) {
        response = found;
      }
      if($.isArray(returnedValue)) {
        returnedValue.push(response);
      }
      else if(returnedValue !== undefined) {
        returnedValue = [returnedValue, response];
      }
      else if(response !== undefined) {
        returnedValue = response;
      }
      return found;
    }
  };

  if(methodInvoked) {
    if(instance === undefined) {
      module.initialize();
    }
    module.invoke(query);
  }
  else {
    if(instance !== undefined) {
      module.destroy();
    }
    module.initialize();
  }
  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.site.settings = {

  name        : 'Site',
  namespace   : 'site',

  error : {
    console : 'Console cannot be restored, most likely it was overwritten outside of module',
    method : 'The method you called is not defined.'
  },

  debug       : false,
  verbose     : false,
  performance : true,

  modules: [
    'accordion',
    'api',
    'checkbox',
    'dimmer',
    'dropdown',
    'embed',
    'form',
    'modal',
    'nag',
    'popup',
    'rating',
    'shape',
    'sidebar',
    'state',
    'sticky',
    'tab',
    'transition',
    'visit',
    'visibility'
  ],

  siteNamespace   : 'site',
  namespaceStub   : {
    cache     : {},
    config    : {},
    sections  : {},
    section   : {},
    utilities : {}
  }

};

// allows for selection of elements with data attributes
$.extend($.expr[ ":" ], {
  data: ($.expr.createPseudo)
    ? $.expr.createPseudo(function(dataName) {
        return function(elem) {
          return !!$.data(elem, dataName);
        };
      })
    : function(elem, i, match) {
      // support: jQuery < 1.8
      return !!$.data(elem, match[ 3 ]);
    }
});


})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Form Validation
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.form = function(parameters) {
  var
    $allModules      = $(this),
    moduleSelector   = $allModules.selector || '',

    time             = new Date().getTime(),
    performance      = [],

    query            = arguments[0],
    legacyParameters = arguments[1],
    methodInvoked    = (typeof query == 'string'),
    queryArguments   = [].slice.call(arguments, 1),
    returnedValue
  ;
  $allModules
    .each(function() {
      var
        $module     = $(this),
        element     = this,

        formErrors  = [],
        keyHeldDown = false,

        // set at run-time
        $field,
        $group,
        $message,
        $prompt,
        $submit,
        $clear,
        $reset,

        settings,
        validation,

        metadata,
        selector,
        className,
        regExp,
        error,

        namespace,
        moduleNamespace,
        eventNamespace,

        instance,
        module
      ;

      module      = {

        initialize: function() {

          // settings grabbed at run time
          module.get.settings();
          if(methodInvoked) {
            if(instance === undefined) {
              module.instantiate();
            }
            module.invoke(query);
          }
          else {
            if(instance !== undefined) {
              instance.invoke('destroy');
            }
            module.verbose('Initializing form validation', $module, settings);
            module.bindEvents();
            module.set.defaults();
            module.instantiate();
          }
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous module', instance);
          module.removeEvents();
          $module
            .removeData(moduleNamespace)
          ;
        },

        refresh: function() {
          module.verbose('Refreshing selector cache');
          $field      = $module.find(selector.field);
          $group      = $module.find(selector.group);
          $message    = $module.find(selector.message);
          $prompt     = $module.find(selector.prompt);

          $submit     = $module.find(selector.submit);
          $clear      = $module.find(selector.clear);
          $reset      = $module.find(selector.reset);
        },

        submit: function() {
          module.verbose('Submitting form', $module);
          $module
            .submit()
          ;
        },

        attachEvents: function(selector, action) {
          action = action || 'submit';
          $(selector)
            .on('click' + eventNamespace, function(event) {
              module[action]();
              event.preventDefault();
            })
          ;
        },

        bindEvents: function() {
          module.verbose('Attaching form events');
          $module
            .on('submit' + eventNamespace, module.validate.form)
            .on('blur'   + eventNamespace, selector.field, module.event.field.blur)
            .on('click'  + eventNamespace, selector.submit, module.submit)
            .on('click'  + eventNamespace, selector.reset, module.reset)
            .on('click'  + eventNamespace, selector.clear, module.clear)
          ;
          if(settings.keyboardShortcuts) {
            $module
              .on('keydown' + eventNamespace, selector.field, module.event.field.keydown)
            ;
          }
          $field
            .each(function() {
              var
                $input     = $(this),
                type       = $input.prop('type'),
                inputEvent = module.get.changeEvent(type, $input)
              ;
              $(this)
                .on(inputEvent + eventNamespace, module.event.field.change)
              ;
            })
          ;
        },

        clear: function() {
          $field
            .each(function () {
              var
                $field       = $(this),
                $element     = $field.parent(),
                $fieldGroup  = $field.closest($group),
                $prompt      = $fieldGroup.find(selector.prompt),
                defaultValue = $field.data(metadata.defaultValue) || '',
                isCheckbox   = $element.is(selector.uiCheckbox),
                isDropdown   = $element.is(selector.uiDropdown),
                isErrored    = $fieldGroup.hasClass(className.error)
              ;
              if(isErrored) {
                module.verbose('Resetting error on field', $fieldGroup);
                $fieldGroup.removeClass(className.error);
                $prompt.remove();
              }
              if(isDropdown) {
                module.verbose('Resetting dropdown value', $element, defaultValue);
                $element.dropdown('clear');
              }
              else if(isCheckbox) {
                $field.prop('checked', false);
              }
              else {
                module.verbose('Resetting field value', $field, defaultValue);
                $field.val('');
              }
            })
          ;
        },

        reset: function() {
          $field
            .each(function () {
              var
                $field       = $(this),
                $element     = $field.parent(),
                $fieldGroup  = $field.closest($group),
                $prompt      = $fieldGroup.find(selector.prompt),
                defaultValue = $field.data(metadata.defaultValue),
                isCheckbox   = $element.is(selector.uiCheckbox),
                isDropdown   = $element.is(selector.uiDropdown),
                isErrored    = $fieldGroup.hasClass(className.error)
              ;
              if(defaultValue === undefined) {
                return;
              }
              if(isErrored) {
                module.verbose('Resetting error on field', $fieldGroup);
                $fieldGroup.removeClass(className.error);
                $prompt.remove();
              }
              if(isDropdown) {
                module.verbose('Resetting dropdown value', $element, defaultValue);
                $element.dropdown('restore defaults');
              }
              else if(isCheckbox) {
                module.verbose('Resetting checkbox value', $element, defaultValue);
                $field.prop('checked', defaultValue);
              }
              else {
                module.verbose('Resetting field value', $field, defaultValue);
                $field.val(defaultValue);
              }
            })
          ;
        },

        determine: {
          isValid: function() {
            var
              allValid = true
            ;
            $.each(validation, function(fieldName, field) {
              if( !( module.validate.field(field, fieldName, true) ) ) {
                allValid = false;
              }
            });
            return allValid;
          }
        },

        is: {
          bracketedRule: function(rule) {
            return (rule.type && rule.type.match(settings.regExp.bracket));
          },
          shorthandFields: function(fields) {
            var
              fieldKeys = Object.keys(fields),
              firstRule = fields[fieldKeys[0]]
            ;
            return module.is.shorthandRules(firstRule);
          },
          // duck type rule test
          shorthandRules: function(rules) {
            return (typeof rules == 'string' || $.isArray(rules));
          },
          empty: function($field) {
            if(!$field || $field.length === 0) {
              return true;
            }
            else if($field.is('input[type="checkbox"]')) {
              return !$field.is(':checked');
            }
            else {
              return module.is.blank($field);
            }
          },
          blank: function($field) {
            return $.trim($field.val()) === '';
          },
          valid: function(field) {
            var
              allValid = true
            ;
            if(field) {
              module.verbose('Checking if field is valid', field);
              return module.validate.field(validation[field], field, false);
            }
            else {
              module.verbose('Checking if form is valid');
              $.each(validation, function(fieldName, field) {
                if( !module.is.valid(fieldName) ) {
                  allValid = false;
                }
              });
              return allValid;
            }
          }
        },

        removeEvents: function() {
          $module
            .off(eventNamespace)
          ;
          $field
            .off(eventNamespace)
          ;
          $submit
            .off(eventNamespace)
          ;
          $field
            .off(eventNamespace)
          ;
        },

        event: {
          field: {
            keydown: function(event) {
              var
                $field       = $(this),
                key          = event.which,
                isInput      = $field.is(selector.input),
                isCheckbox   = $field.is(selector.checkbox),
                isInDropdown = ($field.closest(selector.uiDropdown).length > 0),
                keyCode      = {
                  enter  : 13,
                  escape : 27
                }
              ;
              if( key == keyCode.escape) {
                module.verbose('Escape key pressed blurring field');
                $field
                  .blur()
                ;
              }
              if(!event.ctrlKey && key == keyCode.enter && isInput && !isInDropdown && !isCheckbox) {
                if(!keyHeldDown) {
                  $field
                    .one('keyup' + eventNamespace, module.event.field.keyup)
                  ;
                  module.submit();
                  module.debug('Enter pressed on input submitting form');
                }
                keyHeldDown = true;
              }
            },
            keyup: function() {
              keyHeldDown = false;
            },
            blur: function(event) {
              var
                $field          = $(this),
                $fieldGroup     = $field.closest($group),
                validationRules = module.get.validation($field)
              ;
              if( $fieldGroup.hasClass(className.error) ) {
                module.debug('Revalidating field', $field, validationRules);
                if(validationRules) {
                  module.validate.field( validationRules );
                }
              }
              else if(settings.on == 'blur' || settings.on == 'change') {
                if(validationRules) {
                  module.validate.field( validationRules );
                }
              }
            },
            change: function(event) {
              var
                $field      = $(this),
                $fieldGroup = $field.closest($group),
                validationRules = module.get.validation($field)
              ;
              if(validationRules && (settings.on == 'change' || ( $fieldGroup.hasClass(className.error) && settings.revalidate) )) {
                clearTimeout(module.timer);
                module.timer = setTimeout(function() {
                  module.debug('Revalidating field', $field,  module.get.validation($field));
                  module.validate.field( validationRules );
                }, settings.delay);
              }
            }
          }

        },

        get: {
          ancillaryValue: function(rule) {
            if(!rule.type || (!rule.value && !module.is.bracketedRule(rule))) {
              return false;
            }
            return (rule.value !== undefined)
              ? rule.value
              : rule.type.match(settings.regExp.bracket)[1] + ''
            ;
          },
          ruleName: function(rule) {
            if( module.is.bracketedRule(rule) ) {
              return rule.type.replace(rule.type.match(settings.regExp.bracket)[0], '');
            }
            return rule.type;
          },
          changeEvent: function(type, $input) {
            if(type == 'checkbox' || type == 'radio' || type == 'hidden' || $input.is('select')) {
              return 'change';
            }
            else {
              return module.get.inputEvent();
            }
          },
          inputEvent: function() {
            return (document.createElement('input').oninput !== undefined)
              ? 'input'
              : (document.createElement('input').onpropertychange !== undefined)
                ? 'propertychange'
                : 'keyup'
            ;
          },
          fieldsFromShorthand: function(fields) {
            var
              fullFields = {}
            ;
            $.each(fields, function(name, rules) {
              if(typeof rules == 'string') {
                rules = [rules];
              }
              fullFields[name] = {
                rules: []
              };
              $.each(rules, function(index, rule) {
                fullFields[name].rules.push({ type: rule });
              });
            });
            return fullFields;
          },
          prompt: function(rule, field) {
            var
              ruleName      = module.get.ruleName(rule),
              ancillary     = module.get.ancillaryValue(rule),
              prompt        = rule.prompt || settings.prompt[ruleName] || settings.text.unspecifiedRule,
              requiresValue = (prompt.search('{value}') !== -1),
              requiresName  = (prompt.search('{name}') !== -1),
              $label,
              $field,
              name
            ;
            if(requiresName || requiresValue) {
              $field = module.get.field(field.identifier);
            }
            if(requiresValue) {
              prompt = prompt.replace('{value}', $field.val());
            }
            if(requiresName) {
              $label = $field.closest(selector.group).find('label').eq(0);
              name = ($label.length == 1)
                ? $label.text()
                : $field.prop('placeholder') || settings.text.unspecifiedField
              ;
              prompt = prompt.replace('{name}', name);
            }
            prompt = prompt.replace('{identifier}', field.identifier);
            prompt = prompt.replace('{ruleValue}', ancillary);
            if(!rule.prompt) {
              module.verbose('Using default validation prompt for type', prompt, ruleName);
            }
            return prompt;
          },
          settings: function() {
            if($.isPlainObject(parameters)) {
              var
                keys     = Object.keys(parameters),
                isLegacySettings = (keys.length > 0)
                  ? (parameters[keys[0]].identifier !== undefined && parameters[keys[0]].rules !== undefined)
                  : false,
                ruleKeys
              ;
              if(isLegacySettings) {
                // 1.x (ducktyped)
                settings   = $.extend(true, {}, $.fn.form.settings, legacyParameters);
                validation = $.extend({}, $.fn.form.settings.defaults, parameters);
                module.error(settings.error.oldSyntax, element);
                module.verbose('Extending settings from legacy parameters', validation, settings);
              }
              else {
                // 2.x
                if(parameters.fields && module.is.shorthandFields(parameters.fields)) {
                  parameters.fields = module.get.fieldsFromShorthand(parameters.fields);
                }
                settings   = $.extend(true, {}, $.fn.form.settings, parameters);
                validation = $.extend({}, $.fn.form.settings.defaults, settings.fields);
                module.verbose('Extending settings', validation, settings);
              }
            }
            else {
              settings   = $.fn.form.settings;
              validation = $.fn.form.settings.defaults;
              module.verbose('Using default form validation', validation, settings);
            }

            // shorthand
            namespace       = settings.namespace;
            metadata        = settings.metadata;
            selector        = settings.selector;
            className       = settings.className;
            regExp          = settings.regExp;
            error           = settings.error;
            moduleNamespace = 'module-' + namespace;
            eventNamespace  = '.' + namespace;

            // grab instance
            instance = $module.data(moduleNamespace);

            // refresh selector cache
            module.refresh();
          },
          field: function(identifier) {
            module.verbose('Finding field with identifier', identifier);
            identifier = module.escape.string(identifier);
            if($field.filter('#' + identifier).length > 0 ) {
              return $field.filter('#' + identifier);
            }
            else if( $field.filter('[name="' + identifier +'"]').length > 0 ) {
              return $field.filter('[name="' + identifier +'"]');
            }
            else if( $field.filter('[name="' + identifier +'[]"]').length > 0 ) {
              return $field.filter('[name="' + identifier +'[]"]');
            }
            else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').length > 0 ) {
              return $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]');
            }
            return $('<input/>');
          },
          fields: function(fields) {
            var
              $fields = $()
            ;
            $.each(fields, function(index, name) {
              $fields = $fields.add( module.get.field(name) );
            });
            return $fields;
          },
          validation: function($field) {
            var
              fieldValidation,
              identifier
            ;
            if(!validation) {
              return false;
            }
            $.each(validation, function(fieldName, field) {
              identifier = field.identifier || fieldName;
              if( module.get.field(identifier)[0] == $field[0] ) {
                field.identifier = identifier;
                fieldValidation = field;
              }
            });
            return fieldValidation || false;
          },
          value: function (field) {
            var
              fields = [],
              results
            ;
            fields.push(field);
            results = module.get.values.call(element, fields);
            return results[field];
          },
          values: function (fields) {
            var
              $fields = $.isArray(fields)
                ? module.get.fields(fields)
                : $field,
              values = {}
            ;
            $fields.each(function(index, field) {
              var
                $field     = $(field),
                type       = $field.prop('type'),
                name       = $field.prop('name'),
                value      = $field.val(),
                isCheckbox = $field.is(selector.checkbox),
                isRadio    = $field.is(selector.radio),
                isMultiple = (name.indexOf('[]') !== -1),
                isChecked  = (isCheckbox)
                  ? $field.is(':checked')
                  : false
              ;
              if(name) {
                if(isMultiple) {
                  name = name.replace('[]', '');
                  if(!values[name]) {
                    values[name] = [];
                  }
                  if(isCheckbox) {
                    if(isChecked) {
                      values[name].push(value || true);
                    }
                    else {
                      values[name].push(false);
                    }
                  }
                  else {
                    values[name].push(value);
                  }
                }
                else {
                  if(isRadio) {
                    if(values[name] === undefined) {
                      values[name] = (isChecked)
                        ? true
                        : false
                      ;
                    }
                  }
                  else if(isCheckbox) {
                    if(isChecked) {
                      values[name] = value || true;
                    }
                    else {
                      values[name] = false;
                    }
                  }
                  else {
                    values[name] = value;
                  }
                }
              }
            });
            return values;
          }
        },

        has: {

          field: function(identifier) {
            module.verbose('Checking for existence of a field with identifier', identifier);
            identifier = module.escape.string(identifier);
            if(typeof identifier !== 'string') {
              module.error(error.identifier, identifier);
            }
            if($field.filter('#' + identifier).length > 0 ) {
              return true;
            }
            else if( $field.filter('[name="' + identifier +'"]').length > 0 ) {
              return true;
            }
            else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').length > 0 ) {
              return true;
            }
            return false;
          }

        },

        escape: {
          string: function(text) {
            text =  String(text);
            return text.replace(regExp.escape, '\\$&');
          }
        },

        add: {
          // alias
          rule: function(name, rules) {
            module.add.field(name, rules);
          },
          field: function(name, rules) {
            var
              newValidation = {}
            ;
            if(module.is.shorthandRules(rules)) {
              rules = $.isArray(rules)
                ? rules
                : [rules]
              ;
              newValidation[name] = {
                rules: []
              };
              $.each(rules, function(index, rule) {
                newValidation[name].rules.push({ type: rule });
              });
            }
            else {
              newValidation[name] = rules;
            }
            validation = $.extend({}, validation, newValidation);
            module.debug('Adding rules', newValidation, validation);
          },
          fields: function(fields) {
            var
              newValidation
            ;
            if(fields && module.is.shorthandFields(fields)) {
              newValidation = module.get.fieldsFromShorthand(fields);
            }
            else {
              newValidation = fields;
            }
            validation = $.extend({}, validation, newValidation);
          },
          prompt: function(identifier, errors) {
            var
              $field       = module.get.field(identifier),
              $fieldGroup  = $field.closest($group),
              $prompt      = $fieldGroup.children(selector.prompt),
              promptExists = ($prompt.length !== 0)
            ;
            errors = (typeof errors == 'string')
              ? [errors]
              : errors
            ;
            module.verbose('Adding field error state', identifier);
            $fieldGroup
              .addClass(className.error)
            ;
            if(settings.inline) {
              if(!promptExists) {
                $prompt = settings.templates.prompt(errors);
                $prompt
                  .appendTo($fieldGroup)
                ;
              }
              $prompt
                .html(errors[0])
              ;
              if(!promptExists) {
                if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
                  module.verbose('Displaying error with css transition', settings.transition);
                  $prompt.transition(settings.transition + ' in', settings.duration);
                }
                else {
                  module.verbose('Displaying error with fallback javascript animation');
                  $prompt
                    .fadeIn(settings.duration)
                  ;
                }
              }
              else {
                module.verbose('Inline errors are disabled, no inline error added', identifier);
              }
            }
          },
          errors: function(errors) {
            module.debug('Adding form error messages', errors);
            module.set.error();
            $message
              .html( settings.templates.error(errors) )
            ;
          }
        },

        remove: {
          rule: function(field, rule) {
            var
              rules = $.isArray(rule)
                ? rule
                : [rule]
            ;
            if(rule == undefined) {
              module.debug('Removed all rules');
              validation[field].rules = [];
              return;
            }
            if(validation[field] == undefined || !$.isArray(validation[field].rules)) {
              return;
            }
            $.each(validation[field].rules, function(index, rule) {
              if(rules.indexOf(rule.type) !== -1) {
                module.debug('Removed rule', rule.type);
                validation[field].rules.splice(index, 1);
              }
            });
          },
          field: function(field) {
            var
              fields = $.isArray(field)
                ? field
                : [field]
            ;
            $.each(fields, function(index, field) {
              module.remove.rule(field);
            });
          },
          // alias
          rules: function(field, rules) {
            if($.isArray(field)) {
              $.each(fields, function(index, field) {
                module.remove.rule(field, rules);
              });
            }
            else {
              module.remove.rule(field, rules);
            }
          },
          fields: function(fields) {
            module.remove.field(fields);
          },
          prompt: function(identifier) {
            var
              $field      = module.get.field(identifier),
              $fieldGroup = $field.closest($group),
              $prompt     = $fieldGroup.children(selector.prompt)
            ;
            $fieldGroup
              .removeClass(className.error)
            ;
            if(settings.inline && $prompt.is(':visible')) {
              module.verbose('Removing prompt for field', identifier);
              if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
                $prompt.transition(settings.transition + ' out', settings.duration, function() {
                  $prompt.remove();
                });
              }
              else {
                $prompt
                  .fadeOut(settings.duration, function(){
                    $prompt.remove();
                  })
                ;
              }
            }
          }
        },

        set: {
          success: function() {
            $module
              .removeClass(className.error)
              .addClass(className.success)
            ;
          },
          defaults: function () {
            $field
              .each(function () {
                var
                  $field     = $(this),
                  isCheckbox = ($field.filter(selector.checkbox).length > 0),
                  value      = (isCheckbox)
                    ? $field.is(':checked')
                    : $field.val()
                ;
                $field.data(metadata.defaultValue, value);
              })
            ;
          },
          error: function() {
            $module
              .removeClass(className.success)
              .addClass(className.error)
            ;
          },
          value: function (field, value) {
            var
              fields = {}
            ;
            fields[field] = value;
            return module.set.values.call(element, fields);
          },
          values: function (fields) {
            if($.isEmptyObject(fields)) {
              return;
            }
            $.each(fields, function(key, value) {
              var
                $field      = module.get.field(key),
                $element    = $field.parent(),
                isMultiple  = $.isArray(value),
                isCheckbox  = $element.is(selector.uiCheckbox),
                isDropdown  = $element.is(selector.uiDropdown),
                isRadio     = ($field.is(selector.radio) && isCheckbox),
                fieldExists = ($field.length > 0),
                $multipleField
              ;
              if(fieldExists) {
                if(isMultiple && isCheckbox) {
                  module.verbose('Selecting multiple', value, $field);
                  $element.checkbox('uncheck');
                  $.each(value, function(index, value) {
                    $multipleField = $field.filter('[value="' + value + '"]');
                    $element       = $multipleField.parent();
                    if($multipleField.length > 0) {
                      $element.checkbox('check');
                    }
                  });
                }
                else if(isRadio) {
                  module.verbose('Selecting radio value', value, $field);
                  $field.filter('[value="' + value + '"]')
                    .parent(selector.uiCheckbox)
                      .checkbox('check')
                  ;
                }
                else if(isCheckbox) {
                  module.verbose('Setting checkbox value', value, $element);
                  if(value === true) {
                    $element.checkbox('check');
                  }
                  else {
                    $element.checkbox('uncheck');
                  }
                }
                else if(isDropdown) {
                  module.verbose('Setting dropdown value', value, $element);
                  $element.dropdown('set selected', value);
                }
                else {
                  module.verbose('Setting field value', value, $field);
                  $field.val(value);
                }
              }
            });
          }
        },

        validate: {

          form: function(event, ignoreCallbacks) {
            var
              values = module.get.values(),
              apiRequest
            ;

            // input keydown event will fire submit repeatedly by browser default
            if(keyHeldDown) {
              return false;
            }

            // reset errors
            formErrors = [];
            if( module.determine.isValid() ) {
              module.debug('Form has no validation errors, submitting');
              module.set.success();
              if(ignoreCallbacks !== true) {
                return settings.onSuccess.call(element, event, values);
              }
            }
            else {
              module.debug('Form has errors');
              module.set.error();
              if(!settings.inline) {
                module.add.errors(formErrors);
              }
              // prevent ajax submit
              if($module.data('moduleApi') !== undefined) {
                event.stopImmediatePropagation();
              }
              if(ignoreCallbacks !== true) {
                return settings.onFailure.call(element, formErrors, values);
              }
            }
          },

          // takes a validation object and returns whether field passes validation
          field: function(field, fieldName, showErrors) {
            showErrors = (showErrors !== undefined)
              ? showErrors
              : true
            ;
            if(typeof field == 'string') {
              module.verbose('Validating field', field);
              fieldName = field;
              field     = validation[field];
            }
            var
              identifier    = field.identifier || fieldName,
              $field        = module.get.field(identifier),
              $dependsField = (field.depends)
                ? module.get.field(field.depends)
                : false,
              fieldValid  = true,
              fieldErrors = []
            ;
            if(!field.identifier) {
              module.debug('Using field name as identifier', identifier);
              field.identifier = identifier;
            }
            if($field.prop('disabled')) {
              module.debug('Field is disabled. Skipping', identifier);
              fieldValid = true;
            }
            else if(field.optional && module.is.blank($field)){
              module.debug('Field is optional and blank. Skipping', identifier);
              fieldValid = true;
            }
            else if(field.depends && module.is.empty($dependsField)) {
              module.debug('Field depends on another value that is not present or empty. Skipping', $dependsField);
              fieldValid = true;
            }
            else if(field.rules !== undefined) {
              $.each(field.rules, function(index, rule) {
                if( module.has.field(identifier) && !( module.validate.rule(field, rule) ) ) {
                  module.debug('Field is invalid', identifier, rule.type);
                  fieldErrors.push(module.get.prompt(rule, field));
                  fieldValid = false;
                }
              });
            }
            if(fieldValid) {
              if(showErrors) {
                module.remove.prompt(identifier, fieldErrors);
                settings.onValid.call($field);
              }
            }
            else {
              if(showErrors) {
                formErrors = formErrors.concat(fieldErrors);
                module.add.prompt(identifier, fieldErrors);
                settings.onInvalid.call($field, fieldErrors);
              }
              return false;
            }
            return true;
          },

          // takes validation rule and returns whether field passes rule
          rule: function(field, rule) {
            var
              $field       = module.get.field(field.identifier),
              type         = rule.type,
              value        = $field.val(),
              isValid      = true,
              ancillary    = module.get.ancillaryValue(rule),
              ruleName     = module.get.ruleName(rule),
              ruleFunction = settings.rules[ruleName]
            ;
            if( !$.isFunction(ruleFunction) ) {
              module.error(error.noRule, ruleName);
              return;
            }
            // cast to string avoiding encoding special values
            value = (value === undefined || value === '' || value === null)
              ? ''
              : $.trim(value + '')
            ;
            return ruleFunction.call($field, value, ancillary);
          }
        },

        setting: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.length > 1) {
              title += ' ' + '(' + $allModules.length + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };
      module.initialize();
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.form.settings = {

  name              : 'Form',
  namespace         : 'form',

  debug             : false,
  verbose           : false,
  performance       : true,

  fields            : false,

  keyboardShortcuts : true,
  on                : 'submit',
  inline            : false,

  delay             : 200,
  revalidate        : true,

  transition        : 'scale',
  duration          : 200,

  onValid           : function() {},
  onInvalid         : function() {},
  onSuccess         : function() { return true; },
  onFailure         : function() { return false; },

  metadata : {
    defaultValue : 'default',
    validate     : 'validate'
  },

  regExp: {
    htmlID  : /^[a-zA-Z][\w:.-]*$/g,
    bracket : /\[(.*)\]/i,
    decimal : /^\d+\.?\d*$/,
    email   : /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i,
    escape  : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
    flags   : /^\/(.*)\/(.*)?/,
    integer : /^\-?\d+$/,
    number  : /^\-?\d*(\.\d+)?$/,
    url     : /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/i
  },

  text: {
    unspecifiedRule  : 'Please enter a valid value',
    unspecifiedField : 'This field'
  },

  prompt: {
    empty                : '{name} must have a value',
    checked              : '{name} must be checked',
    email                : '{name} must be a valid e-mail',
    url                  : '{name} must be a valid url',
    regExp               : '{name} is not formatted correctly',
    integer              : '{name} must be an integer',
    decimal              : '{name} must be a decimal number',
    number               : '{name} must be set to a number',
    is                   : '{name} must be "{ruleValue}"',
    isExactly            : '{name} must be exactly "{ruleValue}"',
    not                  : '{name} cannot be set to "{ruleValue}"',
    notExactly           : '{name} cannot be set to exactly "{ruleValue}"',
    contain              : '{name} cannot contain "{ruleValue}"',
    containExactly       : '{name} cannot contain exactly "{ruleValue}"',
    doesntContain        : '{name} must contain  "{ruleValue}"',
    doesntContainExactly : '{name} must contain exactly "{ruleValue}"',
    minLength            : '{name} must be at least {ruleValue} characters',
    length               : '{name} must be at least {ruleValue} characters',
    exactLength          : '{name} must be exactly {ruleValue} characters',
    maxLength            : '{name} cannot be longer than {ruleValue} characters',
    match                : '{name} must match {ruleValue} field',
    different            : '{name} must have a different value than {ruleValue} field',
    creditCard           : '{name} must be a valid credit card number',
    minCount             : '{name} must have at least {ruleValue} choices',
    exactCount           : '{name} must have exactly {ruleValue} choices',
    maxCount             : '{name} must have {ruleValue} or less choices'
  },

  selector : {
    checkbox   : 'input[type="checkbox"], input[type="radio"]',
    clear      : '.clear',
    field      : 'input, textarea, select',
    group      : '.field',
    input      : 'input',
    message    : '.error.message',
    prompt     : '.prompt.label',
    radio      : 'input[type="radio"]',
    reset      : '.reset:not([type="reset"])',
    submit     : '.submit:not([type="submit"])',
    uiCheckbox : '.ui.checkbox',
    uiDropdown : '.ui.dropdown'
  },

  className : {
    error   : 'error',
    label   : 'ui prompt label',
    pressed : 'down',
    success : 'success'
  },

  error: {
    identifier : 'You must specify a string identifier for each field',
    method     : 'The method you called is not defined.',
    noRule     : 'There is no rule matching the one you specified',
    oldSyntax  : 'Starting in 2.0 forms now only take a single settings object. Validation settings converted to new syntax automatically.'
  },

  templates: {

    // template that produces error message
    error: function(errors) {
      var
        html = '<ul class="list">'
      ;
      $.each(errors, function(index, value) {
        html += '<li>' + value + '</li>';
      });
      html += '</ul>';
      return $(html);
    },

    // template that produces label
    prompt: function(errors) {
      return $('<div/>')
        .addClass('ui basic red pointing prompt label')
        .html(errors[0])
      ;
    }
  },

  rules: {

    // is not empty or blank string
    empty: function(value) {
      return !(value === undefined || '' === value || $.isArray(value) && value.length === 0);
    },

    // checkbox checked
    checked: function() {
      return ($(this).filter(':checked').length > 0);
    },

    // is most likely an email
    email: function(value){
      return $.fn.form.settings.regExp.email.test(value);
    },

    // value is most likely url
    url: function(value) {
      return $.fn.form.settings.regExp.url.test(value);
    },

    // matches specified regExp
    regExp: function(value, regExp) {
      if(regExp instanceof RegExp) {
        return value.match(regExp);
      }
      var
        regExpParts = regExp.match($.fn.form.settings.regExp.flags),
        flags
      ;
      // regular expression specified as /baz/gi (flags)
      if(regExpParts) {
        regExp = (regExpParts.length >= 2)
          ? regExpParts[1]
          : regExp
        ;
        flags = (regExpParts.length >= 3)
          ? regExpParts[2]
          : ''
        ;
      }
      return value.match( new RegExp(regExp, flags) );
    },

    // is valid integer or matches range
    integer: function(value, range) {
      var
        intRegExp = $.fn.form.settings.regExp.integer,
        min,
        max,
        parts
      ;
      if( !range || ['', '..'].indexOf(range) !== -1) {
        // do nothing
      }
      else if(range.indexOf('..') == -1) {
        if(intRegExp.test(range)) {
          min = max = range - 0;
        }
      }
      else {
        parts = range.split('..', 2);
        if(intRegExp.test(parts[0])) {
          min = parts[0] - 0;
        }
        if(intRegExp.test(parts[1])) {
          max = parts[1] - 0;
        }
      }
      return (
        intRegExp.test(value) &&
        (min === undefined || value >= min) &&
        (max === undefined || value <= max)
      );
    },

    // is valid number (with decimal)
    decimal: function(value) {
      return $.fn.form.settings.regExp.decimal.test(value);
    },

    // is valid number
    number: function(value) {
      return $.fn.form.settings.regExp.number.test(value);
    },

    // is value (case insensitive)
    is: function(value, text) {
      text = (typeof text == 'string')
        ? text.toLowerCase()
        : text
      ;
      value = (typeof value == 'string')
        ? value.toLowerCase()
        : value
      ;
      return (value == text);
    },

    // is value
    isExactly: function(value, text) {
      return (value == text);
    },

    // value is not another value (case insensitive)
    not: function(value, notValue) {
      value = (typeof value == 'string')
        ? value.toLowerCase()
        : value
      ;
      notValue = (typeof notValue == 'string')
        ? notValue.toLowerCase()
        : notValue
      ;
      return (value != notValue);
    },

    // value is not another value (case sensitive)
    notExactly: function(value, notValue) {
      return (value != notValue);
    },

    // value contains text (insensitive)
    contains: function(value, text) {
      // escape regex characters
      text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
      return (value.search( new RegExp(text, 'i') ) !== -1);
    },

    // value contains text (case sensitive)
    containsExactly: function(value, text) {
      // escape regex characters
      text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
      return (value.search( new RegExp(text) ) !== -1);
    },

    // value contains text (insensitive)
    doesntContain: function(value, text) {
      // escape regex characters
      text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
      return (value.search( new RegExp(text, 'i') ) === -1);
    },

    // value contains text (case sensitive)
    doesntContainExactly: function(value, text) {
      // escape regex characters
      text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
      return (value.search( new RegExp(text) ) === -1);
    },

    // is at least string length
    minLength: function(value, requiredLength) {
      return (value !== undefined)
        ? (value.length >= requiredLength)
        : false
      ;
    },

    // see rls notes for 2.0.6 (this is a duplicate of minLength)
    length: function(value, requiredLength) {
      return (value !== undefined)
        ? (value.length >= requiredLength)
        : false
      ;
    },

    // is exactly length
    exactLength: function(value, requiredLength) {
      return (value !== undefined)
        ? (value.length == requiredLength)
        : false
      ;
    },

    // is less than length
    maxLength: function(value, maxLength) {
      return (value !== undefined)
        ? (value.length <= maxLength)
        : false
      ;
    },

    // matches another field
    match: function(value, identifier) {
      var
        $form = $(this),
        matchingValue
      ;
      if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
        matchingValue = $('[data-validate="'+ identifier +'"]').val();
      }
      else if($('#' + identifier).length > 0) {
        matchingValue = $('#' + identifier).val();
      }
      else if($('[name="' + identifier +'"]').length > 0) {
        matchingValue = $('[name="' + identifier + '"]').val();
      }
      else if( $('[name="' + identifier +'[]"]').length > 0 ) {
        matchingValue = $('[name="' + identifier +'[]"]');
      }
      return (matchingValue !== undefined)
        ? ( value.toString() == matchingValue.toString() )
        : false
      ;
    },

    // different than another field
    different: function(value, identifier) {
      // use either id or name of field
      var
        $form = $(this),
        matchingValue
      ;
      if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
        matchingValue = $('[data-validate="'+ identifier +'"]').val();
      }
      else if($('#' + identifier).length > 0) {
        matchingValue = $('#' + identifier).val();
      }
      else if($('[name="' + identifier +'"]').length > 0) {
        matchingValue = $('[name="' + identifier + '"]').val();
      }
      else if( $('[name="' + identifier +'[]"]').length > 0 ) {
        matchingValue = $('[name="' + identifier +'[]"]');
      }
      return (matchingValue !== undefined)
        ? ( value.toString() !== matchingValue.toString() )
        : false
      ;
    },

    creditCard: function(cardNumber, cardTypes) {
      var
        cards = {
          visa: {
            pattern : /^4/,
            length  : [16]
          },
          amex: {
            pattern : /^3[47]/,
            length  : [15]
          },
          mastercard: {
            pattern : /^5[1-5]/,
            length  : [16]
          },
          discover: {
            pattern : /^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/,
            length  : [16]
          },
          unionPay: {
            pattern : /^(62|88)/,
            length  : [16, 17, 18, 19]
          },
          jcb: {
            pattern : /^35(2[89]|[3-8][0-9])/,
            length  : [16]
          },
          maestro: {
            pattern : /^(5018|5020|5038|6304|6759|676[1-3])/,
            length  : [12, 13, 14, 15, 16, 17, 18, 19]
          },
          dinersClub: {
            pattern : /^(30[0-5]|^36)/,
            length  : [14]
          },
          laser: {
            pattern : /^(6304|670[69]|6771)/,
            length  : [16, 17, 18, 19]
          },
          visaElectron: {
            pattern : /^(4026|417500|4508|4844|491(3|7))/,
            length  : [16]
          }
        },
        valid         = {},
        validCard     = false,
        requiredTypes = (typeof cardTypes == 'string')
          ? cardTypes.split(',')
          : false,
        unionPay,
        validation
      ;

      if(typeof cardNumber !== 'string' || cardNumber.length === 0) {
        return;
      }

      // allow dashes in card
      cardNumber = cardNumber.replace(/[\-]/g, '');

      // verify card types
      if(requiredTypes) {
        $.each(requiredTypes, function(index, type){
          // verify each card type
          validation = cards[type];
          if(validation) {
            valid = {
              length  : ($.inArray(cardNumber.length, validation.length) !== -1),
              pattern : (cardNumber.search(validation.pattern) !== -1)
            };
            if(valid.length && valid.pattern) {
              validCard = true;
            }
          }
        });

        if(!validCard) {
          return false;
        }
      }

      // skip luhn for UnionPay
      unionPay = {
        number  : ($.inArray(cardNumber.length, cards.unionPay.length) !== -1),
        pattern : (cardNumber.search(cards.unionPay.pattern) !== -1)
      };
      if(unionPay.number && unionPay.pattern) {
        return true;
      }

      // verify luhn, adapted from  <https://gist.github.com/2134376>
      var
        length        = cardNumber.length,
        multiple      = 0,
        producedValue = [
          [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
          [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
        ],
        sum           = 0
      ;
      while (length--) {
        sum += producedValue[multiple][parseInt(cardNumber.charAt(length), 10)];
        multiple ^= 1;
      }
      return (sum % 10 === 0 && sum > 0);
    },

    minCount: function(value, minCount) {
      if(minCount == 0) {
        return true;
      }
      if(minCount == 1) {
        return (value !== '');
      }
      return (value.split(',').length >= minCount);
    },

    exactCount: function(value, exactCount) {
      if(exactCount == 0) {
        return (value === '');
      }
      if(exactCount == 1) {
        return (value !== '' && value.search(',') === -1);
      }
      return (value.split(',').length == exactCount);
    },

    maxCount: function(value, maxCount) {
      if(maxCount == 0) {
        return false;
      }
      if(maxCount == 1) {
        return (value.search(',') === -1);
      }
      return (value.split(',').length <= maxCount);
    }
  }

};

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Accordion
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.accordion = function(parameters) {
  var
    $allModules     = $(this),

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),

    requestAnimationFrame = window.requestAnimationFrame
      || window.mozRequestAnimationFrame
      || window.webkitRequestAnimationFrame
      || window.msRequestAnimationFrame
      || function(callback) { setTimeout(callback, 0); },

    returnedValue
  ;
  $allModules
    .each(function() {
      var
        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.accordion.settings, parameters)
          : $.extend({}, $.fn.accordion.settings),

        className       = settings.className,
        namespace       = settings.namespace,
        selector        = settings.selector,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,
        moduleSelector  = $allModules.selector || '',

        $module  = $(this),
        $title   = $module.find(selector.title),
        $content = $module.find(selector.content),

        element  = this,
        instance = $module.data(moduleNamespace),
        observer,
        module
      ;

      module = {

        initialize: function() {
          module.debug('Initializing', $module);
          module.bind.events();
          if(settings.observeChanges) {
            module.observeChanges();
          }
          module.instantiate();
        },

        instantiate: function() {
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.debug('Destroying previous instance', $module);
          $module
            .off(eventNamespace)
            .removeData(moduleNamespace)
          ;
        },

        refresh: function() {
          $title   = $module.find(selector.title);
          $content = $module.find(selector.content);
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            observer = new MutationObserver(function(mutations) {
              module.debug('DOM tree modified, updating selector cache');
              module.refresh();
            });
            observer.observe(element, {
              childList : true,
              subtree   : true
            });
            module.debug('Setting up mutation observer', observer);
          }
        },

        bind: {
          events: function() {
            module.debug('Binding delegated events');
            $module
              .on(settings.on + eventNamespace, selector.trigger, module.event.click)
            ;
          }
        },

        event: {
          click: function() {
            module.toggle.call(this);
          }
        },

        toggle: function(query) {
          var
            $activeTitle = (query !== undefined)
              ? (typeof query === 'number')
                ? $title.eq(query)
                : $(query).closest(selector.title)
              : $(this).closest(selector.title),
            $activeContent = $activeTitle.next($content),
            isAnimating = $activeContent.hasClass(className.animating),
            isActive    = $activeContent.hasClass(className.active),
            isOpen      = (isActive && !isAnimating),
            isOpening   = (!isActive && isAnimating)
          ;
          module.debug('Toggling visibility of content', $activeTitle);
          if(isOpen || isOpening) {
            if(settings.collapsible) {
              module.close.call($activeTitle);
            }
            else {
              module.debug('Cannot close accordion content collapsing is disabled');
            }
          }
          else {
            module.open.call($activeTitle);
          }
        },

        open: function(query) {
          var
            $activeTitle = (query !== undefined)
              ? (typeof query === 'number')
                ? $title.eq(query)
                : $(query).closest(selector.title)
              : $(this).closest(selector.title),
            $activeContent = $activeTitle.next($content),
            isAnimating = $activeContent.hasClass(className.animating),
            isActive    = $activeContent.hasClass(className.active),
            isOpen      = (isActive || isAnimating)
          ;
          if(isOpen) {
            module.debug('Accordion already open, skipping', $activeContent);
            return;
          }
          module.debug('Opening accordion content', $activeTitle);
          settings.onOpening.call($activeContent);
          if(settings.exclusive) {
            module.closeOthers.call($activeTitle);
          }
          $activeTitle
            .addClass(className.active)
          ;
          $activeContent
            .stop(true, true)
            .addClass(className.animating)
          ;
          if(settings.animateChildren) {
            if($.fn.transition !== undefined && $module.transition('is supported')) {
              $activeContent
                .children()
                  .transition({
                    animation   : 'fade in',
                    queue       : false,
                    useFailSafe : true,
                    debug       : settings.debug,
                    verbose     : settings.verbose,
                    duration    : settings.duration
                  })
              ;
            }
            else {
              $activeContent
                .children()
                  .stop(true, true)
                  .animate({
                    opacity: 1
                  }, settings.duration, module.resetOpacity)
              ;
            }
          }
          $activeContent
            .slideDown(settings.duration, settings.easing, function() {
              $activeContent
                .removeClass(className.animating)
                .addClass(className.active)
              ;
              module.reset.display.call(this);
              settings.onOpen.call(this);
              settings.onChange.call(this);
            })
          ;
        },

        close: function(query) {
          var
            $activeTitle = (query !== undefined)
              ? (typeof query === 'number')
                ? $title.eq(query)
                : $(query).closest(selector.title)
              : $(this).closest(selector.title),
            $activeContent = $activeTitle.next($content),
            isAnimating    = $activeContent.hasClass(className.animating),
            isActive       = $activeContent.hasClass(className.active),
            isOpening      = (!isActive && isAnimating),
            isClosing      = (isActive && isAnimating)
          ;
          if((isActive || isOpening) && !isClosing) {
            module.debug('Closing accordion content', $activeContent);
            settings.onClosing.call($activeContent);
            $activeTitle
              .removeClass(className.active)
            ;
            $activeContent
              .stop(true, true)
              .addClass(className.animating)
            ;
            if(settings.animateChildren) {
              if($.fn.transition !== undefined && $module.transition('is supported')) {
                $activeContent
                  .children()
                    .transition({
                      animation   : 'fade out',
                      queue       : false,
                      useFailSafe : true,
                      debug       : settings.debug,
                      verbose     : settings.verbose,
                      duration    : settings.duration
                    })
                ;
              }
              else {
                $activeContent
                  .children()
                    .stop(true, true)
                    .animate({
                      opacity: 0
                    }, settings.duration, module.resetOpacity)
                ;
              }
            }
            $activeContent
              .slideUp(settings.duration, settings.easing, function() {
                $activeContent
                  .removeClass(className.animating)
                  .removeClass(className.active)
                ;
                module.reset.display.call(this);
                settings.onClose.call(this);
                settings.onChange.call(this);
              })
            ;
          }
        },

        closeOthers: function(index) {
          var
            $activeTitle = (index !== undefined)
              ? $title.eq(index)
              : $(this).closest(selector.title),
            $parentTitles    = $activeTitle.parents(selector.content).prev(selector.title),
            $activeAccordion = $activeTitle.closest(selector.accordion),
            activeSelector   = selector.title + '.' + className.active + ':visible',
            activeContent    = selector.content + '.' + className.active + ':visible',
            $openTitles,
            $nestedTitles,
            $openContents
          ;
          if(settings.closeNested) {
            $openTitles   = $activeAccordion.find(activeSelector).not($parentTitles);
            $openContents = $openTitles.next($content);
          }
          else {
            $openTitles   = $activeAccordion.find(activeSelector).not($parentTitles);
            $nestedTitles = $activeAccordion.find(activeContent).find(activeSelector).not($parentTitles);
            $openTitles   = $openTitles.not($nestedTitles);
            $openContents = $openTitles.next($content);
          }
          if( ($openTitles.length > 0) ) {
            module.debug('Exclusive enabled, closing other content', $openTitles);
            $openTitles
              .removeClass(className.active)
            ;
            $openContents
              .removeClass(className.animating)
              .stop(true, true)
            ;
            if(settings.animateChildren) {
              if($.fn.transition !== undefined && $module.transition('is supported')) {
                $openContents
                  .children()
                    .transition({
                      animation   : 'fade out',
                      useFailSafe : true,
                      debug       : settings.debug,
                      verbose     : settings.verbose,
                      duration    : settings.duration
                    })
                ;
              }
              else {
                $openContents
                  .children()
                    .stop(true, true)
                    .animate({
                      opacity: 0
                    }, settings.duration, module.resetOpacity)
                ;
              }
            }
            $openContents
              .slideUp(settings.duration , settings.easing, function() {
                $(this).removeClass(className.active);
                module.reset.display.call(this);
              })
            ;
          }
        },

        reset: {

          display: function() {
            module.verbose('Removing inline display from element', this);
            $(this).css('display', '');
            if( $(this).attr('style') === '') {
              $(this)
                .attr('style', '')
                .removeAttr('style')
              ;
            }
          },

          opacity: function() {
            module.verbose('Removing inline opacity from element', this);
            $(this).css('opacity', '');
            if( $(this).attr('style') === '') {
              $(this)
                .attr('style', '')
                .removeAttr('style')
              ;
            }
          },

        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          module.debug('Changing internal', name, value);
          if(value !== undefined) {
            if( $.isPlainObject(name) ) {
              $.extend(true, module, name);
            }
            else {
              module[name] = value;
            }
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };
      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;
  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.accordion.settings = {

  name            : 'Accordion',
  namespace       : 'accordion',

  silent          : false,
  debug           : false,
  verbose         : false,
  performance     : true,

  on              : 'click', // event on title that opens accordion

  observeChanges  : true,  // whether accordion should automatically refresh on DOM insertion

  exclusive       : true,  // whether a single accordion content panel should be open at once
  collapsible     : true,  // whether accordion content can be closed
  closeNested     : false, // whether nested content should be closed when a panel is closed
  animateChildren : true,  // whether children opacity should be animated

  duration        : 350, // duration of animation
  easing          : 'easeOutQuad', // easing equation for animation


  onOpening       : function(){}, // callback before open animation
  onOpen          : function(){}, // callback after open animation
  onClosing       : function(){}, // callback before closing animation
  onClose         : function(){}, // callback after closing animation
  onChange        : function(){}, // callback after closing or opening animation

  error: {
    method : 'The method you called is not defined'
  },

  className   : {
    active    : 'active',
    animating : 'animating'
  },

  selector    : {
    accordion : '.accordion',
    title     : '.title',
    trigger   : '.title',
    content   : '.content'
  }

};

// Adds easing
$.extend( $.easing, {
  easeOutQuad: function (x, t, b, c, d) {
    return -c *(t/=d)*(t-2) + b;
  }
});

})( jQuery, window, document );


/*!
 * # Semantic UI 2.2.13 - Checkbox
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.checkbox = function(parameters) {
  var
    $allModules    = $(this),
    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),
    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings        = $.extend(true, {}, $.fn.checkbox.settings, parameters),

        className       = settings.className,
        namespace       = settings.namespace,
        selector        = settings.selector,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $label          = $(this).children(selector.label),
        $input          = $(this).children(selector.input),
        input           = $input[0],

        initialLoad     = false,
        shortcutPressed = false,
        instance        = $module.data(moduleNamespace),

        observer,
        element         = this,
        module
      ;

      module      = {

        initialize: function() {
          module.verbose('Initializing checkbox', settings);

          module.create.label();
          module.bind.events();

          module.set.tabbable();
          module.hide.input();

          module.observeChanges();
          module.instantiate();
          module.setup();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying module');
          module.unbind.events();
          module.show.input();
          $module.removeData(moduleNamespace);
        },

        fix: {
          reference: function() {
            if( $module.is(selector.input) ) {
              module.debug('Behavior called on <input> adjusting invoked element');
              $module = $module.closest(selector.checkbox);
              module.refresh();
            }
          }
        },

        setup: function() {
          module.set.initialLoad();
          if( module.is.indeterminate() ) {
            module.debug('Initial value is indeterminate');
            module.indeterminate();
          }
          else if( module.is.checked() ) {
            module.debug('Initial value is checked');
            module.check();
          }
          else {
            module.debug('Initial value is unchecked');
            module.uncheck();
          }
          module.remove.initialLoad();
        },

        refresh: function() {
          $label = $module.children(selector.label);
          $input = $module.children(selector.input);
          input  = $input[0];
        },

        hide: {
          input: function() {
            module.verbose('Modifying <input> z-index to be unselectable');
            $input.addClass(className.hidden);
          }
        },
        show: {
          input: function() {
            module.verbose('Modifying <input> z-index to be selectable');
            $input.removeClass(className.hidden);
          }
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            observer = new MutationObserver(function(mutations) {
              module.debug('DOM tree modified, updating selector cache');
              module.refresh();
            });
            observer.observe(element, {
              childList : true,
              subtree   : true
            });
            module.debug('Setting up mutation observer', observer);
          }
        },

        attachEvents: function(selector, event) {
          var
            $element = $(selector)
          ;
          event = $.isFunction(module[event])
            ? module[event]
            : module.toggle
          ;
          if($element.length > 0) {
            module.debug('Attaching checkbox events to element', selector, event);
            $element
              .on('click' + eventNamespace, event)
            ;
          }
          else {
            module.error(error.notFound);
          }
        },

        event: {
          click: function(event) {
            var
              $target = $(event.target)
            ;
            if( $target.is(selector.input) ) {
              module.verbose('Using default check action on initialized checkbox');
              return;
            }
            if( $target.is(selector.link) ) {
              module.debug('Clicking link inside checkbox, skipping toggle');
              return;
            }
            module.toggle();
            $input.focus();
            event.preventDefault();
          },
          keydown: function(event) {
            var
              key     = event.which,
              keyCode = {
                enter  : 13,
                space  : 32,
                escape : 27
              }
            ;
            if(key == keyCode.escape) {
              module.verbose('Escape key pressed blurring field');
              $input.blur();
              shortcutPressed = true;
            }
            else if(!event.ctrlKey && ( key == keyCode.space || key == keyCode.enter) ) {
              module.verbose('Enter/space key pressed, toggling checkbox');
              module.toggle();
              shortcutPressed = true;
            }
            else {
              shortcutPressed = false;
            }
          },
          keyup: function(event) {
            if(shortcutPressed) {
              event.preventDefault();
            }
          }
        },

        check: function() {
          if( !module.should.allowCheck() ) {
            return;
          }
          module.debug('Checking checkbox', $input);
          module.set.checked();
          if( !module.should.ignoreCallbacks() ) {
            settings.onChecked.call(input);
            settings.onChange.call(input);
          }
        },

        uncheck: function() {
          if( !module.should.allowUncheck() ) {
            return;
          }
          module.debug('Unchecking checkbox');
          module.set.unchecked();
          if( !module.should.ignoreCallbacks() ) {
            settings.onUnchecked.call(input);
            settings.onChange.call(input);
          }
        },

        indeterminate: function() {
          if( module.should.allowIndeterminate() ) {
            module.debug('Checkbox is already indeterminate');
            return;
          }
          module.debug('Making checkbox indeterminate');
          module.set.indeterminate();
          if( !module.should.ignoreCallbacks() ) {
            settings.onIndeterminate.call(input);
            settings.onChange.call(input);
          }
        },

        determinate: function() {
          if( module.should.allowDeterminate() ) {
            module.debug('Checkbox is already determinate');
            return;
          }
          module.debug('Making checkbox determinate');
          module.set.determinate();
          if( !module.should.ignoreCallbacks() ) {
            settings.onDeterminate.call(input);
            settings.onChange.call(input);
          }
        },

        enable: function() {
          if( module.is.enabled() ) {
            module.debug('Checkbox is already enabled');
            return;
          }
          module.debug('Enabling checkbox');
          module.set.enabled();
          settings.onEnable.call(input);
          // preserve legacy callbacks
          settings.onEnabled.call(input);
        },

        disable: function() {
          if( module.is.disabled() ) {
            module.debug('Checkbox is already disabled');
            return;
          }
          module.debug('Disabling checkbox');
          module.set.disabled();
          settings.onDisable.call(input);
          // preserve legacy callbacks
          settings.onDisabled.call(input);
        },

        get: {
          radios: function() {
            var
              name = module.get.name()
            ;
            return $('input[name="' + name + '"]').closest(selector.checkbox);
          },
          otherRadios: function() {
            return module.get.radios().not($module);
          },
          name: function() {
            return $input.attr('name');
          }
        },

        is: {
          initialLoad: function() {
            return initialLoad;
          },
          radio: function() {
            return ($input.hasClass(className.radio) || $input.attr('type') == 'radio');
          },
          indeterminate: function() {
            return $input.prop('indeterminate') !== undefined && $input.prop('indeterminate');
          },
          checked: function() {
            return $input.prop('checked') !== undefined && $input.prop('checked');
          },
          disabled: function() {
            return $input.prop('disabled') !== undefined && $input.prop('disabled');
          },
          enabled: function() {
            return !module.is.disabled();
          },
          determinate: function() {
            return !module.is.indeterminate();
          },
          unchecked: function() {
            return !module.is.checked();
          }
        },

        should: {
          allowCheck: function() {
            if(module.is.determinate() && module.is.checked() && !module.should.forceCallbacks() ) {
              module.debug('Should not allow check, checkbox is already checked');
              return false;
            }
            if(settings.beforeChecked.apply(input) === false) {
              module.debug('Should not allow check, beforeChecked cancelled');
              return false;
            }
            return true;
          },
          allowUncheck: function() {
            if(module.is.determinate() && module.is.unchecked() && !module.should.forceCallbacks() ) {
              module.debug('Should not allow uncheck, checkbox is already unchecked');
              return false;
            }
            if(settings.beforeUnchecked.apply(input) === false) {
              module.debug('Should not allow uncheck, beforeUnchecked cancelled');
              return false;
            }
            return true;
          },
          allowIndeterminate: function() {
            if(module.is.indeterminate() && !module.should.forceCallbacks() ) {
              module.debug('Should not allow indeterminate, checkbox is already indeterminate');
              return false;
            }
            if(settings.beforeIndeterminate.apply(input) === false) {
              module.debug('Should not allow indeterminate, beforeIndeterminate cancelled');
              return false;
            }
            return true;
          },
          allowDeterminate: function() {
            if(module.is.determinate() && !module.should.forceCallbacks() ) {
              module.debug('Should not allow determinate, checkbox is already determinate');
              return false;
            }
            if(settings.beforeDeterminate.apply(input) === false) {
              module.debug('Should not allow determinate, beforeDeterminate cancelled');
              return false;
            }
            return true;
          },
          forceCallbacks: function() {
            return (module.is.initialLoad() && settings.fireOnInit);
          },
          ignoreCallbacks: function() {
            return (initialLoad && !settings.fireOnInit);
          }
        },

        can: {
          change: function() {
            return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') || $input.prop('readonly') );
          },
          uncheck: function() {
            return (typeof settings.uncheckable === 'boolean')
              ? settings.uncheckable
              : !module.is.radio()
            ;
          }
        },

        set: {
          initialLoad: function() {
            initialLoad = true;
          },
          checked: function() {
            module.verbose('Setting class to checked');
            $module
              .removeClass(className.indeterminate)
              .addClass(className.checked)
            ;
            if( module.is.radio() ) {
              module.uncheckOthers();
            }
            if(!module.is.indeterminate() && module.is.checked()) {
              module.debug('Input is already checked, skipping input property change');
              return;
            }
            module.verbose('Setting state to checked', input);
            $input
              .prop('indeterminate', false)
              .prop('checked', true)
            ;
            module.trigger.change();
          },
          unchecked: function() {
            module.verbose('Removing checked class');
            $module
              .removeClass(className.indeterminate)
              .removeClass(className.checked)
            ;
            if(!module.is.indeterminate() &&  module.is.unchecked() ) {
              module.debug('Input is already unchecked');
              return;
            }
            module.debug('Setting state to unchecked');
            $input
              .prop('indeterminate', false)
              .prop('checked', false)
            ;
            module.trigger.change();
          },
          indeterminate: function() {
            module.verbose('Setting class to indeterminate');
            $module
              .addClass(className.indeterminate)
            ;
            if( module.is.indeterminate() ) {
              module.debug('Input is already indeterminate, skipping input property change');
              return;
            }
            module.debug('Setting state to indeterminate');
            $input
              .prop('indeterminate', true)
            ;
            module.trigger.change();
          },
          determinate: function() {
            module.verbose('Removing indeterminate class');
            $module
              .removeClass(className.indeterminate)
            ;
            if( module.is.determinate() ) {
              module.debug('Input is already determinate, skipping input property change');
              return;
            }
            module.debug('Setting state to determinate');
            $input
              .prop('indeterminate', false)
            ;
          },
          disabled: function() {
            module.verbose('Setting class to disabled');
            $module
              .addClass(className.disabled)
            ;
            if( module.is.disabled() ) {
              module.debug('Input is already disabled, skipping input property change');
              return;
            }
            module.debug('Setting state to disabled');
            $input
              .prop('disabled', 'disabled')
            ;
            module.trigger.change();
          },
          enabled: function() {
            module.verbose('Removing disabled class');
            $module.removeClass(className.disabled);
            if( module.is.enabled() ) {
              module.debug('Input is already enabled, skipping input property change');
              return;
            }
            module.debug('Setting state to enabled');
            $input
              .prop('disabled', false)
            ;
            module.trigger.change();
          },
          tabbable: function() {
            module.verbose('Adding tabindex to checkbox');
            if( $input.attr('tabindex') === undefined) {
              $input.attr('tabindex', 0);
            }
          }
        },

        remove: {
          initialLoad: function() {
            initialLoad = false;
          }
        },

        trigger: {
          change: function() {
            var
              events       = document.createEvent('HTMLEvents'),
              inputElement = $input[0]
            ;
            if(inputElement) {
              module.verbose('Triggering native change event');
              events.initEvent('change', true, false);
              inputElement.dispatchEvent(events);
            }
          }
        },


        create: {
          label: function() {
            if($input.prevAll(selector.label).length > 0) {
              $input.prev(selector.label).detach().insertAfter($input);
              module.debug('Moving existing label', $label);
            }
            else if( !module.has.label() ) {
              $label = $('<label>').insertAfter($input);
              module.debug('Creating label', $label);
            }
          }
        },

        has: {
          label: function() {
            return ($label.length > 0);
          }
        },

        bind: {
          events: function() {
            module.verbose('Attaching checkbox events');
            $module
              .on('click'   + eventNamespace, module.event.click)
              .on('keydown' + eventNamespace, selector.input, module.event.keydown)
              .on('keyup'   + eventNamespace, selector.input, module.event.keyup)
            ;
          }
        },

        unbind: {
          events: function() {
            module.debug('Removing events');
            $module
              .off(eventNamespace)
            ;
          }
        },

        uncheckOthers: function() {
          var
            $radios = module.get.otherRadios()
          ;
          module.debug('Unchecking other radios', $radios);
          $radios.removeClass(className.checked);
        },

        toggle: function() {
          if( !module.can.change() ) {
            if(!module.is.radio()) {
              module.debug('Checkbox is read-only or disabled, ignoring toggle');
            }
            return;
          }
          if( module.is.indeterminate() || module.is.unchecked() ) {
            module.debug('Currently unchecked');
            module.check();
          }
          else if( module.is.checked() && module.can.uncheck() ) {
            module.debug('Currently checked');
            module.uncheck();
          }
        },
        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.checkbox.settings = {

  name                : 'Checkbox',
  namespace           : 'checkbox',

  silent              : false,
  debug               : false,
  verbose             : true,
  performance         : true,

  // delegated event context
  uncheckable         : 'auto',
  fireOnInit          : false,

  onChange            : function(){},

  beforeChecked       : function(){},
  beforeUnchecked     : function(){},
  beforeDeterminate   : function(){},
  beforeIndeterminate : function(){},

  onChecked           : function(){},
  onUnchecked         : function(){},

  onDeterminate       : function() {},
  onIndeterminate     : function() {},

  onEnable            : function(){},
  onDisable           : function(){},

  // preserve misspelled callbacks (will be removed in 3.0)
  onEnabled           : function(){},
  onDisabled          : function(){},

  className       : {
    checked       : 'checked',
    indeterminate : 'indeterminate',
    disabled      : 'disabled',
    hidden        : 'hidden',
    radio         : 'radio',
    readOnly      : 'read-only'
  },

  error     : {
    method       : 'The method you called is not defined'
  },

  selector : {
    checkbox : '.ui.checkbox',
    label    : 'label, .box',
    input    : 'input[type="checkbox"], input[type="radio"]',
    link     : 'a[href]'
  }

};

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Dimmer
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.dimmer = function(parameters) {
  var
    $allModules     = $(this),

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.dimmer.settings, parameters)
          : $.extend({}, $.fn.dimmer.settings),

        selector        = settings.selector,
        namespace       = settings.namespace,
        className       = settings.className,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,
        moduleSelector  = $allModules.selector || '',

        clickEvent      = ('ontouchstart' in document.documentElement)
          ? 'touchstart'
          : 'click',

        $module = $(this),
        $dimmer,
        $dimmable,

        element   = this,
        instance  = $module.data(moduleNamespace),
        module
      ;

      module = {

        preinitialize: function() {
          if( module.is.dimmer() ) {

            $dimmable = $module.parent();
            $dimmer   = $module;
          }
          else {
            $dimmable = $module;
            if( module.has.dimmer() ) {
              if(settings.dimmerName) {
                $dimmer = $dimmable.find(selector.dimmer).filter('.' + settings.dimmerName);
              }
              else {
                $dimmer = $dimmable.find(selector.dimmer);
              }
            }
            else {
              $dimmer = module.create();
            }
            module.set.variation();
          }
        },

        initialize: function() {
          module.debug('Initializing dimmer', settings);

          module.bind.events();
          module.set.dimmable();
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, instance)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous module', $dimmer);
          module.unbind.events();
          module.remove.variation();
          $dimmable
            .off(eventNamespace)
          ;
        },

        bind: {
          events: function() {
            if(settings.on == 'hover') {
              $dimmable
                .on('mouseenter' + eventNamespace, module.show)
                .on('mouseleave' + eventNamespace, module.hide)
              ;
            }
            else if(settings.on == 'click') {
              $dimmable
                .on(clickEvent + eventNamespace, module.toggle)
              ;
            }
            if( module.is.page() ) {
              module.debug('Setting as a page dimmer', $dimmable);
              module.set.pageDimmer();
            }

            if( module.is.closable() ) {
              module.verbose('Adding dimmer close event', $dimmer);
              $dimmable
                .on(clickEvent + eventNamespace, selector.dimmer, module.event.click)
              ;
            }
          }
        },

        unbind: {
          events: function() {
            $module
              .removeData(moduleNamespace)
            ;
            $dimmable
              .off(eventNamespace)
            ;
          }
        },

        event: {
          click: function(event) {
            module.verbose('Determining if event occured on dimmer', event);
            if( $dimmer.find(event.target).length === 0 || $(event.target).is(selector.content) ) {
              module.hide();
              event.stopImmediatePropagation();
            }
          }
        },

        addContent: function(element) {
          var
            $content = $(element)
          ;
          module.debug('Add content to dimmer', $content);
          if($content.parent()[0] !== $dimmer[0]) {
            $content.detach().appendTo($dimmer);
          }
        },

        create: function() {
          var
            $element = $( settings.template.dimmer() )
          ;
          if(settings.dimmerName) {
            module.debug('Creating named dimmer', settings.dimmerName);
            $element.addClass(settings.dimmerName);
          }
          $element
            .appendTo($dimmable)
          ;
          return $element;
        },

        show: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          module.debug('Showing dimmer', $dimmer, settings);
          if( (!module.is.dimmed() || module.is.animating()) && module.is.enabled() ) {
            module.animate.show(callback);
            settings.onShow.call(element);
            settings.onChange.call(element);
          }
          else {
            module.debug('Dimmer is already shown or disabled');
          }
        },

        hide: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if( module.is.dimmed() || module.is.animating() ) {
            module.debug('Hiding dimmer', $dimmer);
            module.animate.hide(callback);
            settings.onHide.call(element);
            settings.onChange.call(element);
          }
          else {
            module.debug('Dimmer is not visible');
          }
        },

        toggle: function() {
          module.verbose('Toggling dimmer visibility', $dimmer);
          if( !module.is.dimmed() ) {
            module.show();
          }
          else {
            module.hide();
          }
        },

        animate: {
          show: function(callback) {
            callback = $.isFunction(callback)
              ? callback
              : function(){}
            ;
            if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) {
              if(settings.opacity !== 'auto') {
                module.set.opacity();
              }
              $dimmer
                .transition({
                  animation   : settings.transition + ' in',
                  queue       : false,
                  duration    : module.get.duration(),
                  useFailSafe : true,
                  onStart     : function() {
                    module.set.dimmed();
                  },
                  onComplete  : function() {
                    module.set.active();
                    callback();
                  }
                })
              ;
            }
            else {
              module.verbose('Showing dimmer animation with javascript');
              module.set.dimmed();
              if(settings.opacity == 'auto') {
                settings.opacity = 0.8;
              }
              $dimmer
                .stop()
                .css({
                  opacity : 0,
                  width   : '100%',
                  height  : '100%'
                })
                .fadeTo(module.get.duration(), settings.opacity, function() {
                  $dimmer.removeAttr('style');
                  module.set.active();
                  callback();
                })
              ;
            }
          },
          hide: function(callback) {
            callback = $.isFunction(callback)
              ? callback
              : function(){}
            ;
            if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) {
              module.verbose('Hiding dimmer with css');
              $dimmer
                .transition({
                  animation   : settings.transition + ' out',
                  queue       : false,
                  duration    : module.get.duration(),
                  useFailSafe : true,
                  onStart     : function() {
                    module.remove.dimmed();
                  },
                  onComplete  : function() {
                    module.remove.active();
                    callback();
                  }
                })
              ;
            }
            else {
              module.verbose('Hiding dimmer with javascript');
              module.remove.dimmed();
              $dimmer
                .stop()
                .fadeOut(module.get.duration(), function() {
                  module.remove.active();
                  $dimmer.removeAttr('style');
                  callback();
                })
              ;
            }
          }
        },

        get: {
          dimmer: function() {
            return $dimmer;
          },
          duration: function() {
            if(typeof settings.duration == 'object') {
              if( module.is.active() ) {
                return settings.duration.hide;
              }
              else {
                return settings.duration.show;
              }
            }
            return settings.duration;
          }
        },

        has: {
          dimmer: function() {
            if(settings.dimmerName) {
              return ($module.find(selector.dimmer).filter('.' + settings.dimmerName).length > 0);
            }
            else {
              return ( $module.find(selector.dimmer).length > 0 );
            }
          }
        },

        is: {
          active: function() {
            return $dimmer.hasClass(className.active);
          },
          animating: function() {
            return ( $dimmer.is(':animated') || $dimmer.hasClass(className.animating) );
          },
          closable: function() {
            if(settings.closable == 'auto') {
              if(settings.on == 'hover') {
                return false;
              }
              return true;
            }
            return settings.closable;
          },
          dimmer: function() {
            return $module.hasClass(className.dimmer);
          },
          dimmable: function() {
            return $module.hasClass(className.dimmable);
          },
          dimmed: function() {
            return $dimmable.hasClass(className.dimmed);
          },
          disabled: function() {
            return $dimmable.hasClass(className.disabled);
          },
          enabled: function() {
            return !module.is.disabled();
          },
          page: function () {
            return $dimmable.is('body');
          },
          pageDimmer: function() {
            return $dimmer.hasClass(className.pageDimmer);
          }
        },

        can: {
          show: function() {
            return !$dimmer.hasClass(className.disabled);
          }
        },

        set: {
          opacity: function(opacity) {
            var
              color      = $dimmer.css('background-color'),
              colorArray = color.split(','),
              isRGB      = (colorArray && colorArray.length == 3),
              isRGBA     = (colorArray && colorArray.length == 4)
            ;
            opacity    = settings.opacity === 0 ? 0 : settings.opacity || opacity;
            if(isRGB || isRGBA) {
              colorArray[3] = opacity + ')';
              color         = colorArray.join(',');
            }
            else {
              color = 'rgba(0, 0, 0, ' + opacity + ')';
            }
            module.debug('Setting opacity to', opacity);
            $dimmer.css('background-color', color);
          },
          active: function() {
            $dimmer.addClass(className.active);
          },
          dimmable: function() {
            $dimmable.addClass(className.dimmable);
          },
          dimmed: function() {
            $dimmable.addClass(className.dimmed);
          },
          pageDimmer: function() {
            $dimmer.addClass(className.pageDimmer);
          },
          disabled: function() {
            $dimmer.addClass(className.disabled);
          },
          variation: function(variation) {
            variation = variation || settings.variation;
            if(variation) {
              $dimmer.addClass(variation);
            }
          }
        },

        remove: {
          active: function() {
            $dimmer
              .removeClass(className.active)
            ;
          },
          dimmed: function() {
            $dimmable.removeClass(className.dimmed);
          },
          disabled: function() {
            $dimmer.removeClass(className.disabled);
          },
          variation: function(variation) {
            variation = variation || settings.variation;
            if(variation) {
              $dimmer.removeClass(variation);
            }
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.length > 1) {
              title += ' ' + '(' + $allModules.length + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      module.preinitialize();

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.dimmer.settings = {

  name        : 'Dimmer',
  namespace   : 'dimmer',

  silent      : false,
  debug       : false,
  verbose     : false,
  performance : true,

  // name to distinguish between multiple dimmers in context
  dimmerName  : false,

  // whether to add a variation type
  variation   : false,

  // whether to bind close events
  closable    : 'auto',

  // whether to use css animations
  useCSS      : true,

  // css animation to use
  transition  : 'fade',

  // event to bind to
  on          : false,

  // overriding opacity value
  opacity     : 'auto',

  // transition durations
  duration    : {
    show : 500,
    hide : 500
  },

  onChange    : function(){},
  onShow      : function(){},
  onHide      : function(){},

  error   : {
    method   : 'The method you called is not defined.'
  },

  className : {
    active     : 'active',
    animating  : 'animating',
    dimmable   : 'dimmable',
    dimmed     : 'dimmed',
    dimmer     : 'dimmer',
    disabled   : 'disabled',
    hide       : 'hide',
    pageDimmer : 'page',
    show       : 'show'
  },

  selector: {
    dimmer   : '> .ui.dimmer',
    content  : '.ui.dimmer > .content, .ui.dimmer > .content > .center'
  },

  template: {
    dimmer: function() {
     return $('<div />').attr('class', 'ui dimmer');
    }
  }

};

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Dropdown
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.dropdown = function(parameters) {
  var
    $allModules    = $(this),
    $document      = $(document),

    moduleSelector = $allModules.selector || '',

    hasTouch       = ('ontouchstart' in document.documentElement),
    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),
    returnedValue
  ;

  $allModules
    .each(function(elementIndex) {
      var
        settings          = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.dropdown.settings, parameters)
          : $.extend({}, $.fn.dropdown.settings),

        className       = settings.className,
        message         = settings.message,
        fields          = settings.fields,
        keys            = settings.keys,
        metadata        = settings.metadata,
        namespace       = settings.namespace,
        regExp          = settings.regExp,
        selector        = settings.selector,
        error           = settings.error,
        templates       = settings.templates,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $context        = $(settings.context),
        $text           = $module.find(selector.text),
        $search         = $module.find(selector.search),
        $sizer          = $module.find(selector.sizer),
        $input          = $module.find(selector.input),
        $icon           = $module.find(selector.icon),

        $combo = ($module.prev().find(selector.text).length > 0)
          ? $module.prev().find(selector.text)
          : $module.prev(),

        $menu           = $module.children(selector.menu),
        $item           = $menu.find(selector.item),

        activated       = false,
        itemActivated   = false,
        internalChange  = false,
        element         = this,
        instance        = $module.data(moduleNamespace),

        initialLoad,
        pageLostFocus,
        willRefocus,
        elementNamespace,
        id,
        selectObserver,
        menuObserver,
        module
      ;

      module = {

        initialize: function() {
          module.debug('Initializing dropdown', settings);

          if( module.is.alreadySetup() ) {
            module.setup.reference();
          }
          else {

            module.setup.layout();

            if(settings.values) {
              module.change.values(settings.values);
            }

            module.refreshData();

            module.save.defaults();
            module.restore.selected();

            module.create.id();
            module.bind.events();

            module.observeChanges();
            module.instantiate();
          }

        },

        instantiate: function() {
          module.verbose('Storing instance of dropdown', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous dropdown', $module);
          module.remove.tabbable();
          $module
            .off(eventNamespace)
            .removeData(moduleNamespace)
          ;
          $menu
            .off(eventNamespace)
          ;
          $document
            .off(elementNamespace)
          ;
          module.disconnect.menuObserver();
          module.disconnect.selectObserver();
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            selectObserver = new MutationObserver(module.event.select.mutation);
            menuObserver   = new MutationObserver(module.event.menu.mutation);
            module.debug('Setting up mutation observer', selectObserver, menuObserver);
            module.observe.select();
            module.observe.menu();
          }
        },

        disconnect: {
          menuObserver: function() {
            if(menuObserver) {
              menuObserver.disconnect();
            }
          },
          selectObserver: function() {
            if(selectObserver) {
              selectObserver.disconnect();
            }
          }
        },
        observe: {
          select: function() {
            if(module.has.input()) {
              selectObserver.observe($module[0], {
                childList : true,
                subtree   : true
              });
            }
          },
          menu: function() {
            if(module.has.menu()) {
              menuObserver.observe($menu[0], {
                childList : true,
                subtree   : true
              });
            }
          }
        },

        create: {
          id: function() {
            id = (Math.random().toString(16) + '000000000').substr(2, 8);
            elementNamespace = '.' + id;
            module.verbose('Creating unique id for element', id);
          },
          userChoice: function(values) {
            var
              $userChoices,
              $userChoice,
              isUserValue,
              html
            ;
            values = values || module.get.userValues();
            if(!values) {
              return false;
            }
            values = $.isArray(values)
              ? values
              : [values]
            ;
            $.each(values, function(index, value) {
              if(module.get.item(value) === false) {
                html         = settings.templates.addition( module.add.variables(message.addResult, value) );
                $userChoice  = $('<div />')
                  .html(html)
                  .attr('data-' + metadata.value, value)
                  .attr('data-' + metadata.text, value)
                  .addClass(className.addition)
                  .addClass(className.item)
                ;
                if(settings.hideAdditions) {
                  $userChoice.addClass(className.hidden);
                }
                $userChoices = ($userChoices === undefined)
                  ? $userChoice
                  : $userChoices.add($userChoice)
                ;
                module.verbose('Creating user choices for value', value, $userChoice);
              }
            });
            return $userChoices;
          },
          userLabels: function(value) {
            var
              userValues = module.get.userValues()
            ;
            if(userValues) {
              module.debug('Adding user labels', userValues);
              $.each(userValues, function(index, value) {
                module.verbose('Adding custom user value');
                module.add.label(value, value);
              });
            }
          },
          menu: function() {
            $menu = $('<div />')
              .addClass(className.menu)
              .appendTo($module)
            ;
          },
          sizer: function() {
            $sizer = $('<span />')
              .addClass(className.sizer)
              .insertAfter($search)
            ;
          }
        },

        search: function(query) {
          query = (query !== undefined)
            ? query
            : module.get.query()
          ;
          module.verbose('Searching for query', query);
          if(module.has.minCharacters(query)) {
            module.filter(query);
          }
          else {
            module.hide();
          }
        },

        select: {
          firstUnfiltered: function() {
            module.verbose('Selecting first non-filtered element');
            module.remove.selectedItem();
            $item
              .not(selector.unselectable)
              .not(selector.addition + selector.hidden)
                .eq(0)
                .addClass(className.selected)
            ;
          },
          nextAvailable: function($selected) {
            $selected = $selected.eq(0);
            var
              $nextAvailable = $selected.nextAll(selector.item).not(selector.unselectable).eq(0),
              $prevAvailable = $selected.prevAll(selector.item).not(selector.unselectable).eq(0),
              hasNext        = ($nextAvailable.length > 0)
            ;
            if(hasNext) {
              module.verbose('Moving selection to', $nextAvailable);
              $nextAvailable.addClass(className.selected);
            }
            else {
              module.verbose('Moving selection to', $prevAvailable);
              $prevAvailable.addClass(className.selected);
            }
          }
        },

        setup: {
          api: function() {
            var
              apiSettings = {
                debug   : settings.debug,
                urlData : {
                  value : module.get.value(),
                  query : module.get.query()
                },
                on    : false
              }
            ;
            module.verbose('First request, initializing API');
            $module
              .api(apiSettings)
            ;
          },
          layout: function() {
            if( $module.is('select') ) {
              module.setup.select();
              module.setup.returnedObject();
            }
            if( !module.has.menu() ) {
              module.create.menu();
            }
            if( module.is.search() && !module.has.search() ) {
              module.verbose('Adding search input');
              $search = $('<input />')
                .addClass(className.search)
                .prop('autocomplete', 'off')
                .insertBefore($text)
              ;
            }
            if( module.is.multiple() && module.is.searchSelection() && !module.has.sizer()) {
              module.create.sizer();
            }
            if(settings.allowTab) {
              module.set.tabbable();
            }
          },
          select: function() {
            var
              selectValues  = module.get.selectValues()
            ;
            module.debug('Dropdown initialized on a select', selectValues);
            if( $module.is('select') ) {
              $input = $module;
            }
            // see if select is placed correctly already
            if($input.parent(selector.dropdown).length > 0) {
              module.debug('UI dropdown already exists. Creating dropdown menu only');
              $module = $input.closest(selector.dropdown);
              if( !module.has.menu() ) {
                module.create.menu();
              }
              $menu = $module.children(selector.menu);
              module.setup.menu(selectValues);
            }
            else {
              module.debug('Creating entire dropdown from select');
              $module = $('<div />')
                .attr('class', $input.attr('class') )
                .addClass(className.selection)
                .addClass(className.dropdown)
                .html( templates.dropdown(selectValues) )
                .insertBefore($input)
              ;
              if($input.hasClass(className.multiple) && $input.prop('multiple') === false) {
                module.error(error.missingMultiple);
                $input.prop('multiple', true);
              }
              if($input.is('[multiple]')) {
                module.set.multiple();
              }
              if ($input.prop('disabled')) {
                module.debug('Disabling dropdown');
                $module.addClass(className.disabled);
              }
              $input
                .removeAttr('class')
                .detach()
                .prependTo($module)
              ;
            }
            module.refresh();
          },
          menu: function(values) {
            $menu.html( templates.menu(values, fields));
            $item = $menu.find(selector.item);
          },
          reference: function() {
            module.debug('Dropdown behavior was called on select, replacing with closest dropdown');
            // replace module reference
            $module  = $module.parent(selector.dropdown);
            instance = $module.data(moduleNamespace);
            element  = $module.get(0);
            module.refresh();
            module.setup.returnedObject();
          },
          returnedObject: function() {
            var
              $firstModules = $allModules.slice(0, elementIndex),
              $lastModules  = $allModules.slice(elementIndex + 1)
            ;
            // adjust all modules to use correct reference
            $allModules = $firstModules.add($module).add($lastModules);
          }
        },

        refresh: function() {
          module.refreshSelectors();
          module.refreshData();
        },

        refreshItems: function() {
          $item = $menu.find(selector.item);
        },

        refreshSelectors: function() {
          module.verbose('Refreshing selector cache');
          $text   = $module.find(selector.text);
          $search = $module.find(selector.search);
          $input  = $module.find(selector.input);
          $icon   = $module.find(selector.icon);
          $combo  = ($module.prev().find(selector.text).length > 0)
            ? $module.prev().find(selector.text)
            : $module.prev()
          ;
          $menu    = $module.children(selector.menu);
          $item    = $menu.find(selector.item);
        },

        refreshData: function() {
          module.verbose('Refreshing cached metadata');
          $item
            .removeData(metadata.text)
            .removeData(metadata.value)
          ;
        },

        clearData: function() {
          module.verbose('Clearing metadata');
          $item
            .removeData(metadata.text)
            .removeData(metadata.value)
          ;
          $module
            .removeData(metadata.defaultText)
            .removeData(metadata.defaultValue)
            .removeData(metadata.placeholderText)
          ;
        },

        toggle: function() {
          module.verbose('Toggling menu visibility');
          if( !module.is.active() ) {
            module.show();
          }
          else {
            module.hide();
          }
        },

        show: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if(!module.can.show() && module.is.remote()) {
            module.debug('No API results retrieved, searching before show');
            module.queryRemote(module.get.query(), module.show);
          }
          if( module.can.show() && !module.is.active() ) {
            module.debug('Showing dropdown');
            if(module.has.message() && !(module.has.maxSelections() || module.has.allResultsFiltered()) ) {
              module.remove.message();
            }
            if(module.is.allFiltered()) {
              return true;
            }
            if(settings.onShow.call(element) !== false) {
              module.animate.show(function() {
                if( module.can.click() ) {
                  module.bind.intent();
                }
                if(module.has.menuSearch()) {
                  module.focusSearch();
                }
                module.set.visible();
                callback.call(element);
              });
            }
          }
        },

        hide: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if( module.is.active() ) {
            module.debug('Hiding dropdown');
            if(settings.onHide.call(element) !== false) {
              module.animate.hide(function() {
                module.remove.visible();
                callback.call(element);
              });
            }
          }
        },

        hideOthers: function() {
          module.verbose('Finding other dropdowns to hide');
          $allModules
            .not($module)
              .has(selector.menu + '.' + className.visible)
                .dropdown('hide')
          ;
        },

        hideMenu: function() {
          module.verbose('Hiding menu  instantaneously');
          module.remove.active();
          module.remove.visible();
          $menu.transition('hide');
        },

        hideSubMenus: function() {
          var
            $subMenus = $menu.children(selector.item).find(selector.menu)
          ;
          module.verbose('Hiding sub menus', $subMenus);
          $subMenus.transition('hide');
        },

        bind: {
          events: function() {
            if(hasTouch) {
              module.bind.touchEvents();
            }
            module.bind.keyboardEvents();
            module.bind.inputEvents();
            module.bind.mouseEvents();
          },
          touchEvents: function() {
            module.debug('Touch device detected binding additional touch events');
            if( module.is.searchSelection() ) {
              // do nothing special yet
            }
            else if( module.is.single() ) {
              $module
                .on('touchstart' + eventNamespace, module.event.test.toggle)
              ;
            }
            $menu
              .on('touchstart' + eventNamespace, selector.item, module.event.item.mouseenter)
            ;
          },
          keyboardEvents: function() {
            module.verbose('Binding keyboard events');
            $module
              .on('keydown' + eventNamespace, module.event.keydown)
            ;
            if( module.has.search() ) {
              $module
                .on(module.get.inputEvent() + eventNamespace, selector.search, module.event.input)
              ;
            }
            if( module.is.multiple() ) {
              $document
                .on('keydown' + elementNamespace, module.event.document.keydown)
              ;
            }
          },
          inputEvents: function() {
            module.verbose('Binding input change events');
            $module
              .on('change' + eventNamespace, selector.input, module.event.change)
            ;
          },
          mouseEvents: function() {
            module.verbose('Binding mouse events');
            if(module.is.multiple()) {
              $module
                .on('click'   + eventNamespace, selector.label,  module.event.label.click)
                .on('click'   + eventNamespace, selector.remove, module.event.remove.click)
              ;
            }
            if( module.is.searchSelection() ) {
              $module
                .on('mousedown' + eventNamespace, module.event.mousedown)
                .on('mouseup'   + eventNamespace, module.event.mouseup)
                .on('mousedown' + eventNamespace, selector.menu,   module.event.menu.mousedown)
                .on('mouseup'   + eventNamespace, selector.menu,   module.event.menu.mouseup)
                .on('click'     + eventNamespace, selector.icon,   module.event.icon.click)
                .on('focus'     + eventNamespace, selector.search, module.event.search.focus)
                .on('click'     + eventNamespace, selector.search, module.event.search.focus)
                .on('blur'      + eventNamespace, selector.search, module.event.search.blur)
                .on('click'     + eventNamespace, selector.text,   module.event.text.focus)
              ;
              if(module.is.multiple()) {
                $module
                  .on('click' + eventNamespace, module.event.click)
                ;
              }
            }
            else {
              if(settings.on == 'click') {
                $module
                  .on('click' + eventNamespace, selector.icon, module.event.icon.click)
                  .on('click' + eventNamespace, module.event.test.toggle)
                ;
              }
              else if(settings.on == 'hover') {
                $module
                  .on('mouseenter' + eventNamespace, module.delay.show)
                  .on('mouseleave' + eventNamespace, module.delay.hide)
                ;
              }
              else {
                $module
                  .on(settings.on + eventNamespace, module.toggle)
                ;
              }
              $module
                .on('mousedown' + eventNamespace, module.event.mousedown)
                .on('mouseup'   + eventNamespace, module.event.mouseup)
                .on('focus'     + eventNamespace, module.event.focus)
              ;
              if(module.has.menuSearch() ) {
                $module
                  .on('blur' + eventNamespace, selector.search, module.event.search.blur)
                ;
              }
              else {
                $module
                  .on('blur' + eventNamespace, module.event.blur)
                ;
              }
            }
            $menu
              .on('mouseenter' + eventNamespace, selector.item, module.event.item.mouseenter)
              .on('mouseleave' + eventNamespace, selector.item, module.event.item.mouseleave)
              .on('click'      + eventNamespace, selector.item, module.event.item.click)
            ;
          },
          intent: function() {
            module.verbose('Binding hide intent event to document');
            if(hasTouch) {
              $document
                .on('touchstart' + elementNamespace, module.event.test.touch)
                .on('touchmove'  + elementNamespace, module.event.test.touch)
              ;
            }
            $document
              .on('click' + elementNamespace, module.event.test.hide)
            ;
          }
        },

        unbind: {
          intent: function() {
            module.verbose('Removing hide intent event from document');
            if(hasTouch) {
              $document
                .off('touchstart' + elementNamespace)
                .off('touchmove' + elementNamespace)
              ;
            }
            $document
              .off('click' + elementNamespace)
            ;
          }
        },

        filter: function(query) {
          var
            searchTerm = (query !== undefined)
              ? query
              : module.get.query(),
            afterFiltered = function() {
              if(module.is.multiple()) {
                module.filterActive();
              }
              if(query || (!query && module.get.activeItem().length == 0)) {
                module.select.firstUnfiltered();
              }
              if( module.has.allResultsFiltered() ) {
                if( settings.onNoResults.call(element, searchTerm) ) {
                  if(settings.allowAdditions) {
                    if(settings.hideAdditions) {
                      module.verbose('User addition with no menu, setting empty style');
                      module.set.empty();
                      module.hideMenu();
                    }
                  }
                  else {
                    module.verbose('All items filtered, showing message', searchTerm);
                    module.add.message(message.noResults);
                  }
                }
                else {
                  module.verbose('All items filtered, hiding dropdown', searchTerm);
                  module.hideMenu();
                }
              }
              else {
                module.remove.empty();
                module.remove.message();
              }
              if(settings.allowAdditions) {
                module.add.userSuggestion(query);
              }
              if(module.is.searchSelection() && module.can.show() && module.is.focusedOnSearch() ) {
                module.show();
              }
            }
          ;
          if(settings.useLabels && module.has.maxSelections()) {
            return;
          }
          if(settings.apiSettings) {
            if( module.can.useAPI() ) {
              module.queryRemote(searchTerm, function() {
                if(settings.filterRemoteData) {
                  module.filterItems(searchTerm);
                }
                afterFiltered();
              });
            }
            else {
              module.error(error.noAPI);
            }
          }
          else {
            module.filterItems(searchTerm);
            afterFiltered();
          }
        },

        queryRemote: function(query, callback) {
          var
            apiSettings = {
              errorDuration : false,
              cache         : 'local',
              throttle      : settings.throttle,
              urlData       : {
                query: query
              },
              onError: function() {
                module.add.message(message.serverError);
                callback();
              },
              onFailure: function() {
                module.add.message(message.serverError);
                callback();
              },
              onSuccess : function(response) {
                module.remove.message();
                module.setup.menu({
                  values: response[fields.remoteValues]
                });
                callback();
              }
            }
          ;
          if( !$module.api('get request') ) {
            module.setup.api();
          }
          apiSettings = $.extend(true, {}, apiSettings, settings.apiSettings);
          $module
            .api('setting', apiSettings)
            .api('query')
          ;
        },

        filterItems: function(query) {
          var
            searchTerm = (query !== undefined)
              ? query
              : module.get.query(),
            results          =  null,
            escapedTerm      = module.escape.string(searchTerm),
            beginsWithRegExp = new RegExp('^' + escapedTerm, 'igm')
          ;
          // avoid loop if we're matching nothing
          if( module.has.query() ) {
            results = [];

            module.verbose('Searching for matching values', searchTerm);
            $item
              .each(function(){
                var
                  $choice = $(this),
                  text,
                  value
                ;
                if(settings.match == 'both' || settings.match == 'text') {
                  text = String(module.get.choiceText($choice, false));
                  if(text.search(beginsWithRegExp) !== -1) {
                    results.push(this);
                    return true;
                  }
                  else if (settings.fullTextSearch === 'exact' && module.exactSearch(searchTerm, text)) {
                    results.push(this);
                    return true;
                  }
                  else if (settings.fullTextSearch === true && module.fuzzySearch(searchTerm, text)) {
                    results.push(this);
                    return true;
                  }
                }
                if(settings.match == 'both' || settings.match == 'value') {
                  value = String(module.get.choiceValue($choice, text));
                  if(value.search(beginsWithRegExp) !== -1) {
                    results.push(this);
                    return true;
                  }
                  else if (settings.fullTextSearch === 'exact' && module.exactSearch(searchTerm, value)) {
                    results.push(this);
                    return true;
                  }
                  else if (settings.fullTextSearch === true && module.fuzzySearch(searchTerm, value)) {
                    results.push(this);
                    return true;
                  }
                }
              })
            ;
          }
          module.debug('Showing only matched items', searchTerm);
          module.remove.filteredItem();
          if(results) {
            $item
              .not(results)
              .addClass(className.filtered)
            ;
          }
        },

        fuzzySearch: function(query, term) {
          var
            termLength  = term.length,
            queryLength = query.length
          ;
          query = query.toLowerCase();
          term  = term.toLowerCase();
          if(queryLength > termLength) {
            return false;
          }
          if(queryLength === termLength) {
            return (query === term);
          }
          search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
            var
              queryCharacter = query.charCodeAt(characterIndex)
            ;
            while(nextCharacterIndex < termLength) {
              if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
                continue search;
              }
            }
            return false;
          }
          return true;
        },
        exactSearch: function (query, term) {
          query = query.toLowerCase();
          term  = term.toLowerCase();
          if(term.indexOf(query) > -1) {
             return true;
          }
          return false;
        },
        filterActive: function() {
          if(settings.useLabels) {
            $item.filter('.' + className.active)
              .addClass(className.filtered)
            ;
          }
        },

        focusSearch: function(skipHandler) {
          if( module.has.search() && !module.is.focusedOnSearch() ) {
            if(skipHandler) {
              $module.off('focus' + eventNamespace, selector.search);
              $search.focus();
              $module.on('focus'  + eventNamespace, selector.search, module.event.search.focus);
            }
            else {
              $search.focus();
            }
          }
        },

        forceSelection: function() {
          var
            $currentlySelected = $item.not(className.filtered).filter('.' + className.selected).eq(0),
            $activeItem        = $item.not(className.filtered).filter('.' + className.active).eq(0),
            $selectedItem      = ($currentlySelected.length > 0)
              ? $currentlySelected
              : $activeItem,
            hasSelected = ($selectedItem.length > 0)
          ;
          if(hasSelected && !module.is.multiple()) {
            module.debug('Forcing partial selection to selected item', $selectedItem);
            module.event.item.click.call($selectedItem, {}, true);
            return;
          }
          else {
            if(settings.allowAdditions) {
              module.set.selected(module.get.query());
              module.remove.searchTerm();
            }
            else {
              module.remove.searchTerm();
            }
          }
        },

        change: {
          values: function(values) {
            if(!settings.allowAdditions) {
              module.clear();
            }
            module.debug('Creating dropdown with specified values', values);
            module.setup.menu({values: values});
            $.each(values, function(index, item) {
              if(item.selected == true) {
                module.debug('Setting initial selection to', item.value);
                module.set.selected(item.value);
                return true;
              }
            });
          }
        },

        event: {
          change: function() {
            if(!internalChange) {
              module.debug('Input changed, updating selection');
              module.set.selected();
            }
          },
          focus: function() {
            if(settings.showOnFocus && !activated && module.is.hidden() && !pageLostFocus) {
              module.show();
            }
          },
          blur: function(event) {
            pageLostFocus = (document.activeElement === this);
            if(!activated && !pageLostFocus) {
              module.remove.activeLabel();
              module.hide();
            }
          },
          mousedown: function() {
            if(module.is.searchSelection()) {
              // prevent menu hiding on immediate re-focus
              willRefocus = true;
            }
            else {
              // prevents focus callback from occurring on mousedown
              activated = true;
            }
          },
          mouseup: function() {
            if(module.is.searchSelection()) {
              // prevent menu hiding on immediate re-focus
              willRefocus = false;
            }
            else {
              activated = false;
            }
          },
          click: function(event) {
            var
              $target = $(event.target)
            ;
            // focus search
            if($target.is($module)) {
              if(!module.is.focusedOnSearch()) {
                module.focusSearch();
              }
              else {
                module.show();
              }
            }
          },
          search: {
            focus: function() {
              activated = true;
              if(module.is.multiple()) {
                module.remove.activeLabel();
              }
              if(settings.showOnFocus) {
                module.search();
              }
            },
            blur: function(event) {
              pageLostFocus = (document.activeElement === this);
              if(module.is.searchSelection() && !willRefocus) {
                if(!itemActivated && !pageLostFocus) {
                  if(settings.forceSelection) {
                    module.forceSelection();
                  }
                  module.hide();
                }
              }
              willRefocus = false;
            }
          },
          icon: {
            click: function(event) {
              module.toggle();
            }
          },
          text: {
            focus: function(event) {
              activated = true;
              module.focusSearch();
            }
          },
          input: function(event) {
            if(module.is.multiple() || module.is.searchSelection()) {
              module.set.filtered();
            }
            clearTimeout(module.timer);
            module.timer = setTimeout(module.search, settings.delay.search);
          },
          label: {
            click: function(event) {
              var
                $label        = $(this),
                $labels       = $module.find(selector.label),
                $activeLabels = $labels.filter('.' + className.active),
                $nextActive   = $label.nextAll('.' + className.active),
                $prevActive   = $label.prevAll('.' + className.active),
                $range = ($nextActive.length > 0)
                  ? $label.nextUntil($nextActive).add($activeLabels).add($label)
                  : $label.prevUntil($prevActive).add($activeLabels).add($label)
              ;
              if(event.shiftKey) {
                $activeLabels.removeClass(className.active);
                $range.addClass(className.active);
              }
              else if(event.ctrlKey) {
                $label.toggleClass(className.active);
              }
              else {
                $activeLabels.removeClass(className.active);
                $label.addClass(className.active);
              }
              settings.onLabelSelect.apply(this, $labels.filter('.' + className.active));
            }
          },
          remove: {
            click: function() {
              var
                $label = $(this).parent()
              ;
              if( $label.hasClass(className.active) ) {
                // remove all selected labels
                module.remove.activeLabels();
              }
              else {
                // remove this label only
                module.remove.activeLabels( $label );
              }
            }
          },
          test: {
            toggle: function(event) {
              var
                toggleBehavior = (module.is.multiple())
                  ? module.show
                  : module.toggle
              ;
              if(module.is.bubbledLabelClick(event) || module.is.bubbledIconClick(event)) {
                return;
              }
              if( module.determine.eventOnElement(event, toggleBehavior) ) {
                event.preventDefault();
              }
            },
            touch: function(event) {
              module.determine.eventOnElement(event, function() {
                if(event.type == 'touchstart') {
                  module.timer = setTimeout(function() {
                    module.hide();
                  }, settings.delay.touch);
                }
                else if(event.type == 'touchmove') {
                  clearTimeout(module.timer);
                }
              });
              event.stopPropagation();
            },
            hide: function(event) {
              module.determine.eventInModule(event, module.hide);
            }
          },
          select: {
            mutation: function(mutations) {
              module.debug('<select> modified, recreating menu');
              var
                isSelectMutation = false
              ;
              $.each(mutations, function(index, mutation) {
                if($(mutation.target).is('select') || $(mutation.addedNodes).is('select')) {
                  isSelectMutation = true;
                  return true;
                }
              });
              if(isSelectMutation) {
                module.disconnect.selectObserver();
                module.refresh();
                module.setup.select();
                module.set.selected();
                module.observe.select();
              }
            }
          },
          menu: {
            mutation: function(mutations) {
              var
                mutation   = mutations[0],
                $addedNode = mutation.addedNodes
                  ? $(mutation.addedNodes[0])
                  : $(false),
                $removedNode = mutation.removedNodes
                  ? $(mutation.removedNodes[0])
                  : $(false),
                $changedNodes  = $addedNode.add($removedNode),
                isUserAddition = $changedNodes.is(selector.addition) || $changedNodes.closest(selector.addition).length > 0,
                isMessage      = $changedNodes.is(selector.message)  || $changedNodes.closest(selector.message).length > 0
              ;
              if(isUserAddition || isMessage) {
                module.debug('Updating item selector cache');
                module.refreshItems();
              }
              else {
                module.debug('Menu modified, updating selector cache');
                module.refresh();
              }
            },
            mousedown: function() {
              itemActivated = true;
            },
            mouseup: function() {
              itemActivated = false;
            }
          },
          item: {
            mouseenter: function(event) {
              var
                $target        = $(event.target),
                $item          = $(this),
                $subMenu       = $item.children(selector.menu),
                $otherMenus    = $item.siblings(selector.item).children(selector.menu),
                hasSubMenu     = ($subMenu.length > 0),
                isBubbledEvent = ($subMenu.find($target).length > 0)
              ;
              if( !isBubbledEvent && hasSubMenu ) {
                clearTimeout(module.itemTimer);
                module.itemTimer = setTimeout(function() {
                  module.verbose('Showing sub-menu', $subMenu);
                  $.each($otherMenus, function() {
                    module.animate.hide(false, $(this));
                  });
                  module.animate.show(false, $subMenu);
                }, settings.delay.show);
                event.preventDefault();
              }
            },
            mouseleave: function(event) {
              var
                $subMenu = $(this).children(selector.menu)
              ;
              if($subMenu.length > 0) {
                clearTimeout(module.itemTimer);
                module.itemTimer = setTimeout(function() {
                  module.verbose('Hiding sub-menu', $subMenu);
                  module.animate.hide(false, $subMenu);
                }, settings.delay.hide);
              }
            },
            click: function (event, skipRefocus) {
              var
                $choice        = $(this),
                $target        = (event)
                  ? $(event.target)
                  : $(''),
                $subMenu       = $choice.find(selector.menu),
                text           = module.get.choiceText($choice),
                value          = module.get.choiceValue($choice, text),
                hasSubMenu     = ($subMenu.length > 0),
                isBubbledEvent = ($subMenu.find($target).length > 0)
              ;
              // prevents IE11 bug where menu receives focus even though `tabindex=-1`
              if(module.has.menuSearch()) {
                $(document.activeElement).blur();
              }
              if(!isBubbledEvent && (!hasSubMenu || settings.allowCategorySelection)) {
                if(module.is.searchSelection()) {
                  if(settings.allowAdditions) {
                    module.remove.userAddition();
                  }
                  module.remove.searchTerm();
                  if(!module.is.focusedOnSearch() && !(skipRefocus == true)) {
                    module.focusSearch(true);
                  }
                }
                if(!settings.useLabels) {
                  module.remove.filteredItem();
                  module.set.scrollPosition($choice);
                }
                module.determine.selectAction.call(this, text, value);
              }
            }
          },

          document: {
            // label selection should occur even when element has no focus
            keydown: function(event) {
              var
                pressedKey    = event.which,
                isShortcutKey = module.is.inObject(pressedKey, keys)
              ;
              if(isShortcutKey) {
                var
                  $label            = $module.find(selector.label),
                  $activeLabel      = $label.filter('.' + className.active),
                  activeValue       = $activeLabel.data(metadata.value),
                  labelIndex        = $label.index($activeLabel),
                  labelCount        = $label.length,
                  hasActiveLabel    = ($activeLabel.length > 0),
                  hasMultipleActive = ($activeLabel.length > 1),
                  isFirstLabel      = (labelIndex === 0),
                  isLastLabel       = (labelIndex + 1 == labelCount),
                  isSearch          = module.is.searchSelection(),
                  isFocusedOnSearch = module.is.focusedOnSearch(),
                  isFocused         = module.is.focused(),
                  caretAtStart      = (isFocusedOnSearch && module.get.caretPosition() === 0),
                  $nextLabel
                ;
                if(isSearch && !hasActiveLabel && !isFocusedOnSearch) {
                  return;
                }

                if(pressedKey == keys.leftArrow) {
                  // activate previous label
                  if((isFocused || caretAtStart) && !hasActiveLabel) {
                    module.verbose('Selecting previous label');
                    $label.last().addClass(className.active);
                  }
                  else if(hasActiveLabel) {
                    if(!event.shiftKey) {
                      module.verbose('Selecting previous label');
                      $label.removeClass(className.active);
                    }
                    else {
                      module.verbose('Adding previous label to selection');
                    }
                    if(isFirstLabel && !hasMultipleActive) {
                      $activeLabel.addClass(className.active);
                    }
                    else {
                      $activeLabel.prev(selector.siblingLabel)
                        .addClass(className.active)
                        .end()
                      ;
                    }
                    event.preventDefault();
                  }
                }
                else if(pressedKey == keys.rightArrow) {
                  // activate first label
                  if(isFocused && !hasActiveLabel) {
                    $label.first().addClass(className.active);
                  }
                  // activate next label
                  if(hasActiveLabel) {
                    if(!event.shiftKey) {
                      module.verbose('Selecting next label');
                      $label.removeClass(className.active);
                    }
                    else {
                      module.verbose('Adding next label to selection');
                    }
                    if(isLastLabel) {
                      if(isSearch) {
                        if(!isFocusedOnSearch) {
                          module.focusSearch();
                        }
                        else {
                          $label.removeClass(className.active);
                        }
                      }
                      else if(hasMultipleActive) {
                        $activeLabel.next(selector.siblingLabel).addClass(className.active);
                      }
                      else {
                        $activeLabel.addClass(className.active);
                      }
                    }
                    else {
                      $activeLabel.next(selector.siblingLabel).addClass(className.active);
                    }
                    event.preventDefault();
                  }
                }
                else if(pressedKey == keys.deleteKey || pressedKey == keys.backspace) {
                  if(hasActiveLabel) {
                    module.verbose('Removing active labels');
                    if(isLastLabel) {
                      if(isSearch && !isFocusedOnSearch) {
                        module.focusSearch();
                      }
                    }
                    $activeLabel.last().next(selector.siblingLabel).addClass(className.active);
                    module.remove.activeLabels($activeLabel);
                    event.preventDefault();
                  }
                  else if(caretAtStart && !hasActiveLabel && pressedKey == keys.backspace) {
                    module.verbose('Removing last label on input backspace');
                    $activeLabel = $label.last().addClass(className.active);
                    module.remove.activeLabels($activeLabel);
                  }
                }
                else {
                  $activeLabel.removeClass(className.active);
                }
              }
            }
          },

          keydown: function(event) {
            var
              pressedKey    = event.which,
              isShortcutKey = module.is.inObject(pressedKey, keys)
            ;
            if(isShortcutKey) {
              var
                $currentlySelected = $item.not(selector.unselectable).filter('.' + className.selected).eq(0),
                $activeItem        = $menu.children('.' + className.active).eq(0),
                $selectedItem      = ($currentlySelected.length > 0)
                  ? $currentlySelected
                  : $activeItem,
                $visibleItems = ($selectedItem.length > 0)
                  ? $selectedItem.siblings(':not(.' + className.filtered +')').addBack()
                  : $menu.children(':not(.' + className.filtered +')'),
                $subMenu              = $selectedItem.children(selector.menu),
                $parentMenu           = $selectedItem.closest(selector.menu),
                inVisibleMenu         = ($parentMenu.hasClass(className.visible) || $parentMenu.hasClass(className.animating) || $parentMenu.parent(selector.menu).length > 0),
                hasSubMenu            = ($subMenu.length> 0),
                hasSelectedItem       = ($selectedItem.length > 0),
                selectedIsSelectable  = ($selectedItem.not(selector.unselectable).length > 0),
                delimiterPressed      = (pressedKey == keys.delimiter && settings.allowAdditions && module.is.multiple()),
                isAdditionWithoutMenu = (settings.allowAdditions && settings.hideAdditions && (pressedKey == keys.enter || delimiterPressed) && selectedIsSelectable),
                $nextItem,
                isSubMenuItem,
                newIndex
              ;
              // allow selection with menu closed
              if(isAdditionWithoutMenu) {
                module.verbose('Selecting item from keyboard shortcut', $selectedItem);
                module.event.item.click.call($selectedItem, event);
                if(module.is.searchSelection()) {
                  module.remove.searchTerm();
                }
              }

              // visible menu keyboard shortcuts
              if( module.is.visible() ) {

                // enter (select or open sub-menu)
                if(pressedKey == keys.enter || delimiterPressed) {
                  if(pressedKey == keys.enter && hasSelectedItem && hasSubMenu && !settings.allowCategorySelection) {
                    module.verbose('Pressed enter on unselectable category, opening sub menu');
                    pressedKey = keys.rightArrow;
                  }
                  else if(selectedIsSelectable) {
                    module.verbose('Selecting item from keyboard shortcut', $selectedItem);
                    module.event.item.click.call($selectedItem, event);
                    if(module.is.searchSelection()) {
                      module.remove.searchTerm();
                    }
                  }
                  event.preventDefault();
                }

                // sub-menu actions
                if(hasSelectedItem) {

                  if(pressedKey == keys.leftArrow) {

                    isSubMenuItem = ($parentMenu[0] !== $menu[0]);

                    if(isSubMenuItem) {
                      module.verbose('Left key pressed, closing sub-menu');
                      module.animate.hide(false, $parentMenu);
                      $selectedItem
                        .removeClass(className.selected)
                      ;
                      $parentMenu
                        .closest(selector.item)
                          .addClass(className.selected)
                      ;
                      event.preventDefault();
                    }
                  }

                  // right arrow (show sub-menu)
                  if(pressedKey == keys.rightArrow) {
                    if(hasSubMenu) {
                      module.verbose('Right key pressed, opening sub-menu');
                      module.animate.show(false, $subMenu);
                      $selectedItem
                        .removeClass(className.selected)
                      ;
                      $subMenu
                        .find(selector.item).eq(0)
                          .addClass(className.selected)
                      ;
                      event.preventDefault();
                    }
                  }
                }

                // up arrow (traverse menu up)
                if(pressedKey == keys.upArrow) {
                  $nextItem = (hasSelectedItem && inVisibleMenu)
                    ? $selectedItem.prevAll(selector.item + ':not(' + selector.unselectable + ')').eq(0)
                    : $item.eq(0)
                  ;
                  if($visibleItems.index( $nextItem ) < 0) {
                    module.verbose('Up key pressed but reached top of current menu');
                    event.preventDefault();
                    return;
                  }
                  else {
                    module.verbose('Up key pressed, changing active item');
                    $selectedItem
                      .removeClass(className.selected)
                    ;
                    $nextItem
                      .addClass(className.selected)
                    ;
                    module.set.scrollPosition($nextItem);
                    if(settings.selectOnKeydown && module.is.single()) {
                      module.set.selectedItem($nextItem);
                    }
                  }
                  event.preventDefault();
                }

                // down arrow (traverse menu down)
                if(pressedKey == keys.downArrow) {
                  $nextItem = (hasSelectedItem && inVisibleMenu)
                    ? $nextItem = $selectedItem.nextAll(selector.item + ':not(' + selector.unselectable + ')').eq(0)
                    : $item.eq(0)
                  ;
                  if($nextItem.length === 0) {
                    module.verbose('Down key pressed but reached bottom of current menu');
                    event.preventDefault();
                    return;
                  }
                  else {
                    module.verbose('Down key pressed, changing active item');
                    $item
                      .removeClass(className.selected)
                    ;
                    $nextItem
                      .addClass(className.selected)
                    ;
                    module.set.scrollPosition($nextItem);
                    if(settings.selectOnKeydown && module.is.single()) {
                      module.set.selectedItem($nextItem);
                    }
                  }
                  event.preventDefault();
                }

                // page down (show next page)
                if(pressedKey == keys.pageUp) {
                  module.scrollPage('up');
                  event.preventDefault();
                }
                if(pressedKey == keys.pageDown) {
                  module.scrollPage('down');
                  event.preventDefault();
                }

                // escape (close menu)
                if(pressedKey == keys.escape) {
                  module.verbose('Escape key pressed, closing dropdown');
                  module.hide();
                }

              }
              else {
                // delimiter key
                if(delimiterPressed) {
                  event.preventDefault();
                }
                // down arrow (open menu)
                if(pressedKey == keys.downArrow && !module.is.visible()) {
                  module.verbose('Down key pressed, showing dropdown');
                  module.show();
                  event.preventDefault();
                }
              }
            }
            else {
              if( !module.has.search() ) {
                module.set.selectedLetter( String.fromCharCode(pressedKey) );
              }
            }
          }
        },

        trigger: {
          change: function() {
            var
              events       = document.createEvent('HTMLEvents'),
              inputElement = $input[0]
            ;
            if(inputElement) {
              module.verbose('Triggering native change event');
              events.initEvent('change', true, false);
              inputElement.dispatchEvent(events);
            }
          }
        },

        determine: {
          selectAction: function(text, value) {
            module.verbose('Determining action', settings.action);
            if( $.isFunction( module.action[settings.action] ) ) {
              module.verbose('Triggering preset action', settings.action, text, value);
              module.action[ settings.action ].call(element, text, value, this);
            }
            else if( $.isFunction(settings.action) ) {
              module.verbose('Triggering user action', settings.action, text, value);
              settings.action.call(element, text, value, this);
            }
            else {
              module.error(error.action, settings.action);
            }
          },
          eventInModule: function(event, callback) {
            var
              $target    = $(event.target),
              inDocument = ($target.closest(document.documentElement).length > 0),
              inModule   = ($target.closest($module).length > 0)
            ;
            callback = $.isFunction(callback)
              ? callback
              : function(){}
            ;
            if(inDocument && !inModule) {
              module.verbose('Triggering event', callback);
              callback();
              return true;
            }
            else {
              module.verbose('Event occurred in dropdown, canceling callback');
              return false;
            }
          },
          eventOnElement: function(event, callback) {
            var
              $target      = $(event.target),
              $label       = $target.closest(selector.siblingLabel),
              inVisibleDOM = document.body.contains(event.target),
              notOnLabel   = ($module.find($label).length === 0),
              notInMenu    = ($target.closest($menu).length === 0)
            ;
            callback = $.isFunction(callback)
              ? callback
              : function(){}
            ;
            if(inVisibleDOM && notOnLabel && notInMenu) {
              module.verbose('Triggering event', callback);
              callback();
              return true;
            }
            else {
              module.verbose('Event occurred in dropdown menu, canceling callback');
              return false;
            }
          }
        },

        action: {

          nothing: function() {},

          activate: function(text, value, element) {
            value = (value !== undefined)
              ? value
              : text
            ;
            if( module.can.activate( $(element) ) ) {
              module.set.selected(value, $(element));
              if(module.is.multiple() && !module.is.allFiltered()) {
                return;
              }
              else {
                module.hideAndClear();
              }
            }
          },

          select: function(text, value, element) {
            value = (value !== undefined)
              ? value
              : text
            ;
            if( module.can.activate( $(element) ) ) {
              module.set.value(value, $(element));
              if(module.is.multiple() && !module.is.allFiltered()) {
                return;
              }
              else {
                module.hideAndClear();
              }
            }
          },

          combo: function(text, value, element) {
            value = (value !== undefined)
              ? value
              : text
            ;
            module.set.selected(value, $(element));
            module.hideAndClear();
          },

          hide: function(text, value, element) {
            module.set.value(value, text);
            module.hideAndClear();
          }

        },

        get: {
          id: function() {
            return id;
          },
          defaultText: function() {
            return $module.data(metadata.defaultText);
          },
          defaultValue: function() {
            return $module.data(metadata.defaultValue);
          },
          placeholderText: function() {
            if(settings.placeholder != 'auto' && typeof settings.placeholder == 'string') {
              return settings.placeholder;
            }
            return $module.data(metadata.placeholderText) || '';
          },
          text: function() {
            return $text.text();
          },
          query: function() {
            return $.trim($search.val());
          },
          searchWidth: function(value) {
            value = (value !== undefined)
              ? value
              : $search.val()
            ;
            $sizer.text(value);
            // prevent rounding issues
            return Math.ceil( $sizer.width() + 1);
          },
          selectionCount: function() {
            var
              values = module.get.values(),
              count
            ;
            count = ( module.is.multiple() )
              ? $.isArray(values)
                ? values.length
                : 0
              : (module.get.value() !== '')
                ? 1
                : 0
            ;
            return count;
          },
          transition: function($subMenu) {
            return (settings.transition == 'auto')
              ? module.is.upward($subMenu)
                ? 'slide up'
                : 'slide down'
              : settings.transition
            ;
          },
          userValues: function() {
            var
              values = module.get.values()
            ;
            if(!values) {
              return false;
            }
            values = $.isArray(values)
              ? values
              : [values]
            ;
            return $.grep(values, function(value) {
              return (module.get.item(value) === false);
            });
          },
          uniqueArray: function(array) {
            return $.grep(array, function (value, index) {
                return $.inArray(value, array) === index;
            });
          },
          caretPosition: function() {
            var
              input = $search.get(0),
              range,
              rangeLength
            ;
            if('selectionStart' in input) {
              return input.selectionStart;
            }
            else if (document.selection) {
              input.focus();
              range       = document.selection.createRange();
              rangeLength = range.text.length;
              range.moveStart('character', -input.value.length);
              return range.text.length - rangeLength;
            }
          },
          value: function() {
            var
              value = ($input.length > 0)
                ? $input.val()
                : $module.data(metadata.value),
              isEmptyMultiselect = ($.isArray(value) && value.length === 1 && value[0] === '')
            ;
            // prevents placeholder element from being selected when multiple
            return (value === undefined || isEmptyMultiselect)
              ? ''
              : value
            ;
          },
          values: function() {
            var
              value = module.get.value()
            ;
            if(value === '') {
              return '';
            }
            return ( !module.has.selectInput() && module.is.multiple() )
              ? (typeof value == 'string') // delimited string
                ? value.split(settings.delimiter)
                : ''
              : value
            ;
          },
          remoteValues: function() {
            var
              values = module.get.values(),
              remoteValues = false
            ;
            if(values) {
              if(typeof values == 'string') {
                values = [values];
              }
              $.each(values, function(index, value) {
                var
                  name = module.read.remoteData(value)
                ;
                module.verbose('Restoring value from session data', name, value);
                if(name) {
                  if(!remoteValues) {
                    remoteValues = {};
                  }
                  remoteValues[value] = name;
                }
              });
            }
            return remoteValues;
          },
          choiceText: function($choice, preserveHTML) {
            preserveHTML = (preserveHTML !== undefined)
              ? preserveHTML
              : settings.preserveHTML
            ;
            if($choice) {
              if($choice.find(selector.menu).length > 0) {
                module.verbose('Retrieving text of element with sub-menu');
                $choice = $choice.clone();
                $choice.find(selector.menu).remove();
                $choice.find(selector.menuIcon).remove();
              }
              return ($choice.data(metadata.text) !== undefined)
                ? $choice.data(metadata.text)
                : (preserveHTML)
                  ? $.trim($choice.html())
                  : $.trim($choice.text())
              ;
            }
          },
          choiceValue: function($choice, choiceText) {
            choiceText = choiceText || module.get.choiceText($choice);
            if(!$choice) {
              return false;
            }
            return ($choice.data(metadata.value) !== undefined)
              ? String( $choice.data(metadata.value) )
              : (typeof choiceText === 'string')
                ? $.trim(choiceText.toLowerCase())
                : String(choiceText)
            ;
          },
          inputEvent: function() {
            var
              input = $search[0]
            ;
            if(input) {
              return (input.oninput !== undefined)
                ? 'input'
                : (input.onpropertychange !== undefined)
                  ? 'propertychange'
                  : 'keyup'
              ;
            }
            return false;
          },
          selectValues: function() {
            var
              select = {}
            ;
            select.values = [];
            $module
              .find('option')
                .each(function() {
                  var
                    $option  = $(this),
                    name     = $option.html(),
                    disabled = $option.attr('disabled'),
                    value    = ( $option.attr('value') !== undefined )
                      ? $option.attr('value')
                      : name
                  ;
                  if(settings.placeholder === 'auto' && value === '') {
                    select.placeholder = name;
                  }
                  else {
                    select.values.push({
                      name     : name,
                      value    : value,
                      disabled : disabled
                    });
                  }
                })
            ;
            if(settings.placeholder && settings.placeholder !== 'auto') {
              module.debug('Setting placeholder value to', settings.placeholder);
              select.placeholder = settings.placeholder;
            }
            if(settings.sortSelect) {
              select.values.sort(function(a, b) {
                return (a.name > b.name)
                  ? 1
                  : -1
                ;
              });
              module.debug('Retrieved and sorted values from select', select);
            }
            else {
              module.debug('Retrieved values from select', select);
            }
            return select;
          },
          activeItem: function() {
            return $item.filter('.'  + className.active);
          },
          selectedItem: function() {
            var
              $selectedItem = $item.not(selector.unselectable).filter('.'  + className.selected)
            ;
            return ($selectedItem.length > 0)
              ? $selectedItem
              : $item.eq(0)
            ;
          },
          itemWithAdditions: function(value) {
            var
              $items       = module.get.item(value),
              $userItems   = module.create.userChoice(value),
              hasUserItems = ($userItems && $userItems.length > 0)
            ;
            if(hasUserItems) {
              $items = ($items.length > 0)
                ? $items.add($userItems)
                : $userItems
              ;
            }
            return $items;
          },
          item: function(value, strict) {
            var
              $selectedItem = false,
              shouldSearch,
              isMultiple
            ;
            value = (value !== undefined)
              ? value
              : ( module.get.values() !== undefined)
                ? module.get.values()
                : module.get.text()
            ;
            shouldSearch = (isMultiple)
              ? (value.length > 0)
              : (value !== undefined && value !== null)
            ;
            isMultiple = (module.is.multiple() && $.isArray(value));
            strict     = (value === '' || value === 0)
              ? true
              : strict || false
            ;
            if(shouldSearch) {
              $item
                .each(function() {
                  var
                    $choice       = $(this),
                    optionText    = module.get.choiceText($choice),
                    optionValue   = module.get.choiceValue($choice, optionText)
                  ;
                  // safe early exit
                  if(optionValue === null || optionValue === undefined) {
                    return;
                  }
                  if(isMultiple) {
                    if($.inArray( String(optionValue), value) !== -1 || $.inArray(optionText, value) !== -1) {
                      $selectedItem = ($selectedItem)
                        ? $selectedItem.add($choice)
                        : $choice
                      ;
                    }
                  }
                  else if(strict) {
                    module.verbose('Ambiguous dropdown value using strict type check', $choice, value);
                    if( optionValue === value || optionText === value) {
                      $selectedItem = $choice;
                      return true;
                    }
                  }
                  else {
                    if( String(optionValue) == String(value) || optionText == value) {
                      module.verbose('Found select item by value', optionValue, value);
                      $selectedItem = $choice;
                      return true;
                    }
                  }
                })
              ;
            }
            return $selectedItem;
          }
        },

        check: {
          maxSelections: function(selectionCount) {
            if(settings.maxSelections) {
              selectionCount = (selectionCount !== undefined)
                ? selectionCount
                : module.get.selectionCount()
              ;
              if(selectionCount >= settings.maxSelections) {
                module.debug('Maximum selection count reached');
                if(settings.useLabels) {
                  $item.addClass(className.filtered);
                  module.add.message(message.maxSelections);
                }
                return true;
              }
              else {
                module.verbose('No longer at maximum selection count');
                module.remove.message();
                module.remove.filteredItem();
                if(module.is.searchSelection()) {
                  module.filterItems();
                }
                return false;
              }
            }
            return true;
          }
        },

        restore: {
          defaults: function() {
            module.clear();
            module.restore.defaultText();
            module.restore.defaultValue();
          },
          defaultText: function() {
            var
              defaultText     = module.get.defaultText(),
              placeholderText = module.get.placeholderText
            ;
            if(defaultText === placeholderText) {
              module.debug('Restoring default placeholder text', defaultText);
              module.set.placeholderText(defaultText);
            }
            else {
              module.debug('Restoring default text', defaultText);
              module.set.text(defaultText);
            }
          },
          placeholderText: function() {
            module.set.placeholderText();
          },
          defaultValue: function() {
            var
              defaultValue = module.get.defaultValue()
            ;
            if(defaultValue !== undefined) {
              module.debug('Restoring default value', defaultValue);
              if(defaultValue !== '') {
                module.set.value(defaultValue);
                module.set.selected();
              }
              else {
                module.remove.activeItem();
                module.remove.selectedItem();
              }
            }
          },
          labels: function() {
            if(settings.allowAdditions) {
              if(!settings.useLabels) {
                module.error(error.labels);
                settings.useLabels = true;
              }
              module.debug('Restoring selected values');
              module.create.userLabels();
            }
            module.check.maxSelections();
          },
          selected: function() {
            module.restore.values();
            if(module.is.multiple()) {
              module.debug('Restoring previously selected values and labels');
              module.restore.labels();
            }
            else {
              module.debug('Restoring previously selected values');
            }
          },
          values: function() {
            // prevents callbacks from occurring on initial load
            module.set.initialLoad();
            if(settings.apiSettings && settings.saveRemoteData && module.get.remoteValues()) {
              module.restore.remoteValues();
            }
            else {
              module.set.selected();
            }
            module.remove.initialLoad();
          },
          remoteValues: function() {
            var
              values = module.get.remoteValues()
            ;
            module.debug('Recreating selected from session data', values);
            if(values) {
              if( module.is.single() ) {
                $.each(values, function(value, name) {
                  module.set.text(name);
                });
              }
              else {
                $.each(values, function(value, name) {
                  module.add.label(value, name);
                });
              }
            }
          }
        },

        read: {
          remoteData: function(value) {
            var
              name
            ;
            if(window.Storage === undefined) {
              module.error(error.noStorage);
              return;
            }
            name = sessionStorage.getItem(value);
            return (name !== undefined)
              ? name
              : false
            ;
          }
        },

        save: {
          defaults: function() {
            module.save.defaultText();
            module.save.placeholderText();
            module.save.defaultValue();
          },
          defaultValue: function() {
            var
              value = module.get.value()
            ;
            module.verbose('Saving default value as', value);
            $module.data(metadata.defaultValue, value);
          },
          defaultText: function() {
            var
              text = module.get.text()
            ;
            module.verbose('Saving default text as', text);
            $module.data(metadata.defaultText, text);
          },
          placeholderText: function() {
            var
              text
            ;
            if(settings.placeholder !== false && $text.hasClass(className.placeholder)) {
              text = module.get.text();
              module.verbose('Saving placeholder text as', text);
              $module.data(metadata.placeholderText, text);
            }
          },
          remoteData: function(name, value) {
            if(window.Storage === undefined) {
              module.error(error.noStorage);
              return;
            }
            module.verbose('Saving remote data to session storage', value, name);
            sessionStorage.setItem(value, name);
          }
        },

        clear: function() {
          if(module.is.multiple() && settings.useLabels) {
            module.remove.labels();
          }
          else {
            module.remove.activeItem();
            module.remove.selectedItem();
          }
          module.set.placeholderText();
          module.clearValue();
        },

        clearValue: function() {
          module.set.value('');
        },

        scrollPage: function(direction, $selectedItem) {
          var
            $currentItem  = $selectedItem || module.get.selectedItem(),
            $menu         = $currentItem.closest(selector.menu),
            menuHeight    = $menu.outerHeight(),
            currentScroll = $menu.scrollTop(),
            itemHeight    = $item.eq(0).outerHeight(),
            itemsPerPage  = Math.floor(menuHeight / itemHeight),
            maxScroll     = $menu.prop('scrollHeight'),
            newScroll     = (direction == 'up')
              ? currentScroll - (itemHeight * itemsPerPage)
              : currentScroll + (itemHeight * itemsPerPage),
            $selectableItem = $item.not(selector.unselectable),
            isWithinRange,
            $nextSelectedItem,
            elementIndex
          ;
          elementIndex      = (direction == 'up')
            ? $selectableItem.index($currentItem) - itemsPerPage
            : $selectableItem.index($currentItem) + itemsPerPage
          ;
          isWithinRange = (direction == 'up')
            ? (elementIndex >= 0)
            : (elementIndex < $selectableItem.length)
          ;
          $nextSelectedItem = (isWithinRange)
            ? $selectableItem.eq(elementIndex)
            : (direction == 'up')
              ? $selectableItem.first()
              : $selectableItem.last()
          ;
          if($nextSelectedItem.length > 0) {
            module.debug('Scrolling page', direction, $nextSelectedItem);
            $currentItem
              .removeClass(className.selected)
            ;
            $nextSelectedItem
              .addClass(className.selected)
            ;
            if(settings.selectOnKeydown && module.is.single()) {
              module.set.selectedItem($nextSelectedItem);
            }
            $menu
              .scrollTop(newScroll)
            ;
          }
        },

        set: {
          filtered: function() {
            var
              isMultiple       = module.is.multiple(),
              isSearch         = module.is.searchSelection(),
              isSearchMultiple = (isMultiple && isSearch),
              searchValue      = (isSearch)
                ? module.get.query()
                : '',
              hasSearchValue   = (typeof searchValue === 'string' && searchValue.length > 0),
              searchWidth      = module.get.searchWidth(),
              valueIsSet       = searchValue !== ''
            ;
            if(isMultiple && hasSearchValue) {
              module.verbose('Adjusting input width', searchWidth, settings.glyphWidth);
              $search.css('width', searchWidth);
            }
            if(hasSearchValue || (isSearchMultiple && valueIsSet)) {
              module.verbose('Hiding placeholder text');
              $text.addClass(className.filtered);
            }
            else if(!isMultiple || (isSearchMultiple && !valueIsSet)) {
              module.verbose('Showing placeholder text');
              $text.removeClass(className.filtered);
            }
          },
          empty: function() {
            $module.addClass(className.empty);
          },
          loading: function() {
            $module.addClass(className.loading);
          },
          placeholderText: function(text) {
            text = text || module.get.placeholderText();
            module.debug('Setting placeholder text', text);
            module.set.text(text);
            $text.addClass(className.placeholder);
          },
          tabbable: function() {
            if( module.is.searchSelection() ) {
              module.debug('Added tabindex to searchable dropdown');
              $search
                .val('')
                .attr('tabindex', 0)
              ;
              $menu
                .attr('tabindex', -1)
              ;
            }
            else {
              module.debug('Added tabindex to dropdown');
              if( $module.attr('tabindex') === undefined) {
                $module
                  .attr('tabindex', 0)
                ;
                $menu
                  .attr('tabindex', -1)
                ;
              }
            }
          },
          initialLoad: function() {
            module.verbose('Setting initial load');
            initialLoad = true;
          },
          activeItem: function($item) {
            if( settings.allowAdditions && $item.filter(selector.addition).length > 0 ) {
              $item.addClass(className.filtered);
            }
            else {
              $item.addClass(className.active);
            }
          },
          partialSearch: function(text) {
            var
              length = module.get.query().length
            ;
            $search.val( text.substr(0 , length));
          },
          scrollPosition: function($item, forceScroll) {
            var
              edgeTolerance = 5,
              $menu,
              hasActive,
              offset,
              itemHeight,
              itemOffset,
              menuOffset,
              menuScroll,
              menuHeight,
              abovePage,
              belowPage
            ;

            $item       = $item || module.get.selectedItem();
            $menu       = $item.closest(selector.menu);
            hasActive   = ($item && $item.length > 0);
            forceScroll = (forceScroll !== undefined)
              ? forceScroll
              : false
            ;
            if($item && $menu.length > 0 && hasActive) {
              itemOffset = $item.position().top;

              $menu.addClass(className.loading);
              menuScroll = $menu.scrollTop();
              menuOffset = $menu.offset().top;
              itemOffset = $item.offset().top;
              offset     = menuScroll - menuOffset + itemOffset;
              if(!forceScroll) {
                menuHeight = $menu.height();
                belowPage  = menuScroll + menuHeight < (offset + edgeTolerance);
                abovePage  = ((offset - edgeTolerance) < menuScroll);
              }
              module.debug('Scrolling to active item', offset);
              if(forceScroll || abovePage || belowPage) {
                $menu.scrollTop(offset);
              }
              $menu.removeClass(className.loading);
            }
          },
          text: function(text) {
            if(settings.action !== 'select') {
              if(settings.action == 'combo') {
                module.debug('Changing combo button text', text, $combo);
                if(settings.preserveHTML) {
                  $combo.html(text);
                }
                else {
                  $combo.text(text);
                }
              }
              else {
                if(text !== module.get.placeholderText()) {
                  $text.removeClass(className.placeholder);
                }
                module.debug('Changing text', text, $text);
                $text
                  .removeClass(className.filtered)
                ;
                if(settings.preserveHTML) {
                  $text.html(text);
                }
                else {
                  $text.text(text);
                }
              }
            }
          },
          selectedItem: function($item) {
            var
              value      = module.get.choiceValue($item),
              searchText = module.get.choiceText($item, false),
              text       = module.get.choiceText($item, true)
            ;
            module.debug('Setting user selection to item', $item);
            module.remove.activeItem();
            module.set.partialSearch(searchText);
            module.set.activeItem($item);
            module.set.selected(value, $item);
            module.set.text(text);
          },
          selectedLetter: function(letter) {
            var
              $selectedItem         = $item.filter('.' + className.selected),
              alreadySelectedLetter = $selectedItem.length > 0 && module.has.firstLetter($selectedItem, letter),
              $nextValue            = false,
              $nextItem
            ;
            // check next of same letter
            if(alreadySelectedLetter) {
              $nextItem = $selectedItem.nextAll($item).eq(0);
              if( module.has.firstLetter($nextItem, letter) ) {
                $nextValue  = $nextItem;
              }
            }
            // check all values
            if(!$nextValue) {
              $item
                .each(function(){
                  if(module.has.firstLetter($(this), letter)) {
                    $nextValue = $(this);
                    return false;
                  }
                })
              ;
            }
            // set next value
            if($nextValue) {
              module.verbose('Scrolling to next value with letter', letter);
              module.set.scrollPosition($nextValue);
              $selectedItem.removeClass(className.selected);
              $nextValue.addClass(className.selected);
              if(settings.selectOnKeydown && module.is.single()) {
                module.set.selectedItem($nextValue);
              }
            }
          },
          direction: function($menu) {
            if(settings.direction == 'auto') {
              // reset position
              module.remove.upward();

              if(module.can.openDownward($menu)) {
                module.remove.upward($menu);
              }
              else {
                module.set.upward($menu);
              }
              if(!module.is.leftward($menu) && !module.can.openRightward($menu)) {
                module.set.leftward($menu);
              }
            }
            else if(settings.direction == 'upward') {
              module.set.upward($menu);
            }
          },
          upward: function($currentMenu) {
            var $element = $currentMenu || $module;
            $element.addClass(className.upward);
          },
          leftward: function($currentMenu) {
            var $element = $currentMenu || $menu;
            $element.addClass(className.leftward);
          },
          value: function(value, text, $selected) {
            var
              escapedValue = module.escape.value(value),
              hasInput     = ($input.length > 0),
              isAddition   = !module.has.value(value),
              currentValue = module.get.values(),
              stringValue  = (value !== undefined)
                ? String(value)
                : value,
              newValue
            ;
            if(hasInput) {
              if(!settings.allowReselection && stringValue == currentValue) {
                module.verbose('Skipping value update already same value', value, currentValue);
                if(!module.is.initialLoad()) {
                  return;
                }
              }

              if( module.is.single() && module.has.selectInput() && module.can.extendSelect() ) {
                module.debug('Adding user option', value);
                module.add.optionValue(value);
              }
              module.debug('Updating input value', escapedValue, currentValue);
              internalChange = true;
              $input
                .val(escapedValue)
              ;
              if(settings.fireOnInit === false && module.is.initialLoad()) {
                module.debug('Input native change event ignored on initial load');
              }
              else {
                module.trigger.change();
              }
              internalChange = false;
            }
            else {
              module.verbose('Storing value in metadata', escapedValue, $input);
              if(escapedValue !== currentValue) {
                $module.data(metadata.value, stringValue);
              }
            }
            if(settings.fireOnInit === false && module.is.initialLoad()) {
              module.verbose('No callback on initial load', settings.onChange);
            }
            else {
              settings.onChange.call(element, value, text, $selected);
            }
          },
          active: function() {
            $module
              .addClass(className.active)
            ;
          },
          multiple: function() {
            $module.addClass(className.multiple);
          },
          visible: function() {
            $module.addClass(className.visible);
          },
          exactly: function(value, $selectedItem) {
            module.debug('Setting selected to exact values');
            module.clear();
            module.set.selected(value, $selectedItem);
          },
          selected: function(value, $selectedItem) {
            var
              isMultiple = module.is.multiple(),
              $userSelectedItem
            ;
            $selectedItem = (settings.allowAdditions)
              ? $selectedItem || module.get.itemWithAdditions(value)
              : $selectedItem || module.get.item(value)
            ;
            if(!$selectedItem) {
              return;
            }
            module.debug('Setting selected menu item to', $selectedItem);
            if(module.is.multiple()) {
              module.remove.searchWidth();
            }
            if(module.is.single()) {
              module.remove.activeItem();
              module.remove.selectedItem();
            }
            else if(settings.useLabels) {
              module.remove.selectedItem();
            }
            // select each item
            $selectedItem
              .each(function() {
                var
                  $selected      = $(this),
                  selectedText   = module.get.choiceText($selected),
                  selectedValue  = module.get.choiceValue($selected, selectedText),

                  isFiltered     = $selected.hasClass(className.filtered),
                  isActive       = $selected.hasClass(className.active),
                  isUserValue    = $selected.hasClass(className.addition),
                  shouldAnimate  = (isMultiple && $selectedItem.length == 1)
                ;
                if(isMultiple) {
                  if(!isActive || isUserValue) {
                    if(settings.apiSettings && settings.saveRemoteData) {
                      module.save.remoteData(selectedText, selectedValue);
                    }
                    if(settings.useLabels) {
                      module.add.value(selectedValue, selectedText, $selected);
                      module.add.label(selectedValue, selectedText, shouldAnimate);
                      module.set.activeItem($selected);
                      module.filterActive();
                      module.select.nextAvailable($selectedItem);
                    }
                    else {
                      module.add.value(selectedValue, selectedText, $selected);
                      module.set.text(module.add.variables(message.count));
                      module.set.activeItem($selected);
                    }
                  }
                  else if(!isFiltered) {
                    module.debug('Selected active value, removing label');
                    module.remove.selected(selectedValue);
                  }
                }
                else {
                  if(settings.apiSettings && settings.saveRemoteData) {
                    module.save.remoteData(selectedText, selectedValue);
                  }
                  module.set.text(selectedText);
                  module.set.value(selectedValue, selectedText, $selected);
                  $selected
                    .addClass(className.active)
                    .addClass(className.selected)
                  ;
                }
              })
            ;
          }
        },

        add: {
          label: function(value, text, shouldAnimate) {
            var
              $next  = module.is.searchSelection()
                ? $search
                : $text,
              escapedValue = module.escape.value(value),
              $label
            ;
            $label =  $('<a />')
              .addClass(className.label)
              .attr('data-' + metadata.value, escapedValue)
              .html(templates.label(escapedValue, text))
            ;
            $label = settings.onLabelCreate.call($label, escapedValue, text);

            if(module.has.label(value)) {
              module.debug('Label already exists, skipping', escapedValue);
              return;
            }
            if(settings.label.variation) {
              $label.addClass(settings.label.variation);
            }
            if(shouldAnimate === true) {
              module.debug('Animating in label', $label);
              $label
                .addClass(className.hidden)
                .insertBefore($next)
                .transition(settings.label.transition, settings.label.duration)
              ;
            }
            else {
              module.debug('Adding selection label', $label);
              $label
                .insertBefore($next)
              ;
            }
          },
          message: function(message) {
            var
              $message = $menu.children(selector.message),
              html     = settings.templates.message(module.add.variables(message))
            ;
            if($message.length > 0) {
              $message
                .html(html)
              ;
            }
            else {
              $message = $('<div/>')
                .html(html)
                .addClass(className.message)
                .appendTo($menu)
              ;
            }
          },
          optionValue: function(value) {
            var
              escapedValue = module.escape.value(value),
              $option      = $input.find('option[value="' + module.escape.string(escapedValue) + '"]'),
              hasOption    = ($option.length > 0)
            ;
            if(hasOption) {
              return;
            }
            // temporarily disconnect observer
            module.disconnect.selectObserver();
            if( module.is.single() ) {
              module.verbose('Removing previous user addition');
              $input.find('option.' + className.addition).remove();
            }
            $('<option/>')
              .prop('value', escapedValue)
              .addClass(className.addition)
              .html(value)
              .appendTo($input)
            ;
            module.verbose('Adding user addition as an <option>', value);
            module.observe.select();
          },
          userSuggestion: function(value) {
            var
              $addition         = $menu.children(selector.addition),
              $existingItem     = module.get.item(value),
              alreadyHasValue   = $existingItem && $existingItem.not(selector.addition).length,
              hasUserSuggestion = $addition.length > 0,
              html
            ;
            if(settings.useLabels && module.has.maxSelections()) {
              return;
            }
            if(value === '' || alreadyHasValue) {
              $addition.remove();
              return;
            }
            if(hasUserSuggestion) {
              $addition
                .data(metadata.value, value)
                .data(metadata.text, value)
                .attr('data-' + metadata.value, value)
                .attr('data-' + metadata.text, value)
                .removeClass(className.filtered)
              ;
              if(!settings.hideAdditions) {
                html = settings.templates.addition( module.add.variables(message.addResult, value) );
                $addition
                  .html(html)
                ;
              }
              module.verbose('Replacing user suggestion with new value', $addition);
            }
            else {
              $addition = module.create.userChoice(value);
              $addition
                .prependTo($menu)
              ;
              module.verbose('Adding item choice to menu corresponding with user choice addition', $addition);
            }
            if(!settings.hideAdditions || module.is.allFiltered()) {
              $addition
                .addClass(className.selected)
                .siblings()
                .removeClass(className.selected)
              ;
            }
            module.refreshItems();
          },
          variables: function(message, term) {
            var
              hasCount    = (message.search('{count}') !== -1),
              hasMaxCount = (message.search('{maxCount}') !== -1),
              hasTerm     = (message.search('{term}') !== -1),
              values,
              count,
              query
            ;
            module.verbose('Adding templated variables to message', message);
            if(hasCount) {
              count  = module.get.selectionCount();
              message = message.replace('{count}', count);
            }
            if(hasMaxCount) {
              count  = module.get.selectionCount();
              message = message.replace('{maxCount}', settings.maxSelections);
            }
            if(hasTerm) {
              query   = term || module.get.query();
              message = message.replace('{term}', query);
            }
            return message;
          },
          value: function(addedValue, addedText, $selectedItem) {
            var
              currentValue = module.get.values(),
              newValue
            ;
            if(addedValue === '') {
              module.debug('Cannot select blank values from multiselect');
              return;
            }
            // extend current array
            if($.isArray(currentValue)) {
              newValue = currentValue.concat([addedValue]);
              newValue = module.get.uniqueArray(newValue);
            }
            else {
              newValue = [addedValue];
            }
            // add values
            if( module.has.selectInput() ) {
              if(module.can.extendSelect()) {
                module.debug('Adding value to select', addedValue, newValue, $input);
                module.add.optionValue(addedValue);
              }
            }
            else {
              newValue = newValue.join(settings.delimiter);
              module.debug('Setting hidden input to delimited value', newValue, $input);
            }

            if(settings.fireOnInit === false && module.is.initialLoad()) {
              module.verbose('Skipping onadd callback on initial load', settings.onAdd);
            }
            else {
              settings.onAdd.call(element, addedValue, addedText, $selectedItem);
            }
            module.set.value(newValue, addedValue, addedText, $selectedItem);
            module.check.maxSelections();
          }
        },

        remove: {
          active: function() {
            $module.removeClass(className.active);
          },
          activeLabel: function() {
            $module.find(selector.label).removeClass(className.active);
          },
          empty: function() {
            $module.removeClass(className.empty);
          },
          loading: function() {
            $module.removeClass(className.loading);
          },
          initialLoad: function() {
            initialLoad = false;
          },
          upward: function($currentMenu) {
            var $element = $currentMenu || $module;
            $element.removeClass(className.upward);
          },
          leftward: function($currentMenu) {
            var $element = $currentMenu || $menu;
            $element.removeClass(className.leftward);
          },
          visible: function() {
            $module.removeClass(className.visible);
          },
          activeItem: function() {
            $item.removeClass(className.active);
          },
          filteredItem: function() {
            if(settings.useLabels && module.has.maxSelections() ) {
              return;
            }
            if(settings.useLabels && module.is.multiple()) {
              $item.not('.' + className.active).removeClass(className.filtered);
            }
            else {
              $item.removeClass(className.filtered);
            }
            module.remove.empty();
          },
          optionValue: function(value) {
            var
              escapedValue = module.escape.value(value),
              $option      = $input.find('option[value="' + module.escape.string(escapedValue) + '"]'),
              hasOption    = ($option.length > 0)
            ;
            if(!hasOption || !$option.hasClass(className.addition)) {
              return;
            }
            // temporarily disconnect observer
            if(selectObserver) {
              selectObserver.disconnect();
              module.verbose('Temporarily disconnecting mutation observer');
            }
            $option.remove();
            module.verbose('Removing user addition as an <option>', escapedValue);
            if(selectObserver) {
              selectObserver.observe($input[0], {
                childList : true,
                subtree   : true
              });
            }
          },
          message: function() {
            $menu.children(selector.message).remove();
          },
          searchWidth: function() {
            $search.css('width', '');
          },
          searchTerm: function() {
            module.verbose('Cleared search term');
            $search.val('');
            module.set.filtered();
          },
          userAddition: function() {
            $item.filter(selector.addition).remove();
          },
          selected: function(value, $selectedItem) {
            $selectedItem = (settings.allowAdditions)
              ? $selectedItem || module.get.itemWithAdditions(value)
              : $selectedItem || module.get.item(value)
            ;

            if(!$selectedItem) {
              return false;
            }

            $selectedItem
              .each(function() {
                var
                  $selected     = $(this),
                  selectedText  = module.get.choiceText($selected),
                  selectedValue = module.get.choiceValue($selected, selectedText)
                ;
                if(module.is.multiple()) {
                  if(settings.useLabels) {
                    module.remove.value(selectedValue, selectedText, $selected);
                    module.remove.label(selectedValue);
                  }
                  else {
                    module.remove.value(selectedValue, selectedText, $selected);
                    if(module.get.selectionCount() === 0) {
                      module.set.placeholderText();
                    }
                    else {
                      module.set.text(module.add.variables(message.count));
                    }
                  }
                }
                else {
                  module.remove.value(selectedValue, selectedText, $selected);
                }
                $selected
                  .removeClass(className.filtered)
                  .removeClass(className.active)
                ;
                if(settings.useLabels) {
                  $selected.removeClass(className.selected);
                }
              })
            ;
          },
          selectedItem: function() {
            $item.removeClass(className.selected);
          },
          value: function(removedValue, removedText, $removedItem) {
            var
              values = module.get.values(),
              newValue
            ;
            if( module.has.selectInput() ) {
              module.verbose('Input is <select> removing selected option', removedValue);
              newValue = module.remove.arrayValue(removedValue, values);
              module.remove.optionValue(removedValue);
            }
            else {
              module.verbose('Removing from delimited values', removedValue);
              newValue = module.remove.arrayValue(removedValue, values);
              newValue = newValue.join(settings.delimiter);
            }
            if(settings.fireOnInit === false && module.is.initialLoad()) {
              module.verbose('No callback on initial load', settings.onRemove);
            }
            else {
              settings.onRemove.call(element, removedValue, removedText, $removedItem);
            }
            module.set.value(newValue, removedText, $removedItem);
            module.check.maxSelections();
          },
          arrayValue: function(removedValue, values) {
            if( !$.isArray(values) ) {
              values = [values];
            }
            values = $.grep(values, function(value){
              return (removedValue != value);
            });
            module.verbose('Removed value from delimited string', removedValue, values);
            return values;
          },
          label: function(value, shouldAnimate) {
            var
              $labels       = $module.find(selector.label),
              $removedLabel = $labels.filter('[data-' + metadata.value + '="' + module.escape.string(value) +'"]')
            ;
            module.verbose('Removing label', $removedLabel);
            $removedLabel.remove();
          },
          activeLabels: function($activeLabels) {
            $activeLabels = $activeLabels || $module.find(selector.label).filter('.' + className.active);
            module.verbose('Removing active label selections', $activeLabels);
            module.remove.labels($activeLabels);
          },
          labels: function($labels) {
            $labels = $labels || $module.find(selector.label);
            module.verbose('Removing labels', $labels);
            $labels
              .each(function(){
                var
                  $label      = $(this),
                  value       = $label.data(metadata.value),
                  stringValue = (value !== undefined)
                    ? String(value)
                    : value,
                  isUserValue = module.is.userValue(stringValue)
                ;
                if(settings.onLabelRemove.call($label, value) === false) {
                  module.debug('Label remove callback cancelled removal');
                  return;
                }
                module.remove.message();
                if(isUserValue) {
                  module.remove.value(stringValue);
                  module.remove.label(stringValue);
                }
                else {
                  // selected will also remove label
                  module.remove.selected(stringValue);
                }
              })
            ;
          },
          tabbable: function() {
            if( module.is.searchSelection() ) {
              module.debug('Searchable dropdown initialized');
              $search
                .removeAttr('tabindex')
              ;
              $menu
                .removeAttr('tabindex')
              ;
            }
            else {
              module.debug('Simple selection dropdown initialized');
              $module
                .removeAttr('tabindex')
              ;
              $menu
                .removeAttr('tabindex')
              ;
            }
          }
        },

        has: {
          menuSearch: function() {
            return (module.has.search() && $search.closest($menu).length > 0);
          },
          search: function() {
            return ($search.length > 0);
          },
          sizer: function() {
            return ($sizer.length > 0);
          },
          selectInput: function() {
            return ( $input.is('select') );
          },
          minCharacters: function(searchTerm) {
            if(settings.minCharacters) {
              searchTerm = (searchTerm !== undefined)
                ? String(searchTerm)
                : String(module.get.query())
              ;
              return (searchTerm.length >= settings.minCharacters);
            }
            return true;
          },
          firstLetter: function($item, letter) {
            var
              text,
              firstLetter
            ;
            if(!$item || $item.length === 0 || typeof letter !== 'string') {
              return false;
            }
            text        = module.get.choiceText($item, false);
            letter      = letter.toLowerCase();
            firstLetter = String(text).charAt(0).toLowerCase();
            return (letter == firstLetter);
          },
          input: function() {
            return ($input.length > 0);
          },
          items: function() {
            return ($item.length > 0);
          },
          menu: function() {
            return ($menu.length > 0);
          },
          message: function() {
            return ($menu.children(selector.message).length !== 0);
          },
          label: function(value) {
            var
              escapedValue = module.escape.value(value),
              $labels      = $module.find(selector.label)
            ;
            return ($labels.filter('[data-' + metadata.value + '="' + module.escape.string(escapedValue) +'"]').length > 0);
          },
          maxSelections: function() {
            return (settings.maxSelections && module.get.selectionCount() >= settings.maxSelections);
          },
          allResultsFiltered: function() {
            var
              $normalResults = $item.not(selector.addition)
            ;
            return ($normalResults.filter(selector.unselectable).length === $normalResults.length);
          },
          userSuggestion: function() {
            return ($menu.children(selector.addition).length > 0);
          },
          query: function() {
            return (module.get.query() !== '');
          },
          value: function(value) {
            var
              values   = module.get.values(),
              hasValue = $.isArray(values)
               ? values && ($.inArray(value, values) !== -1)
               : (values == value)
            ;
            return (hasValue)
              ? true
              : false
            ;
          }
        },

        is: {
          active: function() {
            return $module.hasClass(className.active);
          },
          bubbledLabelClick: function(event) {
            return $(event.target).is('select, input') && $module.closest('label').length > 0;
          },
          bubbledIconClick: function(event) {
            return $(event.target).closest($icon).length > 0;
          },
          alreadySetup: function() {
            return ($module.is('select') && $module.parent(selector.dropdown).data(moduleNamespace) !== undefined && $module.prev().length === 0);
          },
          animating: function($subMenu) {
            return ($subMenu)
              ? $subMenu.transition && $subMenu.transition('is animating')
              : $menu.transition    && $menu.transition('is animating')
            ;
          },
          leftward: function($subMenu) {
            var $selectedMenu = $subMenu || $menu;
            return $selectedMenu.hasClass(className.leftward);
          },
          disabled: function() {
            return $module.hasClass(className.disabled);
          },
          focused: function() {
            return (document.activeElement === $module[0]);
          },
          focusedOnSearch: function() {
            return (document.activeElement === $search[0]);
          },
          allFiltered: function() {
            return( (module.is.multiple() || module.has.search()) && !(settings.hideAdditions == false && module.has.userSuggestion()) && !module.has.message() && module.has.allResultsFiltered() );
          },
          hidden: function($subMenu) {
            return !module.is.visible($subMenu);
          },
          initialLoad: function() {
            return initialLoad;
          },
          inObject: function(needle, object) {
            var
              found = false
            ;
            $.each(object, function(index, property) {
              if(property == needle) {
                found = true;
                return true;
              }
            });
            return found;
          },
          multiple: function() {
            return $module.hasClass(className.multiple);
          },
          remote: function() {
            return settings.apiSettings && module.can.useAPI();
          },
          single: function() {
            return !module.is.multiple();
          },
          selectMutation: function(mutations) {
            var
              selectChanged = false
            ;
            $.each(mutations, function(index, mutation) {
              if(mutation.target && $(mutation.target).is('select')) {
                selectChanged = true;
                return true;
              }
            });
            return selectChanged;
          },
          search: function() {
            return $module.hasClass(className.search);
          },
          searchSelection: function() {
            return ( module.has.search() && $search.parent(selector.dropdown).length === 1 );
          },
          selection: function() {
            return $module.hasClass(className.selection);
          },
          userValue: function(value) {
            return ($.inArray(value, module.get.userValues()) !== -1);
          },
          upward: function($menu) {
            var $element = $menu || $module;
            return $element.hasClass(className.upward);
          },
          visible: function($subMenu) {
            return ($subMenu)
              ? $subMenu.hasClass(className.visible)
              : $menu.hasClass(className.visible)
            ;
          },
          verticallyScrollableContext: function() {
            var
              overflowY = ($context.get(0) !== window)
                ? $context.css('overflow-y')
                : false
            ;
            return (overflowY == 'auto' || overflowY == 'scroll');
          },
          horizontallyScrollableContext: function() {
            var
              overflowX = ($context.get(0) !== window)
                ? $context.css('overflow-X')
                : false
            ;
            return (overflowX == 'auto' || overflowX == 'scroll');
          }
        },

        can: {
          activate: function($item) {
            if(settings.useLabels) {
              return true;
            }
            if(!module.has.maxSelections()) {
              return true;
            }
            if(module.has.maxSelections() && $item.hasClass(className.active)) {
              return true;
            }
            return false;
          },
          openDownward: function($subMenu) {
            var
              $currentMenu    = $subMenu || $menu,
              canOpenDownward = true,
              onScreen        = {},
              calculations
            ;
            $currentMenu
              .addClass(className.loading)
            ;
            calculations = {
              context: {
                scrollTop : $context.scrollTop(),
                height    : $context.outerHeight()
              },
              menu : {
                offset: $currentMenu.offset(),
                height: $currentMenu.outerHeight()
              }
            };
            if(module.is.verticallyScrollableContext()) {
              calculations.menu.offset.top += calculations.context.scrollTop;
            }
            onScreen = {
              above : (calculations.context.scrollTop) <= calculations.menu.offset.top - calculations.menu.height,
              below : (calculations.context.scrollTop + calculations.context.height) >= calculations.menu.offset.top + calculations.menu.height
            };
            if(onScreen.below) {
              module.verbose('Dropdown can fit in context downward', onScreen);
              canOpenDownward = true;
            }
            else if(!onScreen.below && !onScreen.above) {
              module.verbose('Dropdown cannot fit in either direction, favoring downward', onScreen);
              canOpenDownward = true;
            }
            else {
              module.verbose('Dropdown cannot fit below, opening upward', onScreen);
              canOpenDownward = false;
            }
            $currentMenu.removeClass(className.loading);
            return canOpenDownward;
          },
          openRightward: function($subMenu) {
            var
              $currentMenu     = $subMenu || $menu,
              canOpenRightward = true,
              isOffscreenRight = false,
              calculations
            ;
            $currentMenu
              .addClass(className.loading)
            ;
            calculations = {
              context: {
                scrollLeft : $context.scrollLeft(),
                width      : $context.outerWidth()
              },
              menu: {
                offset : $currentMenu.offset(),
                width  : $currentMenu.outerWidth()
              }
            };
            if(module.is.horizontallyScrollableContext()) {
              calculations.menu.offset.left += calculations.context.scrollLeft;
            }
            isOffscreenRight = (calculations.menu.offset.left + calculations.menu.width >= calculations.context.scrollLeft + calculations.context.width);
            if(isOffscreenRight) {
              module.verbose('Dropdown cannot fit in context rightward', isOffscreenRight);
              canOpenRightward = false;
            }
            $currentMenu.removeClass(className.loading);
            return canOpenRightward;
          },
          click: function() {
            return (hasTouch || settings.on == 'click');
          },
          extendSelect: function() {
            return settings.allowAdditions || settings.apiSettings;
          },
          show: function() {
            return !module.is.disabled() && (module.has.items() || module.has.message());
          },
          useAPI: function() {
            return $.fn.api !== undefined;
          }
        },

        animate: {
          show: function(callback, $subMenu) {
            var
              $currentMenu = $subMenu || $menu,
              start = ($subMenu)
                ? function() {}
                : function() {
                  module.hideSubMenus();
                  module.hideOthers();
                  module.set.active();
                },
              transition
            ;
            callback = $.isFunction(callback)
              ? callback
              : function(){}
            ;
            module.verbose('Doing menu show animation', $currentMenu);
            module.set.direction($subMenu);
            transition = module.get.transition($subMenu);
            if( module.is.selection() ) {
              module.set.scrollPosition(module.get.selectedItem(), true);
            }
            if( module.is.hidden($currentMenu) || module.is.animating($currentMenu) ) {
              if(transition == 'none') {
                start();
                $currentMenu.transition('show');
                callback.call(element);
              }
              else if($.fn.transition !== undefined && $module.transition('is supported')) {
                $currentMenu
                  .transition({
                    animation  : transition + ' in',
                    debug      : settings.debug,
                    verbose    : settings.verbose,
                    duration   : settings.duration,
                    queue      : true,
                    onStart    : start,
                    onComplete : function() {
                      callback.call(element);
                    }
                  })
                ;
              }
              else {
                module.error(error.noTransition, transition);
              }
            }
          },
          hide: function(callback, $subMenu) {
            var
              $currentMenu = $subMenu || $menu,
              duration = ($subMenu)
                ? (settings.duration * 0.9)
                : settings.duration,
              start = ($subMenu)
                ? function() {}
                : function() {
                  if( module.can.click() ) {
                    module.unbind.intent();
                  }
                  module.remove.active();
                },
              transition = module.get.transition($subMenu)
            ;
            callback = $.isFunction(callback)
              ? callback
              : function(){}
            ;
            if( module.is.visible($currentMenu) || module.is.animating($currentMenu) ) {
              module.verbose('Doing menu hide animation', $currentMenu);

              if(transition == 'none') {
                start();
                $currentMenu.transition('hide');
                callback.call(element);
              }
              else if($.fn.transition !== undefined && $module.transition('is supported')) {
                $currentMenu
                  .transition({
                    animation  : transition + ' out',
                    duration   : settings.duration,
                    debug      : settings.debug,
                    verbose    : settings.verbose,
                    queue      : true,
                    onStart    : start,
                    onComplete : function() {
                      callback.call(element);
                    }
                  })
                ;
              }
              else {
                module.error(error.transition);
              }
            }
          }
        },

        hideAndClear: function() {
          module.remove.searchTerm();
          if( module.has.maxSelections() ) {
            return;
          }
          if(module.has.search()) {
            module.hide(function() {
              module.remove.filteredItem();
            });
          }
          else {
            module.hide();
          }
        },

        delay: {
          show: function() {
            module.verbose('Delaying show event to ensure user intent');
            clearTimeout(module.timer);
            module.timer = setTimeout(module.show, settings.delay.show);
          },
          hide: function() {
            module.verbose('Delaying hide event to ensure user intent');
            clearTimeout(module.timer);
            module.timer = setTimeout(module.hide, settings.delay.hide);
          }
        },

        escape: {
          value: function(value) {
            var
              multipleValues = $.isArray(value),
              stringValue    = (typeof value === 'string'),
              isUnparsable   = (!stringValue && !multipleValues),
              hasQuotes      = (stringValue && value.search(regExp.quote) !== -1),
              values         = []
            ;
            if(isUnparsable || !hasQuotes) {
              return value;
            }
            module.debug('Encoding quote values for use in select', value);
            if(multipleValues) {
              $.each(value, function(index, value){
                values.push(value.replace(regExp.quote, '&quot;'));
              });
              return values;
            }
            return value.replace(regExp.quote, '&quot;');
          },
          string: function(text) {
            text =  String(text);
            return text.replace(regExp.escape, '\\$&');
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;
  return (returnedValue !== undefined)
    ? returnedValue
    : $allModules
  ;
};

$.fn.dropdown.settings = {

  silent                 : false,
  debug                  : false,
  verbose                : false,
  performance            : true,

  on                     : 'click',    // what event should show menu action on item selection
  action                 : 'activate', // action on item selection (nothing, activate, select, combo, hide, function(){})

  values                 : false,      // specify values to use for dropdown

  apiSettings            : false,
  selectOnKeydown        : true,       // Whether selection should occur automatically when keyboard shortcuts used
  minCharacters          : 0,          // Minimum characters required to trigger API call

  filterRemoteData       : false,      // Whether API results should be filtered after being returned for query term
  saveRemoteData         : true,       // Whether remote name/value pairs should be stored in sessionStorage to allow remote data to be restored on page refresh

  throttle               : 200,        // How long to wait after last user input to search remotely

  context                : window,     // Context to use when determining if on screen
  direction              : 'auto',     // Whether dropdown should always open in one direction
  keepOnScreen           : true,       // Whether dropdown should check whether it is on screen before showing

  match                  : 'both',     // what to match against with search selection (both, text, or label)
  fullTextSearch         : false,      // search anywhere in value (set to 'exact' to require exact matches)

  placeholder            : 'auto',     // whether to convert blank <select> values to placeholder text
  preserveHTML           : true,       // preserve html when selecting value
  sortSelect             : false,      // sort selection on init

  forceSelection         : true,       // force a choice on blur with search selection

  allowAdditions         : false,      // whether multiple select should allow user added values
  hideAdditions          : true,      // whether or not to hide special message prompting a user they can enter a value

  maxSelections          : false,      // When set to a number limits the number of selections to this count
  useLabels              : true,       // whether multiple select should filter currently active selections from choices
  delimiter              : ',',        // when multiselect uses normal <input> the values will be delimited with this character

  showOnFocus            : true,       // show menu on focus
  allowReselection       : false,      // whether current value should trigger callbacks when reselected
  allowTab               : true,       // add tabindex to element
  allowCategorySelection : false,      // allow elements with sub-menus to be selected

  fireOnInit             : false,      // Whether callbacks should fire when initializing dropdown values

  transition             : 'auto',     // auto transition will slide down or up based on direction
  duration               : 200,        // duration of transition

  glyphWidth             : 1.037,      // widest glyph width in em (W is 1.037 em) used to calculate multiselect input width

  // label settings on multi-select
  label: {
    transition : 'scale',
    duration   : 200,
    variation  : false
  },

  // delay before event
  delay : {
    hide   : 300,
    show   : 200,
    search : 20,
    touch  : 50
  },

  /* Callbacks */
  onChange      : function(value, text, $selected){},
  onAdd         : function(value, text, $selected){},
  onRemove      : function(value, text, $selected){},

  onLabelSelect : function($selectedLabels){},
  onLabelCreate : function(value, text) { return $(this); },
  onLabelRemove : function(value) { return true; },
  onNoResults   : function(searchTerm) { return true; },
  onShow        : function(){},
  onHide        : function(){},

  /* Component */
  name           : 'Dropdown',
  namespace      : 'dropdown',

  message: {
    addResult     : 'Add <b>{term}</b>',
    count         : '{count} selected',
    maxSelections : 'Max {maxCount} selections',
    noResults     : 'No results found.',
    serverError   : 'There was an error contacting the server'
  },

  error : {
    action          : 'You called a dropdown action that was not defined',
    alreadySetup    : 'Once a select has been initialized behaviors must be called on the created ui dropdown',
    labels          : 'Allowing user additions currently requires the use of labels.',
    missingMultiple : '<select> requires multiple property to be set to correctly preserve multiple values',
    method          : 'The method you called is not defined.',
    noAPI           : 'The API module is required to load resources remotely',
    noStorage       : 'Saving remote data requires session storage',
    noTransition    : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>'
  },

  regExp : {
    escape   : /[-[\]{}()*+?.,\\^$|#\s]/g,
    quote    : /"/g
  },

  metadata : {
    defaultText     : 'defaultText',
    defaultValue    : 'defaultValue',
    placeholderText : 'placeholder',
    text            : 'text',
    value           : 'value'
  },

  // property names for remote query
  fields: {
    remoteValues : 'results',  // grouping for api results
    values       : 'values',   // grouping for all dropdown values
    disabled     : 'disabled', // whether value should be disabled
    name         : 'name',     // displayed dropdown text
    value        : 'value',    // actual dropdown value
    text         : 'text'      // displayed text when selected
  },

  keys : {
    backspace  : 8,
    delimiter  : 188, // comma
    deleteKey  : 46,
    enter      : 13,
    escape     : 27,
    pageUp     : 33,
    pageDown   : 34,
    leftArrow  : 37,
    upArrow    : 38,
    rightArrow : 39,
    downArrow  : 40
  },

  selector : {
    addition     : '.addition',
    dropdown     : '.ui.dropdown',
    hidden       : '.hidden',
    icon         : '> .dropdown.icon',
    input        : '> input[type="hidden"], > select',
    item         : '.item',
    label        : '> .label',
    remove       : '> .label > .delete.icon',
    siblingLabel : '.label',
    menu         : '.menu',
    message      : '.message',
    menuIcon     : '.dropdown.icon',
    search       : 'input.search, .menu > .search > input, .menu input.search',
    sizer        : '> input.sizer',
    text         : '> .text:not(.icon)',
    unselectable : '.disabled, .filtered'
  },

  className : {
    active      : 'active',
    addition    : 'addition',
    animating   : 'animating',
    disabled    : 'disabled',
    empty       : 'empty',
    dropdown    : 'ui dropdown',
    filtered    : 'filtered',
    hidden      : 'hidden transition',
    item        : 'item',
    label       : 'ui label',
    loading     : 'loading',
    menu        : 'menu',
    message     : 'message',
    multiple    : 'multiple',
    placeholder : 'default',
    sizer       : 'sizer',
    search      : 'search',
    selected    : 'selected',
    selection   : 'selection',
    upward      : 'upward',
    leftward    : 'left',
    visible     : 'visible'
  }

};

/* Templates */
$.fn.dropdown.settings.templates = {

  // generates dropdown from select values
  dropdown: function(select) {
    var
      placeholder = select.placeholder || false,
      values      = select.values || {},
      html        = ''
    ;
    html +=  '<i class="dropdown icon"></i>';
    if(select.placeholder) {
      html += '<div class="default text">' + placeholder + '</div>';
    }
    else {
      html += '<div class="text"></div>';
    }
    html += '<div class="menu">';
    $.each(select.values, function(index, option) {
      html += (option.disabled)
        ? '<div class="disabled item" data-value="' + option.value + '">' + option.name + '</div>'
        : '<div class="item" data-value="' + option.value + '">' + option.name + '</div>'
      ;
    });
    html += '</div>';
    return html;
  },

  // generates just menu from select
  menu: function(response, fields) {
    var
      values = response[fields.values] || {},
      html   = ''
    ;
    $.each(values, function(index, option) {
      var
        maybeText = (option[fields.text])
          ? 'data-text="' + option[fields.text] + '"'
          : '',
        maybeDisabled = (option[fields.disabled])
          ? 'disabled '
          : ''
      ;
      html += '<div class="'+ maybeDisabled +'item" data-value="' + option[fields.value] + '"' + maybeText + '>'
      html +=   option[fields.name];
      html += '</div>';
    });
    return html;
  },

  // generates label for multiselect
  label: function(value, text) {
    return text + '<i class="delete icon"></i>';
  },


  // generates messages like "No results"
  message: function(message) {
    return message;
  },

  // generates user addition to selection menu
  addition: function(choice) {
    return choice;
  }

};

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Embed
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.embed = function(parameters) {

  var
    $allModules     = $(this),

    moduleSelector  = $allModules.selector || '',

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.embed.settings, parameters)
          : $.extend({}, $.fn.embed.settings),

        selector        = settings.selector,
        className       = settings.className,
        sources         = settings.sources,
        error           = settings.error,
        metadata        = settings.metadata,
        namespace       = settings.namespace,
        templates       = settings.templates,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $window         = $(window),
        $module         = $(this),
        $placeholder    = $module.find(selector.placeholder),
        $icon           = $module.find(selector.icon),
        $embed          = $module.find(selector.embed),

        element         = this,
        instance        = $module.data(moduleNamespace),
        module
      ;

      module = {

        initialize: function() {
          module.debug('Initializing embed');
          module.determine.autoplay();
          module.create();
          module.bind.events();
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous instance of embed');
          module.reset();
          $module
            .removeData(moduleNamespace)
            .off(eventNamespace)
          ;
        },

        refresh: function() {
          module.verbose('Refreshing selector cache');
          $placeholder = $module.find(selector.placeholder);
          $icon        = $module.find(selector.icon);
          $embed       = $module.find(selector.embed);
        },

        bind: {
          events: function() {
            if( module.has.placeholder() ) {
              module.debug('Adding placeholder events');
              $module
                .on('click' + eventNamespace, selector.placeholder, module.createAndShow)
                .on('click' + eventNamespace, selector.icon, module.createAndShow)
              ;
            }
          }
        },

        create: function() {
          var
            placeholder = module.get.placeholder()
          ;
          if(placeholder) {
            module.createPlaceholder();
          }
          else {
            module.createAndShow();
          }
        },

        createPlaceholder: function(placeholder) {
          var
            icon  = module.get.icon(),
            url   = module.get.url(),
            embed = module.generate.embed(url)
          ;
          placeholder = placeholder || module.get.placeholder();
          $module.html( templates.placeholder(placeholder, icon) );
          module.debug('Creating placeholder for embed', placeholder, icon);
        },

        createEmbed: function(url) {
          module.refresh();
          url = url || module.get.url();
          $embed = $('<div/>')
            .addClass(className.embed)
            .html( module.generate.embed(url) )
            .appendTo($module)
          ;
          settings.onCreate.call(element, url);
          module.debug('Creating embed object', $embed);
        },

        changeEmbed: function(url) {
          $embed
            .html( module.generate.embed(url) )
          ;
        },

        createAndShow: function() {
          module.createEmbed();
          module.show();
        },

        // sets new embed
        change: function(source, id, url) {
          module.debug('Changing video to ', source, id, url);
          $module
            .data(metadata.source, source)
            .data(metadata.id, id)
          ;
          if(url) {
            $module.data(metadata.url, url);
          }
          else {
            $module.removeData(metadata.url);
          }
          if(module.has.embed()) {
            module.changeEmbed();
          }
          else {
            module.create();
          }
        },

        // clears embed
        reset: function() {
          module.debug('Clearing embed and showing placeholder');
          module.remove.active();
          module.remove.embed();
          module.showPlaceholder();
          settings.onReset.call(element);
        },

        // shows current embed
        show: function() {
          module.debug('Showing embed');
          module.set.active();
          settings.onDisplay.call(element);
        },

        hide: function() {
          module.debug('Hiding embed');
          module.showPlaceholder();
        },

        showPlaceholder: function() {
          module.debug('Showing placeholder image');
          module.remove.active();
          settings.onPlaceholderDisplay.call(element);
        },

        get: {
          id: function() {
            return settings.id || $module.data(metadata.id);
          },
          placeholder: function() {
            return settings.placeholder || $module.data(metadata.placeholder);
          },
          icon: function() {
            return (settings.icon)
              ? settings.icon
              : ($module.data(metadata.icon) !== undefined)
                ? $module.data(metadata.icon)
                : module.determine.icon()
            ;
          },
          source: function(url) {
            return (settings.source)
              ? settings.source
              : ($module.data(metadata.source) !== undefined)
                ? $module.data(metadata.source)
                : module.determine.source()
            ;
          },
          type: function() {
            var source = module.get.source();
            return (sources[source] !== undefined)
              ? sources[source].type
              : false
            ;
          },
          url: function() {
            return (settings.url)
              ? settings.url
              : ($module.data(metadata.url) !== undefined)
                ? $module.data(metadata.url)
                : module.determine.url()
            ;
          }
        },

        determine: {
          autoplay: function() {
            if(module.should.autoplay()) {
              settings.autoplay = true;
            }
          },
          source: function(url) {
            var
              matchedSource = false
            ;
            url = url || module.get.url();
            if(url) {
              $.each(sources, function(name, source) {
                if(url.search(source.domain) !== -1) {
                  matchedSource = name;
                  return false;
                }
              });
            }
            return matchedSource;
          },
          icon: function() {
            var
              source = module.get.source()
            ;
            return (sources[source] !== undefined)
              ? sources[source].icon
              : false
            ;
          },
          url: function() {
            var
              id     = settings.id     || $module.data(metadata.id),
              source = settings.source || $module.data(metadata.source),
              url
            ;
            url = (sources[source] !== undefined)
              ? sources[source].url.replace('{id}', id)
              : false
            ;
            if(url) {
              $module.data(metadata.url, url);
            }
            return url;
          }
        },


        set: {
          active: function() {
            $module.addClass(className.active);
          }
        },

        remove: {
          active: function() {
            $module.removeClass(className.active);
          },
          embed: function() {
            $embed.empty();
          }
        },

        encode: {
          parameters: function(parameters) {
            var
              urlString = [],
              index
            ;
            for (index in parameters) {
              urlString.push( encodeURIComponent(index) + '=' + encodeURIComponent( parameters[index] ) );
            }
            return urlString.join('&amp;');
          }
        },

        generate: {
          embed: function(url) {
            module.debug('Generating embed html');
            var
              source = module.get.source(),
              html,
              parameters
            ;
            url = module.get.url(url);
            if(url) {
              parameters = module.generate.parameters(source);
              html       = templates.iframe(url, parameters);
            }
            else {
              module.error(error.noURL, $module);
            }
            return html;
          },
          parameters: function(source, extraParameters) {
            var
              parameters = (sources[source] && sources[source].parameters !== undefined)
                ? sources[source].parameters(settings)
                : {}
            ;
            extraParameters = extraParameters || settings.parameters;
            if(extraParameters) {
              parameters = $.extend({}, parameters, extraParameters);
            }
            parameters = settings.onEmbed(parameters);
            return module.encode.parameters(parameters);
          }
        },

        has: {
          embed: function() {
            return ($embed.length > 0);
          },
          placeholder: function() {
            return settings.placeholder || $module.data(metadata.placeholder);
          }
        },

        should: {
          autoplay: function() {
            return (settings.autoplay === 'auto')
              ? (settings.placeholder || $module.data(metadata.placeholder) !== undefined)
              : settings.autoplay
            ;
          }
        },

        is: {
          video: function() {
            return module.get.type() == 'video';
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.length > 1) {
              title += ' ' + '(' + $allModules.length + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;
  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.embed.settings = {

  name        : 'Embed',
  namespace   : 'embed',

  silent      : false,
  debug       : false,
  verbose     : false,
  performance : true,

  icon     : false,
  source   : false,
  url      : false,
  id       : false,

  // standard video settings
  autoplay  : 'auto',
  color     : '#444444',
  hd        : true,
  brandedUI : false,

  // additional parameters to include with the embed
  parameters: false,

  onDisplay            : function() {},
  onPlaceholderDisplay : function() {},
  onReset              : function() {},
  onCreate             : function(url) {},
  onEmbed              : function(parameters) {
    return parameters;
  },

  metadata    : {
    id          : 'id',
    icon        : 'icon',
    placeholder : 'placeholder',
    source      : 'source',
    url         : 'url'
  },

  error : {
    noURL  : 'No URL specified',
    method : 'The method you called is not defined'
  },

  className : {
    active : 'active',
    embed  : 'embed'
  },

  selector : {
    embed       : '.embed',
    placeholder : '.placeholder',
    icon        : '.icon'
  },

  sources: {
    youtube: {
      name   : 'youtube',
      type   : 'video',
      icon   : 'video play',
      domain : 'youtube.com',
      url    : '//www.youtube.com/embed/{id}',
      parameters: function(settings) {
        return {
          autohide       : !settings.brandedUI,
          autoplay       : settings.autoplay,
          color          : settings.color || undefined,
          hq             : settings.hd,
          jsapi          : settings.api,
          modestbranding : !settings.brandedUI
        };
      }
    },
    vimeo: {
      name   : 'vimeo',
      type   : 'video',
      icon   : 'video play',
      domain : 'vimeo.com',
      url    : '//player.vimeo.com/video/{id}',
      parameters: function(settings) {
        return {
          api      : settings.api,
          autoplay : settings.autoplay,
          byline   : settings.brandedUI,
          color    : settings.color || undefined,
          portrait : settings.brandedUI,
          title    : settings.brandedUI
        };
      }
    }
  },

  templates: {
    iframe : function(url, parameters) {
      var src = url;
      if (parameters) {
          src += '?' + parameters;
      }
      return ''
        + '<iframe src="' + src + '"'
        + ' width="100%" height="100%"'
        + ' frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
      ;
    },
    placeholder : function(image, icon) {
      var
        html = ''
      ;
      if(icon) {
        html += '<i class="' + icon + ' icon"></i>';
      }
      if(image) {
        html += '<img class="placeholder" src="' + image + '">';
      }
      return html;
    }
  },

  // NOT YET IMPLEMENTED
  api     : false,
  onPause : function() {},
  onPlay  : function() {},
  onStop  : function() {}

};



})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Modal
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.modal = function(parameters) {
  var
    $allModules    = $(this),
    $window        = $(window),
    $document      = $(document),
    $body          = $('body'),

    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),

    requestAnimationFrame = window.requestAnimationFrame
      || window.mozRequestAnimationFrame
      || window.webkitRequestAnimationFrame
      || window.msRequestAnimationFrame
      || function(callback) { setTimeout(callback, 0); },

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings    = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.modal.settings, parameters)
          : $.extend({}, $.fn.modal.settings),

        selector        = settings.selector,
        className       = settings.className,
        namespace       = settings.namespace,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $context        = $(settings.context),
        $close          = $module.find(selector.close),

        $allModals,
        $otherModals,
        $focusedElement,
        $dimmable,
        $dimmer,

        element         = this,
        instance        = $module.data(moduleNamespace),

        ignoreRepeatedEvents = false,

        elementEventNamespace,
        id,
        observer,
        module
      ;
      module  = {

        initialize: function() {
          module.verbose('Initializing dimmer', $context);

          module.create.id();
          module.create.dimmer();
          module.refreshModals();

          module.bind.events();
          if(settings.observeChanges) {
            module.observeChanges();
          }
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of modal');
          instance = module;
          $module
            .data(moduleNamespace, instance)
          ;
        },

        create: {
          dimmer: function() {
            var
              defaultSettings = {
                debug      : settings.debug,
                dimmerName : 'modals'
              },
              dimmerSettings = $.extend(true, defaultSettings, settings.dimmerSettings)
            ;
            if($.fn.dimmer === undefined) {
              module.error(error.dimmer);
              return;
            }
            module.debug('Creating dimmer');
            $dimmable = $context.dimmer(dimmerSettings);
            if(settings.detachable) {
              module.verbose('Modal is detachable, moving content into dimmer');
              $dimmable.dimmer('add content', $module);
            }
            else {
              module.set.undetached();
            }
            $dimmer = $dimmable.dimmer('get dimmer');
          },
          id: function() {
            id = (Math.random().toString(16) + '000000000').substr(2,8);
            elementEventNamespace = '.' + id;
            module.verbose('Creating unique id for element', id);
          }
        },

        destroy: function() {
          module.verbose('Destroying previous modal');
          $module
            .removeData(moduleNamespace)
            .off(eventNamespace)
          ;
          $window.off(elementEventNamespace);
          $dimmer.off(elementEventNamespace);
          $close.off(eventNamespace);
          $context.dimmer('destroy');
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            observer = new MutationObserver(function(mutations) {
              module.debug('DOM tree modified, refreshing');
              module.refresh();
            });
            observer.observe(element, {
              childList : true,
              subtree   : true
            });
            module.debug('Setting up mutation observer', observer);
          }
        },

        refresh: function() {
          module.remove.scrolling();
          module.cacheSizes();
          module.set.screenHeight();
          module.set.type();
          module.set.position();
        },

        refreshModals: function() {
          $otherModals = $module.siblings(selector.modal);
          $allModals   = $otherModals.add($module);
        },

        attachEvents: function(selector, event) {
          var
            $toggle = $(selector)
          ;
          event = $.isFunction(module[event])
            ? module[event]
            : module.toggle
          ;
          if($toggle.length > 0) {
            module.debug('Attaching modal events to element', selector, event);
            $toggle
              .off(eventNamespace)
              .on('click' + eventNamespace, event)
            ;
          }
          else {
            module.error(error.notFound, selector);
          }
        },

        bind: {
          events: function() {
            module.verbose('Attaching events');
            $module
              .on('click' + eventNamespace, selector.close, module.event.close)
              .on('click' + eventNamespace, selector.approve, module.event.approve)
              .on('click' + eventNamespace, selector.deny, module.event.deny)
            ;
            $window
              .on('resize' + elementEventNamespace, module.event.resize)
            ;
          }
        },

        get: {
          id: function() {
            return (Math.random().toString(16) + '000000000').substr(2,8);
          }
        },

        event: {
          approve: function() {
            if(ignoreRepeatedEvents || settings.onApprove.call(element, $(this)) === false) {
              module.verbose('Approve callback returned false cancelling hide');
              return;
            }
            ignoreRepeatedEvents = true;
            module.hide(function() {
              ignoreRepeatedEvents = false;
            });
          },
          deny: function() {
            if(ignoreRepeatedEvents || settings.onDeny.call(element, $(this)) === false) {
              module.verbose('Deny callback returned false cancelling hide');
              return;
            }
            ignoreRepeatedEvents = true;
            module.hide(function() {
              ignoreRepeatedEvents = false;
            });
          },
          close: function() {
            module.hide();
          },
          click: function(event) {
            var
              $target   = $(event.target),
              isInModal = ($target.closest(selector.modal).length > 0),
              isInDOM   = $.contains(document.documentElement, event.target)
            ;
            if(!isInModal && isInDOM) {
              module.debug('Dimmer clicked, hiding all modals');
              if( module.is.active() ) {
                module.remove.clickaway();
                if(settings.allowMultiple) {
                  module.hide();
                }
                else {
                  module.hideAll();
                }
              }
            }
          },
          debounce: function(method, delay) {
            clearTimeout(module.timer);
            module.timer = setTimeout(method, delay);
          },
          keyboard: function(event) {
            var
              keyCode   = event.which,
              escapeKey = 27
            ;
            if(keyCode == escapeKey) {
              if(settings.closable) {
                module.debug('Escape key pressed hiding modal');
                module.hide();
              }
              else {
                module.debug('Escape key pressed, but closable is set to false');
              }
              event.preventDefault();
            }
          },
          resize: function() {
            if( $dimmable.dimmer('is active') && ( module.is.animating() || module.is.active() ) ) {
              requestAnimationFrame(module.refresh);
            }
          }
        },

        toggle: function() {
          if( module.is.active() || module.is.animating() ) {
            module.hide();
          }
          else {
            module.show();
          }
        },

        show: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          module.refreshModals();
          module.set.dimmerSettings();
          module.showModal(callback);
        },

        hide: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          module.refreshModals();
          module.hideModal(callback);
        },

        showModal: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if( module.is.animating() || !module.is.active() ) {

            module.showDimmer();
            module.cacheSizes();
            module.set.position();
            module.set.screenHeight();
            module.set.type();
            module.set.clickaway();

            if( !settings.allowMultiple && module.others.active() ) {
              module.hideOthers(module.showModal);
            }
            else {
              if(settings.allowMultiple && settings.detachable) {
                $module.detach().appendTo($dimmer);
              }
              settings.onShow.call(element);
              if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
                module.debug('Showing modal with css animations');
                $module
                  .transition({
                    debug       : settings.debug,
                    animation   : settings.transition + ' in',
                    queue       : settings.queue,
                    duration    : settings.duration,
                    useFailSafe : true,
                    onComplete : function() {
                      settings.onVisible.apply(element);
                      if(settings.keyboardShortcuts) {
                        module.add.keyboardShortcuts();
                      }
                      module.save.focus();
                      module.set.active();
                      if(settings.autofocus) {
                        module.set.autofocus();
                      }
                      callback();
                    }
                  })
                ;
              }
              else {
                module.error(error.noTransition);
              }
            }
          }
          else {
            module.debug('Modal is already visible');
          }
        },

        hideModal: function(callback, keepDimmed) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          module.debug('Hiding modal');
          if(settings.onHide.call(element, $(this)) === false) {
            module.verbose('Hide callback returned false cancelling hide');
            return;
          }

          if( module.is.animating() || module.is.active() ) {
            if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
              module.remove.active();
              $module
                .transition({
                  debug       : settings.debug,
                  animation   : settings.transition + ' out',
                  queue       : settings.queue,
                  duration    : settings.duration,
                  useFailSafe : true,
                  onStart     : function() {
                    if(!module.others.active() && !keepDimmed) {
                      module.hideDimmer();
                    }
                    if(settings.keyboardShortcuts) {
                      module.remove.keyboardShortcuts();
                    }
                  },
                  onComplete : function() {
                    settings.onHidden.call(element);
                    module.restore.focus();
                    callback();
                  }
                })
              ;
            }
            else {
              module.error(error.noTransition);
            }
          }
        },

        showDimmer: function() {
          if($dimmable.dimmer('is animating') || !$dimmable.dimmer('is active') ) {
            module.debug('Showing dimmer');
            $dimmable.dimmer('show');
          }
          else {
            module.debug('Dimmer already visible');
          }
        },

        hideDimmer: function() {
          if( $dimmable.dimmer('is animating') || ($dimmable.dimmer('is active')) ) {
            $dimmable.dimmer('hide', function() {
              module.remove.clickaway();
              module.remove.screenHeight();
            });
          }
          else {
            module.debug('Dimmer is not visible cannot hide');
            return;
          }
        },

        hideAll: function(callback) {
          var
            $visibleModals = $allModals.filter('.' + className.active + ', .' + className.animating)
          ;
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if( $visibleModals.length > 0 ) {
            module.debug('Hiding all visible modals');
            module.hideDimmer();
            $visibleModals
              .modal('hide modal', callback)
            ;
          }
        },

        hideOthers: function(callback) {
          var
            $visibleModals = $otherModals.filter('.' + className.active + ', .' + className.animating)
          ;
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if( $visibleModals.length > 0 ) {
            module.debug('Hiding other modals', $otherModals);
            $visibleModals
              .modal('hide modal', callback, true)
            ;
          }
        },

        others: {
          active: function() {
            return ($otherModals.filter('.' + className.active).length > 0);
          },
          animating: function() {
            return ($otherModals.filter('.' + className.animating).length > 0);
          }
        },


        add: {
          keyboardShortcuts: function() {
            module.verbose('Adding keyboard shortcuts');
            $document
              .on('keyup' + eventNamespace, module.event.keyboard)
            ;
          }
        },

        save: {
          focus: function() {
            $focusedElement = $(document.activeElement).blur();
          }
        },

        restore: {
          focus: function() {
            if($focusedElement && $focusedElement.length > 0) {
              $focusedElement.focus();
            }
          }
        },

        remove: {
          active: function() {
            $module.removeClass(className.active);
          },
          clickaway: function() {
            if(settings.closable) {
              $dimmer
                .off('click' + elementEventNamespace)
              ;
            }
          },
          bodyStyle: function() {
            if($body.attr('style') === '') {
              module.verbose('Removing style attribute');
              $body.removeAttr('style');
            }
          },
          screenHeight: function() {
            module.debug('Removing page height');
            $body
              .css('height', '')
            ;
          },
          keyboardShortcuts: function() {
            module.verbose('Removing keyboard shortcuts');
            $document
              .off('keyup' + eventNamespace)
            ;
          },
          scrolling: function() {
            $dimmable.removeClass(className.scrolling);
            $module.removeClass(className.scrolling);
          }
        },

        cacheSizes: function() {
          $module.addClass(className.loading);
          var
            scrollHeight = $module.prop('scrollHeight'),
            modalHeight  = $module.outerHeight()
          ;
          if(module.cache === undefined || modalHeight !== 0) {
            module.cache = {
              pageHeight    : $(document).outerHeight(),
              height        : modalHeight + settings.offset,
              scrollHeight  : scrollHeight + settings.offset,
              contextHeight : (settings.context == 'body')
                ? $(window).height()
                : $dimmable.height(),
            };
            module.cache.topOffset = -(module.cache.height / 2);
          }
          $module.removeClass(className.loading);
          module.debug('Caching modal and container sizes', module.cache);
        },

        can: {
          fit: function() {
            var
              contextHeight  = module.cache.contextHeight,
              verticalCenter = module.cache.contextHeight / 2,
              topOffset      = module.cache.topOffset,
              scrollHeight   = module.cache.scrollHeight,
              height         = module.cache.height,
              paddingHeight  = settings.padding,
              startPosition  = (verticalCenter + topOffset)
            ;
            return (scrollHeight > height)
              ? (startPosition + scrollHeight + paddingHeight < contextHeight)
              : (height + (paddingHeight * 2) < contextHeight)
            ;
          }
        },

        is: {
          active: function() {
            return $module.hasClass(className.active);
          },
          animating: function() {
            return $module.transition('is supported')
              ? $module.transition('is animating')
              : $module.is(':visible')
            ;
          },
          scrolling: function() {
            return $dimmable.hasClass(className.scrolling);
          },
          modernBrowser: function() {
            // appName for IE11 reports 'Netscape' can no longer use
            return !(window.ActiveXObject || "ActiveXObject" in window);
          }
        },

        set: {
          autofocus: function() {
            var
              $inputs    = $module.find('[tabindex], :input').filter(':visible'),
              $autofocus = $inputs.filter('[autofocus]'),
              $input     = ($autofocus.length > 0)
                ? $autofocus.first()
                : $inputs.first()
            ;
            if($input.length > 0) {
              $input.focus();
            }
          },
          clickaway: function() {
            if(settings.closable) {
              $dimmer
                .on('click' + elementEventNamespace, module.event.click)
              ;
            }
          },
          dimmerSettings: function() {
            if($.fn.dimmer === undefined) {
              module.error(error.dimmer);
              return;
            }
            var
              defaultSettings = {
                debug      : settings.debug,
                dimmerName : 'modals',
                variation  : false,
                closable   : 'auto',
                duration   : {
                  show     : settings.duration,
                  hide     : settings.duration
                }
              },
              dimmerSettings = $.extend(true, defaultSettings, settings.dimmerSettings)
            ;
            if(settings.inverted) {
              dimmerSettings.variation = (dimmerSettings.variation !== undefined)
                ? dimmerSettings.variation + ' inverted'
                : 'inverted'
              ;
              $dimmer.addClass(className.inverted);
            }
            else {
              $dimmer.removeClass(className.inverted);
            }
            if(settings.blurring) {
              $dimmable.addClass(className.blurring);
            }
            else {
              $dimmable.removeClass(className.blurring);
            }
            $context.dimmer('setting', dimmerSettings);
          },
          screenHeight: function() {
            if( module.can.fit() ) {
              $body.css('height', '');
            }
            else {
              module.debug('Modal is taller than page content, resizing page height');
              $body
                .css('height', module.cache.height + (settings.padding * 2) )
              ;
            }
          },
          active: function() {
            $module.addClass(className.active);
          },
          scrolling: function() {
            $dimmable.addClass(className.scrolling);
            $module.addClass(className.scrolling);
          },
          type: function() {
            if(module.can.fit()) {
              module.verbose('Modal fits on screen');
              if(!module.others.active() && !module.others.animating()) {
                module.remove.scrolling();
              }
            }
            else {
              module.verbose('Modal cannot fit on screen setting to scrolling');
              module.set.scrolling();
            }
          },
          position: function() {
            module.verbose('Centering modal on page', module.cache);
            if(module.can.fit()) {
              $module
                .css({
                  top: '',
                  marginTop: module.cache.topOffset
                })
              ;
            }
            else {
              $module
                .css({
                  marginTop : '',
                  top       : $document.scrollTop()
                })
              ;
            }
          },
          undetached: function() {
            $dimmable.addClass(className.undetached);
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.modal.settings = {

  name           : 'Modal',
  namespace      : 'modal',

  silent         : false,
  debug          : false,
  verbose        : false,
  performance    : true,

  observeChanges : false,

  allowMultiple  : false,
  detachable     : true,
  closable       : true,
  autofocus      : true,

  inverted       : false,
  blurring       : false,

  dimmerSettings : {
    closable : false,
    useCSS   : true
  },

  // whether to use keyboard shortcuts
  keyboardShortcuts: true,

  context    : 'body',

  queue      : false,
  duration   : 500,
  offset     : 0,
  transition : 'scale',

  // padding with edge of page
  padding    : 50,

  // called before show animation
  onShow     : function(){},

  // called after show animation
  onVisible  : function(){},

  // called before hide animation
  onHide     : function(){ return true; },

  // called after hide animation
  onHidden   : function(){},

  // called after approve selector match
  onApprove  : function(){ return true; },

  // called after deny selector match
  onDeny     : function(){ return true; },

  selector    : {
    close    : '> .close',
    approve  : '.actions .positive, .actions .approve, .actions .ok',
    deny     : '.actions .negative, .actions .deny, .actions .cancel',
    modal    : '.ui.modal'
  },
  error : {
    dimmer    : 'UI Dimmer, a required component is not included in this page',
    method    : 'The method you called is not defined.',
    notFound  : 'The element you specified could not be found'
  },
  className : {
    active     : 'active',
    animating  : 'animating',
    blurring   : 'blurring',
    inverted   : 'inverted',
    loading    : 'loading',
    scrolling  : 'scrolling',
    undetached : 'undetached'
  }
};


})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Nag
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.nag = function(parameters) {
  var
    $allModules    = $(this),
    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),
    returnedValue
  ;
  $allModules
    .each(function() {
      var
        settings          = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.nag.settings, parameters)
          : $.extend({}, $.fn.nag.settings),

        className       = settings.className,
        selector        = settings.selector,
        error           = settings.error,
        namespace       = settings.namespace,

        eventNamespace  = '.' + namespace,
        moduleNamespace = namespace + '-module',

        $module         = $(this),

        $close          = $module.find(selector.close),
        $context        = (settings.context)
          ? $(settings.context)
          : $('body'),

        element         = this,
        instance        = $module.data(moduleNamespace),

        moduleOffset,
        moduleHeight,

        contextWidth,
        contextHeight,
        contextOffset,

        yOffset,
        yPosition,

        timer,
        module,

        requestAnimationFrame = window.requestAnimationFrame
          || window.mozRequestAnimationFrame
          || window.webkitRequestAnimationFrame
          || window.msRequestAnimationFrame
          || function(callback) { setTimeout(callback, 0); }
      ;
      module = {

        initialize: function() {
          module.verbose('Initializing element');

          $module
            .on('click' + eventNamespace, selector.close, module.dismiss)
            .data(moduleNamespace, module)
          ;

          if(settings.detachable && $module.parent()[0] !== $context[0]) {
            $module
              .detach()
              .prependTo($context)
            ;
          }

          if(settings.displayTime > 0) {
            setTimeout(module.hide, settings.displayTime);
          }
          module.show();
        },

        destroy: function() {
          module.verbose('Destroying instance');
          $module
            .removeData(moduleNamespace)
            .off(eventNamespace)
          ;
        },

        show: function() {
          if( module.should.show() && !$module.is(':visible') ) {
            module.debug('Showing nag', settings.animation.show);
            if(settings.animation.show == 'fade') {
              $module
                .fadeIn(settings.duration, settings.easing)
              ;
            }
            else {
              $module
                .slideDown(settings.duration, settings.easing)
              ;
            }
          }
        },

        hide: function() {
          module.debug('Showing nag', settings.animation.hide);
          if(settings.animation.show == 'fade') {
            $module
              .fadeIn(settings.duration, settings.easing)
            ;
          }
          else {
            $module
              .slideUp(settings.duration, settings.easing)
            ;
          }
        },

        onHide: function() {
          module.debug('Removing nag', settings.animation.hide);
          $module.remove();
          if (settings.onHide) {
            settings.onHide();
          }
        },

        dismiss: function(event) {
          if(settings.storageMethod) {
            module.storage.set(settings.key, settings.value);
          }
          module.hide();
          event.stopImmediatePropagation();
          event.preventDefault();
        },

        should: {
          show: function() {
            if(settings.persist) {
              module.debug('Persistent nag is set, can show nag');
              return true;
            }
            if( module.storage.get(settings.key) != settings.value.toString() ) {
              module.debug('Stored value is not set, can show nag', module.storage.get(settings.key));
              return true;
            }
            module.debug('Stored value is set, cannot show nag', module.storage.get(settings.key));
            return false;
          }
        },

        get: {
          storageOptions: function() {
            var
              options = {}
            ;
            if(settings.expires) {
              options.expires = settings.expires;
            }
            if(settings.domain) {
              options.domain = settings.domain;
            }
            if(settings.path) {
              options.path = settings.path;
            }
            return options;
          }
        },

        clear: function() {
          module.storage.remove(settings.key);
        },

        storage: {
          set: function(key, value) {
            var
              options = module.get.storageOptions()
            ;
            if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) {
              window.localStorage.setItem(key, value);
              module.debug('Value stored using local storage', key, value);
            }
            else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) {
              window.sessionStorage.setItem(key, value);
              module.debug('Value stored using session storage', key, value);
            }
            else if($.cookie !== undefined) {
              $.cookie(key, value, options);
              module.debug('Value stored using cookie', key, value, options);
            }
            else {
              module.error(error.noCookieStorage);
              return;
            }
          },
          get: function(key, value) {
            var
              storedValue
            ;
            if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) {
              storedValue = window.localStorage.getItem(key);
            }
            else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) {
              storedValue = window.sessionStorage.getItem(key);
            }
            // get by cookie
            else if($.cookie !== undefined) {
              storedValue = $.cookie(key);
            }
            else {
              module.error(error.noCookieStorage);
            }
            if(storedValue == 'undefined' || storedValue == 'null' || storedValue === undefined || storedValue === null) {
              storedValue = undefined;
            }
            return storedValue;
          },
          remove: function(key) {
            var
              options = module.get.storageOptions()
            ;
            if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) {
              window.localStorage.removeItem(key);
            }
            else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) {
              window.sessionStorage.removeItem(key);
            }
            // store by cookie
            else if($.cookie !== undefined) {
              $.removeCookie(key, options);
            }
            else {
              module.error(error.noStorage);
            }
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.nag.settings = {

  name        : 'Nag',

  silent      : false,
  debug       : false,
  verbose     : false,
  performance : true,

  namespace   : 'Nag',

  // allows cookie to be overridden
  persist     : false,

  // set to zero to require manually dismissal, otherwise hides on its own
  displayTime : 0,

  animation   : {
    show : 'slide',
    hide : 'slide'
  },

  context       : false,
  detachable    : false,

  expires       : 30,
  domain        : false,
  path          : '/',

  // type of storage to use
  storageMethod : 'cookie',

  // value to store in dismissed localstorage/cookie
  key           : 'nag',
  value         : 'dismiss',

  error: {
    noCookieStorage : '$.cookie is not included. A storage solution is required.',
    noStorage       : 'Neither $.cookie or store is defined. A storage solution is required for storing state',
    method          : 'The method you called is not defined.'
  },

  className     : {
    bottom : 'bottom',
    fixed  : 'fixed'
  },

  selector      : {
    close : '.close.icon'
  },

  speed         : 500,
  easing        : 'easeOutQuad',

  onHide: function() {}

};

// Adds easing
$.extend( $.easing, {
  easeOutQuad: function (x, t, b, c, d) {
    return -c *(t/=d)*(t-2) + b;
  }
});

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Popup
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.popup = function(parameters) {
  var
    $allModules    = $(this),
    $document      = $(document),
    $window        = $(window),
    $body          = $('body'),

    moduleSelector = $allModules.selector || '',

    hasTouch       = (true),
    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),

    returnedValue
  ;
  $allModules
    .each(function() {
      var
        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.popup.settings, parameters)
          : $.extend({}, $.fn.popup.settings),

        selector           = settings.selector,
        className          = settings.className,
        error              = settings.error,
        metadata           = settings.metadata,
        namespace          = settings.namespace,

        eventNamespace     = '.' + settings.namespace,
        moduleNamespace    = 'module-' + namespace,

        $module            = $(this),
        $context           = $(settings.context),
        $scrollContext     = $(settings.scrollContext),
        $boundary          = $(settings.boundary),
        $target            = (settings.target)
          ? $(settings.target)
          : $module,

        $popup,
        $offsetParent,

        searchDepth        = 0,
        triedPositions     = false,
        openedWithTouch    = false,

        element            = this,
        instance           = $module.data(moduleNamespace),

        documentObserver,
        elementNamespace,
        id,
        module
      ;

      module = {

        // binds events
        initialize: function() {
          module.debug('Initializing', $module);
          module.createID();
          module.bind.events();
          if(!module.exists() && settings.preserve) {
            module.create();
          }
          if(settings.observeChanges) {
            module.observeChanges();
          }
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance', module);
          instance = module;
          $module
            .data(moduleNamespace, instance)
          ;
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            documentObserver = new MutationObserver(module.event.documentChanged);
            documentObserver.observe(document, {
              childList : true,
              subtree   : true
            });
            module.debug('Setting up mutation observer', documentObserver);
          }
        },

        refresh: function() {
          if(settings.popup) {
            $popup = $(settings.popup).eq(0);
          }
          else {
            if(settings.inline) {
              $popup = $target.nextAll(selector.popup).eq(0);
              settings.popup = $popup;
            }
          }
          if(settings.popup) {
            $popup.addClass(className.loading);
            $offsetParent = module.get.offsetParent();
            $popup.removeClass(className.loading);
            if(settings.movePopup && module.has.popup() && module.get.offsetParent($popup)[0] !== $offsetParent[0]) {
              module.debug('Moving popup to the same offset parent as target');
              $popup
                .detach()
                .appendTo($offsetParent)
              ;
            }
          }
          else {
            $offsetParent = (settings.inline)
              ? module.get.offsetParent($target)
              : module.has.popup()
                ? module.get.offsetParent($popup)
                : $body
            ;
          }
          if( $offsetParent.is('html') && $offsetParent[0] !== $body[0] ) {
            module.debug('Setting page as offset parent');
            $offsetParent = $body;
          }
          if( module.get.variation() ) {
            module.set.variation();
          }
        },

        reposition: function() {
          module.refresh();
          module.set.position();
        },

        destroy: function() {
          module.debug('Destroying previous module');
          if(documentObserver) {
            documentObserver.disconnect();
          }
          // remove element only if was created dynamically
          if($popup && !settings.preserve) {
            module.removePopup();
          }
          // clear all timeouts
          clearTimeout(module.hideTimer);
          clearTimeout(module.showTimer);
          // remove events
          module.unbind.close();
          module.unbind.events();
          $module
            .removeData(moduleNamespace)
          ;
        },

        event: {
          start:  function(event) {
            var
              delay = ($.isPlainObject(settings.delay))
                ? settings.delay.show
                : settings.delay
            ;
            clearTimeout(module.hideTimer);
            if(!openedWithTouch) {
              module.showTimer = setTimeout(module.show, delay);
            }
          },
          end:  function() {
            var
              delay = ($.isPlainObject(settings.delay))
                ? settings.delay.hide
                : settings.delay
            ;
            clearTimeout(module.showTimer);
            module.hideTimer = setTimeout(module.hide, delay);
          },
          touchstart: function(event) {
            openedWithTouch = true;
            module.show();
          },
          resize: function() {
            if( module.is.visible() ) {
              module.set.position();
            }
          },
          documentChanged: function(mutations) {
            [].forEach.call(mutations, function(mutation) {
              if(mutation.removedNodes) {
                [].forEach.call(mutation.removedNodes, function(node) {
                  if(node == element || $(node).find(element).length > 0) {
                    module.debug('Element removed from DOM, tearing down events');
                    module.destroy();
                  }
                });
              }
            });
          },
          hideGracefully: function(event) {
            var
              $target = $(event.target),
              isInDOM = $.contains(document.documentElement, event.target),
              inPopup = ($target.closest(selector.popup).length > 0)
            ;
            // don't close on clicks inside popup
            if(event && !inPopup && isInDOM) {
              module.debug('Click occurred outside popup hiding popup');
              module.hide();
            }
            else {
              module.debug('Click was inside popup, keeping popup open');
            }
          }
        },

        // generates popup html from metadata
        create: function() {
          var
            html      = module.get.html(),
            title     = module.get.title(),
            content   = module.get.content()
          ;

          if(html || content || title) {
            module.debug('Creating pop-up html');
            if(!html) {
              html = settings.templates.popup({
                title   : title,
                content : content
              });
            }
            $popup = $('<div/>')
              .addClass(className.popup)
              .data(metadata.activator, $module)
              .html(html)
            ;
            if(settings.inline) {
              module.verbose('Inserting popup element inline', $popup);
              $popup
                .insertAfter($module)
              ;
            }
            else {
              module.verbose('Appending popup element to body', $popup);
              $popup
                .appendTo( $context )
              ;
            }
            module.refresh();
            module.set.variation();

            if(settings.hoverable) {
              module.bind.popup();
            }
            settings.onCreate.call($popup, element);
          }
          else if($target.next(selector.popup).length !== 0) {
            module.verbose('Pre-existing popup found');
            settings.inline = true;
            settings.popup  = $target.next(selector.popup).data(metadata.activator, $module);
            module.refresh();
            if(settings.hoverable) {
              module.bind.popup();
            }
          }
          else if(settings.popup) {
            $(settings.popup).data(metadata.activator, $module);
            module.verbose('Used popup specified in settings');
            module.refresh();
            if(settings.hoverable) {
              module.bind.popup();
            }
          }
          else {
            module.debug('No content specified skipping display', element);
          }
        },

        createID: function() {
          id = (Math.random().toString(16) + '000000000').substr(2, 8);
          elementNamespace = '.' + id;
          module.verbose('Creating unique id for element', id);
        },

        // determines popup state
        toggle: function() {
          module.debug('Toggling pop-up');
          if( module.is.hidden() ) {
            module.debug('Popup is hidden, showing pop-up');
            module.unbind.close();
            module.show();
          }
          else {
            module.debug('Popup is visible, hiding pop-up');
            module.hide();
          }
        },

        show: function(callback) {
          callback = callback || function(){};
          module.debug('Showing pop-up', settings.transition);
          if(module.is.hidden() && !( module.is.active() && module.is.dropdown()) ) {
            if( !module.exists() ) {
              module.create();
            }
            if(settings.onShow.call($popup, element) === false) {
              module.debug('onShow callback returned false, cancelling popup animation');
              return;
            }
            else if(!settings.preserve && !settings.popup) {
              module.refresh();
            }
            if( $popup && module.set.position() ) {
              module.save.conditions();
              if(settings.exclusive) {
                module.hideAll();
              }
              module.animate.show(callback);
            }
          }
        },


        hide: function(callback) {
          callback = callback || function(){};
          if( module.is.visible() || module.is.animating() ) {
            if(settings.onHide.call($popup, element) === false) {
              module.debug('onHide callback returned false, cancelling popup animation');
              return;
            }
            module.remove.visible();
            module.unbind.close();
            module.restore.conditions();
            module.animate.hide(callback);
          }
        },

        hideAll: function() {
          $(selector.popup)
            .filter('.' + className.popupVisible)
            .each(function() {
              $(this)
                .data(metadata.activator)
                  .popup('hide')
              ;
            })
          ;
        },
        exists: function() {
          if(!$popup) {
            return false;
          }
          if(settings.inline || settings.popup) {
            return ( module.has.popup() );
          }
          else {
            return ( $popup.closest($context).length >= 1 )
              ? true
              : false
            ;
          }
        },

        removePopup: function() {
          if( module.has.popup() && !settings.popup) {
            module.debug('Removing popup', $popup);
            $popup.remove();
            $popup = undefined;
            settings.onRemove.call($popup, element);
          }
        },

        save: {
          conditions: function() {
            module.cache = {
              title: $module.attr('title')
            };
            if (module.cache.title) {
              $module.removeAttr('title');
            }
            module.verbose('Saving original attributes', module.cache.title);
          }
        },
        restore: {
          conditions: function() {
            if(module.cache && module.cache.title) {
              $module.attr('title', module.cache.title);
              module.verbose('Restoring original attributes', module.cache.title);
            }
            return true;
          }
        },
        supports: {
          svg: function() {
            return (typeof SVGGraphicsElement === 'undefined');
          }
        },
        animate: {
          show: function(callback) {
            callback = $.isFunction(callback) ? callback : function(){};
            if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
              module.set.visible();
              $popup
                .transition({
                  animation  : settings.transition + ' in',
                  queue      : false,
                  debug      : settings.debug,
                  verbose    : settings.verbose,
                  duration   : settings.duration,
                  onComplete : function() {
                    module.bind.close();
                    callback.call($popup, element);
                    settings.onVisible.call($popup, element);
                  }
                })
              ;
            }
            else {
              module.error(error.noTransition);
            }
          },
          hide: function(callback) {
            callback = $.isFunction(callback) ? callback : function(){};
            module.debug('Hiding pop-up');
            if(settings.onHide.call($popup, element) === false) {
              module.debug('onHide callback returned false, cancelling popup animation');
              return;
            }
            if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
              $popup
                .transition({
                  animation  : settings.transition + ' out',
                  queue      : false,
                  duration   : settings.duration,
                  debug      : settings.debug,
                  verbose    : settings.verbose,
                  onComplete : function() {
                    module.reset();
                    callback.call($popup, element);
                    settings.onHidden.call($popup, element);
                  }
                })
              ;
            }
            else {
              module.error(error.noTransition);
            }
          }
        },

        change: {
          content: function(html) {
            $popup.html(html);
          }
        },

        get: {
          html: function() {
            $module.removeData(metadata.html);
            return $module.data(metadata.html) || settings.html;
          },
          title: function() {
            $module.removeData(metadata.title);
            return $module.data(metadata.title) || settings.title;
          },
          content: function() {
            $module.removeData(metadata.content);
            return $module.data(metadata.content) || $module.attr('title') || settings.content;
          },
          variation: function() {
            $module.removeData(metadata.variation);
            return $module.data(metadata.variation) || settings.variation;
          },
          popup: function() {
            return $popup;
          },
          popupOffset: function() {
            return $popup.offset();
          },
          calculations: function() {
            var
              targetElement    = $target[0],
              isWindow         = ($boundary[0] == window),
              targetPosition   = (settings.inline || (settings.popup && settings.movePopup))
                ? $target.position()
                : $target.offset(),
              screenPosition = (isWindow)
                ? { top: 0, left: 0 }
                : $boundary.offset(),
              calculations   = {},
              scroll = (isWindow)
                ? { top: $window.scrollTop(), left: $window.scrollLeft() }
                : { top: 0, left: 0},
              screen
            ;
            calculations = {
              // element which is launching popup
              target : {
                element : $target[0],
                width   : $target.outerWidth(),
                height  : $target.outerHeight(),
                top     : targetPosition.top,
                left    : targetPosition.left,
                margin  : {}
              },
              // popup itself
              popup : {
                width  : $popup.outerWidth(),
                height : $popup.outerHeight()
              },
              // offset container (or 3d context)
              parent : {
                width  : $offsetParent.outerWidth(),
                height : $offsetParent.outerHeight()
              },
              // screen boundaries
              screen : {
                top  : screenPosition.top,
                left : screenPosition.left,
                scroll: {
                  top  : scroll.top,
                  left : scroll.left
                },
                width  : $boundary.width(),
                height : $boundary.height()
              }
            };

            // add in container calcs if fluid
            if( settings.setFluidWidth && module.is.fluid() ) {
              calculations.container = {
                width: $popup.parent().outerWidth()
              };
              calculations.popup.width = calculations.container.width;
            }

            // add in margins if inline
            calculations.target.margin.top = (settings.inline)
              ? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-top'), 10)
              : 0
            ;
            calculations.target.margin.left = (settings.inline)
              ? module.is.rtl()
                ? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-right'), 10)
                : parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-left'), 10)
              : 0
            ;
            // calculate screen boundaries
            screen = calculations.screen;
            calculations.boundary = {
              top    : screen.top + screen.scroll.top,
              bottom : screen.top + screen.scroll.top + screen.height,
              left   : screen.left + screen.scroll.left,
              right  : screen.left + screen.scroll.left + screen.width
            };
            return calculations;
          },
          id: function() {
            return id;
          },
          startEvent: function() {
            if(settings.on == 'hover') {
              return 'mouseenter';
            }
            else if(settings.on == 'focus') {
              return 'focus';
            }
            return false;
          },
          scrollEvent: function() {
            return 'scroll';
          },
          endEvent: function() {
            if(settings.on == 'hover') {
              return 'mouseleave';
            }
            else if(settings.on == 'focus') {
              return 'blur';
            }
            return false;
          },
          distanceFromBoundary: function(offset, calculations) {
            var
              distanceFromBoundary = {},
              popup,
              boundary
            ;
            calculations = calculations || module.get.calculations();

            // shorthand
            popup        = calculations.popup;
            boundary     = calculations.boundary;

            if(offset) {
              distanceFromBoundary = {
                top    : (offset.top - boundary.top),
                left   : (offset.left - boundary.left),
                right  : (boundary.right - (offset.left + popup.width) ),
                bottom : (boundary.bottom - (offset.top + popup.height) )
              };
              module.verbose('Distance from boundaries determined', offset, distanceFromBoundary);
            }
            return distanceFromBoundary;
          },
          offsetParent: function($target) {
            var
              element = ($target !== undefined)
                ? $target[0]
                : $module[0],
              parentNode = element.parentNode,
              $node    = $(parentNode)
            ;
            if(parentNode) {
              var
                is2D     = ($node.css('transform') === 'none'),
                isStatic = ($node.css('position') === 'static'),
                isHTML   = $node.is('html')
              ;
              while(parentNode && !isHTML && isStatic && is2D) {
                parentNode = parentNode.parentNode;
                $node    = $(parentNode);
                is2D     = ($node.css('transform') === 'none');
                isStatic = ($node.css('position') === 'static');
                isHTML   = $node.is('html');
              }
            }
            return ($node && $node.length > 0)
              ? $node
              : $()
            ;
          },
          positions: function() {
            return {
              'top left'      : false,
              'top center'    : false,
              'top right'     : false,
              'bottom left'   : false,
              'bottom center' : false,
              'bottom right'  : false,
              'left center'   : false,
              'right center'  : false
            };
          },
          nextPosition: function(position) {
            var
              positions          = position.split(' '),
              verticalPosition   = positions[0],
              horizontalPosition = positions[1],
              opposite = {
                top    : 'bottom',
                bottom : 'top',
                left   : 'right',
                right  : 'left'
              },
              adjacent = {
                left   : 'center',
                center : 'right',
                right  : 'left'
              },
              backup = {
                'top left'      : 'top center',
                'top center'    : 'top right',
                'top right'     : 'right center',
                'right center'  : 'bottom right',
                'bottom right'  : 'bottom center',
                'bottom center' : 'bottom left',
                'bottom left'   : 'left center',
                'left center'   : 'top left'
              },
              adjacentsAvailable = (verticalPosition == 'top' || verticalPosition == 'bottom'),
              oppositeTried = false,
              adjacentTried = false,
              nextPosition  = false
            ;
            if(!triedPositions) {
              module.verbose('All available positions available');
              triedPositions = module.get.positions();
            }

            module.debug('Recording last position tried', position);
            triedPositions[position] = true;

            if(settings.prefer === 'opposite') {
              nextPosition  = [opposite[verticalPosition], horizontalPosition];
              nextPosition  = nextPosition.join(' ');
              oppositeTried = (triedPositions[nextPosition] === true);
              module.debug('Trying opposite strategy', nextPosition);
            }
            if((settings.prefer === 'adjacent') && adjacentsAvailable ) {
              nextPosition  = [verticalPosition, adjacent[horizontalPosition]];
              nextPosition  = nextPosition.join(' ');
              adjacentTried = (triedPositions[nextPosition] === true);
              module.debug('Trying adjacent strategy', nextPosition);
            }
            if(adjacentTried || oppositeTried) {
              module.debug('Using backup position', nextPosition);
              nextPosition = backup[position];
            }
            return nextPosition;
          }
        },

        set: {
          position: function(position, calculations) {

            // exit conditions
            if($target.length === 0 || $popup.length === 0) {
              module.error(error.notFound);
              return;
            }
            var
              offset,
              distanceAway,
              target,
              popup,
              parent,
              positioning,
              popupOffset,
              distanceFromBoundary
            ;

            calculations = calculations || module.get.calculations();
            position     = position     || $module.data(metadata.position) || settings.position;

            offset       = $module.data(metadata.offset) || settings.offset;
            distanceAway = settings.distanceAway;

            // shorthand
            target = calculations.target;
            popup  = calculations.popup;
            parent = calculations.parent;

            if(target.width === 0 && target.height === 0 && !module.is.svg(target.element)) {
              module.debug('Popup target is hidden, no action taken');
              return false;
            }

            if(settings.inline) {
              module.debug('Adding margin to calculation', target.margin);
              if(position == 'left center' || position == 'right center') {
                offset       +=  target.margin.top;
                distanceAway += -target.margin.left;
              }
              else if (position == 'top left' || position == 'top center' || position == 'top right') {
                offset       += target.margin.left;
                distanceAway -= target.margin.top;
              }
              else {
                offset       += target.margin.left;
                distanceAway += target.margin.top;
              }
            }

            module.debug('Determining popup position from calculations', position, calculations);

            if (module.is.rtl()) {
              position = position.replace(/left|right/g, function (match) {
                return (match == 'left')
                  ? 'right'
                  : 'left'
                ;
              });
              module.debug('RTL: Popup position updated', position);
            }

            // if last attempt use specified last resort position
            if(searchDepth == settings.maxSearchDepth && typeof settings.lastResort === 'string') {
              position = settings.lastResort;
            }

            switch (position) {
              case 'top left':
                positioning = {
                  top    : 'auto',
                  bottom : parent.height - target.top + distanceAway,
                  left   : target.left + offset,
                  right  : 'auto'
                };
              break;
              case 'top center':
                positioning = {
                  bottom : parent.height - target.top + distanceAway,
                  left   : target.left + (target.width / 2) - (popup.width / 2) + offset,
                  top    : 'auto',
                  right  : 'auto'
                };
              break;
              case 'top right':
                positioning = {
                  bottom :  parent.height - target.top + distanceAway,
                  right  :  parent.width - target.left - target.width - offset,
                  top    : 'auto',
                  left   : 'auto'
                };
              break;
              case 'left center':
                positioning = {
                  top    : target.top + (target.height / 2) - (popup.height / 2) + offset,
                  right  : parent.width - target.left + distanceAway,
                  left   : 'auto',
                  bottom : 'auto'
                };
              break;
              case 'right center':
                positioning = {
                  top    : target.top + (target.height / 2) - (popup.height / 2) + offset,
                  left   : target.left + target.width + distanceAway,
                  bottom : 'auto',
                  right  : 'auto'
                };
              break;
              case 'bottom left':
                positioning = {
                  top    : target.top + target.height + distanceAway,
                  left   : target.left + offset,
                  bottom : 'auto',
                  right  : 'auto'
                };
              break;
              case 'bottom center':
                positioning = {
                  top    : target.top + target.height + distanceAway,
                  left   : target.left + (target.width / 2) - (popup.width / 2) + offset,
                  bottom : 'auto',
                  right  : 'auto'
                };
              break;
              case 'bottom right':
                positioning = {
                  top    : target.top + target.height + distanceAway,
                  right  : parent.width - target.left  - target.width - offset,
                  left   : 'auto',
                  bottom : 'auto'
                };
              break;
            }
            if(positioning === undefined) {
              module.error(error.invalidPosition, position);
            }

            module.debug('Calculated popup positioning values', positioning);

            // tentatively place on stage
            $popup
              .css(positioning)
              .removeClass(className.position)
              .addClass(position)
              .addClass(className.loading)
            ;

            popupOffset = module.get.popupOffset();

            // see if any boundaries are surpassed with this tentative position
            distanceFromBoundary = module.get.distanceFromBoundary(popupOffset, calculations);

            if( module.is.offstage(distanceFromBoundary, position) ) {
              module.debug('Position is outside viewport', position);
              if(searchDepth < settings.maxSearchDepth) {
                searchDepth++;
                position = module.get.nextPosition(position);
                module.debug('Trying new position', position);
                return ($popup)
                  ? module.set.position(position, calculations)
                  : false
                ;
              }
              else {
                if(settings.lastResort) {
                  module.debug('No position found, showing with last position');
                }
                else {
                  module.debug('Popup could not find a position to display', $popup);
                  module.error(error.cannotPlace, element);
                  module.remove.attempts();
                  module.remove.loading();
                  module.reset();
                  settings.onUnplaceable.call($popup, element);
                  return false;
                }
              }
            }
            module.debug('Position is on stage', position);
            module.remove.attempts();
            module.remove.loading();
            if( settings.setFluidWidth && module.is.fluid() ) {
              module.set.fluidWidth(calculations);
            }
            return true;
          },

          fluidWidth: function(calculations) {
            calculations = calculations || module.get.calculations();
            module.debug('Automatically setting element width to parent width', calculations.parent.width);
            $popup.css('width', calculations.container.width);
          },

          variation: function(variation) {
            variation = variation || module.get.variation();
            if(variation && module.has.popup() ) {
              module.verbose('Adding variation to popup', variation);
              $popup.addClass(variation);
            }
          },

          visible: function() {
            $module.addClass(className.visible);
          }
        },

        remove: {
          loading: function() {
            $popup.removeClass(className.loading);
          },
          variation: function(variation) {
            variation = variation || module.get.variation();
            if(variation) {
              module.verbose('Removing variation', variation);
              $popup.removeClass(variation);
            }
          },
          visible: function() {
            $module.removeClass(className.visible);
          },
          attempts: function() {
            module.verbose('Resetting all searched positions');
            searchDepth    = 0;
            triedPositions = false;
          }
        },

        bind: {
          events: function() {
            module.debug('Binding popup events to module');
            if(settings.on == 'click') {
              $module
                .on('click' + eventNamespace, module.toggle)
              ;
            }
            if(settings.on == 'hover' && hasTouch) {
              $module
                .on('touchstart' + eventNamespace, module.event.touchstart)
              ;
            }
            if( module.get.startEvent() ) {
              $module
                .on(module.get.startEvent() + eventNamespace, module.event.start)
                .on(module.get.endEvent() + eventNamespace, module.event.end)
              ;
            }
            if(settings.target) {
              module.debug('Target set to element', $target);
            }
            $window.on('resize' + elementNamespace, module.event.resize);
          },
          popup: function() {
            module.verbose('Allowing hover events on popup to prevent closing');
            if( $popup && module.has.popup() ) {
              $popup
                .on('mouseenter' + eventNamespace, module.event.start)
                .on('mouseleave' + eventNamespace, module.event.end)
              ;
            }
          },
          close: function() {
            if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) {
              module.bind.closeOnScroll();
            }
            if(settings.on == 'hover' && openedWithTouch) {
              module.bind.touchClose();
            }
            if(settings.on == 'click' && settings.closable) {
              module.bind.clickaway();
            }
          },
          closeOnScroll: function() {
            module.verbose('Binding scroll close event to document');
            $scrollContext
              .one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully)
            ;
          },
          touchClose: function() {
            module.verbose('Binding popup touchclose event to document');
            $document
              .on('touchstart' + elementNamespace, function(event) {
                module.verbose('Touched away from popup');
                module.event.hideGracefully.call(element, event);
              })
            ;
          },
          clickaway: function() {
            module.verbose('Binding popup close event to document');
            $document
              .on('click' + elementNamespace, function(event) {
                module.verbose('Clicked away from popup');
                module.event.hideGracefully.call(element, event);
              })
            ;
          }
        },

        unbind: {
          events: function() {
            $window
              .off(elementNamespace)
            ;
            $module
              .off(eventNamespace)
            ;
          },
          close: function() {
            $document
              .off(elementNamespace)
            ;
            $scrollContext
              .off(elementNamespace)
            ;
          },
        },

        has: {
          popup: function() {
            return ($popup && $popup.length > 0);
          }
        },

        is: {
          offstage: function(distanceFromBoundary, position) {
            var
              offstage = []
            ;
            // return boundaries that have been surpassed
            $.each(distanceFromBoundary, function(direction, distance) {
              if(distance < -settings.jitter) {
                module.debug('Position exceeds allowable distance from edge', direction, distance, position);
                offstage.push(direction);
              }
            });
            if(offstage.length > 0) {
              return true;
            }
            else {
              return false;
            }
          },
          svg: function(element) {
            return module.supports.svg() && (element instanceof SVGGraphicsElement);
          },
          active: function() {
            return $module.hasClass(className.active);
          },
          animating: function() {
            return ($popup !== undefined && $popup.hasClass(className.animating) );
          },
          fluid: function() {
            return ($popup !== undefined && $popup.hasClass(className.fluid));
          },
          visible: function() {
            return ($popup !== undefined && $popup.hasClass(className.popupVisible));
          },
          dropdown: function() {
            return $module.hasClass(className.dropdown);
          },
          hidden: function() {
            return !module.is.visible();
          },
          rtl: function () {
            return $module.css('direction') == 'rtl';
          }
        },

        reset: function() {
          module.remove.visible();
          if(settings.preserve) {
            if($.fn.transition !== undefined) {
              $popup
                .transition('remove transition')
              ;
            }
          }
          else {
            module.removePopup();
          }
        },

        setting: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.popup.settings = {

  name           : 'Popup',

  // module settings
  silent         : false,
  debug          : false,
  verbose        : false,
  performance    : true,
  namespace      : 'popup',

  // whether it should use dom mutation observers
  observeChanges : true,

  // callback only when element added to dom
  onCreate       : function(){},

  // callback before element removed from dom
  onRemove       : function(){},

  // callback before show animation
  onShow         : function(){},

  // callback after show animation
  onVisible      : function(){},

  // callback before hide animation
  onHide         : function(){},

  // callback when popup cannot be positioned in visible screen
  onUnplaceable  : function(){},

  // callback after hide animation
  onHidden       : function(){},

  // when to show popup
  on             : 'hover',

  // element to use to determine if popup is out of boundary
  boundary       : window,

  // whether to add touchstart events when using hover
  addTouchEvents : true,

  // default position relative to element
  position       : 'top left',

  // name of variation to use
  variation      : '',

  // whether popup should be moved to context
  movePopup      : true,

  // element which popup should be relative to
  target         : false,

  // jq selector or element that should be used as popup
  popup          : false,

  // popup should remain inline next to activator
  inline         : false,

  // popup should be removed from page on hide
  preserve       : false,

  // popup should not close when being hovered on
  hoverable      : false,

  // explicitly set content
  content        : false,

  // explicitly set html
  html           : false,

  // explicitly set title
  title          : false,

  // whether automatically close on clickaway when on click
  closable       : true,

  // automatically hide on scroll
  hideOnScroll   : 'auto',

  // hide other popups on show
  exclusive      : false,

  // context to attach popups
  context        : 'body',

  // context for binding scroll events
  scrollContext  : window,

  // position to prefer when calculating new position
  prefer         : 'opposite',

  // specify position to appear even if it doesn't fit
  lastResort     : false,

  // delay used to prevent accidental refiring of animations due to user error
  delay        : {
    show : 50,
    hide : 70
  },

  // whether fluid variation should assign width explicitly
  setFluidWidth  : true,

  // transition settings
  duration       : 200,
  transition     : 'scale',

  // distance away from activating element in px
  distanceAway   : 0,

  // number of pixels an element is allowed to be "offstage" for a position to be chosen (allows for rounding)
  jitter         : 2,

  // offset on aligning axis from calculated position
  offset         : 0,

  // maximum times to look for a position before failing (9 positions total)
  maxSearchDepth : 15,

  error: {
    invalidPosition : 'The position you specified is not a valid position',
    cannotPlace     : 'Popup does not fit within the boundaries of the viewport',
    method          : 'The method you called is not defined.',
    noTransition    : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>',
    notFound        : 'The target or popup you specified does not exist on the page'
  },

  metadata: {
    activator : 'activator',
    content   : 'content',
    html      : 'html',
    offset    : 'offset',
    position  : 'position',
    title     : 'title',
    variation : 'variation'
  },

  className   : {
    active       : 'active',
    animating    : 'animating',
    dropdown     : 'dropdown',
    fluid        : 'fluid',
    loading      : 'loading',
    popup        : 'ui popup',
    position     : 'top left center bottom right',
    visible      : 'visible',
    popupVisible : 'visible'
  },

  selector    : {
    popup    : '.ui.popup'
  },

  templates: {
    escape: function(string) {
      var
        badChars     = /[&<>"'`]/g,
        shouldEscape = /[&<>"'`]/,
        escape       = {
          "&": "&amp;",
          "<": "&lt;",
          ">": "&gt;",
          '"': "&quot;",
          "'": "&#x27;",
          "`": "&#x60;"
        },
        escapedChar  = function(chr) {
          return escape[chr];
        }
      ;
      if(shouldEscape.test(string)) {
        return string.replace(badChars, escapedChar);
      }
      return string;
    },
    popup: function(text) {
      var
        html   = '',
        escape = $.fn.popup.settings.templates.escape
      ;
      if(typeof text !== undefined) {
        if(typeof text.title !== undefined && text.title) {
          text.title = escape(text.title);
          html += '<div class="header">' + text.title + '</div>';
        }
        if(typeof text.content !== undefined && text.content) {
          text.content = escape(text.content);
          html += '<div class="content">' + text.content + '</div>';
        }
      }
      return html;
    }
  }

};


})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Progress
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

var
  global = (typeof window != 'undefined' && window.Math == Math)
    ? window
    : (typeof self != 'undefined' && self.Math == Math)
      ? self
      : Function('return this')()
;

$.fn.progress = function(parameters) {
  var
    $allModules    = $(this),

    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings          = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.progress.settings, parameters)
          : $.extend({}, $.fn.progress.settings),

        className       = settings.className,
        metadata        = settings.metadata,
        namespace       = settings.namespace,
        selector        = settings.selector,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $bar            = $(this).find(selector.bar),
        $progress       = $(this).find(selector.progress),
        $label          = $(this).find(selector.label),

        element         = this,
        instance        = $module.data(moduleNamespace),

        animating = false,
        transitionEnd,
        module
      ;

      module = {

        initialize: function() {
          module.debug('Initializing progress bar', settings);

          module.set.duration();
          module.set.transitionEvent();

          module.read.metadata();
          module.read.settings();

          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of progress', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },
        destroy: function() {
          module.verbose('Destroying previous progress for', $module);
          clearInterval(instance.interval);
          module.remove.state();
          $module.removeData(moduleNamespace);
          instance = undefined;
        },

        reset: function() {
          module.remove.nextValue();
          module.update.progress(0);
        },

        complete: function() {
          if(module.percent === undefined || module.percent < 100) {
            module.remove.progressPoll();
            module.set.percent(100);
          }
        },

        read: {
          metadata: function() {
            var
              data = {
                percent : $module.data(metadata.percent),
                total   : $module.data(metadata.total),
                value   : $module.data(metadata.value)
              }
            ;
            if(data.percent) {
              module.debug('Current percent value set from metadata', data.percent);
              module.set.percent(data.percent);
            }
            if(data.total) {
              module.debug('Total value set from metadata', data.total);
              module.set.total(data.total);
            }
            if(data.value) {
              module.debug('Current value set from metadata', data.value);
              module.set.value(data.value);
              module.set.progress(data.value);
            }
          },
          settings: function() {
            if(settings.total !== false) {
              module.debug('Current total set in settings', settings.total);
              module.set.total(settings.total);
            }
            if(settings.value !== false) {
              module.debug('Current value set in settings', settings.value);
              module.set.value(settings.value);
              module.set.progress(module.value);
            }
            if(settings.percent !== false) {
              module.debug('Current percent set in settings', settings.percent);
              module.set.percent(settings.percent);
            }
          }
        },

        bind: {
          transitionEnd: function(callback) {
            var
              transitionEnd = module.get.transitionEnd()
            ;
            $bar
              .one(transitionEnd + eventNamespace, function(event) {
                clearTimeout(module.failSafeTimer);
                callback.call(this, event);
              })
            ;
            module.failSafeTimer = setTimeout(function() {
              $bar.triggerHandler(transitionEnd);
            }, settings.duration + settings.failSafeDelay);
            module.verbose('Adding fail safe timer', module.timer);
          }
        },

        increment: function(incrementValue) {
          var
            maxValue,
            startValue,
            newValue
          ;
          if( module.has.total() ) {
            startValue     = module.get.value();
            incrementValue = incrementValue || 1;
            newValue       = startValue + incrementValue;
          }
          else {
            startValue     = module.get.percent();
            incrementValue = incrementValue || module.get.randomValue();

            newValue       = startValue + incrementValue;
            maxValue       = 100;
            module.debug('Incrementing percentage by', startValue, newValue);
          }
          newValue = module.get.normalizedValue(newValue);
          module.set.progress(newValue);
        },
        decrement: function(decrementValue) {
          var
            total     = module.get.total(),
            startValue,
            newValue
          ;
          if(total) {
            startValue     =  module.get.value();
            decrementValue =  decrementValue || 1;
            newValue       =  startValue - decrementValue;
            module.debug('Decrementing value by', decrementValue, startValue);
          }
          else {
            startValue     =  module.get.percent();
            decrementValue =  decrementValue || module.get.randomValue();
            newValue       =  startValue - decrementValue;
            module.debug('Decrementing percentage by', decrementValue, startValue);
          }
          newValue = module.get.normalizedValue(newValue);
          module.set.progress(newValue);
        },

        has: {
          progressPoll: function() {
            return module.progressPoll;
          },
          total: function() {
            return (module.get.total() !== false);
          }
        },

        get: {
          text: function(templateText) {
            var
              value   = module.value                || 0,
              total   = module.total                || 0,
              percent = (animating)
                ? module.get.displayPercent()
                : module.percent || 0,
              left = (module.total > 0)
                ? (total - value)
                : (100 - percent)
            ;
            templateText = templateText || '';
            templateText = templateText
              .replace('{value}', value)
              .replace('{total}', total)
              .replace('{left}', left)
              .replace('{percent}', percent)
            ;
            module.verbose('Adding variables to progress bar text', templateText);
            return templateText;
          },

          normalizedValue: function(value) {
            if(value < 0) {
              module.debug('Value cannot decrement below 0');
              return 0;
            }
            if(module.has.total()) {
              if(value > module.total) {
                module.debug('Value cannot increment above total', module.total);
                return module.total;
              }
            }
            else if(value > 100 ) {
              module.debug('Value cannot increment above 100 percent');
              return 100;
            }
            return value;
          },

          updateInterval: function() {
            if(settings.updateInterval == 'auto') {
              return settings.duration;
            }
            return settings.updateInterval;
          },

          randomValue: function() {
            module.debug('Generating random increment percentage');
            return Math.floor((Math.random() * settings.random.max) + settings.random.min);
          },

          numericValue: function(value) {
            return (typeof value === 'string')
              ? (value.replace(/[^\d.]/g, '') !== '')
                ? +(value.replace(/[^\d.]/g, ''))
                : false
              : value
            ;
          },

          transitionEnd: function() {
            var
              element     = document.createElement('element'),
              transitions = {
                'transition'       :'transitionend',
                'OTransition'      :'oTransitionEnd',
                'MozTransition'    :'transitionend',
                'WebkitTransition' :'webkitTransitionEnd'
              },
              transition
            ;
            for(transition in transitions){
              if( element.style[transition] !== undefined ){
                return transitions[transition];
              }
            }
          },

          // gets current displayed percentage (if animating values this is the intermediary value)
          displayPercent: function() {
            var
              barWidth       = $bar.width(),
              totalWidth     = $module.width(),
              minDisplay     = parseInt($bar.css('min-width'), 10),
              displayPercent = (barWidth > minDisplay)
                ? (barWidth / totalWidth * 100)
                : module.percent
            ;
            return (settings.precision > 0)
              ? Math.round(displayPercent * (10 * settings.precision)) / (10 * settings.precision)
              : Math.round(displayPercent)
            ;
          },

          percent: function() {
            return module.percent || 0;
          },
          value: function() {
            return module.nextValue || module.value || 0;
          },
          total: function() {
            return module.total || false;
          }
        },

        create: {
          progressPoll: function() {
            module.progressPoll = setTimeout(function() {
              module.update.toNextValue();
              module.remove.progressPoll();
            }, module.get.updateInterval());
          },
        },

        is: {
          complete: function() {
            return module.is.success() || module.is.warning() || module.is.error();
          },
          success: function() {
            return $module.hasClass(className.success);
          },
          warning: function() {
            return $module.hasClass(className.warning);
          },
          error: function() {
            return $module.hasClass(className.error);
          },
          active: function() {
            return $module.hasClass(className.active);
          },
          visible: function() {
            return $module.is(':visible');
          }
        },

        remove: {
          progressPoll: function() {
            module.verbose('Removing progress poll timer');
            if(module.progressPoll) {
              clearTimeout(module.progressPoll);
              delete module.progressPoll;
            }
          },
          nextValue: function() {
            module.verbose('Removing progress value stored for next update');
            delete module.nextValue;
          },
          state: function() {
            module.verbose('Removing stored state');
            delete module.total;
            delete module.percent;
            delete module.value;
          },
          active: function() {
            module.verbose('Removing active state');
            $module.removeClass(className.active);
          },
          success: function() {
            module.verbose('Removing success state');
            $module.removeClass(className.success);
          },
          warning: function() {
            module.verbose('Removing warning state');
            $module.removeClass(className.warning);
          },
          error: function() {
            module.verbose('Removing error state');
            $module.removeClass(className.error);
          }
        },

        set: {
          barWidth: function(value) {
            if(value > 100) {
              module.error(error.tooHigh, value);
            }
            else if (value < 0) {
              module.error(error.tooLow, value);
            }
            else {
              $bar
                .css('width', value + '%')
              ;
              $module
                .attr('data-percent', parseInt(value, 10))
              ;
            }
          },
          duration: function(duration) {
            duration = duration || settings.duration;
            duration = (typeof duration == 'number')
              ? duration + 'ms'
              : duration
            ;
            module.verbose('Setting progress bar transition duration', duration);
            $bar
              .css({
                'transition-duration':  duration
              })
            ;
          },
          percent: function(percent) {
            percent = (typeof percent == 'string')
              ? +(percent.replace('%', ''))
              : percent
            ;
            // round display percentage
            percent = (settings.precision > 0)
              ? Math.round(percent * (10 * settings.precision)) / (10 * settings.precision)
              : Math.round(percent)
            ;
            module.percent = percent;
            if( !module.has.total() ) {
              module.value = (settings.precision > 0)
                ? Math.round( (percent / 100) * module.total * (10 * settings.precision)) / (10 * settings.precision)
                : Math.round( (percent / 100) * module.total * 10) / 10
              ;
              if(settings.limitValues) {
                module.value = (module.value > 100)
                  ? 100
                  : (module.value < 0)
                    ? 0
                    : module.value
                ;
              }
            }
            module.set.barWidth(percent);
            module.set.labelInterval();
            module.set.labels();
            settings.onChange.call(element, percent, module.value, module.total);
          },
          labelInterval: function() {
            var
              animationCallback = function() {
                module.verbose('Bar finished animating, removing continuous label updates');
                clearInterval(module.interval);
                animating = false;
                module.set.labels();
              }
            ;
            clearInterval(module.interval);
            module.bind.transitionEnd(animationCallback);
            animating = true;
            module.interval = setInterval(function() {
              var
                isInDOM = $.contains(document.documentElement, element)
              ;
              if(!isInDOM) {
                clearInterval(module.interval);
                animating = false;
              }
              module.set.labels();
            }, settings.framerate);
          },
          labels: function() {
            module.verbose('Setting both bar progress and outer label text');
            module.set.barLabel();
            module.set.state();
          },
          label: function(text) {
            text = text || '';
            if(text) {
              text = module.get.text(text);
              module.verbose('Setting label to text', text);
              $label.text(text);
            }
          },
          state: function(percent) {
            percent = (percent !== undefined)
              ? percent
              : module.percent
            ;
            if(percent === 100) {
              if(settings.autoSuccess && !(module.is.warning() || module.is.error() || module.is.success())) {
                module.set.success();
                module.debug('Automatically triggering success at 100%');
              }
              else {
                module.verbose('Reached 100% removing active state');
                module.remove.active();
                module.remove.progressPoll();
              }
            }
            else if(percent > 0) {
              module.verbose('Adjusting active progress bar label', percent);
              module.set.active();
            }
            else {
              module.remove.active();
              module.set.label(settings.text.active);
            }
          },
          barLabel: function(text) {
            if(text !== undefined) {
              $progress.text( module.get.text(text) );
            }
            else if(settings.label == 'ratio' && module.total) {
              module.verbose('Adding ratio to bar label');
              $progress.text( module.get.text(settings.text.ratio) );
            }
            else if(settings.label == 'percent') {
              module.verbose('Adding percentage to bar label');
              $progress.text( module.get.text(settings.text.percent) );
            }
          },
          active: function(text) {
            text = text || settings.text.active;
            module.debug('Setting active state');
            if(settings.showActivity && !module.is.active() ) {
              $module.addClass(className.active);
            }
            module.remove.warning();
            module.remove.error();
            module.remove.success();
            text = settings.onLabelUpdate('active', text, module.value, module.total);
            if(text) {
              module.set.label(text);
            }
            module.bind.transitionEnd(function() {
              settings.onActive.call(element, module.value, module.total);
            });
          },
          success : function(text) {
            text = text || settings.text.success || settings.text.active;
            module.debug('Setting success state');
            $module.addClass(className.success);
            module.remove.active();
            module.remove.warning();
            module.remove.error();
            module.complete();
            if(settings.text.success) {
              text = settings.onLabelUpdate('success', text, module.value, module.total);
              module.set.label(text);
            }
            else {
              text = settings.onLabelUpdate('active', text, module.value, module.total);
              module.set.label(text);
            }
            module.bind.transitionEnd(function() {
              settings.onSuccess.call(element, module.total);
            });
          },
          warning : function(text) {
            text = text || settings.text.warning;
            module.debug('Setting warning state');
            $module.addClass(className.warning);
            module.remove.active();
            module.remove.success();
            module.remove.error();
            module.complete();
            text = settings.onLabelUpdate('warning', text, module.value, module.total);
            if(text) {
              module.set.label(text);
            }
            module.bind.transitionEnd(function() {
              settings.onWarning.call(element, module.value, module.total);
            });
          },
          error : function(text) {
            text = text || settings.text.error;
            module.debug('Setting error state');
            $module.addClass(className.error);
            module.remove.active();
            module.remove.success();
            module.remove.warning();
            module.complete();
            text = settings.onLabelUpdate('error', text, module.value, module.total);
            if(text) {
              module.set.label(text);
            }
            module.bind.transitionEnd(function() {
              settings.onError.call(element, module.value, module.total);
            });
          },
          transitionEvent: function() {
            transitionEnd = module.get.transitionEnd();
          },
          total: function(totalValue) {
            module.total = totalValue;
          },
          value: function(value) {
            module.value = value;
          },
          progress: function(value) {
            if(!module.has.progressPoll()) {
              module.debug('First update in progress update interval, immediately updating', value);
              module.update.progress(value);
              module.create.progressPoll();
            }
            else {
              module.debug('Updated within interval, setting next update to use new value', value);
              module.set.nextValue(value);
            }
          },
          nextValue: function(value) {
            module.nextValue = value;
          }
        },

        update: {
          toNextValue: function() {
            var
              nextValue = module.nextValue
            ;
            if(nextValue) {
              module.debug('Update interval complete using last updated value', nextValue);
              module.update.progress(nextValue);
              module.remove.nextValue();
            }
          },
          progress: function(value) {
            var
              percentComplete
            ;
            value = module.get.numericValue(value);
            if(value === false) {
              module.error(error.nonNumeric, value);
            }
            value = module.get.normalizedValue(value);
            if( module.has.total() ) {
              module.set.value(value);
              percentComplete = (value / module.total) * 100;
              module.debug('Calculating percent complete from total', percentComplete);
              module.set.percent( percentComplete );
            }
            else {
              percentComplete = value;
              module.debug('Setting value to exact percentage value', percentComplete);
              module.set.percent( percentComplete );
            }
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.progress.settings = {

  name         : 'Progress',
  namespace    : 'progress',

  silent       : false,
  debug        : false,
  verbose      : false,
  performance  : true,

  random       : {
    min : 2,
    max : 5
  },

  duration       : 300,

  updateInterval : 'auto',

  autoSuccess    : true,
  showActivity   : true,
  limitValues    : true,

  label          : 'percent',
  precision      : 0,
  framerate      : (1000 / 30), /// 30 fps

  percent        : false,
  total          : false,
  value          : false,

  // delay in ms for fail safe animation callback
  failSafeDelay : 100,

  onLabelUpdate : function(state, text, value, total){
    return text;
  },
  onChange      : function(percent, value, total){},
  onSuccess     : function(total){},
  onActive      : function(value, total){},
  onError       : function(value, total){},
  onWarning     : function(value, total){},

  error    : {
    method     : 'The method you called is not defined.',
    nonNumeric : 'Progress value is non numeric',
    tooHigh    : 'Value specified is above 100%',
    tooLow     : 'Value specified is below 0%'
  },

  regExp: {
    variable: /\{\$*[A-z0-9]+\}/g
  },

  metadata: {
    percent : 'percent',
    total   : 'total',
    value   : 'value'
  },

  selector : {
    bar      : '> .bar',
    label    : '> .label',
    progress : '.bar > .progress'
  },

  text : {
    active  : false,
    error   : false,
    success : false,
    warning : false,
    percent : '{percent}%',
    ratio   : '{value} of {total}'
  },

  className : {
    active  : 'active',
    error   : 'error',
    success : 'success',
    warning : 'warning'
  }

};


})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Rating
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.rating = function(parameters) {
  var
    $allModules     = $(this),
    moduleSelector  = $allModules.selector || '',

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),
    returnedValue
  ;
  $allModules
    .each(function() {
      var
        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.rating.settings, parameters)
          : $.extend({}, $.fn.rating.settings),

        namespace       = settings.namespace,
        className       = settings.className,
        metadata        = settings.metadata,
        selector        = settings.selector,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        element         = this,
        instance        = $(this).data(moduleNamespace),

        $module         = $(this),
        $icon           = $module.find(selector.icon),

        initialLoad,
        module
      ;

      module = {

        initialize: function() {
          module.verbose('Initializing rating module', settings);

          if($icon.length === 0) {
            module.setup.layout();
          }

          if(settings.interactive) {
            module.enable();
          }
          else {
            module.disable();
          }
          module.set.initialLoad();
          module.set.rating( module.get.initialRating() );
          module.remove.initialLoad();
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Instantiating module', settings);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous instance', instance);
          module.remove.events();
          $module
            .removeData(moduleNamespace)
          ;
        },

        refresh: function() {
          $icon   = $module.find(selector.icon);
        },

        setup: {
          layout: function() {
            var
              maxRating = module.get.maxRating(),
              html      = $.fn.rating.settings.templates.icon(maxRating)
            ;
            module.debug('Generating icon html dynamically');
            $module
              .html(html)
            ;
            module.refresh();
          }
        },

        event: {
          mouseenter: function() {
            var
              $activeIcon = $(this)
            ;
            $activeIcon
              .nextAll()
                .removeClass(className.selected)
            ;
            $module
              .addClass(className.selected)
            ;
            $activeIcon
              .addClass(className.selected)
                .prevAll()
                .addClass(className.selected)
            ;
          },
          mouseleave: function() {
            $module
              .removeClass(className.selected)
            ;
            $icon
              .removeClass(className.selected)
            ;
          },
          click: function() {
            var
              $activeIcon   = $(this),
              currentRating = module.get.rating(),
              rating        = $icon.index($activeIcon) + 1,
              canClear      = (settings.clearable == 'auto')
               ? ($icon.length === 1)
               : settings.clearable
            ;
            if(canClear && currentRating == rating) {
              module.clearRating();
            }
            else {
              module.set.rating( rating );
            }
          }
        },

        clearRating: function() {
          module.debug('Clearing current rating');
          module.set.rating(0);
        },

        bind: {
          events: function() {
            module.verbose('Binding events');
            $module
              .on('mouseenter' + eventNamespace, selector.icon, module.event.mouseenter)
              .on('mouseleave' + eventNamespace, selector.icon, module.event.mouseleave)
              .on('click'      + eventNamespace, selector.icon, module.event.click)
            ;
          }
        },

        remove: {
          events: function() {
            module.verbose('Removing events');
            $module
              .off(eventNamespace)
            ;
          },
          initialLoad: function() {
            initialLoad = false;
          }
        },

        enable: function() {
          module.debug('Setting rating to interactive mode');
          module.bind.events();
          $module
            .removeClass(className.disabled)
          ;
        },

        disable: function() {
          module.debug('Setting rating to read-only mode');
          module.remove.events();
          $module
            .addClass(className.disabled)
          ;
        },

        is: {
          initialLoad: function() {
            return initialLoad;
          }
        },

        get: {
          initialRating: function() {
            if($module.data(metadata.rating) !== undefined) {
              $module.removeData(metadata.rating);
              return $module.data(metadata.rating);
            }
            return settings.initialRating;
          },
          maxRating: function() {
            if($module.data(metadata.maxRating) !== undefined) {
              $module.removeData(metadata.maxRating);
              return $module.data(metadata.maxRating);
            }
            return settings.maxRating;
          },
          rating: function() {
            var
              currentRating = $icon.filter('.' + className.active).length
            ;
            module.verbose('Current rating retrieved', currentRating);
            return currentRating;
          }
        },

        set: {
          rating: function(rating) {
            var
              ratingIndex = (rating - 1 >= 0)
                ? (rating - 1)
                : 0,
              $activeIcon = $icon.eq(ratingIndex)
            ;
            $module
              .removeClass(className.selected)
            ;
            $icon
              .removeClass(className.selected)
              .removeClass(className.active)
            ;
            if(rating > 0) {
              module.verbose('Setting current rating to', rating);
              $activeIcon
                .prevAll()
                .addBack()
                  .addClass(className.active)
              ;
            }
            if(!module.is.initialLoad()) {
              settings.onRate.call(element, rating);
            }
          },
          initialLoad: function() {
            initialLoad = true;
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.length > 1) {
              title += ' ' + '(' + $allModules.length + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };
      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.rating.settings = {

  name          : 'Rating',
  namespace     : 'rating',

  slent         : false,
  debug         : false,
  verbose       : false,
  performance   : true,

  initialRating : 0,
  interactive   : true,
  maxRating     : 4,
  clearable     : 'auto',

  fireOnInit    : false,

  onRate        : function(rating){},

  error         : {
    method    : 'The method you called is not defined',
    noMaximum : 'No maximum rating specified. Cannot generate HTML automatically'
  },


  metadata: {
    rating    : 'rating',
    maxRating : 'maxRating'
  },

  className : {
    active   : 'active',
    disabled : 'disabled',
    selected : 'selected',
    loading  : 'loading'
  },

  selector  : {
    icon : '.icon'
  },

  templates: {
    icon: function(maxRating) {
      var
        icon = 1,
        html = ''
      ;
      while(icon <= maxRating) {
        html += '<i class="icon"></i>';
        icon++;
      }
      return html;
    }
  }

};

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Search
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.search = function(parameters) {
  var
    $allModules     = $(this),
    moduleSelector  = $allModules.selector || '',

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),
    returnedValue
  ;
  $(this)
    .each(function() {
      var
        settings          = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.search.settings, parameters)
          : $.extend({}, $.fn.search.settings),

        className        = settings.className,
        metadata         = settings.metadata,
        regExp           = settings.regExp,
        fields           = settings.fields,
        selector         = settings.selector,
        error            = settings.error,
        namespace        = settings.namespace,

        eventNamespace   = '.' + namespace,
        moduleNamespace  = namespace + '-module',

        $module          = $(this),
        $prompt          = $module.find(selector.prompt),
        $searchButton    = $module.find(selector.searchButton),
        $results         = $module.find(selector.results),
        $result          = $module.find(selector.result),
        $category        = $module.find(selector.category),

        element          = this,
        instance         = $module.data(moduleNamespace),

        disabledBubbled  = false,
        resultsDismissed = false,

        module
      ;

      module = {

        initialize: function() {
          module.verbose('Initializing module');
          module.determine.searchFields();
          module.bind.events();
          module.set.type();
          module.create.results();
          module.instantiate();
        },
        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },
        destroy: function() {
          module.verbose('Destroying instance');
          $module
            .off(eventNamespace)
            .removeData(moduleNamespace)
          ;
        },

        refresh: function() {
          module.debug('Refreshing selector cache');
          $prompt         = $module.find(selector.prompt);
          $searchButton   = $module.find(selector.searchButton);
          $category       = $module.find(selector.category);
          $results        = $module.find(selector.results);
          $result         = $module.find(selector.result);
        },

        refreshResults: function() {
          $results = $module.find(selector.results);
          $result  = $module.find(selector.result);
        },

        bind: {
          events: function() {
            module.verbose('Binding events to search');
            if(settings.automatic) {
              $module
                .on(module.get.inputEvent() + eventNamespace, selector.prompt, module.event.input)
              ;
              $prompt
                .attr('autocomplete', 'off')
              ;
            }
            $module
              // prompt
              .on('focus'     + eventNamespace, selector.prompt, module.event.focus)
              .on('blur'      + eventNamespace, selector.prompt, module.event.blur)
              .on('keydown'   + eventNamespace, selector.prompt, module.handleKeyboard)
              // search button
              .on('click'     + eventNamespace, selector.searchButton, module.query)
              // results
              .on('mousedown' + eventNamespace, selector.results, module.event.result.mousedown)
              .on('mouseup'   + eventNamespace, selector.results, module.event.result.mouseup)
              .on('click'     + eventNamespace, selector.result,  module.event.result.click)
            ;
          }
        },

        determine: {
          searchFields: function() {
            // this makes sure $.extend does not add specified search fields to default fields
            // this is the only setting which should not extend defaults
            if(parameters && parameters.searchFields !== undefined) {
              settings.searchFields = parameters.searchFields;
            }
          }
        },

        event: {
          input: function() {
            if(settings.searchDelay) {
              clearTimeout(module.timer);
              module.timer = setTimeout(function() {
                if(module.is.focused()) {
                  module.query();
                }
              }, settings.searchDelay);
            }
            else {
              module.query();
            }
          },
          focus: function() {
            module.set.focus();
            if(settings.searchOnFocus && module.has.minimumCharacters() ) {
              module.query(function() {
                if(module.can.show() ) {
                  module.showResults();
                }
              });
            }
          },
          blur: function(event) {
            var
              pageLostFocus = (document.activeElement === this),
              callback      = function() {
                module.cancel.query();
                module.remove.focus();
                module.timer = setTimeout(module.hideResults, settings.hideDelay);
              }
            ;
            if(pageLostFocus) {
              return;
            }
            resultsDismissed = false;
            if(module.resultsClicked) {
              module.debug('Determining if user action caused search to close');
              $module
                .one('click.close' + eventNamespace, selector.results, function(event) {
                  if(module.is.inMessage(event) || disabledBubbled) {
                    $prompt.focus();
                    return;
                  }
                  disabledBubbled = false;
                  if( !module.is.animating() && !module.is.hidden()) {
                    callback();
                  }
                })
              ;
            }
            else {
              module.debug('Input blurred without user action, closing results');
              callback();
            }
          },
          result: {
            mousedown: function() {
              module.resultsClicked = true;
            },
            mouseup: function() {
              module.resultsClicked = false;
            },
            click: function(event) {
              module.debug('Search result selected');
              var
                $result = $(this),
                $title  = $result.find(selector.title).eq(0),
                $link   = $result.is('a[href]')
                  ? $result
                  : $result.find('a[href]').eq(0),
                href    = $link.attr('href')   || false,
                target  = $link.attr('target') || false,
                title   = $title.html(),
                // title is used for result lookup
                value   = ($title.length > 0)
                  ? $title.text()
                  : false,
                results = module.get.results(),
                result  = $result.data(metadata.result) || module.get.result(value, results),
                returnedValue
              ;
              if( $.isFunction(settings.onSelect) ) {
                if(settings.onSelect.call(element, result, results) === false) {
                  module.debug('Custom onSelect callback cancelled default select action');
                  disabledBubbled = true;
                  return;
                }
              }
              module.hideResults();
              if(value) {
                module.set.value(value);
              }
              if(href) {
                module.verbose('Opening search link found in result', $link);
                if(target == '_blank' || event.ctrlKey) {
                  window.open(href);
                }
                else {
                  window.location.href = (href);
                }
              }
            }
          }
        },
        handleKeyboard: function(event) {
          var
            // force selector refresh
            $result         = $module.find(selector.result),
            $category       = $module.find(selector.category),
            $activeResult   = $result.filter('.' + className.active),
            currentIndex    = $result.index( $activeResult ),
            resultSize      = $result.length,
            hasActiveResult = $activeResult.length > 0,

            keyCode         = event.which,
            keys            = {
              backspace : 8,
              enter     : 13,
              escape    : 27,
              upArrow   : 38,
              downArrow : 40
            },
            newIndex
          ;
          // search shortcuts
          if(keyCode == keys.escape) {
            module.verbose('Escape key pressed, blurring search field');
            module.hideResults();
            resultsDismissed = true;
          }
          if( module.is.visible() ) {
            if(keyCode == keys.enter) {
              module.verbose('Enter key pressed, selecting active result');
              if( $result.filter('.' + className.active).length > 0 ) {
                module.event.result.click.call($result.filter('.' + className.active), event);
                event.preventDefault();
                return false;
              }
            }
            else if(keyCode == keys.upArrow && hasActiveResult) {
              module.verbose('Up key pressed, changing active result');
              newIndex = (currentIndex - 1 < 0)
                ? currentIndex
                : currentIndex - 1
              ;
              $category
                .removeClass(className.active)
              ;
              $result
                .removeClass(className.active)
                .eq(newIndex)
                  .addClass(className.active)
                  .closest($category)
                    .addClass(className.active)
              ;
              event.preventDefault();
            }
            else if(keyCode == keys.downArrow) {
              module.verbose('Down key pressed, changing active result');
              newIndex = (currentIndex + 1 >= resultSize)
                ? currentIndex
                : currentIndex + 1
              ;
              $category
                .removeClass(className.active)
              ;
              $result
                .removeClass(className.active)
                .eq(newIndex)
                  .addClass(className.active)
                  .closest($category)
                    .addClass(className.active)
              ;
              event.preventDefault();
            }
          }
          else {
            // query shortcuts
            if(keyCode == keys.enter) {
              module.verbose('Enter key pressed, executing query');
              module.query();
              module.set.buttonPressed();
              $prompt.one('keyup', module.remove.buttonFocus);
            }
          }
        },

        setup: {
          api: function(searchTerm, callback) {
            var
              apiSettings = {
                debug             : settings.debug,
                on                : false,
                cache             : true,
                action            : 'search',
                urlData           : {
                  query : searchTerm
                },
                onSuccess         : function(response) {
                  module.parse.response.call(element, response, searchTerm);
                  callback();
                },
                onFailure         : function() {
                  module.displayMessage(error.serverError);
                  callback();
                },
                onAbort : function(response) {
                },
                onError           : module.error
              },
              searchHTML
            ;
            $.extend(true, apiSettings, settings.apiSettings);
            module.verbose('Setting up API request', apiSettings);
            $module.api(apiSettings);
          }
        },

        can: {
          useAPI: function() {
            return $.fn.api !== undefined;
          },
          show: function() {
            return module.is.focused() && !module.is.visible() && !module.is.empty();
          },
          transition: function() {
            return settings.transition && $.fn.transition !== undefined && $module.transition('is supported');
          }
        },

        is: {
          animating: function() {
            return $results.hasClass(className.animating);
          },
          hidden: function() {
            return $results.hasClass(className.hidden);
          },
          inMessage: function(event) {
            if(!event.target) {
              return;
            }
            var
              $target = $(event.target),
              isInDOM = $.contains(document.documentElement, event.target)
            ;
            return (isInDOM && $target.closest(selector.message).length > 0);
          },
          empty: function() {
            return ($results.html() === '');
          },
          visible: function() {
            return ($results.filter(':visible').length > 0);
          },
          focused: function() {
            return ($prompt.filter(':focus').length > 0);
          }
        },

        get: {
          inputEvent: function() {
            var
              prompt = $prompt[0],
              inputEvent   = (prompt !== undefined && prompt.oninput !== undefined)
                ? 'input'
                : (prompt !== undefined && prompt.onpropertychange !== undefined)
                  ? 'propertychange'
                  : 'keyup'
            ;
            return inputEvent;
          },
          value: function() {
            return $prompt.val();
          },
          results: function() {
            var
              results = $module.data(metadata.results)
            ;
            return results;
          },
          result: function(value, results) {
            var
              lookupFields = ['title', 'id'],
              result       = false
            ;
            value = (value !== undefined)
              ? value
              : module.get.value()
            ;
            results = (results !== undefined)
              ? results
              : module.get.results()
            ;
            if(settings.type === 'category') {
              module.debug('Finding result that matches', value);
              $.each(results, function(index, category) {
                if($.isArray(category.results)) {
                  result = module.search.object(value, category.results, lookupFields)[0];
                  // don't continue searching if a result is found
                  if(result) {
                    return false;
                  }
                }
              });
            }
            else {
              module.debug('Finding result in results object', value);
              result = module.search.object(value, results, lookupFields)[0];
            }
            return result || false;
          },
        },

        select: {
          firstResult: function() {
            module.verbose('Selecting first result');
            $result.first().addClass(className.active);
          }
        },

        set: {
          focus: function() {
            $module.addClass(className.focus);
          },
          loading: function() {
            $module.addClass(className.loading);
          },
          value: function(value) {
            module.verbose('Setting search input value', value);
            $prompt
              .val(value)
            ;
          },
          type: function(type) {
            type = type || settings.type;
            if(settings.type == 'category') {
              $module.addClass(settings.type);
            }
          },
          buttonPressed: function() {
            $searchButton.addClass(className.pressed);
          }
        },

        remove: {
          loading: function() {
            $module.removeClass(className.loading);
          },
          focus: function() {
            $module.removeClass(className.focus);
          },
          buttonPressed: function() {
            $searchButton.removeClass(className.pressed);
          }
        },

        query: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          var
            searchTerm = module.get.value(),
            cache = module.read.cache(searchTerm)
          ;
          callback = callback || function() {};
          if( module.has.minimumCharacters() )  {
            if(cache) {
              module.debug('Reading result from cache', searchTerm);
              module.save.results(cache.results);
              module.addResults(cache.html);
              module.inject.id(cache.results);
              callback();
            }
            else {
              module.debug('Querying for', searchTerm);
              if($.isPlainObject(settings.source) || $.isArray(settings.source)) {
                module.search.local(searchTerm);
                callback();
              }
              else if( module.can.useAPI() ) {
                module.search.remote(searchTerm, callback);
              }
              else {
                module.error(error.source);
                callback();
              }
            }
            settings.onSearchQuery.call(element, searchTerm);
          }
          else {
            module.hideResults();
          }
        },

        search: {
          local: function(searchTerm) {
            var
              results = module.search.object(searchTerm, settings.content),
              searchHTML
            ;
            module.set.loading();
            module.save.results(results);
            module.debug('Returned local search results', results);

            searchHTML = module.generateResults({
              results: results
            });
            module.remove.loading();
            module.addResults(searchHTML);
            module.inject.id(results);
            module.write.cache(searchTerm, {
              html    : searchHTML,
              results : results
            });
          },
          remote: function(searchTerm, callback) {
            callback = $.isFunction(callback)
              ? callback
              : function(){}
            ;
            if($module.api('is loading')) {
              $module.api('abort');
            }
            module.setup.api(searchTerm, callback);
            $module
              .api('query')
            ;
          },
          object: function(searchTerm, source, searchFields) {
            var
              results      = [],
              fuzzyResults = [],
              searchExp    = searchTerm.toString().replace(regExp.escape, '\\$&'),
              matchRegExp  = new RegExp(regExp.beginsWith + searchExp, 'i'),

              // avoid duplicates when pushing results
              addResult = function(array, result) {
                var
                  notResult      = ($.inArray(result, results) == -1),
                  notFuzzyResult = ($.inArray(result, fuzzyResults) == -1)
                ;
                if(notResult && notFuzzyResult) {
                  array.push(result);
                }
              }
            ;
            source = source || settings.source;
            searchFields = (searchFields !== undefined)
              ? searchFields
              : settings.searchFields
            ;

            // search fields should be array to loop correctly
            if(!$.isArray(searchFields)) {
              searchFields = [searchFields];
            }

            // exit conditions if no source
            if(source === undefined || source === false) {
              module.error(error.source);
              return [];
            }

            // iterate through search fields looking for matches
            $.each(searchFields, function(index, field) {
              $.each(source, function(label, content) {
                var
                  fieldExists = (typeof content[field] == 'string')
                ;
                if(fieldExists) {
                  if( content[field].search(matchRegExp) !== -1) {
                    // content starts with value (first in results)
                    addResult(results, content);
                  }
                  else if(settings.searchFullText && module.fuzzySearch(searchTerm, content[field]) ) {
                    // content fuzzy matches (last in results)
                    addResult(fuzzyResults, content);
                  }
                }
              });
            });
            return $.merge(results, fuzzyResults);
          }
        },

        fuzzySearch: function(query, term) {
          var
            termLength  = term.length,
            queryLength = query.length
          ;
          if(typeof query !== 'string') {
            return false;
          }
          query = query.toLowerCase();
          term  = term.toLowerCase();
          if(queryLength > termLength) {
            return false;
          }
          if(queryLength === termLength) {
            return (query === term);
          }
          search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
            var
              queryCharacter = query.charCodeAt(characterIndex)
            ;
            while(nextCharacterIndex < termLength) {
              if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
                continue search;
              }
            }
            return false;
          }
          return true;
        },

        parse: {
          response: function(response, searchTerm) {
            var
              searchHTML = module.generateResults(response)
            ;
            module.verbose('Parsing server response', response);
            if(response !== undefined) {
              if(searchTerm !== undefined && response[fields.results] !== undefined) {
                module.addResults(searchHTML);
                module.inject.id(response[fields.results]);
                module.write.cache(searchTerm, {
                  html    : searchHTML,
                  results : response[fields.results]
                });
                module.save.results(response[fields.results]);
              }
            }
          }
        },

        cancel: {
          query: function() {
            if( module.can.useAPI() ) {
              $module.api('abort');
            }
          }
        },

        has: {
          minimumCharacters: function() {
            var
              searchTerm    = module.get.value(),
              numCharacters = searchTerm.length
            ;
            return (numCharacters >= settings.minCharacters);
          },
          results: function() {
            if($results.length === 0) {
              return false;
            }
            var
              html = $results.html()
            ;
            return html != '';
          }
        },

        clear: {
          cache: function(value) {
            var
              cache = $module.data(metadata.cache)
            ;
            if(!value) {
              module.debug('Clearing cache', value);
              $module.removeData(metadata.cache);
            }
            else if(value && cache && cache[value]) {
              module.debug('Removing value from cache', value);
              delete cache[value];
              $module.data(metadata.cache, cache);
            }
          }
        },

        read: {
          cache: function(name) {
            var
              cache = $module.data(metadata.cache)
            ;
            if(settings.cache) {
              module.verbose('Checking cache for generated html for query', name);
              return (typeof cache == 'object') && (cache[name] !== undefined)
                ? cache[name]
                : false
              ;
            }
            return false;
          }
        },

        create: {
          id: function(resultIndex, categoryIndex) {
            var
              resultID      = (resultIndex + 1), // not zero indexed
              categoryID    = (categoryIndex + 1),
              firstCharCode,
              letterID,
              id
            ;
            if(categoryIndex !== undefined) {
              // start char code for "A"
              letterID = String.fromCharCode(97 + categoryIndex);
              id          = letterID + resultID;
              module.verbose('Creating category result id', id);
            }
            else {
              id = resultID;
              module.verbose('Creating result id', id);
            }
            return id;
          },
          results: function() {
            if($results.length === 0) {
              $results = $('<div />')
                .addClass(className.results)
                .appendTo($module)
              ;
            }
          }
        },

        inject: {
          result: function(result, resultIndex, categoryIndex) {
            module.verbose('Injecting result into results');
            var
              $selectedResult = (categoryIndex !== undefined)
                ? $results
                    .children().eq(categoryIndex)
                      .children(selector.result).eq(resultIndex)
                : $results
                    .children(selector.result).eq(resultIndex)
            ;
            module.verbose('Injecting results metadata', $selectedResult);
            $selectedResult
              .data(metadata.result, result)
            ;
          },
          id: function(results) {
            module.debug('Injecting unique ids into results');
            var
              // since results may be object, we must use counters
              categoryIndex = 0,
              resultIndex   = 0
            ;
            if(settings.type === 'category') {
              // iterate through each category result
              $.each(results, function(index, category) {
                resultIndex = 0;
                $.each(category.results, function(index, value) {
                  var
                    result = category.results[index]
                  ;
                  if(result.id === undefined) {
                    result.id = module.create.id(resultIndex, categoryIndex);
                  }
                  module.inject.result(result, resultIndex, categoryIndex);
                  resultIndex++;
                });
                categoryIndex++;
              });
            }
            else {
              // top level
              $.each(results, function(index, value) {
                var
                  result = results[index]
                ;
                if(result.id === undefined) {
                  result.id = module.create.id(resultIndex);
                }
                module.inject.result(result, resultIndex);
                resultIndex++;
              });
            }
            return results;
          }
        },

        save: {
          results: function(results) {
            module.verbose('Saving current search results to metadata', results);
            $module.data(metadata.results, results);
          }
        },

        write: {
          cache: function(name, value) {
            var
              cache = ($module.data(metadata.cache) !== undefined)
                ? $module.data(metadata.cache)
                : {}
            ;
            if(settings.cache) {
              module.verbose('Writing generated html to cache', name, value);
              cache[name] = value;
              $module
                .data(metadata.cache, cache)
              ;
            }
          }
        },

        addResults: function(html) {
          if( $.isFunction(settings.onResultsAdd) ) {
            if( settings.onResultsAdd.call($results, html) === false ) {
              module.debug('onResultsAdd callback cancelled default action');
              return false;
            }
          }
          if(html) {
            $results
              .html(html)
            ;
            module.refreshResults();
            if(settings.selectFirstResult) {
              module.select.firstResult();
            }
            module.showResults();
          }
          else {
            module.hideResults(function() {
              $results.empty();
            });
          }
        },

        showResults: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if(resultsDismissed) {
            return;
          }
          if(!module.is.visible() && module.has.results()) {
            if( module.can.transition() ) {
              module.debug('Showing results with css animations');
              $results
                .transition({
                  animation  : settings.transition + ' in',
                  debug      : settings.debug,
                  verbose    : settings.verbose,
                  duration   : settings.duration,
                  onComplete : function() {
                    callback();
                  },
                  queue      : true
                })
              ;
            }
            else {
              module.debug('Showing results with javascript');
              $results
                .stop()
                .fadeIn(settings.duration, settings.easing)
              ;
            }
            settings.onResultsOpen.call($results);
          }
        },
        hideResults: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if( module.is.visible() ) {
            if( module.can.transition() ) {
              module.debug('Hiding results with css animations');
              $results
                .transition({
                  animation  : settings.transition + ' out',
                  debug      : settings.debug,
                  verbose    : settings.verbose,
                  duration   : settings.duration,
                  onComplete : function() {
                    callback();
                  },
                  queue      : true
                })
              ;
            }
            else {
              module.debug('Hiding results with javascript');
              $results
                .stop()
                .fadeOut(settings.duration, settings.easing)
              ;
            }
            settings.onResultsClose.call($results);
          }
        },

        generateResults: function(response) {
          module.debug('Generating html from response', response);
          var
            template       = settings.templates[settings.type],
            isProperObject = ($.isPlainObject(response[fields.results]) && !$.isEmptyObject(response[fields.results])),
            isProperArray  = ($.isArray(response[fields.results]) && response[fields.results].length > 0),
            html           = ''
          ;
          if(isProperObject || isProperArray ) {
            if(settings.maxResults > 0) {
              if(isProperObject) {
                if(settings.type == 'standard') {
                  module.error(error.maxResults);
                }
              }
              else {
                response[fields.results] = response[fields.results].slice(0, settings.maxResults);
              }
            }
            if($.isFunction(template)) {
              html = template(response, fields);
            }
            else {
              module.error(error.noTemplate, false);
            }
          }
          else if(settings.showNoResults) {
            html = module.displayMessage(error.noResults, 'empty');
          }
          settings.onResults.call(element, response);
          return html;
        },

        displayMessage: function(text, type) {
          type = type || 'standard';
          module.debug('Displaying message', text, type);
          module.addResults( settings.templates.message(text, type) );
          return settings.templates.message(text, type);
        },

        setting: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.length > 1) {
              title += ' ' + '(' + $allModules.length + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };
      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }

    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.search.settings = {

  name              : 'Search',
  namespace         : 'search',

  silent            : false,
  debug             : false,
  verbose           : false,
  performance       : true,

  // template to use (specified in settings.templates)
  type              : 'standard',

  // minimum characters required to search
  minCharacters     : 1,

  // whether to select first result after searching automatically
  selectFirstResult : false,

  // API config
  apiSettings       : false,

  // object to search
  source            : false,

  // Whether search should query current term on focus
  searchOnFocus     : true,

  // fields to search
  searchFields   : [
    'title',
    'description'
  ],

  // field to display in standard results template
  displayField   : '',

  // whether to include fuzzy results in local search
  searchFullText : true,

  // whether to add events to prompt automatically
  automatic      : true,

  // delay before hiding menu after blur
  hideDelay      : 0,

  // delay before searching
  searchDelay    : 200,

  // maximum results returned from local
  maxResults     : 7,

  // whether to store lookups in local cache
  cache          : true,

  // whether no results errors should be shown
  showNoResults  : true,

  // transition settings
  transition     : 'scale',
  duration       : 200,
  easing         : 'easeOutExpo',

  // callbacks
  onSelect       : false,
  onResultsAdd   : false,

  onSearchQuery  : function(query){},
  onResults      : function(response){},

  onResultsOpen  : function(){},
  onResultsClose : function(){},

  className: {
    animating : 'animating',
    active    : 'active',
    empty     : 'empty',
    focus     : 'focus',
    hidden    : 'hidden',
    loading   : 'loading',
    results   : 'results',
    pressed   : 'down'
  },

  error : {
    source      : 'Cannot search. No source used, and Semantic API module was not included',
    noResults   : 'Your search returned no results',
    logging     : 'Error in debug logging, exiting.',
    noEndpoint  : 'No search endpoint was specified',
    noTemplate  : 'A valid template name was not specified.',
    serverError : 'There was an issue querying the server.',
    maxResults  : 'Results must be an array to use maxResults setting',
    method      : 'The method you called is not defined.'
  },

  metadata: {
    cache   : 'cache',
    results : 'results',
    result  : 'result'
  },

  regExp: {
    escape     : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
    beginsWith : '(?:\s|^)'
  },

  // maps api response attributes to internal representation
  fields: {
    categories      : 'results',     // array of categories (category view)
    categoryName    : 'name',        // name of category (category view)
    categoryResults : 'results',     // array of results (category view)
    description     : 'description', // result description
    image           : 'image',       // result image
    price           : 'price',       // result price
    results         : 'results',     // array of results (standard)
    title           : 'title',       // result title
    url             : 'url',         // result url
    action          : 'action',      // "view more" object name
    actionText      : 'text',        // "view more" text
    actionURL       : 'url'          // "view more" url
  },

  selector : {
    prompt       : '.prompt',
    searchButton : '.search.button',
    results      : '.results',
    message      : '.results > .message',
    category     : '.category',
    result       : '.result',
    title        : '.title, .name'
  },

  templates: {
    escape: function(string) {
      var
        badChars     = /[&<>"'`]/g,
        shouldEscape = /[&<>"'`]/,
        escape       = {
          "&": "&amp;",
          "<": "&lt;",
          ">": "&gt;",
          '"': "&quot;",
          "'": "&#x27;",
          "`": "&#x60;"
        },
        escapedChar  = function(chr) {
          return escape[chr];
        }
      ;
      if(shouldEscape.test(string)) {
        return string.replace(badChars, escapedChar);
      }
      return string;
    },
    message: function(message, type) {
      var
        html = ''
      ;
      if(message !== undefined && type !== undefined) {
        html +=  ''
          + '<div class="message ' + type + '">'
        ;
        // message type
        if(type == 'empty') {
          html += ''
            + '<div class="header">No Results</div class="header">'
            + '<div class="description">' + message + '</div class="description">'
          ;
        }
        else {
          html += ' <div class="description">' + message + '</div>';
        }
        html += '</div>';
      }
      return html;
    },
    category: function(response, fields) {
      var
        html = '',
        escape = $.fn.search.settings.templates.escape
      ;
      if(response[fields.categoryResults] !== undefined) {

        // each category
        $.each(response[fields.categoryResults], function(index, category) {
          if(category[fields.results] !== undefined && category.results.length > 0) {

            html  += '<div class="category">';

            if(category[fields.categoryName] !== undefined) {
              html += '<div class="name">' + category[fields.categoryName] + '</div>';
            }

            // each item inside category
            $.each(category.results, function(index, result) {
              if(result[fields.url]) {
                html  += '<a class="result" href="' + result[fields.url] + '">';
              }
              else {
                html  += '<a class="result">';
              }
              if(result[fields.image] !== undefined) {
                html += ''
                  + '<div class="image">'
                  + ' <img src="' + result[fields.image] + '">'
                  + '</div>'
                ;
              }
              html += '<div class="content">';
              if(result[fields.price] !== undefined) {
                html += '<div class="price">' + result[fields.price] + '</div>';
              }
              if(result[fields.title] !== undefined) {
                html += '<div class="title">' + result[fields.title] + '</div>';
              }
              if(result[fields.description] !== undefined) {
                html += '<div class="description">' + result[fields.description] + '</div>';
              }
              html  += ''
                + '</div>'
              ;
              html += '</a>';
            });
            html  += ''
              + '</div>'
            ;
          }
        });
        if(response[fields.action]) {
          html += ''
          + '<a href="' + response[fields.action][fields.actionURL] + '" class="action">'
          +   response[fields.action][fields.actionText]
          + '</a>';
        }
        return html;
      }
      return false;
    },
    standard: function(response, fields) {
      var
        html = ''
      ;
      if(response[fields.results] !== undefined) {

        // each result
        $.each(response[fields.results], function(index, result) {
          if(result[fields.url]) {
            html  += '<a class="result" href="' + result[fields.url] + '">';
          }
          else {
            html  += '<a class="result">';
          }
          if(result[fields.image] !== undefined) {
            html += ''
              + '<div class="image">'
              + ' <img src="' + result[fields.image] + '">'
              + '</div>'
            ;
          }
          html += '<div class="content">';
          if(result[fields.price] !== undefined) {
            html += '<div class="price">' + result[fields.price] + '</div>';
          }
          if(result[fields.title] !== undefined) {
            html += '<div class="title">' + result[fields.title] + '</div>';
          }
          if(result[fields.description] !== undefined) {
            html += '<div class="description">' + result[fields.description] + '</div>';
          }
          html  += ''
            + '</div>'
          ;
          html += '</a>';
        });

        if(response[fields.action]) {
          html += ''
          + '<a href="' + response[fields.action][fields.actionURL] + '" class="action">'
          +   response[fields.action][fields.actionText]
          + '</a>';
        }
        return html;
      }
      return false;
    }
  }
};

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Shape
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.shape = function(parameters) {
  var
    $allModules     = $(this),
    $body           = $('body'),

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),

    requestAnimationFrame = window.requestAnimationFrame
      || window.mozRequestAnimationFrame
      || window.webkitRequestAnimationFrame
      || window.msRequestAnimationFrame
      || function(callback) { setTimeout(callback, 0); },

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        moduleSelector = $allModules.selector || '',
        settings       = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.shape.settings, parameters)
          : $.extend({}, $.fn.shape.settings),

        // internal aliases
        namespace     = settings.namespace,
        selector      = settings.selector,
        error         = settings.error,
        className     = settings.className,

        // define namespaces for modules
        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        // selector cache
        $module       = $(this),
        $sides        = $module.find(selector.sides),
        $side         = $module.find(selector.side),

        // private variables
        nextIndex = false,
        $activeSide,
        $nextSide,

        // standard module
        element       = this,
        instance      = $module.data(moduleNamespace),
        module
      ;

      module = {

        initialize: function() {
          module.verbose('Initializing module for', element);
          module.set.defaultSide();
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, instance)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous module for', element);
          $module
            .removeData(moduleNamespace)
            .off(eventNamespace)
          ;
        },

        refresh: function() {
          module.verbose('Refreshing selector cache for', element);
          $module = $(element);
          $sides  = $(this).find(selector.shape);
          $side   = $(this).find(selector.side);
        },

        repaint: function() {
          module.verbose('Forcing repaint event');
          var
            shape          = $sides[0] || document.createElement('div'),
            fakeAssignment = shape.offsetWidth
          ;
        },

        animate: function(propertyObject, callback) {
          module.verbose('Animating box with properties', propertyObject);
          callback = callback || function(event) {
            module.verbose('Executing animation callback');
            if(event !== undefined) {
              event.stopPropagation();
            }
            module.reset();
            module.set.active();
          };
          settings.beforeChange.call($nextSide[0]);
          if(module.get.transitionEvent()) {
            module.verbose('Starting CSS animation');
            $module
              .addClass(className.animating)
            ;
            $sides
              .css(propertyObject)
              .one(module.get.transitionEvent(), callback)
            ;
            module.set.duration(settings.duration);
            requestAnimationFrame(function() {
              $module
                .addClass(className.animating)
              ;
              $activeSide
                .addClass(className.hidden)
              ;
            });
          }
          else {
            callback();
          }
        },

        queue: function(method) {
          module.debug('Queueing animation of', method);
          $sides
            .one(module.get.transitionEvent(), function() {
              module.debug('Executing queued animation');
              setTimeout(function(){
                $module.shape(method);
              }, 0);
            })
          ;
        },

        reset: function() {
          module.verbose('Animating states reset');
          $module
            .removeClass(className.animating)
            .attr('style', '')
            .removeAttr('style')
          ;
          // removeAttr style does not consistently work in safari
          $sides
            .attr('style', '')
            .removeAttr('style')
          ;
          $side
            .attr('style', '')
            .removeAttr('style')
            .removeClass(className.hidden)
          ;
          $nextSide
            .removeClass(className.animating)
            .attr('style', '')
            .removeAttr('style')
          ;
        },

        is: {
          complete: function() {
            return ($side.filter('.' + className.active)[0] == $nextSide[0]);
          },
          animating: function() {
            return $module.hasClass(className.animating);
          }
        },

        set: {

          defaultSide: function() {
            $activeSide = $module.find('.' + settings.className.active);
            $nextSide   = ( $activeSide.next(selector.side).length > 0 )
              ? $activeSide.next(selector.side)
              : $module.find(selector.side).first()
            ;
            nextIndex = false;
            module.verbose('Active side set to', $activeSide);
            module.verbose('Next side set to', $nextSide);
          },

          duration: function(duration) {
            duration = duration || settings.duration;
            duration = (typeof duration == 'number')
              ? duration + 'ms'
              : duration
            ;
            module.verbose('Setting animation duration', duration);
            if(settings.duration || settings.duration === 0) {
              $sides.add($side)
                .css({
                  '-webkit-transition-duration': duration,
                  '-moz-transition-duration': duration,
                  '-ms-transition-duration': duration,
                  '-o-transition-duration': duration,
                  'transition-duration': duration
                })
              ;
            }
          },

          currentStageSize: function() {
            var
              $activeSide = $module.find('.' + settings.className.active),
              width       = $activeSide.outerWidth(true),
              height      = $activeSide.outerHeight(true)
            ;
            $module
              .css({
                width: width,
                height: height
              })
            ;
          },

          stageSize: function() {
            var
              $clone      = $module.clone().addClass(className.loading),
              $activeSide = $clone.find('.' + settings.className.active),
              $nextSide   = (nextIndex)
                ? $clone.find(selector.side).eq(nextIndex)
                : ( $activeSide.next(selector.side).length > 0 )
                  ? $activeSide.next(selector.side)
                  : $clone.find(selector.side).first(),
              newWidth    = (settings.width == 'next')
                ? $nextSide.outerWidth(true)
                : (settings.width == 'initial')
                  ? $module.width()
                  : settings.width,
              newHeight    = (settings.height == 'next')
                ? $nextSide.outerHeight(true)
                : (settings.height == 'initial')
                  ? $module.height()
                  : settings.height
            ;
            $activeSide.removeClass(className.active);
            $nextSide.addClass(className.active);
            $clone.insertAfter($module);
            $clone.remove();
            if(settings.width != 'auto') {
              $module.css('width', newWidth + settings.jitter);
              module.verbose('Specifying width during animation', newWidth);
            }
            if(settings.height != 'auto') {
              $module.css('height', newHeight + settings.jitter);
              module.verbose('Specifying height during animation', newHeight);
            }
          },

          nextSide: function(selector) {
            nextIndex = selector;
            $nextSide = $side.filter(selector);
            nextIndex = $side.index($nextSide);
            if($nextSide.length === 0) {
              module.set.defaultSide();
              module.error(error.side);
            }
            module.verbose('Next side manually set to', $nextSide);
          },

          active: function() {
            module.verbose('Setting new side to active', $nextSide);
            $side
              .removeClass(className.active)
            ;
            $nextSide
              .addClass(className.active)
            ;
            settings.onChange.call($nextSide[0]);
            module.set.defaultSide();
          }
        },

        flip: {

          up: function() {
            if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
              module.debug('Side already visible', $nextSide);
              return;
            }
            if( !module.is.animating()) {
              module.debug('Flipping up', $nextSide);
              var
                transform = module.get.transform.up()
              ;
              module.set.stageSize();
              module.stage.above();
              module.animate(transform);
            }
            else {
              module.queue('flip up');
            }
          },

          down: function() {
            if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
              module.debug('Side already visible', $nextSide);
              return;
            }
            if( !module.is.animating()) {
              module.debug('Flipping down', $nextSide);
              var
                transform = module.get.transform.down()
              ;
              module.set.stageSize();
              module.stage.below();
              module.animate(transform);
            }
            else {
              module.queue('flip down');
            }
          },

          left: function() {
            if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
              module.debug('Side already visible', $nextSide);
              return;
            }
            if( !module.is.animating()) {
              module.debug('Flipping left', $nextSide);
              var
                transform = module.get.transform.left()
              ;
              module.set.stageSize();
              module.stage.left();
              module.animate(transform);
            }
            else {
              module.queue('flip left');
            }
          },

          right: function() {
            if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
              module.debug('Side already visible', $nextSide);
              return;
            }
            if( !module.is.animating()) {
              module.debug('Flipping right', $nextSide);
              var
                transform = module.get.transform.right()
              ;
              module.set.stageSize();
              module.stage.right();
              module.animate(transform);
            }
            else {
              module.queue('flip right');
            }
          },

          over: function() {
            if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
              module.debug('Side already visible', $nextSide);
              return;
            }
            if( !module.is.animating()) {
              module.debug('Flipping over', $nextSide);
              module.set.stageSize();
              module.stage.behind();
              module.animate(module.get.transform.over() );
            }
            else {
              module.queue('flip over');
            }
          },

          back: function() {
            if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
              module.debug('Side already visible', $nextSide);
              return;
            }
            if( !module.is.animating()) {
              module.debug('Flipping back', $nextSide);
              module.set.stageSize();
              module.stage.behind();
              module.animate(module.get.transform.back() );
            }
            else {
              module.queue('flip back');
            }
          }

        },

        get: {

          transform: {
            up: function() {
              var
                translate = {
                  y: -(($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
                  z: -($activeSide.outerHeight(true) / 2)
                }
              ;
              return {
                transform: 'translateY(' + translate.y + 'px) translateZ('+ translate.z + 'px) rotateX(-90deg)'
              };
            },

            down: function() {
              var
                translate = {
                  y: -(($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
                  z: -($activeSide.outerHeight(true) / 2)
                }
              ;
              return {
                transform: 'translateY(' + translate.y + 'px) translateZ('+ translate.z + 'px) rotateX(90deg)'
              };
            },

            left: function() {
              var
                translate = {
                  x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2),
                  z : -($activeSide.outerWidth(true) / 2)
                }
              ;
              return {
                transform: 'translateX(' + translate.x + 'px) translateZ(' + translate.z + 'px) rotateY(90deg)'
              };
            },

            right: function() {
              var
                translate = {
                  x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2),
                  z : -($activeSide.outerWidth(true) / 2)
                }
              ;
              return {
                transform: 'translateX(' + translate.x + 'px) translateZ(' + translate.z + 'px) rotateY(-90deg)'
              };
            },

            over: function() {
              var
                translate = {
                  x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2)
                }
              ;
              return {
                transform: 'translateX(' + translate.x + 'px) rotateY(180deg)'
              };
            },

            back: function() {
              var
                translate = {
                  x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2)
                }
              ;
              return {
                transform: 'translateX(' + translate.x + 'px) rotateY(-180deg)'
              };
            }
          },

          transitionEvent: function() {
            var
              element     = document.createElement('element'),
              transitions = {
                'transition'       :'transitionend',
                'OTransition'      :'oTransitionEnd',
                'MozTransition'    :'transitionend',
                'WebkitTransition' :'webkitTransitionEnd'
              },
              transition
            ;
            for(transition in transitions){
              if( element.style[transition] !== undefined ){
                return transitions[transition];
              }
            }
          },

          nextSide: function() {
            return ( $activeSide.next(selector.side).length > 0 )
              ? $activeSide.next(selector.side)
              : $module.find(selector.side).first()
            ;
          }

        },

        stage: {

          above: function() {
            var
              box = {
                origin : (($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
                depth  : {
                  active : ($nextSide.outerHeight(true) / 2),
                  next   : ($activeSide.outerHeight(true) / 2)
                }
              }
            ;
            module.verbose('Setting the initial animation position as above', $nextSide, box);
            $sides
              .css({
                'transform' : 'translateZ(-' + box.depth.active + 'px)'
              })
            ;
            $activeSide
              .css({
                'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
              })
            ;
            $nextSide
              .addClass(className.animating)
              .css({
                'top'       : box.origin + 'px',
                'transform' : 'rotateX(90deg) translateZ(' + box.depth.next + 'px)'
              })
            ;
          },

          below: function() {
            var
              box = {
                origin : (($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
                depth  : {
                  active : ($nextSide.outerHeight(true) / 2),
                  next   : ($activeSide.outerHeight(true) / 2)
                }
              }
            ;
            module.verbose('Setting the initial animation position as below', $nextSide, box);
            $sides
              .css({
                'transform' : 'translateZ(-' + box.depth.active + 'px)'
              })
            ;
            $activeSide
              .css({
                'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
              })
            ;
            $nextSide
              .addClass(className.animating)
              .css({
                'top'       : box.origin + 'px',
                'transform' : 'rotateX(-90deg) translateZ(' + box.depth.next + 'px)'
              })
            ;
          },

          left: function() {
            var
              height = {
                active : $activeSide.outerWidth(true),
                next   : $nextSide.outerWidth(true)
              },
              box = {
                origin : ( ( height.active - height.next ) / 2),
                depth  : {
                  active : (height.next / 2),
                  next   : (height.active / 2)
                }
              }
            ;
            module.verbose('Setting the initial animation position as left', $nextSide, box);
            $sides
              .css({
                'transform' : 'translateZ(-' + box.depth.active + 'px)'
              })
            ;
            $activeSide
              .css({
                'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
              })
            ;
            $nextSide
              .addClass(className.animating)
              .css({
                'left'      : box.origin + 'px',
                'transform' : 'rotateY(-90deg) translateZ(' + box.depth.next + 'px)'
              })
            ;
          },

          right: function() {
            var
              height = {
                active : $activeSide.outerWidth(true),
                next   : $nextSide.outerWidth(true)
              },
              box = {
                origin : ( ( height.active - height.next ) / 2),
                depth  : {
                  active : (height.next / 2),
                  next   : (height.active / 2)
                }
              }
            ;
            module.verbose('Setting the initial animation position as left', $nextSide, box);
            $sides
              .css({
                'transform' : 'translateZ(-' + box.depth.active + 'px)'
              })
            ;
            $activeSide
              .css({
                'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
              })
            ;
            $nextSide
              .addClass(className.animating)
              .css({
                'left'      : box.origin + 'px',
                'transform' : 'rotateY(90deg) translateZ(' + box.depth.next + 'px)'
              })
            ;
          },

          behind: function() {
            var
              height = {
                active : $activeSide.outerWidth(true),
                next   : $nextSide.outerWidth(true)
              },
              box = {
                origin : ( ( height.active - height.next ) / 2),
                depth  : {
                  active : (height.next / 2),
                  next   : (height.active / 2)
                }
              }
            ;
            module.verbose('Setting the initial animation position as behind', $nextSide, box);
            $activeSide
              .css({
                'transform' : 'rotateY(0deg)'
              })
            ;
            $nextSide
              .addClass(className.animating)
              .css({
                'left'      : box.origin + 'px',
                'transform' : 'rotateY(-180deg)'
              })
            ;
          }
        },
        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.length > 1) {
              title += ' ' + '(' + $allModules.length + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.shape.settings = {

  // module info
  name : 'Shape',

  // hide all debug content
  silent     : false,

  // debug content outputted to console
  debug      : false,

  // verbose debug output
  verbose    : false,

  // fudge factor in pixels when swapping from 2d to 3d (can be useful to correct rounding errors)
  jitter     : 0,

  // performance data output
  performance: true,

  // event namespace
  namespace  : 'shape',

  // width during animation, can be set to 'auto', initial', 'next' or pixel amount
  width: 'initial',

  // height during animation, can be set to 'auto', 'initial', 'next' or pixel amount
  height: 'initial',

  // callback occurs on side change
  beforeChange : function() {},
  onChange     : function() {},

  // allow animation to same side
  allowRepeats: false,

  // animation duration
  duration   : false,

  // possible errors
  error: {
    side   : 'You tried to switch to a side that does not exist.',
    method : 'The method you called is not defined'
  },

  // classnames used
  className   : {
    animating : 'animating',
    hidden    : 'hidden',
    loading   : 'loading',
    active    : 'active'
  },

  // selectors used
  selector    : {
    sides : '.sides',
    side  : '.side'
  }

};


})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Sidebar
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.sidebar = function(parameters) {
  var
    $allModules     = $(this),
    $window         = $(window),
    $document       = $(document),
    $html           = $('html'),
    $head           = $('head'),

    moduleSelector  = $allModules.selector || '',

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),

    requestAnimationFrame = window.requestAnimationFrame
      || window.mozRequestAnimationFrame
      || window.webkitRequestAnimationFrame
      || window.msRequestAnimationFrame
      || function(callback) { setTimeout(callback, 0); },

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.sidebar.settings, parameters)
          : $.extend({}, $.fn.sidebar.settings),

        selector        = settings.selector,
        className       = settings.className,
        namespace       = settings.namespace,
        regExp          = settings.regExp,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $context        = $(settings.context),

        $sidebars       = $module.children(selector.sidebar),
        $fixed          = $context.children(selector.fixed),
        $pusher         = $context.children(selector.pusher),
        $style,

        element         = this,
        instance        = $module.data(moduleNamespace),

        elementNamespace,
        id,
        currentScroll,
        transitionEvent,

        module
      ;

      module      = {

        initialize: function() {
          module.debug('Initializing sidebar', parameters);

          module.create.id();

          transitionEvent = module.get.transitionEvent();

          // avoids locking rendering if initialized in onReady
          if(settings.delaySetup) {
            requestAnimationFrame(module.setup.layout);
          }
          else {
            module.setup.layout();
          }

          requestAnimationFrame(function() {
            module.setup.cache();
          });

          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        create: {
          id: function() {
            id = (Math.random().toString(16) + '000000000').substr(2,8);
            elementNamespace = '.' + id;
            module.verbose('Creating unique id for element', id);
          }
        },

        destroy: function() {
          module.verbose('Destroying previous module for', $module);
          $module
            .off(eventNamespace)
            .removeData(moduleNamespace)
          ;
          if(module.is.ios()) {
            module.remove.ios();
          }
          // bound by uuid
          $context.off(elementNamespace);
          $window.off(elementNamespace);
          $document.off(elementNamespace);
        },

        event: {
          clickaway: function(event) {
            var
              clickedInPusher = ($pusher.find(event.target).length > 0 || $pusher.is(event.target)),
              clickedContext  = ($context.is(event.target))
            ;
            if(clickedInPusher) {
              module.verbose('User clicked on dimmed page');
              module.hide();
            }
            if(clickedContext) {
              module.verbose('User clicked on dimmable context (scaled out page)');
              module.hide();
            }
          },
          touch: function(event) {
            //event.stopPropagation();
          },
          containScroll: function(event) {
            if(element.scrollTop <= 0)  {
              element.scrollTop = 1;
            }
            if((element.scrollTop + element.offsetHeight) >= element.scrollHeight) {
              element.scrollTop = element.scrollHeight - element.offsetHeight - 1;
            }
          },
          scroll: function(event) {
            if( $(event.target).closest(selector.sidebar).length === 0 ) {
              event.preventDefault();
            }
          }
        },

        bind: {
          clickaway: function() {
            module.verbose('Adding clickaway events to context', $context);
            if(settings.closable) {
              $context
                .on('click'    + elementNamespace, module.event.clickaway)
                .on('touchend' + elementNamespace, module.event.clickaway)
              ;
            }
          },
          scrollLock: function() {
            if(settings.scrollLock) {
              module.debug('Disabling page scroll');
              $window
                .on('DOMMouseScroll' + elementNamespace, module.event.scroll)
              ;
            }
            module.verbose('Adding events to contain sidebar scroll');
            $document
              .on('touchmove' + elementNamespace, module.event.touch)
            ;
            $module
              .on('scroll' + eventNamespace, module.event.containScroll)
            ;
          }
        },
        unbind: {
          clickaway: function() {
            module.verbose('Removing clickaway events from context', $context);
            $context.off(elementNamespace);
          },
          scrollLock: function() {
            module.verbose('Removing scroll lock from page');
            $document.off(elementNamespace);
            $window.off(elementNamespace);
            $module.off('scroll' + eventNamespace);
          }
        },

        add: {
          inlineCSS: function() {
            var
              width     = module.cache.width  || $module.outerWidth(),
              height    = module.cache.height || $module.outerHeight(),
              isRTL     = module.is.rtl(),
              direction = module.get.direction(),
              distance  = {
                left   : width,
                right  : -width,
                top    : height,
                bottom : -height
              },
              style
            ;

            if(isRTL){
              module.verbose('RTL detected, flipping widths');
              distance.left = -width;
              distance.right = width;
            }

            style  = '<style>';

            if(direction === 'left' || direction === 'right') {
              module.debug('Adding CSS rules for animation distance', width);
              style  += ''
                + ' .ui.visible.' + direction + '.sidebar ~ .fixed,'
                + ' .ui.visible.' + direction + '.sidebar ~ .pusher {'
                + '   -webkit-transform: translate3d('+ distance[direction] + 'px, 0, 0);'
                + '           transform: translate3d('+ distance[direction] + 'px, 0, 0);'
                + ' }'
              ;
            }
            else if(direction === 'top' || direction == 'bottom') {
              style  += ''
                + ' .ui.visible.' + direction + '.sidebar ~ .fixed,'
                + ' .ui.visible.' + direction + '.sidebar ~ .pusher {'
                + '   -webkit-transform: translate3d(0, ' + distance[direction] + 'px, 0);'
                + '           transform: translate3d(0, ' + distance[direction] + 'px, 0);'
                + ' }'
              ;
            }

            /* IE is only browser not to create context with transforms */
            /* https://www.w3.org/Bugs/Public/show_bug.cgi?id=16328 */
            if( module.is.ie() ) {
              if(direction === 'left' || direction === 'right') {
                module.debug('Adding CSS rules for animation distance', width);
                style  += ''
                  + ' body.pushable > .ui.visible.' + direction + '.sidebar ~ .pusher:after {'
                  + '   -webkit-transform: translate3d('+ distance[direction] + 'px, 0, 0);'
                  + '           transform: translate3d('+ distance[direction] + 'px, 0, 0);'
                  + ' }'
                ;
              }
              else if(direction === 'top' || direction == 'bottom') {
                style  += ''
                  + ' body.pushable > .ui.visible.' + direction + '.sidebar ~ .pusher:after {'
                  + '   -webkit-transform: translate3d(0, ' + distance[direction] + 'px, 0);'
                  + '           transform: translate3d(0, ' + distance[direction] + 'px, 0);'
                  + ' }'
                ;
              }
              /* opposite sides visible forces content overlay */
              style += ''
                + ' body.pushable > .ui.visible.left.sidebar ~ .ui.visible.right.sidebar ~ .pusher:after,'
                + ' body.pushable > .ui.visible.right.sidebar ~ .ui.visible.left.sidebar ~ .pusher:after {'
                + '   -webkit-transform: translate3d(0px, 0, 0);'
                + '           transform: translate3d(0px, 0, 0);'
                + ' }'
              ;
            }
            style += '</style>';
            $style = $(style)
              .appendTo($head)
            ;
            module.debug('Adding sizing css to head', $style);
          }
        },

        refresh: function() {
          module.verbose('Refreshing selector cache');
          $context  = $(settings.context);
          $sidebars = $context.children(selector.sidebar);
          $pusher   = $context.children(selector.pusher);
          $fixed    = $context.children(selector.fixed);
          module.clear.cache();
        },

        refreshSidebars: function() {
          module.verbose('Refreshing other sidebars');
          $sidebars = $context.children(selector.sidebar);
        },

        repaint: function() {
          module.verbose('Forcing repaint event');
          element.style.display = 'none';
          var ignored = element.offsetHeight;
          element.scrollTop = element.scrollTop;
          element.style.display = '';
        },

        setup: {
          cache: function() {
            module.cache = {
              width  : $module.outerWidth(),
              height : $module.outerHeight(),
              rtl    : ($module.css('direction') == 'rtl')
            };
          },
          layout: function() {
            if( $context.children(selector.pusher).length === 0 ) {
              module.debug('Adding wrapper element for sidebar');
              module.error(error.pusher);
              $pusher = $('<div class="pusher" />');
              $context
                .children()
                  .not(selector.omitted)
                  .not($sidebars)
                  .wrapAll($pusher)
              ;
              module.refresh();
            }
            if($module.nextAll(selector.pusher).length === 0 || $module.nextAll(selector.pusher)[0] !== $pusher[0]) {
              module.debug('Moved sidebar to correct parent element');
              module.error(error.movedSidebar, element);
              $module.detach().prependTo($context);
              module.refresh();
            }
            module.clear.cache();
            module.set.pushable();
            module.set.direction();
          }
        },

        attachEvents: function(selector, event) {
          var
            $toggle = $(selector)
          ;
          event = $.isFunction(module[event])
            ? module[event]
            : module.toggle
          ;
          if($toggle.length > 0) {
            module.debug('Attaching sidebar events to element', selector, event);
            $toggle
              .on('click' + eventNamespace, event)
            ;
          }
          else {
            module.error(error.notFound, selector);
          }
        },

        show: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if(module.is.hidden()) {
            module.refreshSidebars();
            if(settings.overlay)  {
              module.error(error.overlay);
              settings.transition = 'overlay';
            }
            module.refresh();
            if(module.othersActive()) {
              module.debug('Other sidebars currently visible');
              if(settings.exclusive) {
                // if not overlay queue animation after hide
                if(settings.transition != 'overlay') {
                  module.hideOthers(module.show);
                  return;
                }
                else {
                  module.hideOthers();
                }
              }
              else {
                settings.transition = 'overlay';
              }
            }
            module.pushPage(function() {
              callback.call(element);
              settings.onShow.call(element);
            });
            settings.onChange.call(element);
            settings.onVisible.call(element);
          }
          else {
            module.debug('Sidebar is already visible');
          }
        },

        hide: function(callback) {
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if(module.is.visible() || module.is.animating()) {
            module.debug('Hiding sidebar', callback);
            module.refreshSidebars();
            module.pullPage(function() {
              callback.call(element);
              settings.onHidden.call(element);
            });
            settings.onChange.call(element);
            settings.onHide.call(element);
          }
        },

        othersAnimating: function() {
          return ($sidebars.not($module).filter('.' + className.animating).length > 0);
        },
        othersVisible: function() {
          return ($sidebars.not($module).filter('.' + className.visible).length > 0);
        },
        othersActive: function() {
          return(module.othersVisible() || module.othersAnimating());
        },

        hideOthers: function(callback) {
          var
            $otherSidebars = $sidebars.not($module).filter('.' + className.visible),
            sidebarCount   = $otherSidebars.length,
            callbackCount  = 0
          ;
          callback = callback || function(){};
          $otherSidebars
            .sidebar('hide', function() {
              callbackCount++;
              if(callbackCount == sidebarCount) {
                callback();
              }
            })
          ;
        },

        toggle: function() {
          module.verbose('Determining toggled direction');
          if(module.is.hidden()) {
            module.show();
          }
          else {
            module.hide();
          }
        },

        pushPage: function(callback) {
          var
            transition = module.get.transition(),
            $transition = (transition === 'overlay' || module.othersActive())
              ? $module
              : $pusher,
            animate,
            dim,
            transitionEnd
          ;
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          if(settings.transition == 'scale down') {
            module.scrollToTop();
          }
          module.set.transition(transition);
          module.repaint();
          animate = function() {
            module.bind.clickaway();
            module.add.inlineCSS();
            module.set.animating();
            module.set.visible();
          };
          dim = function() {
            module.set.dimmed();
          };
          transitionEnd = function(event) {
            if( event.target == $transition[0] ) {
              $transition.off(transitionEvent + elementNamespace, transitionEnd);
              module.remove.animating();
              module.bind.scrollLock();
              callback.call(element);
            }
          };
          $transition.off(transitionEvent + elementNamespace);
          $transition.on(transitionEvent + elementNamespace, transitionEnd);
          requestAnimationFrame(animate);
          if(settings.dimPage && !module.othersVisible()) {
            requestAnimationFrame(dim);
          }
        },

        pullPage: function(callback) {
          var
            transition = module.get.transition(),
            $transition = (transition == 'overlay' || module.othersActive())
              ? $module
              : $pusher,
            animate,
            transitionEnd
          ;
          callback = $.isFunction(callback)
            ? callback
            : function(){}
          ;
          module.verbose('Removing context push state', module.get.direction());

          module.unbind.clickaway();
          module.unbind.scrollLock();

          animate = function() {
            module.set.transition(transition);
            module.set.animating();
            module.remove.visible();
            if(settings.dimPage && !module.othersVisible()) {
              $pusher.removeClass(className.dimmed);
            }
          };
          transitionEnd = function(event) {
            if( event.target == $transition[0] ) {
              $transition.off(transitionEvent + elementNamespace, transitionEnd);
              module.remove.animating();
              module.remove.transition();
              module.remove.inlineCSS();
              if(transition == 'scale down' || (settings.returnScroll && module.is.mobile()) ) {
                module.scrollBack();
              }
              callback.call(element);
            }
          };
          $transition.off(transitionEvent + elementNamespace);
          $transition.on(transitionEvent + elementNamespace, transitionEnd);
          requestAnimationFrame(animate);
        },

        scrollToTop: function() {
          module.verbose('Scrolling to top of page to avoid animation issues');
          currentScroll = $(window).scrollTop();
          $module.scrollTop(0);
          window.scrollTo(0, 0);
        },

        scrollBack: function() {
          module.verbose('Scrolling back to original page position');
          window.scrollTo(0, currentScroll);
        },

        clear: {
          cache: function() {
            module.verbose('Clearing cached dimensions');
            module.cache = {};
          }
        },

        set: {

          // ios only (scroll on html not document). This prevent auto-resize canvas/scroll in ios
          // (This is no longer necessary in latest iOS)
          ios: function() {
            $html.addClass(className.ios);
          },

          // container
          pushed: function() {
            $context.addClass(className.pushed);
          },
          pushable: function() {
            $context.addClass(className.pushable);
          },

          // pusher
          dimmed: function() {
            $pusher.addClass(className.dimmed);
          },

          // sidebar
          active: function() {
            $module.addClass(className.active);
          },
          animating: function() {
            $module.addClass(className.animating);
          },
          transition: function(transition) {
            transition = transition || module.get.transition();
            $module.addClass(transition);
          },
          direction: function(direction) {
            direction = direction || module.get.direction();
            $module.addClass(className[direction]);
          },
          visible: function() {
            $module.addClass(className.visible);
          },
          overlay: function() {
            $module.addClass(className.overlay);
          }
        },
        remove: {

          inlineCSS: function() {
            module.debug('Removing inline css styles', $style);
            if($style && $style.length > 0) {
              $style.remove();
            }
          },

          // ios scroll on html not document
          ios: function() {
            $html.removeClass(className.ios);
          },

          // context
          pushed: function() {
            $context.removeClass(className.pushed);
          },
          pushable: function() {
            $context.removeClass(className.pushable);
          },

          // sidebar
          active: function() {
            $module.removeClass(className.active);
          },
          animating: function() {
            $module.removeClass(className.animating);
          },
          transition: function(transition) {
            transition = transition || module.get.transition();
            $module.removeClass(transition);
          },
          direction: function(direction) {
            direction = direction || module.get.direction();
            $module.removeClass(className[direction]);
          },
          visible: function() {
            $module.removeClass(className.visible);
          },
          overlay: function() {
            $module.removeClass(className.overlay);
          }
        },

        get: {
          direction: function() {
            if($module.hasClass(className.top)) {
              return className.top;
            }
            else if($module.hasClass(className.right)) {
              return className.right;
            }
            else if($module.hasClass(className.bottom)) {
              return className.bottom;
            }
            return className.left;
          },
          transition: function() {
            var
              direction = module.get.direction(),
              transition
            ;
            transition = ( module.is.mobile() )
              ? (settings.mobileTransition == 'auto')
                ? settings.defaultTransition.mobile[direction]
                : settings.mobileTransition
              : (settings.transition == 'auto')
                ? settings.defaultTransition.computer[direction]
                : settings.transition
            ;
            module.verbose('Determined transition', transition);
            return transition;
          },
          transitionEvent: function() {
            var
              element     = document.createElement('element'),
              transitions = {
                'transition'       :'transitionend',
                'OTransition'      :'oTransitionEnd',
                'MozTransition'    :'transitionend',
                'WebkitTransition' :'webkitTransitionEnd'
              },
              transition
            ;
            for(transition in transitions){
              if( element.style[transition] !== undefined ){
                return transitions[transition];
              }
            }
          }
        },

        is: {

          ie: function() {
            var
              isIE11 = (!(window.ActiveXObject) && 'ActiveXObject' in window),
              isIE   = ('ActiveXObject' in window)
            ;
            return (isIE11 || isIE);
          },

          ios: function() {
            var
              userAgent      = navigator.userAgent,
              isIOS          = userAgent.match(regExp.ios),
              isMobileChrome = userAgent.match(regExp.mobileChrome)
            ;
            if(isIOS && !isMobileChrome) {
              module.verbose('Browser was found to be iOS', userAgent);
              return true;
            }
            else {
              return false;
            }
          },
          mobile: function() {
            var
              userAgent    = navigator.userAgent,
              isMobile     = userAgent.match(regExp.mobile)
            ;
            if(isMobile) {
              module.verbose('Browser was found to be mobile', userAgent);
              return true;
            }
            else {
              module.verbose('Browser is not mobile, using regular transition', userAgent);
              return false;
            }
          },
          hidden: function() {
            return !module.is.visible();
          },
          visible: function() {
            return $module.hasClass(className.visible);
          },
          // alias
          open: function() {
            return module.is.visible();
          },
          closed: function() {
            return module.is.hidden();
          },
          vertical: function() {
            return $module.hasClass(className.top);
          },
          animating: function() {
            return $context.hasClass(className.animating);
          },
          rtl: function () {
            if(module.cache.rtl === undefined) {
              module.cache.rtl = ($module.css('direction') == 'rtl');
            }
            return module.cache.rtl;
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      }
    ;

    if(methodInvoked) {
      if(instance === undefined) {
        module.initialize();
      }
      module.invoke(query);
    }
    else {
      if(instance !== undefined) {
        module.invoke('destroy');
      }
      module.initialize();
    }
  });

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.sidebar.settings = {

  name              : 'Sidebar',
  namespace         : 'sidebar',

  silent            : false,
  debug             : false,
  verbose           : false,
  performance       : true,

  transition        : 'auto',
  mobileTransition  : 'auto',

  defaultTransition : {
    computer: {
      left   : 'uncover',
      right  : 'uncover',
      top    : 'overlay',
      bottom : 'overlay'
    },
    mobile: {
      left   : 'uncover',
      right  : 'uncover',
      top    : 'overlay',
      bottom : 'overlay'
    }
  },

  context           : 'body',
  exclusive         : false,
  closable          : true,
  dimPage           : true,
  scrollLock        : false,
  returnScroll      : false,
  delaySetup        : false,

  duration          : 500,

  onChange          : function(){},
  onShow            : function(){},
  onHide            : function(){},

  onHidden          : function(){},
  onVisible         : function(){},

  className         : {
    active    : 'active',
    animating : 'animating',
    dimmed    : 'dimmed',
    ios       : 'ios',
    pushable  : 'pushable',
    pushed    : 'pushed',
    right     : 'right',
    top       : 'top',
    left      : 'left',
    bottom    : 'bottom',
    visible   : 'visible'
  },

  selector: {
    fixed   : '.fixed',
    omitted : 'script, link, style, .ui.modal, .ui.dimmer, .ui.nag, .ui.fixed',
    pusher  : '.pusher',
    sidebar : '.ui.sidebar'
  },

  regExp: {
    ios          : /(iPad|iPhone|iPod)/g,
    mobileChrome : /(CriOS)/g,
    mobile       : /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/g
  },

  error   : {
    method       : 'The method you called is not defined.',
    pusher       : 'Had to add pusher element. For optimal performance make sure body content is inside a pusher element',
    movedSidebar : 'Had to move sidebar. For optimal performance make sure sidebar and pusher are direct children of your body tag',
    overlay      : 'The overlay setting is no longer supported, use animation: overlay',
    notFound     : 'There were no elements that matched the specified selector'
  }

};


})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Sticky
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.sticky = function(parameters) {
  var
    $allModules    = $(this),
    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),
    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings              = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.sticky.settings, parameters)
          : $.extend({}, $.fn.sticky.settings),

        className             = settings.className,
        namespace             = settings.namespace,
        error                 = settings.error,

        eventNamespace        = '.' + namespace,
        moduleNamespace       = 'module-' + namespace,

        $module               = $(this),
        $window               = $(window),
        $scroll               = $(settings.scrollContext),
        $container,
        $context,

        selector              = $module.selector || '',
        instance              = $module.data(moduleNamespace),

        requestAnimationFrame = window.requestAnimationFrame
          || window.mozRequestAnimationFrame
          || window.webkitRequestAnimationFrame
          || window.msRequestAnimationFrame
          || function(callback) { setTimeout(callback, 0); },

        element         = this,

        documentObserver,
        observer,
        module
      ;

      module      = {

        initialize: function() {

          module.determineContainer();
          module.determineContext();
          module.verbose('Initializing sticky', settings, $container);

          module.save.positions();
          module.checkErrors();
          module.bind.events();

          if(settings.observeChanges) {
            module.observeChanges();
          }
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous instance');
          module.reset();
          if(documentObserver) {
            documentObserver.disconnect();
          }
          if(observer) {
            observer.disconnect();
          }
          $window
            .off('load' + eventNamespace, module.event.load)
            .off('resize' + eventNamespace, module.event.resize)
          ;
          $scroll
            .off('scrollchange' + eventNamespace, module.event.scrollchange)
          ;
          $module.removeData(moduleNamespace);
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            documentObserver = new MutationObserver(module.event.documentChanged);
            observer         = new MutationObserver(module.event.changed);
            documentObserver.observe(document, {
              childList : true,
              subtree   : true
            });
            observer.observe(element, {
              childList : true,
              subtree   : true
            });
            observer.observe($context[0], {
              childList : true,
              subtree   : true
            });
            module.debug('Setting up mutation observer', observer);
          }
        },

        determineContainer: function() {
          if(settings.container) {
            $container = $(settings.container);
          }
          else {
            $container = $module.offsetParent();
          }
        },

        determineContext: function() {
          if(settings.context) {
            $context = $(settings.context);
          }
          else {
            $context = $container;
          }
          if($context.length === 0) {
            module.error(error.invalidContext, settings.context, $module);
            return;
          }
        },

        checkErrors: function() {
          if( module.is.hidden() ) {
            module.error(error.visible, $module);
          }
          if(module.cache.element.height > module.cache.context.height) {
            module.reset();
            module.error(error.elementSize, $module);
            return;
          }
        },

        bind: {
          events: function() {
            $window
              .on('load' + eventNamespace, module.event.load)
              .on('resize' + eventNamespace, module.event.resize)
            ;
            // pub/sub pattern
            $scroll
              .off('scroll' + eventNamespace)
              .on('scroll' + eventNamespace, module.event.scroll)
              .on('scrollchange' + eventNamespace, module.event.scrollchange)
            ;
          }
        },

        event: {
          changed: function(mutations) {
            clearTimeout(module.timer);
            module.timer = setTimeout(function() {
              module.verbose('DOM tree modified, updating sticky menu', mutations);
              module.refresh();
            }, 100);
          },
          documentChanged: function(mutations) {
            [].forEach.call(mutations, function(mutation) {
              if(mutation.removedNodes) {
                [].forEach.call(mutation.removedNodes, function(node) {
                  if(node == element || $(node).find(element).length > 0) {
                    module.debug('Element removed from DOM, tearing down events');
                    module.destroy();
                  }
                });
              }
            });
          },
          load: function() {
            module.verbose('Page contents finished loading');
            requestAnimationFrame(module.refresh);
          },
          resize: function() {
            module.verbose('Window resized');
            requestAnimationFrame(module.refresh);
          },
          scroll: function() {
            requestAnimationFrame(function() {
              $scroll.triggerHandler('scrollchange' + eventNamespace, $scroll.scrollTop() );
            });
          },
          scrollchange: function(event, scrollPosition) {
            module.stick(scrollPosition);
            settings.onScroll.call(element);
          }
        },

        refresh: function(hardRefresh) {
          module.reset();
          if(!settings.context) {
            module.determineContext();
          }
          if(hardRefresh) {
            module.determineContainer();
          }
          module.save.positions();
          module.stick();
          settings.onReposition.call(element);
        },

        supports: {
          sticky: function() {
            var
              $element = $('<div/>'),
              element = $element[0]
            ;
            $element.addClass(className.supported);
            return($element.css('position').match('sticky'));
          }
        },

        save: {
          lastScroll: function(scroll) {
            module.lastScroll = scroll;
          },
          elementScroll: function(scroll) {
            module.elementScroll = scroll;
          },
          positions: function() {
            var
              scrollContext = {
                height : $scroll.height()
              },
              element = {
                margin: {
                  top    : parseInt($module.css('margin-top'), 10),
                  bottom : parseInt($module.css('margin-bottom'), 10),
                },
                offset : $module.offset(),
                width  : $module.outerWidth(),
                height : $module.outerHeight()
              },
              context = {
                offset : $context.offset(),
                height : $context.outerHeight()
              },
              container = {
                height: $container.outerHeight()
              }
            ;
            if( !module.is.standardScroll() ) {
              module.debug('Non-standard scroll. Removing scroll offset from element offset');

              scrollContext.top  = $scroll.scrollTop();
              scrollContext.left = $scroll.scrollLeft();

              element.offset.top  += scrollContext.top;
              context.offset.top  += scrollContext.top;
              element.offset.left += scrollContext.left;
              context.offset.left += scrollContext.left;
            }
            module.cache = {
              fits          : ( (element.height + settings.offset) <= scrollContext.height),
              sameHeight    : (element.height == context.height),
              scrollContext : {
                height : scrollContext.height
              },
              element: {
                margin : element.margin,
                top    : element.offset.top - element.margin.top,
                left   : element.offset.left,
                width  : element.width,
                height : element.height,
                bottom : element.offset.top + element.height
              },
              context: {
                top           : context.offset.top,
                height        : context.height,
                bottom        : context.offset.top + context.height
              }
            };
            module.set.containerSize();

            module.stick();
            module.debug('Caching element positions', module.cache);
          }
        },

        get: {
          direction: function(scroll) {
            var
              direction = 'down'
            ;
            scroll = scroll || $scroll.scrollTop();
            if(module.lastScroll !== undefined) {
              if(module.lastScroll < scroll) {
                direction = 'down';
              }
              else if(module.lastScroll > scroll) {
                direction = 'up';
              }
            }
            return direction;
          },
          scrollChange: function(scroll) {
            scroll = scroll || $scroll.scrollTop();
            return (module.lastScroll)
              ? (scroll - module.lastScroll)
              : 0
            ;
          },
          currentElementScroll: function() {
            if(module.elementScroll) {
              return module.elementScroll;
            }
            return ( module.is.top() )
              ? Math.abs(parseInt($module.css('top'), 10))    || 0
              : Math.abs(parseInt($module.css('bottom'), 10)) || 0
            ;
          },

          elementScroll: function(scroll) {
            scroll = scroll || $scroll.scrollTop();
            var
              element        = module.cache.element,
              scrollContext  = module.cache.scrollContext,
              delta          = module.get.scrollChange(scroll),
              maxScroll      = (element.height - scrollContext.height + settings.offset),
              elementScroll  = module.get.currentElementScroll(),
              possibleScroll = (elementScroll + delta)
            ;
            if(module.cache.fits || possibleScroll < 0) {
              elementScroll = 0;
            }
            else if(possibleScroll > maxScroll ) {
              elementScroll = maxScroll;
            }
            else {
              elementScroll = possibleScroll;
            }
            return elementScroll;
          }
        },

        remove: {
          lastScroll: function() {
            delete module.lastScroll;
          },
          elementScroll: function(scroll) {
            delete module.elementScroll;
          },
          minimumSize: function() {
            $container
              .css('min-height', '')
            ;
          },
          offset: function() {
            $module.css('margin-top', '');
          }
        },

        set: {
          offset: function() {
            module.verbose('Setting offset on element', settings.offset);
            $module
              .css('margin-top', settings.offset)
            ;
          },
          containerSize: function() {
            var
              tagName = $container.get(0).tagName
            ;
            if(tagName === 'HTML' || tagName == 'body') {
              // this can trigger for too many reasons
              //module.error(error.container, tagName, $module);
              module.determineContainer();
            }
            else {
              if( Math.abs($container.outerHeight() - module.cache.context.height) > settings.jitter) {
                module.debug('Context has padding, specifying exact height for container', module.cache.context.height);
                $container.css({
                  height: module.cache.context.height
                });
              }
            }
          },
          minimumSize: function() {
            var
              element   = module.cache.element
            ;
            $container
              .css('min-height', element.height)
            ;
          },
          scroll: function(scroll) {
            module.debug('Setting scroll on element', scroll);
            if(module.elementScroll == scroll) {
              return;
            }
            if( module.is.top() ) {
              $module
                .css('bottom', '')
                .css('top', -scroll)
              ;
            }
            if( module.is.bottom() ) {
              $module
                .css('top', '')
                .css('bottom', scroll)
              ;
            }
          },
          size: function() {
            if(module.cache.element.height !== 0 && module.cache.element.width !== 0) {
              element.style.setProperty('width',  module.cache.element.width  + 'px', 'important');
              element.style.setProperty('height', module.cache.element.height + 'px', 'important');
            }
          }
        },

        is: {
          standardScroll: function() {
            return ($scroll[0] == window);
          },
          top: function() {
            return $module.hasClass(className.top);
          },
          bottom: function() {
            return $module.hasClass(className.bottom);
          },
          initialPosition: function() {
            return (!module.is.fixed() && !module.is.bound());
          },
          hidden: function() {
            return (!$module.is(':visible'));
          },
          bound: function() {
            return $module.hasClass(className.bound);
          },
          fixed: function() {
            return $module.hasClass(className.fixed);
          }
        },

        stick: function(scroll) {
          var
            cachedPosition = scroll || $scroll.scrollTop(),
            cache          = module.cache,
            fits           = cache.fits,
            sameHeight     = cache.sameHeight,
            element        = cache.element,
            scrollContext  = cache.scrollContext,
            context        = cache.context,
            offset         = (module.is.bottom() && settings.pushing)
              ? settings.bottomOffset
              : settings.offset,
            scroll         = {
              top    : cachedPosition + offset,
              bottom : cachedPosition + offset + scrollContext.height
            },
            direction      = module.get.direction(scroll.top),
            elementScroll  = (fits)
              ? 0
              : module.get.elementScroll(scroll.top),

            // shorthand
            doesntFit      = !fits,
            elementVisible = (element.height !== 0)
          ;
          if(elementVisible && !sameHeight) {

            if( module.is.initialPosition() ) {
              if(scroll.top >= context.bottom) {
                module.debug('Initial element position is bottom of container');
                module.bindBottom();
              }
              else if(scroll.top > element.top) {
                if( (element.height + scroll.top - elementScroll) >= context.bottom ) {
                  module.debug('Initial element position is bottom of container');
                  module.bindBottom();
                }
                else {
                  module.debug('Initial element position is fixed');
                  module.fixTop();
                }
              }

            }
            else if( module.is.fixed() ) {

              // currently fixed top
              if( module.is.top() ) {
                if( scroll.top <= element.top ) {
                  module.debug('Fixed element reached top of container');
                  module.setInitialPosition();
                }
                else if( (element.height + scroll.top - elementScroll) >= context.bottom ) {
                  module.debug('Fixed element reached bottom of container');
                  module.bindBottom();
                }
                // scroll element if larger than screen
                else if(doesntFit) {
                  module.set.scroll(elementScroll);
                  module.save.lastScroll(scroll.top);
                  module.save.elementScroll(elementScroll);
                }
              }

              // currently fixed bottom
              else if(module.is.bottom() ) {

                // top edge
                if( (scroll.bottom - element.height) <= element.top) {
                  module.debug('Bottom fixed rail has reached top of container');
                  module.setInitialPosition();
                }
                // bottom edge
                else if(scroll.bottom >= context.bottom) {
                  module.debug('Bottom fixed rail has reached bottom of container');
                  module.bindBottom();
                }
                // scroll element if larger than screen
                else if(doesntFit) {
                  module.set.scroll(elementScroll);
                  module.save.lastScroll(scroll.top);
                  module.save.elementScroll(elementScroll);
                }

              }
            }
            else if( module.is.bottom() ) {
              if( scroll.top <= element.top ) {
                module.debug('Jumped from bottom fixed to top fixed, most likely used home/end button');
                module.setInitialPosition();
              }
              else {
                if(settings.pushing) {
                  if(module.is.bound() && scroll.bottom <= context.bottom ) {
                    module.debug('Fixing bottom attached element to bottom of browser.');
                    module.fixBottom();
                  }
                }
                else {
                  if(module.is.bound() && (scroll.top <= context.bottom - element.height) ) {
                    module.debug('Fixing bottom attached element to top of browser.');
                    module.fixTop();
                  }
                }
              }
            }
          }
        },

        bindTop: function() {
          module.debug('Binding element to top of parent container');
          module.remove.offset();
          $module
            .css({
              left         : '',
              top          : '',
              marginBottom : ''
            })
            .removeClass(className.fixed)
            .removeClass(className.bottom)
            .addClass(className.bound)
            .addClass(className.top)
          ;
          settings.onTop.call(element);
          settings.onUnstick.call(element);
        },
        bindBottom: function() {
          module.debug('Binding element to bottom of parent container');
          module.remove.offset();
          $module
            .css({
              left         : '',
              top          : ''
            })
            .removeClass(className.fixed)
            .removeClass(className.top)
            .addClass(className.bound)
            .addClass(className.bottom)
          ;
          settings.onBottom.call(element);
          settings.onUnstick.call(element);
        },

        setInitialPosition: function() {
          module.debug('Returning to initial position');
          module.unfix();
          module.unbind();
        },


        fixTop: function() {
          module.debug('Fixing element to top of page');
          if(settings.setSize) {
            module.set.size();
          }
          module.set.minimumSize();
          module.set.offset();
          $module
            .css({
              left         : module.cache.element.left,
              bottom       : '',
              marginBottom : ''
            })
            .removeClass(className.bound)
            .removeClass(className.bottom)
            .addClass(className.fixed)
            .addClass(className.top)
          ;
          settings.onStick.call(element);
        },

        fixBottom: function() {
          module.debug('Sticking element to bottom of page');
          if(settings.setSize) {
            module.set.size();
          }
          module.set.minimumSize();
          module.set.offset();
          $module
            .css({
              left         : module.cache.element.left,
              bottom       : '',
              marginBottom : ''
            })
            .removeClass(className.bound)
            .removeClass(className.top)
            .addClass(className.fixed)
            .addClass(className.bottom)
          ;
          settings.onStick.call(element);
        },

        unbind: function() {
          if( module.is.bound() ) {
            module.debug('Removing container bound position on element');
            module.remove.offset();
            $module
              .removeClass(className.bound)
              .removeClass(className.top)
              .removeClass(className.bottom)
            ;
          }
        },

        unfix: function() {
          if( module.is.fixed() ) {
            module.debug('Removing fixed position on element');
            module.remove.minimumSize();
            module.remove.offset();
            $module
              .removeClass(className.fixed)
              .removeClass(className.top)
              .removeClass(className.bottom)
            ;
            settings.onUnstick.call(element);
          }
        },

        reset: function() {
          module.debug('Resetting elements position');
          module.unbind();
          module.unfix();
          module.resetCSS();
          module.remove.offset();
          module.remove.lastScroll();
        },

        resetCSS: function() {
          $module
            .css({
              width  : '',
              height : ''
            })
          ;
          $container
            .css({
              height: ''
            })
          ;
        },

        setting: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 0);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.sticky.settings = {

  name           : 'Sticky',
  namespace      : 'sticky',

  silent         : false,
  debug          : false,
  verbose        : true,
  performance    : true,

  // whether to stick in the opposite direction on scroll up
  pushing        : false,

  context        : false,
  container      : false,

  // Context to watch scroll events
  scrollContext  : window,

  // Offset to adjust scroll
  offset         : 0,

  // Offset to adjust scroll when attached to bottom of screen
  bottomOffset   : 0,

  // will only set container height if difference between context and container is larger than this number
  jitter         : 5,

  // set width of sticky element when it is fixed to page (used to make sure 100% width is maintained if no fixed size set)
  setSize        : true,

  // Whether to automatically observe changes with Mutation Observers
  observeChanges : false,

  // Called when position is recalculated
  onReposition   : function(){},

  // Called on each scroll
  onScroll       : function(){},

  // Called when element is stuck to viewport
  onStick        : function(){},

  // Called when element is unstuck from viewport
  onUnstick      : function(){},

  // Called when element reaches top of context
  onTop          : function(){},

  // Called when element reaches bottom of context
  onBottom       : function(){},

  error         : {
    container      : 'Sticky element must be inside a relative container',
    visible        : 'Element is hidden, you must call refresh after element becomes visible. Use silent setting to surpress this warning in production.',
    method         : 'The method you called is not defined.',
    invalidContext : 'Context specified does not exist',
    elementSize    : 'Sticky element is larger than its container, cannot create sticky.'
  },

  className : {
    bound     : 'bound',
    fixed     : 'fixed',
    supported : 'native',
    top       : 'top',
    bottom    : 'bottom'
  }

};

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Tab
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.tab = function(parameters) {

  var
    // use window context if none specified
    $allModules     = $.isFunction(this)
        ? $(window)
        : $(this),

    moduleSelector  = $allModules.selector || '',
    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),

    initializedHistory = false,
    returnedValue
  ;

  $allModules
    .each(function() {
      var

        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.tab.settings, parameters)
          : $.extend({}, $.fn.tab.settings),

        className       = settings.className,
        metadata        = settings.metadata,
        selector        = settings.selector,
        error           = settings.error,

        eventNamespace  = '.' + settings.namespace,
        moduleNamespace = 'module-' + settings.namespace,

        $module         = $(this),
        $context,
        $tabs,

        cache           = {},
        firstLoad       = true,
        recursionDepth  = 0,
        element         = this,
        instance        = $module.data(moduleNamespace),

        activeTabPath,
        parameterArray,
        module,

        historyEvent

      ;

      module = {

        initialize: function() {
          module.debug('Initializing tab menu item', $module);
          module.fix.callbacks();
          module.determineTabs();

          module.debug('Determining tabs', settings.context, $tabs);
          // set up automatic routing
          if(settings.auto) {
            module.set.auto();
          }
          module.bind.events();

          if(settings.history && !initializedHistory) {
            module.initializeHistory();
            initializedHistory = true;
          }

          module.instantiate();
        },

        instantiate: function () {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.debug('Destroying tabs', $module);
          $module
            .removeData(moduleNamespace)
            .off(eventNamespace)
          ;
        },

        bind: {
          events: function() {
            // if using $.tab don't add events
            if( !$.isWindow( element ) ) {
              module.debug('Attaching tab activation events to element', $module);
              $module
                .on('click' + eventNamespace, module.event.click)
              ;
            }
          }
        },

        determineTabs: function() {
          var
            $reference
          ;

          // determine tab context
          if(settings.context === 'parent') {
            if($module.closest(selector.ui).length > 0) {
              $reference = $module.closest(selector.ui);
              module.verbose('Using closest UI element as parent', $reference);
            }
            else {
              $reference = $module;
            }
            $context = $reference.parent();
            module.verbose('Determined parent element for creating context', $context);
          }
          else if(settings.context) {
            $context = $(settings.context);
            module.verbose('Using selector for tab context', settings.context, $context);
          }
          else {
            $context = $('body');
          }
          // find tabs
          if(settings.childrenOnly) {
            $tabs = $context.children(selector.tabs);
            module.debug('Searching tab context children for tabs', $context, $tabs);
          }
          else {
            $tabs = $context.find(selector.tabs);
            module.debug('Searching tab context for tabs', $context, $tabs);
          }
        },

        fix: {
          callbacks: function() {
            if( $.isPlainObject(parameters) && (parameters.onTabLoad || parameters.onTabInit) ) {
              if(parameters.onTabLoad) {
                parameters.onLoad = parameters.onTabLoad;
                delete parameters.onTabLoad;
                module.error(error.legacyLoad, parameters.onLoad);
              }
              if(parameters.onTabInit) {
                parameters.onFirstLoad = parameters.onTabInit;
                delete parameters.onTabInit;
                module.error(error.legacyInit, parameters.onFirstLoad);
              }
              settings = $.extend(true, {}, $.fn.tab.settings, parameters);
            }
          }
        },

        initializeHistory: function() {
          module.debug('Initializing page state');
          if( $.address === undefined ) {
            module.error(error.state);
            return false;
          }
          else {
            if(settings.historyType == 'state') {
              module.debug('Using HTML5 to manage state');
              if(settings.path !== false) {
                $.address
                  .history(true)
                  .state(settings.path)
                ;
              }
              else {
                module.error(error.path);
                return false;
              }
            }
            $.address
              .bind('change', module.event.history.change)
            ;
          }
        },

        event: {
          click: function(event) {
            var
              tabPath = $(this).data(metadata.tab)
            ;
            if(tabPath !== undefined) {
              if(settings.history) {
                module.verbose('Updating page state', event);
                $.address.value(tabPath);
              }
              else {
                module.verbose('Changing tab', event);
                module.changeTab(tabPath);
              }
              event.preventDefault();
            }
            else {
              module.debug('No tab specified');
            }
          },
          history: {
            change: function(event) {
              var
                tabPath   = event.pathNames.join('/') || module.get.initialPath(),
                pageTitle = settings.templates.determineTitle(tabPath) || false
              ;
              module.performance.display();
              module.debug('History change event', tabPath, event);
              historyEvent = event;
              if(tabPath !== undefined) {
                module.changeTab(tabPath);
              }
              if(pageTitle) {
                $.address.title(pageTitle);
              }
            }
          }
        },

        refresh: function() {
          if(activeTabPath) {
            module.debug('Refreshing tab', activeTabPath);
            module.changeTab(activeTabPath);
          }
        },

        cache: {

          read: function(cacheKey) {
            return (cacheKey !== undefined)
              ? cache[cacheKey]
              : false
            ;
          },
          add: function(cacheKey, content) {
            cacheKey = cacheKey || activeTabPath;
            module.debug('Adding cached content for', cacheKey);
            cache[cacheKey] = content;
          },
          remove: function(cacheKey) {
            cacheKey = cacheKey || activeTabPath;
            module.debug('Removing cached content for', cacheKey);
            delete cache[cacheKey];
          }
        },

        set: {
          auto: function() {
            var
              url = (typeof settings.path == 'string')
                ? settings.path.replace(/\/$/, '') + '/{$tab}'
                : '/{$tab}'
            ;
            module.verbose('Setting up automatic tab retrieval from server', url);
            if($.isPlainObject(settings.apiSettings)) {
              settings.apiSettings.url = url;
            }
            else {
              settings.apiSettings = {
                url: url
              };
            }
          },
          loading: function(tabPath) {
            var
              $tab      = module.get.tabElement(tabPath),
              isLoading = $tab.hasClass(className.loading)
            ;
            if(!isLoading) {
              module.verbose('Setting loading state for', $tab);
              $tab
                .addClass(className.loading)
                .siblings($tabs)
                  .removeClass(className.active + ' ' + className.loading)
              ;
              if($tab.length > 0) {
                settings.onRequest.call($tab[0], tabPath);
              }
            }
          },
          state: function(state) {
            $.address.value(state);
          }
        },

        changeTab: function(tabPath) {
          var
            pushStateAvailable = (window.history && window.history.pushState),
            shouldIgnoreLoad   = (pushStateAvailable && settings.ignoreFirstLoad && firstLoad),
            remoteContent      = (settings.auto || $.isPlainObject(settings.apiSettings) ),
            // only add default path if not remote content
            pathArray = (remoteContent && !shouldIgnoreLoad)
              ? module.utilities.pathToArray(tabPath)
              : module.get.defaultPathArray(tabPath)
          ;
          tabPath = module.utilities.arrayToPath(pathArray);
          $.each(pathArray, function(index, tab) {
            var
              currentPathArray   = pathArray.slice(0, index + 1),
              currentPath        = module.utilities.arrayToPath(currentPathArray),

              isTab              = module.is.tab(currentPath),
              isLastIndex        = (index + 1 == pathArray.length),

              $tab               = module.get.tabElement(currentPath),
              $anchor,
              nextPathArray,
              nextPath,
              isLastTab
            ;
            module.verbose('Looking for tab', tab);
            if(isTab) {
              module.verbose('Tab was found', tab);
              // scope up
              activeTabPath  = currentPath;
              parameterArray = module.utilities.filterArray(pathArray, currentPathArray);

              if(isLastIndex) {
                isLastTab = true;
              }
              else {
                nextPathArray = pathArray.slice(0, index + 2);
                nextPath      = module.utilities.arrayToPath(nextPathArray);
                isLastTab     = ( !module.is.tab(nextPath) );
                if(isLastTab) {
                  module.verbose('Tab parameters found', nextPathArray);
                }
              }
              if(isLastTab && remoteContent) {
                if(!shouldIgnoreLoad) {
                  module.activate.navigation(currentPath);
                  module.fetch.content(currentPath, tabPath);
                }
                else {
                  module.debug('Ignoring remote content on first tab load', currentPath);
                  firstLoad = false;
                  module.cache.add(tabPath, $tab.html());
                  module.activate.all(currentPath);
                  settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent);
                  settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent);
                }
                return false;
              }
              else {
                module.debug('Opened local tab', currentPath);
                module.activate.all(currentPath);
                if( !module.cache.read(currentPath) ) {
                  module.cache.add(currentPath, true);
                  module.debug('First time tab loaded calling tab init');
                  settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent);
                }
                settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent);
              }

            }
            else if(tabPath.search('/') == -1 && tabPath !== '') {
              // look for in page anchor
              $anchor     = $('#' + tabPath + ', a[name="' + tabPath + '"]');
              currentPath = $anchor.closest('[data-tab]').data(metadata.tab);
              $tab        = module.get.tabElement(currentPath);
              // if anchor exists use parent tab
              if($anchor && $anchor.length > 0 && currentPath) {
                module.debug('Anchor link used, opening parent tab', $tab, $anchor);
                if( !$tab.hasClass(className.active) ) {
                  setTimeout(function() {
                    module.scrollTo($anchor);
                  }, 0);
                }
                module.activate.all(currentPath);
                if( !module.cache.read(currentPath) ) {
                  module.cache.add(currentPath, true);
                  module.debug('First time tab loaded calling tab init');
                  settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent);
                }
                settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent);
                return false;
              }
            }
            else {
              module.error(error.missingTab, $module, $context, currentPath);
              return false;
            }
          });
        },

        scrollTo: function($element) {
          var
            scrollOffset = ($element && $element.length > 0)
              ? $element.offset().top
              : false
          ;
          if(scrollOffset !== false) {
            module.debug('Forcing scroll to an in-page link in a hidden tab', scrollOffset, $element);
            $(document).scrollTop(scrollOffset);
          }
        },

        update: {
          content: function(tabPath, html, evaluateScripts) {
            var
              $tab = module.get.tabElement(tabPath),
              tab  = $tab[0]
            ;
            evaluateScripts = (evaluateScripts !== undefined)
              ? evaluateScripts
              : settings.evaluateScripts
            ;
            if(typeof settings.cacheType == 'string' && settings.cacheType.toLowerCase() == 'dom' && typeof html !== 'string') {
              $tab
                .empty()
                .append($(html).clone(true))
              ;
            }
            else {
              if(evaluateScripts) {
                module.debug('Updating HTML and evaluating inline scripts', tabPath, html);
                $tab.html(html);
              }
              else {
                module.debug('Updating HTML', tabPath, html);
                tab.innerHTML = html;
              }
            }
          }
        },

        fetch: {

          content: function(tabPath, fullTabPath) {
            var
              $tab        = module.get.tabElement(tabPath),
              apiSettings = {
                dataType         : 'html',
                encodeParameters : false,
                on               : 'now',
                cache            : settings.alwaysRefresh,
                headers          : {
                  'X-Remote': true
                },
                onSuccess : function(response) {
                  if(settings.cacheType == 'response') {
                    module.cache.add(fullTabPath, response);
                  }
                  module.update.content(tabPath, response);
                  if(tabPath == activeTabPath) {
                    module.debug('Content loaded', tabPath);
                    module.activate.tab(tabPath);
                  }
                  else {
                    module.debug('Content loaded in background', tabPath);
                  }
                  settings.onFirstLoad.call($tab[0], tabPath, parameterArray, historyEvent);
                  settings.onLoad.call($tab[0], tabPath, parameterArray, historyEvent);

                  if(settings.loadOnce) {
                    module.cache.add(fullTabPath, true);
                  }
                  else if(typeof settings.cacheType == 'string' && settings.cacheType.toLowerCase() == 'dom' && $tab.children().length > 0) {
                    setTimeout(function() {
                      var
                        $clone = $tab.children().clone(true)
                      ;
                      $clone = $clone.not('script');
                      module.cache.add(fullTabPath, $clone);
                    }, 0);
                  }
                  else {
                    module.cache.add(fullTabPath, $tab.html());
                  }
                },
                urlData: {
                  tab: fullTabPath
                }
              },
              request         = $tab.api('get request') || false,
              existingRequest = ( request && request.state() === 'pending' ),
              requestSettings,
              cachedContent
            ;

            fullTabPath   = fullTabPath || tabPath;
            cachedContent = module.cache.read(fullTabPath);


            if(settings.cache && cachedContent) {
              module.activate.tab(tabPath);
              module.debug('Adding cached content', fullTabPath);
              if(!settings.loadOnce) {
                if(settings.evaluateScripts == 'once') {
                  module.update.content(tabPath, cachedContent, false);
                }
                else {
                  module.update.content(tabPath, cachedContent);
                }
              }
              settings.onLoad.call($tab[0], tabPath, parameterArray, historyEvent);
            }
            else if(existingRequest) {
              module.set.loading(tabPath);
              module.debug('Content is already loading', fullTabPath);
            }
            else if($.api !== undefined) {
              requestSettings = $.extend(true, {}, settings.apiSettings, apiSettings);
              module.debug('Retrieving remote content', fullTabPath, requestSettings);
              module.set.loading(tabPath);
              $tab.api(requestSettings);
            }
            else {
              module.error(error.api);
            }
          }
        },

        activate: {
          all: function(tabPath) {
            module.activate.tab(tabPath);
            module.activate.navigation(tabPath);
          },
          tab: function(tabPath) {
            var
              $tab          = module.get.tabElement(tabPath),
              $deactiveTabs = (settings.deactivate == 'siblings')
                ? $tab.siblings($tabs)
                : $tabs.not($tab),
              isActive      = $tab.hasClass(className.active)
            ;
            module.verbose('Showing tab content for', $tab);
            if(!isActive) {
              $tab
                .addClass(className.active)
              ;
              $deactiveTabs
                .removeClass(className.active + ' ' + className.loading)
              ;
              if($tab.length > 0) {
                settings.onVisible.call($tab[0], tabPath);
              }
            }
          },
          navigation: function(tabPath) {
            var
              $navigation         = module.get.navElement(tabPath),
              $deactiveNavigation = (settings.deactivate == 'siblings')
                ? $navigation.siblings($allModules)
                : $allModules.not($navigation),
              isActive    = $navigation.hasClass(className.active)
            ;
            module.verbose('Activating tab navigation for', $navigation, tabPath);
            if(!isActive) {
              $navigation
                .addClass(className.active)
              ;
              $deactiveNavigation
                .removeClass(className.active + ' ' + className.loading)
              ;
            }
          }
        },

        deactivate: {
          all: function() {
            module.deactivate.navigation();
            module.deactivate.tabs();
          },
          navigation: function() {
            $allModules
              .removeClass(className.active)
            ;
          },
          tabs: function() {
            $tabs
              .removeClass(className.active + ' ' + className.loading)
            ;
          }
        },

        is: {
          tab: function(tabName) {
            return (tabName !== undefined)
              ? ( module.get.tabElement(tabName).length > 0 )
              : false
            ;
          }
        },

        get: {
          initialPath: function() {
            return $allModules.eq(0).data(metadata.tab) || $tabs.eq(0).data(metadata.tab);
          },
          path: function() {
            return $.address.value();
          },
          // adds default tabs to tab path
          defaultPathArray: function(tabPath) {
            return module.utilities.pathToArray( module.get.defaultPath(tabPath) );
          },
          defaultPath: function(tabPath) {
            var
              $defaultNav = $allModules.filter('[data-' + metadata.tab + '^="' + tabPath + '/"]').eq(0),
              defaultTab  = $defaultNav.data(metadata.tab) || false
            ;
            if( defaultTab ) {
              module.debug('Found default tab', defaultTab);
              if(recursionDepth < settings.maxDepth) {
                recursionDepth++;
                return module.get.defaultPath(defaultTab);
              }
              module.error(error.recursion);
            }
            else {
              module.debug('No default tabs found for', tabPath, $tabs);
            }
            recursionDepth = 0;
            return tabPath;
          },
          navElement: function(tabPath) {
            tabPath = tabPath || activeTabPath;
            return $allModules.filter('[data-' + metadata.tab + '="' + tabPath + '"]');
          },
          tabElement: function(tabPath) {
            var
              $fullPathTab,
              $simplePathTab,
              tabPathArray,
              lastTab
            ;
            tabPath        = tabPath || activeTabPath;
            tabPathArray   = module.utilities.pathToArray(tabPath);
            lastTab        = module.utilities.last(tabPathArray);
            $fullPathTab   = $tabs.filter('[data-' + metadata.tab + '="' + tabPath + '"]');
            $simplePathTab = $tabs.filter('[data-' + metadata.tab + '="' + lastTab + '"]');
            return ($fullPathTab.length > 0)
              ? $fullPathTab
              : $simplePathTab
            ;
          },
          tab: function() {
            return activeTabPath;
          }
        },

        utilities: {
          filterArray: function(keepArray, removeArray) {
            return $.grep(keepArray, function(keepValue) {
              return ( $.inArray(keepValue, removeArray) == -1);
            });
          },
          last: function(array) {
            return $.isArray(array)
              ? array[ array.length - 1]
              : false
            ;
          },
          pathToArray: function(pathName) {
            if(pathName === undefined) {
              pathName = activeTabPath;
            }
            return typeof pathName == 'string'
              ? pathName.split('/')
              : [pathName]
            ;
          },
          arrayToPath: function(pathArray) {
            return $.isArray(pathArray)
              ? pathArray.join('/')
              : false
            ;
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };
      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;
  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;

};

// shortcut for tabbed content with no defined navigation
$.tab = function() {
  $(window).tab.apply(this, arguments);
};

$.fn.tab.settings = {

  name            : 'Tab',
  namespace       : 'tab',

  silent          : false,
  debug           : false,
  verbose         : false,
  performance     : true,

  auto            : false,      // uses pjax style endpoints fetching content from same url with remote-content headers
  history         : false,      // use browser history
  historyType     : 'hash',     // #/ or html5 state
  path            : false,      // base path of url

  context         : false,      // specify a context that tabs must appear inside
  childrenOnly    : false,      // use only tabs that are children of context
  maxDepth        : 25,         // max depth a tab can be nested

  deactivate      : 'siblings', // whether tabs should deactivate sibling menu elements or all elements initialized together

  alwaysRefresh   : false,      // load tab content new every tab click
  cache           : true,       // cache the content requests to pull locally
  loadOnce        : false,      // Whether tab data should only be loaded once when using remote content
  cacheType       : 'response', // Whether to cache exact response, or to html cache contents after scripts execute
  ignoreFirstLoad : false,      // don't load remote content on first load

  apiSettings     : false,      // settings for api call
  evaluateScripts : 'once',     // whether inline scripts should be parsed (true/false/once). Once will not re-evaluate on cached content

  onFirstLoad : function(tabPath, parameterArray, historyEvent) {}, // called first time loaded
  onLoad      : function(tabPath, parameterArray, historyEvent) {}, // called on every load
  onVisible   : function(tabPath, parameterArray, historyEvent) {}, // called every time tab visible
  onRequest   : function(tabPath, parameterArray, historyEvent) {}, // called ever time a tab beings loading remote content

  templates : {
    determineTitle: function(tabArray) {} // returns page title for path
  },

  error: {
    api        : 'You attempted to load content without API module',
    method     : 'The method you called is not defined',
    missingTab : 'Activated tab cannot be found. Tabs are case-sensitive.',
    noContent  : 'The tab you specified is missing a content url.',
    path       : 'History enabled, but no path was specified',
    recursion  : 'Max recursive depth reached',
    legacyInit : 'onTabInit has been renamed to onFirstLoad in 2.0, please adjust your code.',
    legacyLoad : 'onTabLoad has been renamed to onLoad in 2.0. Please adjust your code',
    state      : 'History requires Asual\'s Address library <https://github.com/asual/jquery-address>'
  },

  metadata : {
    tab    : 'tab',
    loaded : 'loaded',
    promise: 'promise'
  },

  className   : {
    loading : 'loading',
    active  : 'active'
  },

  selector    : {
    tabs : '.ui.tab',
    ui   : '.ui'
  }

};

})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Transition
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.transition = function() {
  var
    $allModules     = $(this),
    moduleSelector  = $allModules.selector || '',

    time            = new Date().getTime(),
    performance     = [],

    moduleArguments = arguments,
    query           = moduleArguments[0],
    queryArguments  = [].slice.call(arguments, 1),
    methodInvoked   = (typeof query === 'string'),

    requestAnimationFrame = window.requestAnimationFrame
      || window.mozRequestAnimationFrame
      || window.webkitRequestAnimationFrame
      || window.msRequestAnimationFrame
      || function(callback) { setTimeout(callback, 0); },

    returnedValue
  ;
  $allModules
    .each(function(index) {
      var
        $module  = $(this),
        element  = this,

        // set at run time
        settings,
        instance,

        error,
        className,
        metadata,
        animationEnd,
        animationName,

        namespace,
        moduleNamespace,
        eventNamespace,
        module
      ;

      module = {

        initialize: function() {

          // get full settings
          settings        = module.get.settings.apply(element, moduleArguments);

          // shorthand
          className       = settings.className;
          error           = settings.error;
          metadata        = settings.metadata;

          // define namespace
          eventNamespace  = '.' + settings.namespace;
          moduleNamespace = 'module-' + settings.namespace;
          instance        = $module.data(moduleNamespace) || module;

          // get vendor specific events
          animationEnd    = module.get.animationEndEvent();

          if(methodInvoked) {
            methodInvoked = module.invoke(query);
          }

          // method not invoked, lets run an animation
          if(methodInvoked === false) {
            module.verbose('Converted arguments into settings object', settings);
            if(settings.interval) {
              module.delay(settings.animate);
            }
            else  {
              module.animate();
            }
            module.instantiate();
          }
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, instance)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous module for', element);
          $module
            .removeData(moduleNamespace)
          ;
        },

        refresh: function() {
          module.verbose('Refreshing display type on next animation');
          delete module.displayType;
        },

        forceRepaint: function() {
          module.verbose('Forcing element repaint');
          var
            $parentElement = $module.parent(),
            $nextElement = $module.next()
          ;
          if($nextElement.length === 0) {
            $module.detach().appendTo($parentElement);
          }
          else {
            $module.detach().insertBefore($nextElement);
          }
        },

        repaint: function() {
          module.verbose('Repainting element');
          var
            fakeAssignment = element.offsetWidth
          ;
        },

        delay: function(interval) {
          var
            direction = module.get.animationDirection(),
            shouldReverse,
            delay
          ;
          if(!direction) {
            direction = module.can.transition()
              ? module.get.direction()
              : 'static'
            ;
          }
          interval = (interval !== undefined)
            ? interval
            : settings.interval
          ;
          shouldReverse = (settings.reverse == 'auto' && direction == className.outward);
          delay = (shouldReverse || settings.reverse == true)
            ? ($allModules.length - index) * settings.interval
            : index * settings.interval
          ;
          module.debug('Delaying animation by', delay);
          setTimeout(module.animate, delay);
        },

        animate: function(overrideSettings) {
          settings = overrideSettings || settings;
          if(!module.is.supported()) {
            module.error(error.support);
            return false;
          }
          module.debug('Preparing animation', settings.animation);
          if(module.is.animating()) {
            if(settings.queue) {
              if(!settings.allowRepeats && module.has.direction() && module.is.occurring() && module.queuing !== true) {
                module.debug('Animation is currently occurring, preventing queueing same animation', settings.animation);
              }
              else {
                module.queue(settings.animation);
              }
              return false;
            }
            else if(!settings.allowRepeats && module.is.occurring()) {
              module.debug('Animation is already occurring, will not execute repeated animation', settings.animation);
              return false;
            }
            else {
              module.debug('New animation started, completing previous early', settings.animation);
              instance.complete();
            }
          }
          if( module.can.animate() ) {
            module.set.animating(settings.animation);
          }
          else {
            module.error(error.noAnimation, settings.animation, element);
          }
        },

        reset: function() {
          module.debug('Resetting animation to beginning conditions');
          module.remove.animationCallbacks();
          module.restore.conditions();
          module.remove.animating();
        },

        queue: function(animation) {
          module.debug('Queueing animation of', animation);
          module.queuing = true;
          $module
            .one(animationEnd + '.queue' + eventNamespace, function() {
              module.queuing = false;
              module.repaint();
              module.animate.apply(this, settings);
            })
          ;
        },

        complete: function (event) {
          module.debug('Animation complete', settings.animation);
          module.remove.completeCallback();
          module.remove.failSafe();
          if(!module.is.looping()) {
            if( module.is.outward() ) {
              module.verbose('Animation is outward, hiding element');
              module.restore.conditions();
              module.hide();
            }
            else if( module.is.inward() ) {
              module.verbose('Animation is outward, showing element');
              module.restore.conditions();
              module.show();
            }
            else {
              module.verbose('Static animation completed');
              module.restore.conditions();
              settings.onComplete.call(element);
            }
          }
        },

        force: {
          visible: function() {
            var
              style          = $module.attr('style'),
              userStyle      = module.get.userStyle(),
              displayType    = module.get.displayType(),
              overrideStyle  = userStyle + 'display: ' + displayType + ' !important;',
              currentDisplay = $module.css('display'),
              emptyStyle     = (style === undefined || style === '')
            ;
            if(currentDisplay !== displayType) {
              module.verbose('Overriding default display to show element', displayType);
              $module
                .attr('style', overrideStyle)
              ;
            }
            else if(emptyStyle) {
              $module.removeAttr('style');
            }
          },
          hidden: function() {
            var
              style          = $module.attr('style'),
              currentDisplay = $module.css('display'),
              emptyStyle     = (style === undefined || style === '')
            ;
            if(currentDisplay !== 'none' && !module.is.hidden()) {
              module.verbose('Overriding default display to hide element');
              $module
                .css('display', 'none')
              ;
            }
            else if(emptyStyle) {
              $module
                .removeAttr('style')
              ;
            }
          }
        },

        has: {
          direction: function(animation) {
            var
              hasDirection = false
            ;
            animation = animation || settings.animation;
            if(typeof animation === 'string') {
              animation = animation.split(' ');
              $.each(animation, function(index, word){
                if(word === className.inward || word === className.outward) {
                  hasDirection = true;
                }
              });
            }
            return hasDirection;
          },
          inlineDisplay: function() {
            var
              style = $module.attr('style') || ''
            ;
            return $.isArray(style.match(/display.*?;/, ''));
          }
        },

        set: {
          animating: function(animation) {
            var
              animationClass,
              direction
            ;
            // remove previous callbacks
            module.remove.completeCallback();

            // determine exact animation
            animation      = animation || settings.animation;
            animationClass = module.get.animationClass(animation);

            // save animation class in cache to restore class names
            module.save.animation(animationClass);

            // override display if necessary so animation appears visibly
            module.force.visible();

            module.remove.hidden();
            module.remove.direction();

            module.start.animation(animationClass);

          },
          duration: function(animationName, duration) {
            duration = duration || settings.duration;
            duration = (typeof duration == 'number')
              ? duration + 'ms'
              : duration
            ;
            if(duration || duration === 0) {
              module.verbose('Setting animation duration', duration);
              $module
                .css({
                  'animation-duration':  duration
                })
              ;
            }
          },
          direction: function(direction) {
            direction = direction || module.get.direction();
            if(direction == className.inward) {
              module.set.inward();
            }
            else {
              module.set.outward();
            }
          },
          looping: function() {
            module.debug('Transition set to loop');
            $module
              .addClass(className.looping)
            ;
          },
          hidden: function() {
            $module
              .addClass(className.transition)
              .addClass(className.hidden)
            ;
          },
          inward: function() {
            module.debug('Setting direction to inward');
            $module
              .removeClass(className.outward)
              .addClass(className.inward)
            ;
          },
          outward: function() {
            module.debug('Setting direction to outward');
            $module
              .removeClass(className.inward)
              .addClass(className.outward)
            ;
          },
          visible: function() {
            $module
              .addClass(className.transition)
              .addClass(className.visible)
            ;
          }
        },

        start: {
          animation: function(animationClass) {
            animationClass = animationClass || module.get.animationClass();
            module.debug('Starting tween', animationClass);
            $module
              .addClass(animationClass)
              .one(animationEnd + '.complete' + eventNamespace, module.complete)
            ;
            if(settings.useFailSafe) {
              module.add.failSafe();
            }
            module.set.duration(settings.duration);
            settings.onStart.call(element);
          }
        },

        save: {
          animation: function(animation) {
            if(!module.cache) {
              module.cache = {};
            }
            module.cache.animation = animation;
          },
          displayType: function(displayType) {
            if(displayType !== 'none') {
              $module.data(metadata.displayType, displayType);
            }
          },
          transitionExists: function(animation, exists) {
            $.fn.transition.exists[animation] = exists;
            module.verbose('Saving existence of transition', animation, exists);
          }
        },

        restore: {
          conditions: function() {
            var
              animation = module.get.currentAnimation()
            ;
            if(animation) {
              $module
                .removeClass(animation)
              ;
              module.verbose('Removing animation class', module.cache);
            }
            module.remove.duration();
          }
        },

        add: {
          failSafe: function() {
            var
              duration = module.get.duration()
            ;
            module.timer = setTimeout(function() {
              $module.triggerHandler(animationEnd);
            }, duration + settings.failSafeDelay);
            module.verbose('Adding fail safe timer', module.timer);
          }
        },

        remove: {
          animating: function() {
            $module.removeClass(className.animating);
          },
          animationCallbacks: function() {
            module.remove.queueCallback();
            module.remove.completeCallback();
          },
          queueCallback: function() {
            $module.off('.queue' + eventNamespace);
          },
          completeCallback: function() {
            $module.off('.complete' + eventNamespace);
          },
          display: function() {
            $module.css('display', '');
          },
          direction: function() {
            $module
              .removeClass(className.inward)
              .removeClass(className.outward)
            ;
          },
          duration: function() {
            $module
              .css('animation-duration', '')
            ;
          },
          failSafe: function() {
            module.verbose('Removing fail safe timer', module.timer);
            if(module.timer) {
              clearTimeout(module.timer);
            }
          },
          hidden: function() {
            $module.removeClass(className.hidden);
          },
          visible: function() {
            $module.removeClass(className.visible);
          },
          looping: function() {
            module.debug('Transitions are no longer looping');
            if( module.is.looping() ) {
              module.reset();
              $module
                .removeClass(className.looping)
              ;
            }
          },
          transition: function() {
            $module
              .removeClass(className.visible)
              .removeClass(className.hidden)
            ;
          }
        },
        get: {
          settings: function(animation, duration, onComplete) {
            // single settings object
            if(typeof animation == 'object') {
              return $.extend(true, {}, $.fn.transition.settings, animation);
            }
            // all arguments provided
            else if(typeof onComplete == 'function') {
              return $.extend({}, $.fn.transition.settings, {
                animation  : animation,
                onComplete : onComplete,
                duration   : duration
              });
            }
            // only duration provided
            else if(typeof duration == 'string' || typeof duration == 'number') {
              return $.extend({}, $.fn.transition.settings, {
                animation : animation,
                duration  : duration
              });
            }
            // duration is actually settings object
            else if(typeof duration == 'object') {
              return $.extend({}, $.fn.transition.settings, duration, {
                animation : animation
              });
            }
            // duration is actually callback
            else if(typeof duration == 'function') {
              return $.extend({}, $.fn.transition.settings, {
                animation  : animation,
                onComplete : duration
              });
            }
            // only animation provided
            else {
              return $.extend({}, $.fn.transition.settings, {
                animation : animation
              });
            }
          },
          animationClass: function(animation) {
            var
              animationClass = animation || settings.animation,
              directionClass = (module.can.transition() && !module.has.direction())
                ? module.get.direction() + ' '
                : ''
            ;
            return className.animating + ' '
              + className.transition + ' '
              + directionClass
              + animationClass
            ;
          },
          currentAnimation: function() {
            return (module.cache && module.cache.animation !== undefined)
              ? module.cache.animation
              : false
            ;
          },
          currentDirection: function() {
            return module.is.inward()
              ? className.inward
              : className.outward
            ;
          },
          direction: function() {
            return module.is.hidden() || !module.is.visible()
              ? className.inward
              : className.outward
            ;
          },
          animationDirection: function(animation) {
            var
              direction
            ;
            animation = animation || settings.animation;
            if(typeof animation === 'string') {
              animation = animation.split(' ');
              // search animation name for out/in class
              $.each(animation, function(index, word){
                if(word === className.inward) {
                  direction = className.inward;
                }
                else if(word === className.outward) {
                  direction = className.outward;
                }
              });
            }
            // return found direction
            if(direction) {
              return direction;
            }
            return false;
          },
          duration: function(duration) {
            duration = duration || settings.duration;
            if(duration === false) {
              duration = $module.css('animation-duration') || 0;
            }
            return (typeof duration === 'string')
              ? (duration.indexOf('ms') > -1)
                ? parseFloat(duration)
                : parseFloat(duration) * 1000
              : duration
            ;
          },
          displayType: function(shouldDetermine) {
            shouldDetermine = (shouldDetermine !== undefined)
              ? shouldDetermine
              : true
            ;
            if(settings.displayType) {
              return settings.displayType;
            }
            if(shouldDetermine && $module.data(metadata.displayType) === undefined) {
              // create fake element to determine display state
              module.can.transition(true);
            }
            return $module.data(metadata.displayType);
          },
          userStyle: function(style) {
            style = style || $module.attr('style') || '';
            return style.replace(/display.*?;/, '');
          },
          transitionExists: function(animation) {
            return $.fn.transition.exists[animation];
          },
          animationStartEvent: function() {
            var
              element     = document.createElement('div'),
              animations  = {
                'animation'       :'animationstart',
                'OAnimation'      :'oAnimationStart',
                'MozAnimation'    :'mozAnimationStart',
                'WebkitAnimation' :'webkitAnimationStart'
              },
              animation
            ;
            for(animation in animations){
              if( element.style[animation] !== undefined ){
                return animations[animation];
              }
            }
            return false;
          },
          animationEndEvent: function() {
            var
              element     = document.createElement('div'),
              animations  = {
                'animation'       :'animationend',
                'OAnimation'      :'oAnimationEnd',
                'MozAnimation'    :'mozAnimationEnd',
                'WebkitAnimation' :'webkitAnimationEnd'
              },
              animation
            ;
            for(animation in animations){
              if( element.style[animation] !== undefined ){
                return animations[animation];
              }
            }
            return false;
          }

        },

        can: {
          transition: function(forced) {
            var
              animation         = settings.animation,
              transitionExists  = module.get.transitionExists(animation),
              displayType       = module.get.displayType(false),
              elementClass,
              tagName,
              $clone,
              currentAnimation,
              inAnimation,
              directionExists
            ;
            if( transitionExists === undefined || forced) {
              module.verbose('Determining whether animation exists');
              elementClass = $module.attr('class');
              tagName      = $module.prop('tagName');

              $clone = $('<' + tagName + ' />').addClass( elementClass ).insertAfter($module);
              currentAnimation = $clone
                .addClass(animation)
                .removeClass(className.inward)
                .removeClass(className.outward)
                .addClass(className.animating)
                .addClass(className.transition)
                .css('animationName')
              ;
              inAnimation = $clone
                .addClass(className.inward)
                .css('animationName')
              ;
              if(!displayType) {
                displayType = $clone
                  .attr('class', elementClass)
                  .removeAttr('style')
                  .removeClass(className.hidden)
                  .removeClass(className.visible)
                  .show()
                  .css('display')
                ;
                module.verbose('Determining final display state', displayType);
                module.save.displayType(displayType);
              }

              $clone.remove();
              if(currentAnimation != inAnimation) {
                module.debug('Direction exists for animation', animation);
                directionExists = true;
              }
              else if(currentAnimation == 'none' || !currentAnimation) {
                module.debug('No animation defined in css', animation);
                return;
              }
              else {
                module.debug('Static animation found', animation, displayType);
                directionExists = false;
              }
              module.save.transitionExists(animation, directionExists);
            }
            return (transitionExists !== undefined)
              ? transitionExists
              : directionExists
            ;
          },
          animate: function() {
            // can transition does not return a value if animation does not exist
            return (module.can.transition() !== undefined);
          }
        },

        is: {
          animating: function() {
            return $module.hasClass(className.animating);
          },
          inward: function() {
            return $module.hasClass(className.inward);
          },
          outward: function() {
            return $module.hasClass(className.outward);
          },
          looping: function() {
            return $module.hasClass(className.looping);
          },
          occurring: function(animation) {
            animation = animation || settings.animation;
            animation = '.' + animation.replace(' ', '.');
            return ( $module.filter(animation).length > 0 );
          },
          visible: function() {
            return $module.is(':visible');
          },
          hidden: function() {
            return $module.css('visibility') === 'hidden';
          },
          supported: function() {
            return(animationEnd !== false);
          }
        },

        hide: function() {
          module.verbose('Hiding element');
          if( module.is.animating() ) {
            module.reset();
          }
          element.blur(); // IE will trigger focus change if element is not blurred before hiding
          module.remove.display();
          module.remove.visible();
          module.set.hidden();
          module.force.hidden();
          settings.onHide.call(element);
          settings.onComplete.call(element);
          // module.repaint();
        },

        show: function(display) {
          module.verbose('Showing element', display);
          module.remove.hidden();
          module.set.visible();
          module.force.visible();
          settings.onShow.call(element);
          settings.onComplete.call(element);
          // module.repaint();
        },

        toggle: function() {
          if( module.is.visible() ) {
            module.hide();
          }
          else {
            module.show();
          }
        },

        stop: function() {
          module.debug('Stopping current animation');
          $module.triggerHandler(animationEnd);
        },

        stopAll: function() {
          module.debug('Stopping all animation');
          module.remove.queueCallback();
          $module.triggerHandler(animationEnd);
        },

        clear: {
          queue: function() {
            module.debug('Clearing animation queue');
            module.remove.queueCallback();
          }
        },

        enable: function() {
          module.verbose('Starting animation');
          $module.removeClass(className.disabled);
        },

        disable: function() {
          module.debug('Stopping animation');
          $module.addClass(className.disabled);
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.length > 1) {
              title += ' ' + '(' + $allModules.length + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        // modified for transition to return invoke success
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }

          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return (found !== undefined)
            ? found
            : false
          ;
        }
      };
      module.initialize();
    })
  ;
  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

// Records if CSS transition is available
$.fn.transition.exists = {};

$.fn.transition.settings = {

  // module info
  name          : 'Transition',

  // hide all output from this component regardless of other settings
  silent        : false,

  // debug content outputted to console
  debug         : false,

  // verbose debug output
  verbose       : false,

  // performance data output
  performance   : true,

  // event namespace
  namespace     : 'transition',

  // delay between animations in group
  interval      : 0,

  // whether group animations should be reversed
  reverse       : 'auto',

  // animation callback event
  onStart       : function() {},
  onComplete    : function() {},
  onShow        : function() {},
  onHide        : function() {},

  // whether timeout should be used to ensure callback fires in cases animationend does not
  useFailSafe   : true,

  // delay in ms for fail safe
  failSafeDelay : 100,

  // whether EXACT animation can occur twice in a row
  allowRepeats  : false,

  // Override final display type on visible
  displayType   : false,

  // animation duration
  animation     : 'fade',
  duration      : false,

  // new animations will occur after previous ones
  queue         : true,

  metadata : {
    displayType: 'display'
  },

  className   : {
    animating  : 'animating',
    disabled   : 'disabled',
    hidden     : 'hidden',
    inward     : 'in',
    loading    : 'loading',
    looping    : 'looping',
    outward    : 'out',
    transition : 'transition',
    visible    : 'visible'
  },

  // possible errors
  error: {
    noAnimation : 'Element is no longer attached to DOM. Unable to animate.  Use silent setting to surpress this warning in production.',
    repeated    : 'That animation is already occurring, cancelling repeated animation',
    method      : 'The method you called is not defined',
    support     : 'This browser does not support CSS animations'
  }

};


})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - API
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

var
  window = (typeof window != 'undefined' && window.Math == Math)
    ? window
    : (typeof self != 'undefined' && self.Math == Math)
      ? self
      : Function('return this')()
;

$.api = $.fn.api = function(parameters) {

  var
    // use window context if none specified
    $allModules     = $.isFunction(this)
        ? $(window)
        : $(this),
    moduleSelector = $allModules.selector || '',
    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings          = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.api.settings, parameters)
          : $.extend({}, $.fn.api.settings),

        // internal aliases
        namespace       = settings.namespace,
        metadata        = settings.metadata,
        selector        = settings.selector,
        error           = settings.error,
        className       = settings.className,

        // define namespaces for modules
        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        // element that creates request
        $module         = $(this),
        $form           = $module.closest(selector.form),

        // context used for state
        $context        = (settings.stateContext)
          ? $(settings.stateContext)
          : $module,

        // request details
        ajaxSettings,
        requestSettings,
        url,
        data,
        requestStartTime,

        // standard module
        element         = this,
        context         = $context[0],
        instance        = $module.data(moduleNamespace),
        module
      ;

      module = {

        initialize: function() {
          if(!methodInvoked) {
            module.bind.events();
          }
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, instance)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous module for', element);
          $module
            .removeData(moduleNamespace)
            .off(eventNamespace)
          ;
        },

        bind: {
          events: function() {
            var
              triggerEvent = module.get.event()
            ;
            if( triggerEvent ) {
              module.verbose('Attaching API events to element', triggerEvent);
              $module
                .on(triggerEvent + eventNamespace, module.event.trigger)
              ;
            }
            else if(settings.on == 'now') {
              module.debug('Querying API endpoint immediately');
              module.query();
            }
          }
        },

        decode: {
          json: function(response) {
            if(response !== undefined && typeof response == 'string') {
              try {
               response = JSON.parse(response);
              }
              catch(e) {
                // isnt json string
              }
            }
            return response;
          }
        },

        read: {
          cachedResponse: function(url) {
            var
              response
            ;
            if(window.Storage === undefined) {
              module.error(error.noStorage);
              return;
            }
            response = sessionStorage.getItem(url);
            module.debug('Using cached response', url, response);
            response = module.decode.json(response);
            return response;
          }
        },
        write: {
          cachedResponse: function(url, response) {
            if(response && response === '') {
              module.debug('Response empty, not caching', response);
              return;
            }
            if(window.Storage === undefined) {
              module.error(error.noStorage);
              return;
            }
            if( $.isPlainObject(response) ) {
              response = JSON.stringify(response);
            }
            sessionStorage.setItem(url, response);
            module.verbose('Storing cached response for url', url, response);
          }
        },

        query: function() {

          if(module.is.disabled()) {
            module.debug('Element is disabled API request aborted');
            return;
          }

          if(module.is.loading()) {
            if(settings.interruptRequests) {
              module.debug('Interrupting previous request');
              module.abort();
            }
            else {
              module.debug('Cancelling request, previous request is still pending');
              return;
            }
          }

          // pass element metadata to url (value, text)
          if(settings.defaultData) {
            $.extend(true, settings.urlData, module.get.defaultData());
          }

          // Add form content
          if(settings.serializeForm) {
            settings.data = module.add.formData(settings.data);
          }

          // call beforesend and get any settings changes
          requestSettings = module.get.settings();

          // check if before send cancelled request
          if(requestSettings === false) {
            module.cancelled = true;
            module.error(error.beforeSend);
            return;
          }
          else {
            module.cancelled = false;
          }

          // get url
          url = module.get.templatedURL();

          if(!url && !module.is.mocked()) {
            module.error(error.missingURL);
            return;
          }

          // replace variables
          url = module.add.urlData( url );
          // missing url parameters
          if( !url && !module.is.mocked()) {
            return;
          }

          requestSettings.url = settings.base + url;

          // look for jQuery ajax parameters in settings
          ajaxSettings = $.extend(true, {}, settings, {
            type       : settings.method || settings.type,
            data       : data,
            url        : settings.base + url,
            beforeSend : settings.beforeXHR,
            success    : function() {},
            failure    : function() {},
            complete   : function() {}
          });

          module.debug('Querying URL', ajaxSettings.url);
          module.verbose('Using AJAX settings', ajaxSettings);
          if(settings.cache === 'local' && module.read.cachedResponse(url)) {
            module.debug('Response returned from local cache');
            module.request = module.create.request();
            module.request.resolveWith(context, [ module.read.cachedResponse(url) ]);
            return;
          }

          if( !settings.throttle ) {
            module.debug('Sending request', data, ajaxSettings.method);
            module.send.request();
          }
          else {
            if(!settings.throttleFirstRequest && !module.timer) {
              module.debug('Sending request', data, ajaxSettings.method);
              module.send.request();
              module.timer = setTimeout(function(){}, settings.throttle);
            }
            else {
              module.debug('Throttling request', settings.throttle);
              clearTimeout(module.timer);
              module.timer = setTimeout(function() {
                if(module.timer) {
                  delete module.timer;
                }
                module.debug('Sending throttled request', data, ajaxSettings.method);
                module.send.request();
              }, settings.throttle);
            }
          }

        },

        should: {
          removeError: function() {
            return ( settings.hideError === true || (settings.hideError === 'auto' && !module.is.form()) );
          }
        },

        is: {
          disabled: function() {
            return ($module.filter(selector.disabled).length > 0);
          },
          expectingJSON: function() {
            return settings.dataType === 'json' || settings.dataType === 'jsonp';
          },
          form: function() {
            return $module.is('form') || $context.is('form');
          },
          mocked: function() {
            return (settings.mockResponse || settings.mockResponseAsync || settings.response || settings.responseAsync);
          },
          input: function() {
            return $module.is('input');
          },
          loading: function() {
            return (module.request)
              ? (module.request.state() == 'pending')
              : false
            ;
          },
          abortedRequest: function(xhr) {
            if(xhr && xhr.readyState !== undefined && xhr.readyState === 0) {
              module.verbose('XHR request determined to be aborted');
              return true;
            }
            else {
              module.verbose('XHR request was not aborted');
              return false;
            }
          },
          validResponse: function(response) {
            if( (!module.is.expectingJSON()) || !$.isFunction(settings.successTest) ) {
              module.verbose('Response is not JSON, skipping validation', settings.successTest, response);
              return true;
            }
            module.debug('Checking JSON returned success', settings.successTest, response);
            if( settings.successTest(response) ) {
              module.debug('Response passed success test', response);
              return true;
            }
            else {
              module.debug('Response failed success test', response);
              return false;
            }
          }
        },

        was: {
          cancelled: function() {
            return (module.cancelled || false);
          },
          succesful: function() {
            return (module.request && module.request.state() == 'resolved');
          },
          failure: function() {
            return (module.request && module.request.state() == 'rejected');
          },
          complete: function() {
            return (module.request && (module.request.state() == 'resolved' || module.request.state() == 'rejected') );
          }
        },

        add: {
          urlData: function(url, urlData) {
            var
              requiredVariables,
              optionalVariables
            ;
            if(url) {
              requiredVariables = url.match(settings.regExp.required);
              optionalVariables = url.match(settings.regExp.optional);
              urlData           = urlData || settings.urlData;
              if(requiredVariables) {
                module.debug('Looking for required URL variables', requiredVariables);
                $.each(requiredVariables, function(index, templatedString) {
                  var
                    // allow legacy {$var} style
                    variable = (templatedString.indexOf('$') !== -1)
                      ? templatedString.substr(2, templatedString.length - 3)
                      : templatedString.substr(1, templatedString.length - 2),
                    value   = ($.isPlainObject(urlData) && urlData[variable] !== undefined)
                      ? urlData[variable]
                      : ($module.data(variable) !== undefined)
                        ? $module.data(variable)
                        : ($context.data(variable) !== undefined)
                          ? $context.data(variable)
                          : urlData[variable]
                  ;
                  // remove value
                  if(value === undefined) {
                    module.error(error.requiredParameter, variable, url);
                    url = false;
                    return false;
                  }
                  else {
                    module.verbose('Found required variable', variable, value);
                    value = (settings.encodeParameters)
                      ? module.get.urlEncodedValue(value)
                      : value
                    ;
                    url = url.replace(templatedString, value);
                  }
                });
              }
              if(optionalVariables) {
                module.debug('Looking for optional URL variables', requiredVariables);
                $.each(optionalVariables, function(index, templatedString) {
                  var
                    // allow legacy {/$var} style
                    variable = (templatedString.indexOf('$') !== -1)
                      ? templatedString.substr(3, templatedString.length - 4)
                      : templatedString.substr(2, templatedString.length - 3),
                    value   = ($.isPlainObject(urlData) && urlData[variable] !== undefined)
                      ? urlData[variable]
                      : ($module.data(variable) !== undefined)
                        ? $module.data(variable)
                        : ($context.data(variable) !== undefined)
                          ? $context.data(variable)
                          : urlData[variable]
                  ;
                  // optional replacement
                  if(value !== undefined) {
                    module.verbose('Optional variable Found', variable, value);
                    url = url.replace(templatedString, value);
                  }
                  else {
                    module.verbose('Optional variable not found', variable);
                    // remove preceding slash if set
                    if(url.indexOf('/' + templatedString) !== -1) {
                      url = url.replace('/' + templatedString, '');
                    }
                    else {
                      url = url.replace(templatedString, '');
                    }
                  }
                });
              }
            }
            return url;
          },
          formData: function(data) {
            var
              canSerialize = ($.fn.serializeObject !== undefined),
              formData     = (canSerialize)
                ? $form.serializeObject()
                : $form.serialize(),
              hasOtherData
            ;
            data         = data || settings.data;
            hasOtherData = $.isPlainObject(data);

            if(hasOtherData) {
              if(canSerialize) {
                module.debug('Extending existing data with form data', data, formData);
                data = $.extend(true, {}, data, formData);
              }
              else {
                module.error(error.missingSerialize);
                module.debug('Cant extend data. Replacing data with form data', data, formData);
                data = formData;
              }
            }
            else {
              module.debug('Adding form data', formData);
              data = formData;
            }
            return data;
          }
        },

        send: {
          request: function() {
            module.set.loading();
            module.request = module.create.request();
            if( module.is.mocked() ) {
              module.mockedXHR = module.create.mockedXHR();
            }
            else {
              module.xhr = module.create.xhr();
            }
            settings.onRequest.call(context, module.request, module.xhr);
          }
        },

        event: {
          trigger: function(event) {
            module.query();
            if(event.type == 'submit' || event.type == 'click') {
              event.preventDefault();
            }
          },
          xhr: {
            always: function() {
              // nothing special
            },
            done: function(response, textStatus, xhr) {
              var
                context            = this,
                elapsedTime        = (new Date().getTime() - requestStartTime),
                timeLeft           = (settings.loadingDuration - elapsedTime),
                translatedResponse = ( $.isFunction(settings.onResponse) )
                  ? module.is.expectingJSON()
                    ? settings.onResponse.call(context, $.extend(true, {}, response))
                    : settings.onResponse.call(context, response)
                  : false
              ;
              timeLeft = (timeLeft > 0)
                ? timeLeft
                : 0
              ;
              if(translatedResponse) {
                module.debug('Modified API response in onResponse callback', settings.onResponse, translatedResponse, response);
                response = translatedResponse;
              }
              if(timeLeft > 0) {
                module.debug('Response completed early delaying state change by', timeLeft);
              }
              setTimeout(function() {
                if( module.is.validResponse(response) ) {
                  module.request.resolveWith(context, [response, xhr]);
                }
                else {
                  module.request.rejectWith(context, [xhr, 'invalid']);
                }
              }, timeLeft);
            },
            fail: function(xhr, status, httpMessage) {
              var
                context     = this,
                elapsedTime = (new Date().getTime() - requestStartTime),
                timeLeft    = (settings.loadingDuration - elapsedTime)
              ;
              timeLeft = (timeLeft > 0)
                ? timeLeft
                : 0
              ;
              if(timeLeft > 0) {
                module.debug('Response completed early delaying state change by', timeLeft);
              }
              setTimeout(function() {
                if( module.is.abortedRequest(xhr) ) {
                  module.request.rejectWith(context, [xhr, 'aborted', httpMessage]);
                }
                else {
                  module.request.rejectWith(context, [xhr, 'error', status, httpMessage]);
                }
              }, timeLeft);
            }
          },
          request: {
            done: function(response, xhr) {
              module.debug('Successful API Response', response);
              if(settings.cache === 'local' && url) {
                module.write.cachedResponse(url, response);
                module.debug('Saving server response locally', module.cache);
              }
              settings.onSuccess.call(context, response, $module, xhr);
            },
            complete: function(firstParameter, secondParameter) {
              var
                xhr,
                response
              ;
              // have to guess callback parameters based on request success
              if( module.was.succesful() ) {
                response = firstParameter;
                xhr      = secondParameter;
              }
              else {
                xhr      = firstParameter;
                response = module.get.responseFromXHR(xhr);
              }
              module.remove.loading();
              settings.onComplete.call(context, response, $module, xhr);
            },
            fail: function(xhr, status, httpMessage) {
              var
                // pull response from xhr if available
                response     = module.get.responseFromXHR(xhr),
                errorMessage = module.get.errorFromRequest(response, status, httpMessage)
              ;
              if(status == 'aborted') {
                module.debug('XHR Aborted (Most likely caused by page navigation or CORS Policy)', status, httpMessage);
                settings.onAbort.call(context, status, $module, xhr);
                return true;
              }
              else if(status == 'invalid') {
                module.debug('JSON did not pass success test. A server-side error has most likely occurred', response);
              }
              else if(status == 'error') {
                if(xhr !== undefined) {
                  module.debug('XHR produced a server error', status, httpMessage);
                  // make sure we have an error to display to console
                  if( xhr.status != 200 && httpMessage !== undefined && httpMessage !== '') {
                    module.error(error.statusMessage + httpMessage, ajaxSettings.url);
                  }
                  settings.onError.call(context, errorMessage, $module, xhr);
                }
              }

              if(settings.errorDuration && status !== 'aborted') {
                module.debug('Adding error state');
                module.set.error();
                if( module.should.removeError() ) {
                  setTimeout(module.remove.error, settings.errorDuration);
                }
              }
              module.debug('API Request failed', errorMessage, xhr);
              settings.onFailure.call(context, response, $module, xhr);
            }
          }
        },

        create: {

          request: function() {
            // api request promise
            return $.Deferred()
              .always(module.event.request.complete)
              .done(module.event.request.done)
              .fail(module.event.request.fail)
            ;
          },

          mockedXHR: function () {
            var
              // xhr does not simulate these properties of xhr but must return them
              textStatus     = false,
              status         = false,
              httpMessage    = false,
              responder      = settings.mockResponse      || settings.response,
              asyncResponder = settings.mockResponseAsync || settings.responseAsync,
              asyncCallback,
              response,
              mockedXHR
            ;

            mockedXHR = $.Deferred()
              .always(module.event.xhr.complete)
              .done(module.event.xhr.done)
              .fail(module.event.xhr.fail)
            ;

            if(responder) {
              if( $.isFunction(responder) ) {
                module.debug('Using specified synchronous callback', responder);
                response = responder.call(context, requestSettings);
              }
              else {
                module.debug('Using settings specified response', responder);
                response = responder;
              }
              // simulating response
              mockedXHR.resolveWith(context, [ response, textStatus, { responseText: response }]);
            }
            else if( $.isFunction(asyncResponder) ) {
              asyncCallback = function(response) {
                module.debug('Async callback returned response', response);

                if(response) {
                  mockedXHR.resolveWith(context, [ response, textStatus, { responseText: response }]);
                }
                else {
                  mockedXHR.rejectWith(context, [{ responseText: response }, status, httpMessage]);
                }
              };
              module.debug('Using specified async response callback', asyncResponder);
              asyncResponder.call(context, requestSettings, asyncCallback);
            }
            return mockedXHR;
          },

          xhr: function() {
            var
              xhr
            ;
            // ajax request promise
            xhr = $.ajax(ajaxSettings)
              .always(module.event.xhr.always)
              .done(module.event.xhr.done)
              .fail(module.event.xhr.fail)
            ;
            module.verbose('Created server request', xhr, ajaxSettings);
            return xhr;
          }
        },

        set: {
          error: function() {
            module.verbose('Adding error state to element', $context);
            $context.addClass(className.error);
          },
          loading: function() {
            module.verbose('Adding loading state to element', $context);
            $context.addClass(className.loading);
            requestStartTime = new Date().getTime();
          }
        },

        remove: {
          error: function() {
            module.verbose('Removing error state from element', $context);
            $context.removeClass(className.error);
          },
          loading: function() {
            module.verbose('Removing loading state from element', $context);
            $context.removeClass(className.loading);
          }
        },

        get: {
          responseFromXHR: function(xhr) {
            return $.isPlainObject(xhr)
              ? (module.is.expectingJSON())
                ? module.decode.json(xhr.responseText)
                : xhr.responseText
              : false
            ;
          },
          errorFromRequest: function(response, status, httpMessage) {
            return ($.isPlainObject(response) && response.error !== undefined)
              ? response.error // use json error message
              : (settings.error[status] !== undefined) // use server error message
                ? settings.error[status]
                : httpMessage
            ;
          },
          request: function() {
            return module.request || false;
          },
          xhr: function() {
            return module.xhr || false;
          },
          settings: function() {
            var
              runSettings
            ;
            runSettings = settings.beforeSend.call(context, settings);
            if(runSettings) {
              if(runSettings.success !== undefined) {
                module.debug('Legacy success callback detected', runSettings);
                module.error(error.legacyParameters, runSettings.success);
                runSettings.onSuccess = runSettings.success;
              }
              if(runSettings.failure !== undefined) {
                module.debug('Legacy failure callback detected', runSettings);
                module.error(error.legacyParameters, runSettings.failure);
                runSettings.onFailure = runSettings.failure;
              }
              if(runSettings.complete !== undefined) {
                module.debug('Legacy complete callback detected', runSettings);
                module.error(error.legacyParameters, runSettings.complete);
                runSettings.onComplete = runSettings.complete;
              }
            }
            if(runSettings === undefined) {
              module.error(error.noReturnedValue);
            }
            if(runSettings === false) {
              return runSettings;
            }
            return (runSettings !== undefined)
              ? $.extend(true, {}, runSettings)
              : $.extend(true, {}, settings)
            ;
          },
          urlEncodedValue: function(value) {
            var
              decodedValue   = window.decodeURIComponent(value),
              encodedValue   = window.encodeURIComponent(value),
              alreadyEncoded = (decodedValue !== value)
            ;
            if(alreadyEncoded) {
              module.debug('URL value is already encoded, avoiding double encoding', value);
              return value;
            }
            module.verbose('Encoding value using encodeURIComponent', value, encodedValue);
            return encodedValue;
          },
          defaultData: function() {
            var
              data = {}
            ;
            if( !$.isWindow(element) ) {
              if( module.is.input() ) {
                data.value = $module.val();
              }
              else if( module.is.form() ) {

              }
              else {
                data.text = $module.text();
              }
            }
            return data;
          },
          event: function() {
            if( $.isWindow(element) || settings.on == 'now' ) {
              module.debug('API called without element, no events attached');
              return false;
            }
            else if(settings.on == 'auto') {
              if( $module.is('input') ) {
                return (element.oninput !== undefined)
                  ? 'input'
                  : (element.onpropertychange !== undefined)
                    ? 'propertychange'
                    : 'keyup'
                ;
              }
              else if( $module.is('form') ) {
                return 'submit';
              }
              else {
                return 'click';
              }
            }
            else {
              return settings.on;
            }
          },
          templatedURL: function(action) {
            action = action || $module.data(metadata.action) || settings.action || false;
            url    = $module.data(metadata.url) || settings.url || false;
            if(url) {
              module.debug('Using specified url', url);
              return url;
            }
            if(action) {
              module.debug('Looking up url for action', action, settings.api);
              if(settings.api[action] === undefined && !module.is.mocked()) {
                module.error(error.missingAction, settings.action, settings.api);
                return;
              }
              url = settings.api[action];
            }
            else if( module.is.form() ) {
              url = $module.attr('action') || $context.attr('action') || false;
              module.debug('No url or action specified, defaulting to form action', url);
            }
            return url;
          }
        },

        abort: function() {
          var
            xhr = module.get.xhr()
          ;
          if( xhr && xhr.state() !== 'resolved') {
            module.debug('Cancelling API request');
            xhr.abort();
          }
        },

        // reset state
        reset: function() {
          module.remove.error();
          module.remove.loading();
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                //'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.api.settings = {

  name              : 'API',
  namespace         : 'api',

  debug             : false,
  verbose           : false,
  performance       : true,

  // object containing all templates endpoints
  api               : {},

  // whether to cache responses
  cache             : true,

  // whether new requests should abort previous requests
  interruptRequests : true,

  // event binding
  on                : 'auto',

  // context for applying state classes
  stateContext      : false,

  // duration for loading state
  loadingDuration   : 0,

  // whether to hide errors after a period of time
  hideError         : 'auto',

  // duration for error state
  errorDuration     : 2000,

  // whether parameters should be encoded with encodeURIComponent
  encodeParameters  : true,

  // API action to use
  action            : false,

  // templated URL to use
  url               : false,

  // base URL to apply to all endpoints
  base              : '',

  // data that will
  urlData           : {},

  // whether to add default data to url data
  defaultData          : true,

  // whether to serialize closest form
  serializeForm        : false,

  // how long to wait before request should occur
  throttle             : 0,

  // whether to throttle first request or only repeated
  throttleFirstRequest : true,

  // standard ajax settings
  method            : 'get',
  data              : {},
  dataType          : 'json',

  // mock response
  mockResponse      : false,
  mockResponseAsync : false,

  // aliases for mock
  response          : false,
  responseAsync     : false,

  // callbacks before request
  beforeSend  : function(settings) { return settings; },
  beforeXHR   : function(xhr) {},
  onRequest   : function(promise, xhr) {},

  // after request
  onResponse  : false, // function(response) { },

  // response was successful, if JSON passed validation
  onSuccess   : function(response, $module) {},

  // request finished without aborting
  onComplete  : function(response, $module) {},

  // failed JSON success test
  onFailure   : function(response, $module) {},

  // server error
  onError     : function(errorMessage, $module) {},

  // request aborted
  onAbort     : function(errorMessage, $module) {},

  successTest : false,

  // errors
  error : {
    beforeSend        : 'The before send function has aborted the request',
    error             : 'There was an error with your request',
    exitConditions    : 'API Request Aborted. Exit conditions met',
    JSONParse         : 'JSON could not be parsed during error handling',
    legacyParameters  : 'You are using legacy API success callback names',
    method            : 'The method you called is not defined',
    missingAction     : 'API action used but no url was defined',
    missingSerialize  : 'jquery-serialize-object is required to add form data to an existing data object',
    missingURL        : 'No URL specified for api event',
    noReturnedValue   : 'The beforeSend callback must return a settings object, beforeSend ignored.',
    noStorage         : 'Caching responses locally requires session storage',
    parseError        : 'There was an error parsing your request',
    requiredParameter : 'Missing a required URL parameter: ',
    statusMessage     : 'Server gave an error: ',
    timeout           : 'Your request timed out'
  },

  regExp  : {
    required : /\{\$*[A-z0-9]+\}/g,
    optional : /\{\/\$*[A-z0-9]+\}/g,
  },

  className: {
    loading : 'loading',
    error   : 'error'
  },

  selector: {
    disabled : '.disabled',
    form      : 'form'
  },

  metadata: {
    action  : 'action',
    url     : 'url'
  }
};



})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - State
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.state = function(parameters) {
  var
    $allModules     = $(this),

    moduleSelector  = $allModules.selector || '',

    hasTouch        = ('ontouchstart' in document.documentElement),
    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),

    returnedValue
  ;
  $allModules
    .each(function() {
      var
        settings          = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.state.settings, parameters)
          : $.extend({}, $.fn.state.settings),

        error           = settings.error,
        metadata        = settings.metadata,
        className       = settings.className,
        namespace       = settings.namespace,
        states          = settings.states,
        text            = settings.text,

        eventNamespace  = '.' + namespace,
        moduleNamespace = namespace + '-module',

        $module         = $(this),

        element         = this,
        instance        = $module.data(moduleNamespace),

        module
      ;
      module = {

        initialize: function() {
          module.verbose('Initializing module');

          // allow module to guess desired state based on element
          if(settings.automatic) {
            module.add.defaults();
          }

          // bind events with delegated events
          if(settings.context && moduleSelector !== '') {
            $(settings.context)
              .on(moduleSelector, 'mouseenter' + eventNamespace, module.change.text)
              .on(moduleSelector, 'mouseleave' + eventNamespace, module.reset.text)
              .on(moduleSelector, 'click'      + eventNamespace, module.toggle.state)
            ;
          }
          else {
            $module
              .on('mouseenter' + eventNamespace, module.change.text)
              .on('mouseleave' + eventNamespace, module.reset.text)
              .on('click'      + eventNamespace, module.toggle.state)
            ;
          }
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous module', instance);
          $module
            .off(eventNamespace)
            .removeData(moduleNamespace)
          ;
        },

        refresh: function() {
          module.verbose('Refreshing selector cache');
          $module = $(element);
        },

        add: {
          defaults: function() {
            var
              userStates = parameters && $.isPlainObject(parameters.states)
                ? parameters.states
                : {}
            ;
            $.each(settings.defaults, function(type, typeStates) {
              if( module.is[type] !== undefined && module.is[type]() ) {
                module.verbose('Adding default states', type, element);
                $.extend(settings.states, typeStates, userStates);
              }
            });
          }
        },

        is: {

          active: function() {
            return $module.hasClass(className.active);
          },
          loading: function() {
            return $module.hasClass(className.loading);
          },
          inactive: function() {
            return !( $module.hasClass(className.active) );
          },
          state: function(state) {
            if(className[state] === undefined) {
              return false;
            }
            return $module.hasClass( className[state] );
          },

          enabled: function() {
            return !( $module.is(settings.filter.active) );
          },
          disabled: function() {
            return ( $module.is(settings.filter.active) );
          },
          textEnabled: function() {
            return !( $module.is(settings.filter.text) );
          },

          // definitions for automatic type detection
          button: function() {
            return $module.is('.button:not(a, .submit)');
          },
          input: function() {
            return $module.is('input');
          },
          progress: function() {
            return $module.is('.ui.progress');
          }
        },

        allow: function(state) {
          module.debug('Now allowing state', state);
          states[state] = true;
        },
        disallow: function(state) {
          module.debug('No longer allowing', state);
          states[state] = false;
        },

        allows: function(state) {
          return states[state] || false;
        },

        enable: function() {
          $module.removeClass(className.disabled);
        },

        disable: function() {
          $module.addClass(className.disabled);
        },

        setState: function(state) {
          if(module.allows(state)) {
            $module.addClass( className[state] );
          }
        },

        removeState: function(state) {
          if(module.allows(state)) {
            $module.removeClass( className[state] );
          }
        },

        toggle: {
          state: function() {
            var
              apiRequest,
              requestCancelled
            ;
            if( module.allows('active') && module.is.enabled() ) {
              module.refresh();
              if($.fn.api !== undefined) {
                apiRequest       = $module.api('get request');
                requestCancelled = $module.api('was cancelled');
                if( requestCancelled ) {
                  module.debug('API Request cancelled by beforesend');
                  settings.activateTest   = function(){ return false; };
                  settings.deactivateTest = function(){ return false; };
                }
                else if(apiRequest) {
                  module.listenTo(apiRequest);
                  return;
                }
              }
              module.change.state();
            }
          }
        },

        listenTo: function(apiRequest) {
          module.debug('API request detected, waiting for state signal', apiRequest);
          if(apiRequest) {
            if(text.loading) {
              module.update.text(text.loading);
            }
            $.when(apiRequest)
              .then(function() {
                if(apiRequest.state() == 'resolved') {
                  module.debug('API request succeeded');
                  settings.activateTest   = function(){ return true; };
                  settings.deactivateTest = function(){ return true; };
                }
                else {
                  module.debug('API request failed');
                  settings.activateTest   = function(){ return false; };
                  settings.deactivateTest = function(){ return false; };
                }
                module.change.state();
              })
            ;
          }
        },

        // checks whether active/inactive state can be given
        change: {

          state: function() {
            module.debug('Determining state change direction');
            // inactive to active change
            if( module.is.inactive() ) {
              module.activate();
            }
            else {
              module.deactivate();
            }
            if(settings.sync) {
              module.sync();
            }
            settings.onChange.call(element);
          },

          text: function() {
            if( module.is.textEnabled() ) {
              if(module.is.disabled() ) {
                module.verbose('Changing text to disabled text', text.hover);
                module.update.text(text.disabled);
              }
              else if( module.is.active() ) {
                if(text.hover) {
                  module.verbose('Changing text to hover text', text.hover);
                  module.update.text(text.hover);
                }
                else if(text.deactivate) {
                  module.verbose('Changing text to deactivating text', text.deactivate);
                  module.update.text(text.deactivate);
                }
              }
              else {
                if(text.hover) {
                  module.verbose('Changing text to hover text', text.hover);
                  module.update.text(text.hover);
                }
                else if(text.activate){
                  module.verbose('Changing text to activating text', text.activate);
                  module.update.text(text.activate);
                }
              }
            }
          }

        },

        activate: function() {
          if( settings.activateTest.call(element) ) {
            module.debug('Setting state to active');
            $module
              .addClass(className.active)
            ;
            module.update.text(text.active);
            settings.onActivate.call(element);
          }
        },

        deactivate: function() {
          if( settings.deactivateTest.call(element) ) {
            module.debug('Setting state to inactive');
            $module
              .removeClass(className.active)
            ;
            module.update.text(text.inactive);
            settings.onDeactivate.call(element);
          }
        },

        sync: function() {
          module.verbose('Syncing other buttons to current state');
          if( module.is.active() ) {
            $allModules
              .not($module)
                .state('activate');
          }
          else {
            $allModules
              .not($module)
                .state('deactivate')
            ;
          }
        },

        get: {
          text: function() {
            return (settings.selector.text)
              ? $module.find(settings.selector.text).text()
              : $module.html()
            ;
          },
          textFor: function(state) {
            return text[state] || false;
          }
        },

        flash: {
          text: function(text, duration, callback) {
            var
              previousText = module.get.text()
            ;
            module.debug('Flashing text message', text, duration);
            text     = text     || settings.text.flash;
            duration = duration || settings.flashDuration;
            callback = callback || function() {};
            module.update.text(text);
            setTimeout(function(){
              module.update.text(previousText);
              callback.call(element);
            }, duration);
          }
        },

        reset: {
          // on mouseout sets text to previous value
          text: function() {
            var
              activeText   = text.active   || $module.data(metadata.storedText),
              inactiveText = text.inactive || $module.data(metadata.storedText)
            ;
            if( module.is.textEnabled() ) {
              if( module.is.active() && activeText) {
                module.verbose('Resetting active text', activeText);
                module.update.text(activeText);
              }
              else if(inactiveText) {
                module.verbose('Resetting inactive text', activeText);
                module.update.text(inactiveText);
              }
            }
          }
        },

        update: {
          text: function(text) {
            var
              currentText = module.get.text()
            ;
            if(text && text !== currentText) {
              module.debug('Updating text', text);
              if(settings.selector.text) {
                $module
                  .data(metadata.storedText, text)
                  .find(settings.selector.text)
                    .text(text)
                ;
              }
              else {
                $module
                  .data(metadata.storedText, text)
                  .html(text)
                ;
              }
            }
            else {
              module.debug('Text is already set, ignoring update', text);
            }
          }
        },

        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            if($.isPlainObject(settings[name])) {
              $.extend(true, settings[name], value);
            }
            else {
              settings[name] = value;
            }
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.state.settings = {

  // module info
  name           : 'State',

  // debug output
  debug          : false,

  // verbose debug output
  verbose        : false,

  // namespace for events
  namespace      : 'state',

  // debug data includes performance
  performance    : true,

  // callback occurs on state change
  onActivate     : function() {},
  onDeactivate   : function() {},
  onChange       : function() {},

  // state test functions
  activateTest   : function() { return true; },
  deactivateTest : function() { return true; },

  // whether to automatically map default states
  automatic      : true,

  // activate / deactivate changes all elements instantiated at same time
  sync           : false,

  // default flash text duration, used for temporarily changing text of an element
  flashDuration  : 1000,

  // selector filter
  filter     : {
    text   : '.loading, .disabled',
    active : '.disabled'
  },

  context    : false,

  // error
  error: {
    beforeSend : 'The before send function has cancelled state change',
    method     : 'The method you called is not defined.'
  },

  // metadata
  metadata: {
    promise    : 'promise',
    storedText : 'stored-text'
  },

  // change class on state
  className: {
    active   : 'active',
    disabled : 'disabled',
    error    : 'error',
    loading  : 'loading',
    success  : 'success',
    warning  : 'warning'
  },

  selector: {
    // selector for text node
    text: false
  },

  defaults : {
    input: {
      disabled : true,
      loading  : true,
      active   : true
    },
    button: {
      disabled : true,
      loading  : true,
      active   : true,
    },
    progress: {
      active   : true,
      success  : true,
      warning  : true,
      error    : true
    }
  },

  states     : {
    active   : true,
    disabled : true,
    error    : true,
    loading  : true,
    success  : true,
    warning  : true
  },

  text     : {
    disabled   : false,
    flash      : false,
    hover      : false,
    active     : false,
    inactive   : false,
    activate   : false,
    deactivate : false
  }

};



})( jQuery, window, document );

/*!
 * # Semantic UI 2.2.13 - Visibility
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ($, window, document, undefined) {

"use strict";

window = (typeof window != 'undefined' && window.Math == Math)
  ? window
  : (typeof self != 'undefined' && self.Math == Math)
    ? self
    : Function('return this')()
;

$.fn.visibility = function(parameters) {
  var
    $allModules    = $(this),
    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),
    returnedValue,

    moduleCount    = $allModules.length,
    loadedCount    = 0
  ;

  $allModules
    .each(function() {
      var
        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, $.fn.visibility.settings, parameters)
          : $.extend({}, $.fn.visibility.settings),

        className       = settings.className,
        namespace       = settings.namespace,
        error           = settings.error,
        metadata        = settings.metadata,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $window         = $(window),

        $module         = $(this),
        $context        = $(settings.context),

        $placeholder,

        selector        = $module.selector || '',
        instance        = $module.data(moduleNamespace),

        requestAnimationFrame = window.requestAnimationFrame
          || window.mozRequestAnimationFrame
          || window.webkitRequestAnimationFrame
          || window.msRequestAnimationFrame
          || function(callback) { setTimeout(callback, 0); },

        element         = this,
        disabled        = false,

        contextObserver,
        observer,
        module
      ;

      module = {

        initialize: function() {
          module.debug('Initializing', settings);

          module.setup.cache();

          if( module.should.trackChanges() ) {

            if(settings.type == 'image') {
              module.setup.image();
            }
            if(settings.type == 'fixed') {
              module.setup.fixed();
            }

            if(settings.observeChanges) {
              module.observeChanges();
            }
            module.bind.events();
          }

          module.save.position();
          if( !module.is.visible() ) {
            module.error(error.visible, $module);
          }

          if(settings.initialCheck) {
            module.checkVisibility();
          }
          module.instantiate();
        },

        instantiate: function() {
          module.debug('Storing instance', module);
          $module
            .data(moduleNamespace, module)
          ;
          instance = module;
        },

        destroy: function() {
          module.verbose('Destroying previous module');
          if(observer) {
            observer.disconnect();
          }
          if(contextObserver) {
            contextObserver.disconnect();
          }
          $window
            .off('load'   + eventNamespace, module.event.load)
            .off('resize' + eventNamespace, module.event.resize)
          ;
          $context
            .off('scroll'       + eventNamespace, module.event.scroll)
            .off('scrollchange' + eventNamespace, module.event.scrollchange)
          ;
          if(settings.type == 'fixed') {
            module.resetFixed();
            module.remove.placeholder();
          }
          $module
            .off(eventNamespace)
            .removeData(moduleNamespace)
          ;
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            contextObserver = new MutationObserver(module.event.contextChanged);
            observer        = new MutationObserver(module.event.changed);
            contextObserver.observe(document, {
              childList : true,
              subtree   : true
            });
            observer.observe(element, {
              childList : true,
              subtree   : true
            });
            module.debug('Setting up mutation observer', observer);
          }
        },

        bind: {
          events: function() {
            module.verbose('Binding visibility events to scroll and resize');
            if(settings.refreshOnLoad) {
              $window
                .on('load'   + eventNamespace, module.event.load)
              ;
            }
            $window
              .on('resize' + eventNamespace, module.event.resize)
            ;
            // pub/sub pattern
            $context
              .off('scroll'      + eventNamespace)
              .on('scroll'       + eventNamespace, module.event.scroll)
              .on('scrollchange' + eventNamespace, module.event.scrollchange)
            ;
          }
        },

        event: {
          changed: function(mutations) {
            module.verbose('DOM tree modified, updating visibility calculations');
            module.timer = setTimeout(function() {
              module.verbose('DOM tree modified, updating sticky menu');
              module.refresh();
            }, 100);
          },
          contextChanged: function(mutations) {
            [].forEach.call(mutations, function(mutation) {
              if(mutation.removedNodes) {
                [].forEach.call(mutation.removedNodes, function(node) {
                  if(node == element || $(node).find(element).length > 0) {
                    module.debug('Element removed from DOM, tearing down events');
                    module.destroy();
                  }
                });
              }
            });
          },
          resize: function() {
            module.debug('Window resized');
            if(settings.refreshOnResize) {
              requestAnimationFrame(module.refresh);
            }
          },
          load: function() {
            module.debug('Page finished loading');
            requestAnimationFrame(module.refresh);
          },
          // publishes scrollchange event on one scroll
          scroll: function() {
            if(settings.throttle) {
              clearTimeout(module.timer);
              module.timer = setTimeout(function() {
                $context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]);
              }, settings.throttle);
            }
            else {
              requestAnimationFrame(function() {
                $context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]);
              });
            }
          },
          // subscribes to scrollchange
          scrollchange: function(event, scrollPosition) {
            module.checkVisibility(scrollPosition);
          },
        },

        precache: function(images, callback) {
          if (!(images instanceof Array)) {
            images = [images];
          }
          var
            imagesLength  = images.length,
            loadedCounter = 0,
            cache         = [],
            cacheImage    = document.createElement('img'),
            handleLoad    = function() {
              loadedCounter++;
              if (loadedCounter >= images.length) {
                if ($.isFunction(callback)) {
                  callback();
                }
              }
            }
          ;
          while (imagesLength--) {
            cacheImage         = document.createElement('img');
            cacheImage.onload  = handleLoad;
            cacheImage.onerror = handleLoad;
            cacheImage.src     = images[imagesLength];
            cache.push(cacheImage);
          }
        },

        enableCallbacks: function() {
          module.debug('Allowing callbacks to occur');
          disabled = false;
        },

        disableCallbacks: function() {
          module.debug('Disabling all callbacks temporarily');
          disabled = true;
        },

        should: {
          trackChanges: function() {
            if(methodInvoked) {
              module.debug('One time query, no need to bind events');
              return false;
            }
            module.debug('Callbacks being attached');
            return true;
          }
        },

        setup: {
          cache: function() {
            module.cache = {
              occurred : {},
              screen   : {},
              element  : {},
            };
          },
          image: function() {
            var
              src = $module.data(metadata.src)
            ;
            if(src) {
              module.verbose('Lazy loading image', src);
              settings.once           = true;
              settings.observeChanges = false;

              // show when top visible
              settings.onOnScreen = function() {
                module.debug('Image on screen', element);
                module.precache(src, function() {
                  module.set.image(src, function() {
                    loadedCount++;
                    if(loadedCount == moduleCount) {
                      settings.onAllLoaded.call(this);
                    }
                    settings.onLoad.call(this);
                  });
                });
              };
            }
          },
          fixed: function() {
            module.debug('Setting up fixed');
            settings.once           = false;
            settings.observeChanges = false;
            settings.initialCheck   = true;
            settings.refreshOnLoad  = true;
            if(!parameters.transition) {
              settings.transition = false;
            }
            module.create.placeholder();
            module.debug('Added placeholder', $placeholder);
            settings.onTopPassed = function() {
              module.debug('Element passed, adding fixed position', $module);
              module.show.placeholder();
              module.set.fixed();
              if(settings.transition) {
                if($.fn.transition !== undefined) {
                  $module.transition(settings.transition, settings.duration);
                }
              }
            };
            settings.onTopPassedReverse = function() {
              module.debug('Element returned to position, removing fixed', $module);
              module.hide.placeholder();
              module.remove.fixed();
            };
          }
        },

        create: {
          placeholder: function() {
            module.verbose('Creating fixed position placeholder');
            $placeholder = $module
              .clone(false)
              .css('display', 'none')
              .addClass(className.placeholder)
              .insertAfter($module)
            ;
          }
        },

        show: {
          placeholder: function() {
            module.verbose('Showing placeholder');
            $placeholder
              .css('display', 'block')
              .css('visibility', 'hidden')
            ;
          }
        },
        hide: {
          placeholder: function() {
            module.verbose('Hiding placeholder');
            $placeholder
              .css('display', 'none')
              .css('visibility', '')
            ;
          }
        },

        set: {
          fixed: function() {
            module.verbose('Setting element to fixed position');
            $module
              .addClass(className.fixed)
              .css({
                position : 'fixed',
                top      : settings.offset + 'px',
                left     : 'auto',
                zIndex   : settings.zIndex
              })
            ;
            settings.onFixed.call(element);
          },
          image: function(src, callback) {
            $module
              .attr('src', src)
            ;
            if(settings.transition) {
              if( $.fn.transition !== undefined) {
                if($module.hasClass(className.visible)) {
                  module.debug('Transition already occurred on this image, skipping animation');
                  return;
                }
                $module.transition(settings.transition, settings.duration, callback);
              }
              else {
                $module.fadeIn(settings.duration, callback);
              }
            }
            else {
              $module.show();
            }
          }
        },

        is: {
          onScreen: function() {
            var
              calculations   = module.get.elementCalculations()
            ;
            return calculations.onScreen;
          },
          offScreen: function() {
            var
              calculations   = module.get.elementCalculations()
            ;
            return calculations.offScreen;
          },
          visible: function() {
            if(module.cache && module.cache.element) {
              return !(module.cache.element.width === 0 && module.cache.element.offset.top === 0);
            }
            return false;
          },
          verticallyScrollableContext: function() {
            var
              overflowY = ($context.get(0) !== window)
                ? $context.css('overflow-y')
                : false
            ;
            return (overflowY == 'auto' || overflowY == 'scroll');
          },
          horizontallyScrollableContext: function() {
            var
              overflowX = ($context.get(0) !== window)
                ? $context.css('overflow-x')
                : false
            ;
            return (overflowX == 'auto' || overflowX == 'scroll');
          }
        },

        refresh: function() {
          module.debug('Refreshing constants (width/height)');
          if(settings.type == 'fixed') {
            module.resetFixed();
          }
          module.reset();
          module.save.position();
          if(settings.checkOnRefresh) {
            module.checkVisibility();
          }
          settings.onRefresh.call(element);
        },

        resetFixed: function () {
          module.remove.fixed();
          module.remove.occurred();
        },

        reset: function() {
          module.verbose('Resetting all cached values');
          if( $.isPlainObject(module.cache) ) {
            module.cache.screen = {};
            module.cache.element = {};
          }
        },

        checkVisibility: function(scroll) {
          module.verbose('Checking visibility of element', module.cache.element);

          if( !disabled && module.is.visible() ) {

            // save scroll position
            module.save.scroll(scroll);

            // update calculations derived from scroll
            module.save.calculations();

            // percentage
            module.passed();

            // reverse (must be first)
            module.passingReverse();
            module.topVisibleReverse();
            module.bottomVisibleReverse();
            module.topPassedReverse();
            module.bottomPassedReverse();

            // one time
            module.onScreen();
            module.offScreen();
            module.passing();
            module.topVisible();
            module.bottomVisible();
            module.topPassed();
            module.bottomPassed();

            // on update callback
            if(settings.onUpdate) {
              settings.onUpdate.call(element, module.get.elementCalculations());
            }
          }
        },

        passed: function(amount, newCallback) {
          var
            calculations   = module.get.elementCalculations(),
            amountInPixels
          ;
          // assign callback
          if(amount && newCallback) {
            settings.onPassed[amount] = newCallback;
          }
          else if(amount !== undefined) {
            return (module.get.pixelsPassed(amount) > calculations.pixelsPassed);
          }
          else if(calculations.passing) {
            $.each(settings.onPassed, function(amount, callback) {
              if(calculations.bottomVisible || calculations.pixelsPassed > module.get.pixelsPassed(amount)) {
                module.execute(callback, amount);
              }
              else if(!settings.once) {
                module.remove.occurred(callback);
              }
            });
          }
        },

        onScreen: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onOnScreen,
            callbackName = 'onScreen'
          ;
          if(newCallback) {
            module.debug('Adding callback for onScreen', newCallback);
            settings.onOnScreen = newCallback;
          }
          if(calculations.onScreen) {
            module.execute(callback, callbackName);
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback !== undefined) {
            return calculations.onOnScreen;
          }
        },

        offScreen: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onOffScreen,
            callbackName = 'offScreen'
          ;
          if(newCallback) {
            module.debug('Adding callback for offScreen', newCallback);
            settings.onOffScreen = newCallback;
          }
          if(calculations.offScreen) {
            module.execute(callback, callbackName);
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback !== undefined) {
            return calculations.onOffScreen;
          }
        },

        passing: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onPassing,
            callbackName = 'passing'
          ;
          if(newCallback) {
            module.debug('Adding callback for passing', newCallback);
            settings.onPassing = newCallback;
          }
          if(calculations.passing) {
            module.execute(callback, callbackName);
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback !== undefined) {
            return calculations.passing;
          }
        },


        topVisible: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onTopVisible,
            callbackName = 'topVisible'
          ;
          if(newCallback) {
            module.debug('Adding callback for top visible', newCallback);
            settings.onTopVisible = newCallback;
          }
          if(calculations.topVisible) {
            module.execute(callback, callbackName);
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback === undefined) {
            return calculations.topVisible;
          }
        },

        bottomVisible: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onBottomVisible,
            callbackName = 'bottomVisible'
          ;
          if(newCallback) {
            module.debug('Adding callback for bottom visible', newCallback);
            settings.onBottomVisible = newCallback;
          }
          if(calculations.bottomVisible) {
            module.execute(callback, callbackName);
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback === undefined) {
            return calculations.bottomVisible;
          }
        },

        topPassed: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onTopPassed,
            callbackName = 'topPassed'
          ;
          if(newCallback) {
            module.debug('Adding callback for top passed', newCallback);
            settings.onTopPassed = newCallback;
          }
          if(calculations.topPassed) {
            module.execute(callback, callbackName);
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback === undefined) {
            return calculations.topPassed;
          }
        },

        bottomPassed: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onBottomPassed,
            callbackName = 'bottomPassed'
          ;
          if(newCallback) {
            module.debug('Adding callback for bottom passed', newCallback);
            settings.onBottomPassed = newCallback;
          }
          if(calculations.bottomPassed) {
            module.execute(callback, callbackName);
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback === undefined) {
            return calculations.bottomPassed;
          }
        },

        passingReverse: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onPassingReverse,
            callbackName = 'passingReverse'
          ;
          if(newCallback) {
            module.debug('Adding callback for passing reverse', newCallback);
            settings.onPassingReverse = newCallback;
          }
          if(!calculations.passing) {
            if(module.get.occurred('passing')) {
              module.execute(callback, callbackName);
            }
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback !== undefined) {
            return !calculations.passing;
          }
        },


        topVisibleReverse: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onTopVisibleReverse,
            callbackName = 'topVisibleReverse'
          ;
          if(newCallback) {
            module.debug('Adding callback for top visible reverse', newCallback);
            settings.onTopVisibleReverse = newCallback;
          }
          if(!calculations.topVisible) {
            if(module.get.occurred('topVisible')) {
              module.execute(callback, callbackName);
            }
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback === undefined) {
            return !calculations.topVisible;
          }
        },

        bottomVisibleReverse: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onBottomVisibleReverse,
            callbackName = 'bottomVisibleReverse'
          ;
          if(newCallback) {
            module.debug('Adding callback for bottom visible reverse', newCallback);
            settings.onBottomVisibleReverse = newCallback;
          }
          if(!calculations.bottomVisible) {
            if(module.get.occurred('bottomVisible')) {
              module.execute(callback, callbackName);
            }
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback === undefined) {
            return !calculations.bottomVisible;
          }
        },

        topPassedReverse: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onTopPassedReverse,
            callbackName = 'topPassedReverse'
          ;
          if(newCallback) {
            module.debug('Adding callback for top passed reverse', newCallback);
            settings.onTopPassedReverse = newCallback;
          }
          if(!calculations.topPassed) {
            if(module.get.occurred('topPassed')) {
              module.execute(callback, callbackName);
            }
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback === undefined) {
            return !calculations.onTopPassed;
          }
        },

        bottomPassedReverse: function(newCallback) {
          var
            calculations = module.get.elementCalculations(),
            callback     = newCallback || settings.onBottomPassedReverse,
            callbackName = 'bottomPassedReverse'
          ;
          if(newCallback) {
            module.debug('Adding callback for bottom passed reverse', newCallback);
            settings.onBottomPassedReverse = newCallback;
          }
          if(!calculations.bottomPassed) {
            if(module.get.occurred('bottomPassed')) {
              module.execute(callback, callbackName);
            }
          }
          else if(!settings.once) {
            module.remove.occurred(callbackName);
          }
          if(newCallback === undefined) {
            return !calculations.bottomPassed;
          }
        },

        execute: function(callback, callbackName) {
          var
            calculations = module.get.elementCalculations(),
            screen       = module.get.screenCalculations()
          ;
          callback = callback || false;
          if(callback) {
            if(settings.continuous) {
              module.debug('Callback being called continuously', callbackName, calculations);
              callback.call(element, calculations, screen);
            }
            else if(!module.get.occurred(callbackName)) {
              module.debug('Conditions met', callbackName, calculations);
              callback.call(element, calculations, screen);
            }
          }
          module.save.occurred(callbackName);
        },

        remove: {
          fixed: function() {
            module.debug('Removing fixed position');
            $module
              .removeClass(className.fixed)
              .css({
                position : '',
                top      : '',
                left     : '',
                zIndex   : ''
              })
            ;
            settings.onUnfixed.call(element);
          },
          placeholder: function() {
            module.debug('Removing placeholder content');
            if($placeholder) {
              $placeholder.remove();
            }
          },
          occurred: function(callback) {
            if(callback) {
              var
                occurred = module.cache.occurred
              ;
              if(occurred[callback] !== undefined && occurred[callback] === true) {
                module.debug('Callback can now be called again', callback);
                module.cache.occurred[callback] = false;
              }
            }
            else {
              module.cache.occurred = {};
            }
          }
        },

        save: {
          calculations: function() {
            module.verbose('Saving all calculations necessary to determine positioning');
            module.save.direction();
            module.save.screenCalculations();
            module.save.elementCalculations();
          },
          occurred: function(callback) {
            if(callback) {
              if(module.cache.occurred[callback] === undefined || (module.cache.occurred[callback] !== true)) {
                module.verbose('Saving callback occurred', callback);
                module.cache.occurred[callback] = true;
              }
            }
          },
          scroll: function(scrollPosition) {
            scrollPosition      = scrollPosition + settings.offset || $context.scrollTop() + settings.offset;
            module.cache.scroll = scrollPosition;
          },
          direction: function() {
            var
              scroll     = module.get.scroll(),
              lastScroll = module.get.lastScroll(),
              direction
            ;
            if(scroll > lastScroll && lastScroll) {
              direction = 'down';
            }
            else if(scroll < lastScroll && lastScroll) {
              direction = 'up';
            }
            else {
              direction = 'static';
            }
            module.cache.direction = direction;
            return module.cache.direction;
          },
          elementPosition: function() {
            var
              element = module.cache.element,
              screen  = module.get.screenSize()
            ;
            module.verbose('Saving element position');
            // (quicker than $.extend)
            element.fits          = (element.height < screen.height);
            element.offset        = $module.offset();
            element.width         = $module.outerWidth();
            element.height        = $module.outerHeight();
            // compensate for scroll in context
            if(module.is.verticallyScrollableContext()) {
              element.offset.top += $context.scrollTop() - $context.offset().top;
            }
            if(module.is.horizontallyScrollableContext()) {
              element.offset.left += $context.scrollLeft - $context.offset().left;
            }
            // store
            module.cache.element = element;
            return element;
          },
          elementCalculations: function() {
            var
              screen     = module.get.screenCalculations(),
              element    = module.get.elementPosition()
            ;
            // offset
            if(settings.includeMargin) {
              element.margin        = {};
              element.margin.top    = parseInt($module.css('margin-top'), 10);
              element.margin.bottom = parseInt($module.css('margin-bottom'), 10);
              element.top    = element.offset.top - element.margin.top;
              element.bottom = element.offset.top + element.height + element.margin.bottom;
            }
            else {
              element.top    = element.offset.top;
              element.bottom = element.offset.top + element.height;
            }

            // visibility
            element.topPassed        = (screen.top >= element.top);
            element.bottomPassed     = (screen.top >= element.bottom);
            element.topVisible       = (screen.bottom >= element.top) && !element.bottomPassed;
            element.bottomVisible    = (screen.bottom >= element.bottom) && !element.topPassed;
            element.pixelsPassed     = 0;
            element.percentagePassed = 0;

            // meta calculations
            element.onScreen  = (element.topVisible && !element.bottomPassed);
            element.passing   = (element.topPassed && !element.bottomPassed);
            element.offScreen = (!element.onScreen);

            // passing calculations
            if(element.passing) {
              element.pixelsPassed     = (screen.top - element.top);
              element.percentagePassed = (screen.top - element.top) / element.height;
            }
            module.cache.element = element;
            module.verbose('Updated element calculations', element);
            return element;
          },
          screenCalculations: function() {
            var
              scroll = module.get.scroll()
            ;
            module.save.direction();
            module.cache.screen.top    = scroll;
            module.cache.screen.bottom = scroll + module.cache.screen.height;
            return module.cache.screen;
          },
          screenSize: function() {
            module.verbose('Saving window position');
            module.cache.screen = {
              height: $context.height()
            };
          },
          position: function() {
            module.save.screenSize();
            module.save.elementPosition();
          }
        },

        get: {
          pixelsPassed: function(amount) {
            var
              element = module.get.elementCalculations()
            ;
            if(amount.search('%') > -1) {
              return ( element.height * (parseInt(amount, 10) / 100) );
            }
            return parseInt(amount, 10);
          },
          occurred: function(callback) {
            return (module.cache.occurred !== undefined)
              ? module.cache.occurred[callback] || false
              : false
            ;
          },
          direction: function() {
            if(module.cache.direction === undefined) {
              module.save.direction();
            }
            return module.cache.direction;
          },
          elementPosition: function() {
            if(module.cache.element === undefined) {
              module.save.elementPosition();
            }
            return module.cache.element;
          },
          elementCalculations: function() {
            if(module.cache.element === undefined) {
              module.save.elementCalculations();
            }
            return module.cache.element;
          },
          screenCalculations: function() {
            if(module.cache.screen === undefined) {
              module.save.screenCalculations();
            }
            return module.cache.screen;
          },
          screenSize: function() {
            if(module.cache.screen === undefined) {
              module.save.screenSize();
            }
            return module.cache.screen;
          },
          scroll: function() {
            if(module.cache.scroll === undefined) {
              module.save.scroll();
            }
            return module.cache.scroll;
          },
          lastScroll: function() {
            if(module.cache.screen === undefined) {
              module.debug('First scroll event, no last scroll could be found');
              return false;
            }
            return module.cache.screen.top;
          }
        },

        setting: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(!settings.silent && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(!settings.silent && settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          if(!settings.silent) {
            module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
            module.error.apply(console, arguments);
          }
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        instance.save.scroll();
        instance.save.calculations();
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.visibility.settings = {

  name                   : 'Visibility',
  namespace              : 'visibility',

  debug                  : false,
  verbose                : false,
  performance            : true,

  // whether to use mutation observers to follow changes
  observeChanges         : true,

  // check position immediately on init
  initialCheck           : true,

  // whether to refresh calculations after all page images load
  refreshOnLoad          : true,

  // whether to refresh calculations after page resize event
  refreshOnResize        : true,

  // should call callbacks on refresh event (resize, etc)
  checkOnRefresh         : true,

  // callback should only occur one time
  once                   : true,

  // callback should fire continuously whe evaluates to true
  continuous             : false,

  // offset to use with scroll top
  offset                 : 0,

  // whether to include margin in elements position
  includeMargin          : false,

  // scroll context for visibility checks
  context                : window,

  // visibility check delay in ms (defaults to animationFrame)
  throttle               : false,

  // special visibility type (image, fixed)
  type                   : false,

  // z-index to use with visibility 'fixed'
  zIndex                 : '10',

  // image only animation settings
  transition             : 'fade in',
  duration               : 1000,

  // array of callbacks for percentage
  onPassed               : {},

  // standard callbacks
  onOnScreen             : false,
  onOffScreen            : false,
  onPassing              : false,
  onTopVisible           : false,
  onBottomVisible        : false,
  onTopPassed            : false,
  onBottomPassed         : false,

  // reverse callbacks
  onPassingReverse       : false,
  onTopVisibleReverse    : false,
  onBottomVisibleReverse : false,
  onTopPassedReverse     : false,
  onBottomPassedReverse  : false,

  // special callbacks for image
  onLoad                 : function() {},
  onAllLoaded            : function() {},

  // special callbacks for fixed position
  onFixed                : function() {},
  onUnfixed              : function() {},

  // utility callbacks
  onUpdate               : false, // disabled by default for performance
  onRefresh              : function(){},

  metadata : {
    src: 'src'
  },

  className: {
    fixed       : 'fixed',
    placeholder : 'placeholder',
    visible     : 'visible'
  },

  error : {
    method  : 'The method you called is not defined.',
    visible : 'Element is hidden, you must call refresh after element becomes visible'
  }

};

})( jQuery, window, document );
(function() {
  var last_flatten_select_id, proxied;

  window.delay = function(ms, func) {
    return setTimeout(func, ms);
  };

  window.comments_text_area_index = 0;

  window.filter_pairs = [];

  window.filter_accordion = function(e) {
    var filter_pairs, item, target, val;
    val = $j(e.target).val().toLowerCase();
    target = $j("" + ($j(e.target).attr('for')));
    filter_pairs = [];
    item = $j(e.target).attr('item');
    target.find("" + item).each(function() {
      if ($j(this).text().toLowerCase().search(val) !== -1) {
        return $j(this).show();
      } else {
        return $j(this).hide();
      }
    });
    target.find('.title').each(function() {
      if ($j(this).next('.content').find(item + ":visible").length < 1) {
        return $j(this).next('.content').hide();
      } else {
        return $j(this).next('.content').show();
      }
    });
    return true;
  };

  $j.fn.filterer = function() {
    var target;
    $j(this).addClass('initialized');
    target = $j("" + ($j(this).attr('for')));
    if (target.hasClass('accordion')) {
      $j(this).on('keyup', filter_accordion);
    }
    if (target.hasClass('table')) {
      alert(' We got table');
    }
    return $j(this);
  };

  proxied = window.alert;

  last_flatten_select_id = 0;

  window.selectFlatten = function(flatten_select_id, value_to_select) {
    var buttons, select;
    buttons = $j("#" + flatten_select_id + "_flatten_select");
    buttons.children().removeClass('active');
    buttons.find("div.button[val='" + value_to_select + "']").addClass('active');
    select = $j("select[flatten_id=" + flatten_select_id + "]");
    select.find('option').prop('selected', false);
    select.find("option[value='" + value_to_select + "']").prop('selected', true);
    return true;
  };

  window.initAccordion = function(item) {
    var options;
    options = {};
    if (item.data('exclusive') != null) {
      options.exclusive = item.data('exclusive');
    }
    if (item.data('collapsible') != null) {
      options.collapsible = item.data('collapsible');
    }
    options.onOpen = function(e) {
      return $j('.toggle_filter', this).addClass('expanded');
    };
    item.accordion(options);
    item.addClass('initialized');
    return true;
  };

  window.initEverything = function() {
    $j("select.combo:not(.initialized)").select2().addClass('initialized');
    $j('.popup:not(.initialized)').popup().addClass('initialized');
    $j('.ui.accordion:not(.initialized)').each(function() {
      if ($j(this).parents('.accordion').length > 0) {
        return $j(this).addClass('initialized');
      }
    });
    $j('.ui.accordion:not(.initialized)').each(function() {
      return initAccordion($j(this));
    });
    $j('.filterer:not(.initialized)').each(function() {
      return $j(this).filterer().focus();
    });
    $j("select.flatten").each(function() {
      var html, select;
      last_flatten_select_id += 1;
      select = $j(this);
      select.hide();
      select.attr('flatten_id', last_flatten_select_id);
      select.removeClass('flatten');
      html = "<div class='ui buttons tiny " + (select.attr('class').replace('flatten', '')) + "' id='" + last_flatten_select_id + "_flatten_select'>";
      select.find('option').each(function() {
        return html += "<div class='ui button " + ($j(this).attr('selected') ? 'active' : void 0) + "' val='" + ($j(this).val()) + "' onClick='selectFlatten(" + last_flatten_select_id + ", \"" + ($j(this).val()) + "\")'>" + ($j(this).html()) + "</div>";
      });
      html << "</div>";
      select.parent().append(html);
      return true;
    });
    $j('i.link.icon').live('click', function() {
      return window.location = $j(this).attr('href');
    });
    $j('.ago').each(function() {
      var appendix, now, now_local, origin, popup_time, time_section, v, val;
      if (typeof $j(this).attr('data-content') === "undefined") {
        popup_time = $j(this).attr('title');
        if (!popup_time) {
          popup_time = $j(this).html();
        }
        $j(this).attr('origin-time', $j(this).html()).attr('data-content', popup_time).popup({
          debug: false
        });
      }
      val = new Date($j(this).attr('data-content'));
      now_local = new Date();
      now = new Date(now_local.getTime() + now_local.getTimezoneOffset() * 60000);
      time_section = now - val;
      origin = {
        min: 1000 * 60,
        hour: 1000 * 60 * 60,
        day: 1000 * 60 * 60 * 24,
        week: 1000 * 60 * 60 * 24 * 7,
        month: 1000 * 60 * 60 * 24 * 30,
        year: 1000 * 60 * 60 * 24 * 30 * 365
      };
      switch (true) {
        case time_section < origin.hour:
          v = parseInt(time_section / origin.min);
          appendix = v === 1 ? "minute" : "minutes";
          break;
        case time_section < origin.day:
          v = parseInt(time_section / origin.hour);
          appendix = v === 1 ? "hour" : "hours";
          break;
        case time_section < origin.week:
          v = parseInt(time_section / origin.day);
          appendix = v === 1 ? "day" : "days";
          break;
        case time_section < origin.month:
          v = parseInt(time_section / origin.week);
          appendix = v === 1 ? "week" : "weeks";
          break;
        case time_section < origin.year:
          v = parseInt(time_section / origin.month);
          appendix = v === 1 ? "month" : "monthes";
          break;
        case time_section >= origin.year:
          v = parseInt(time_section / origin.year);
          appendix = v === 1 ? "year" : "years";
          break;
        default:
          v = "few";
          appendix = "seconds";
      }
      $j(this).html(v + " " + appendix + " ago");
      return true;
    });
    $j('.transform_to_text_area:not(.initialized)').addClass('initialized').each(function() {
      $j(this).attr('data-content', 'Rich Text Editor').popup({
        debug: false
      });
      $j(this).parent().find('input[type=text]').attr('id', 'comment_field_' + comments_text_area_index);
      $j(this).parent().parent().find('input[name=comment_virtual_id]').val('comment_field_' + comments_text_area_index);
      comments_text_area_index += 1;
      $j(this).click(function() {
        var input, textarea, textarea_id;
        input = $j(this).parent().find('input[type=text]');
        $j(this).hide();
        textarea_id = input.prop('id');
        textarea = $j('<textarea>');
        $j.each($j(input).get(0).attributes, function(i, attrib) {
          return $j(textarea).attr(attrib.name, attrib.value);
        });
        $j(textarea).html(input.val());
        $j(input).replaceWith(textarea);
        tinyMCE.init({
          mode: "exact",
          elements: textarea_id,
          theme: "simple"
        });
        delay(1000, function() {
          return tinyMCE.execCommand('mceFocus', true, textarea_id);
        });
        $j(this).parent().find('.transform_to_text_field').show().attr('data-content', 'Simple field').css('cursor', 'pointer').popup({
          debug: false
        });
        return true;
      });
      $j(this).parent().find('.transform_to_text_field').click(function() {
        var input, textarea;
        textarea = $j(this).parent().find('textarea');
        input = $j('<input type="text">');
        $j(input).val(tinyMCE.get(textarea.prop('id')).getContent().replace(/<\/?[^>]+>/gi, ''));
        tinyMCE.execCommand('mceRemoveEditor', true, textarea.prop('id'));
        $j.each($j(textarea).get(0).attributes, function(i, attrib) {
          return $j(input).attr(attrib.name, attrib.value);
        });
        $j(textarea).replaceWith(input);
        $j(this).hide();
        $j(this).parent().find('.transform_to_text_area').show();
        return true;
      });
      return true;
    });
    return true;
  };

  window.initEverythingWithDelay = function() {
    initEverything();
    return setTimeout(function() {
      return initEverythingWithDelay();
    }, 1500);
  };

  $j(document).ready(function() {
    $j('.has_popup').livequery(function() {
      return $j(this).removeClass('has_popup').popup();
    });
    $j('.ui.dropdown:not(.icon.initialized):not(.no_auto_init)').livequery(function() {
      var $this, action;
      $this = $j(this);
      action = $this.data('action') || 'activate';
      return $this.dropdown({
        action: action
      }).addClass('initialized');
    });
    return initEverythingWithDelay();
  });

  window.semantic_loaded = true;

}).call(this);
/*
 * NchanSubscriber
 * usage: var sub = new NchanSubscriber(url, opt);
 * 
 * opt = {
 *   subscriber: 'longpoll', 'eventsource', or 'websocket',
 *     //or an array of the above indicating subscriber type preference
 *   reconnect: undefined or 'session' or 'persist'
 *     //if the HTML5 sessionStore or localStore should be used to resume
 *     //connections interrupted by a page load
 *   shared: true or undefined
 *     //share connection to same subscriber url between browser 
 *     //windows and tabs using localStorage. In shared mode, 
 *     //only 1 running subscriber is allowed per url per window/tab.
 * }
 * 
 * sub.on("transportSetup", function(opt, subscriberName) {
 *   // opt is a hash/object - not all transports support all options equally. Only longpoll supports arbitrary headers
 *   // subscriberName is a string
 *   //
 *   // longpoll transport supports:
 *   //   opt.longpoll.pollDelay - delay in milliseconds between successful requests
 *   // eventsource transport supports:
 *   //   opt.eventsource.withCredentials - boolean enabling the withCredentials CORS setting
 * });
 * 
 * sub.on("transportNativeCreated", function(nativeTransportObject, subscriberName) {
 *   // nativeTransportObject is the native transport object and depends on the subscriber type
 *   // subscriberName is a string
 * });
 *
 * sub.on("transportNativeBeforeDestroy", function(nativeTransportObject, subscriberName) {
 *   // nativeTransportObject is the native transport object and depends on the subscriber type
 *   // subscriberName is a string
 * });
 *
 * sub.on("message", function(message, message_metadata) {
 *   // message is a string
 *   // message_metadata may contain 'id' and 'content-type'
 * });
 * 
 * sub.on('connect', function(evt) {
 *   //fired when first connected. 
 * });
 * 
 * sub.on('disconnect', function(evt) {
 *   // when disconnected.
 * });
 * 
 * sub.on('error', function(code, message) {
 *   //error callback. not sure about the parameters yet
 * });
 * 
 * sub.reconnect; // should subscriber try to reconnect? true by default.
 * sub.reconnectTimeout; //how long to wait to reconnect? does not apply to EventSource, which reconnects on its own.
 * sub.lastMessageId; //last message id. useful for resuming a connection without loss or repetition.
 * 
 * sub.start(); // begin (or resume) subscribing
 * sub.stop(); // stop subscriber. do not reconnect.
 */

//Thanks Darren Whitlen ( @prawnsalad ) for your feedback


;(function (global, moduleName, factory) { // eslint-disable-line
  "use strict";
  /* eslint-disable no-undef */
  var newModule = factory(global);
  if (typeof module === "object" && module != null && module.exports) {
    module.exports = newModule;
  } else if (typeof define === "function" && define.amd) {
    define(function () { return newModule; });
  } else {
    global[moduleName] = newModule;
  }
  /* eslint-enable no-undef */
})(typeof window !== "undefined" ? window : this, "NchanSubscriber", function factory(global, undefined) { // eslint-disable-line

  // https://github.com/yanatan16/nanoajax
  var nanoajax={};
  (function(){var e=["responseType","withCredentials","timeout","onprogress"];nanoajax.ajax=function(r,o){var a=r.headers||{},u=r.body,s=r.method||(u?"POST":"GET"),i=false;var f=t(r.cors);function l(e,t){return function(){if(!i){o(f.status===undefined?e:f.status,f.status===0?"Error":f.response||f.responseText||t,f);i=true}}}f.open(s,r.url,true);var d=f.onload=l(200);f.onreadystatechange=function(){if(f.readyState===4)d()};f.onerror=l(null,"Error");f.ontimeout=l(null,"Timeout");f.onabort=l(null,"Abort");if(u){n(a,"X-Requested-With","XMLHttpRequest");if(!global.FormData||!(u instanceof global.FormData)){n(a,"Content-Type","application/x-www-form-urlencoded")}}for(var p=0,c=e.length,g;p<c;p++){g=e[p];if(r[g]!==undefined)f[g]=r[g]}for(var g in a)f.setRequestHeader(g,a[g]);f.send(u);return f};function t(e){if(e&&global.XDomainRequest&&!/MSIE 1/.test(navigator.userAgent))return new XDomainRequest;if(global.XMLHttpRequest)return new XMLHttpRequest}function n(e,t,n){e[t]=e[t]||n}})(); // eslint-disable-line


  // https://github.com/component/emitter
  function Emitter(t){return t?mixin(t):void 0}function mixin(t){for(var e in Emitter.prototype)t[e]=Emitter.prototype[e];return t}Emitter.prototype.on=Emitter.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Emitter.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i=this._callbacks["$"+t];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r,s=0;s<i.length;s++)if(r=i[s],r===e||r.fn===e){i.splice(s,1);break}return this},Emitter.prototype.emit=function(t){this._callbacks=this._callbacks||{};var e=[].slice.call(arguments,1),i=this._callbacks["$"+t];if(i){i=i.slice(0);for(var r=0,s=i.length;s>r;++r)i[r].apply(this,e)}return this},Emitter.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Emitter.prototype.hasListeners=function(t){return!!this.listeners(t).length};// eslint-disable-line

  var ughbind = (Function.prototype.bind
    ? function ughbind(fn, thisObj) {
      return fn.bind(thisObj);
    }
    : function ughbind(fn, thisObj) {
      return function() {
        fn.apply(thisObj, arguments);
      };
    }
  );

  var sharedSubscriberTable={};

  "use strict"; 
  function NchanSubscriber(url, opt) {
    if(typeof window !== "undefined" && this === window) {
      throw "use 'new NchanSubscriber(...)' to initialize";
    }
    
    this.url = url;
    opt = opt || {};
    
    //which transport should i use?
    if(typeof opt === "string") {
      opt = {subscriber: opt}; 
    }
    if(opt.transport && !opt.subscriber) {
      opt.subscriber = opt.transport;
    }
    if(typeof opt.subscriber === "string") {
      opt.subscriber = [ opt.subscriber ];
    }
    this.desiredTransport = opt.subscriber;
    
    if(opt.shared) {
      if (!("localStorage" in global)) {
        throw "localStorage unavailable for use in shared NchanSubscriber";
      }
      
      var pre = "NchanSubscriber:" + this.url + ":shared:";
      var sharedKey = function(key) { return pre + key; };
      var localStorage = global.localStorage;
      this.shared = {
        id: "" + Math.random() + Math.random(),
        key: sharedKey,
        get: function(key) {
          return localStorage.getItem(sharedKey(key));
        },
        set: function(key, val) {
          return localStorage.setItem(sharedKey(key), val);
        },
        setWithId: ughbind(function(key, val) {
          return this.shared.set(key, "##" + this.shared.id + ":" + val);
        }, this),
        getWithId: ughbind(function(key) {
          return this.shared.stripIdFromVal(this.shared.get(key));
        }, this),
        stripIdFromVal: function(val) {
          if(!val) {
            return val;
          }
          var sep = val.indexOf(":");
          if(val[0]!=val[1] || val[0]!="#" || !sep) {
            //throw "not an event value with id";
            return val; //for backwards-compatibility
          }
          return val.substring(sep+1, val.length);
        },
        remove: function(key) {
          return localStorage.removeItem(sharedKey(key));
        },
        matchEventKey: ughbind(function(ev, key) {
          if(ev.storageArea && ev.storageArea != localStorage){
            return false;
          }
          return ev.key == sharedKey(key);
        }, this),
        matchEventKeyWithId: ughbind(function(ev, key) {
          if(this.shared.matchEventKey(ev, key)) {
            var val = ev.newValue;
            var sep = val.indexOf(":");
            if(val[0]!=val[1] || val[0]!="#" || !sep) {
              //throw "not an event value with id";
              return true; //for backwards-compatibility
            }
            var id = val.substring(2, sep);
            return (id != this.shared.id); //ignore own events (accomodations for IE. Fuckin' IE, even after all these years...)
          }
          else {
            return false;
          }
        }, this),
        setRole: ughbind(function(role) {
          //console.log(this.url, "set shared role to ", role);
          if(role == "master" && this.shared.role != "master") {
            var now = new Date().getTime()/1000;
            this.shared.setWithId("master:created", now);
            this.shared.setWithId("master:lastSeen", now);
          }
          if(role == "slave" && !this.lastMessageId) {
            this.lastMessageId = this.shared.get("msg:id");
          }
          this.shared.role = role;
          return this;
        }, this),
        
        demoteToSlave: ughbind(function() {
          //console.log("demote to slave");
          if(this.shared.role != "master") {
            throw "can't demote non-master to slave";
          }
          if(this.running) {
            this.stop();
            this.shared.setRole("slave");
            this.initializeTransport();
            this.start();
          }
          else {
            this.initializeTransport();
          }
        }, this),
        
        maybePromoteToMaster: ughbind(function() {
          if(!(this.running || this.starting)) {
            //console.log(this.url, "stopped Subscriber won't be promoted to master");
            return this;
          }
          if(this.shared.maybePromotingToMaster) {
            //console.log(this.url, " already maybePromotingToMaster");
            return;
          }
          this.shared.maybePromotingToMaster = true;
          
          //console.log(this.url, "maybe promote to master");
          var processRoll;
          
          var lotteryRoundDuration = 2000;
          var currentContenders = 0;
          
          //roll the dice
          var roll = Math.random();
          var bestRoll = roll;
          
          var checkRollInterval;
          var checkRoll = ughbind(function(dontProcess) {
            var latestSharedRollTime = parseFloat(this.shared.getWithId("lotteryTime"));
            var latestSharedRoll = parseFloat(this.shared.getWithId("lottery"));
            var notStale = !latestSharedRollTime || (latestSharedRollTime > (new Date().getTime() - lotteryRoundDuration * 2));
            if(notStale && latestSharedRoll && (!bestRoll || latestSharedRoll > bestRoll)) {
              bestRoll = latestSharedRoll;
            }
            if(!dontProcess) {
              processRoll();
            }
          }, this);
          
          checkRoll(true);
          this.shared.setWithId("lottery", roll);
          this.shared.setWithId("lotteryTime", new Date().getTime() / 1000);
          
          var rollCallback = ughbind(function(ev) {
            if(this.shared.matchEventKeyWithId(ev, "lottery") && ev.newValue) {
              currentContenders += 1;
              var newVal = parseFloat(this.shared.stripIdFromVal(ev.newValue));
              var oldVal = parseFloat(this.shared.stripIdFromVal(ev.oldValue));
              if(oldVal > newVal) {
                this.shared.setWithId("lottery", oldVal);
              }
              
              if(!bestRoll || newVal >= bestRoll) {
                //console.log("new bestRoll", newVal);
                bestRoll = newVal;
              }
            }
          }, this);
          global.addEventListener("storage", rollCallback);
          
          var finish = ughbind(function() {
            //console.log("finish");
            this.shared.maybePromotingToMaster = false;
            //console.log(this.url, this.shared.role);
            global.removeEventListener("storage", rollCallback);
            if(checkRollInterval) {
              clearInterval(checkRollInterval);
            }
            if(this.shared && this.shared.role == "master") {
              this.shared.remove("lottery");
              this.shared.remove("lotteryTime");
            }
            if(this.running) {
              this.stop();
              this.initializeTransport();
              this.start();
            }
            else {
              this.initializeTransport();
              if(this.starting) {
                this.start();
              }
            }
          }, this);
          
          processRoll = ughbind(function() {
            //console.log("roll, bestroll", roll, bestRoll);
            if(roll < bestRoll) {
              //console.log(this.url, "loser");
              this.shared.setRole("slave");
              finish();
            }
            else if(roll >= bestRoll) {
              //var now = new Date().getTime() / 1000;
              //var lotteryTime = parseFloat(this.shared.getWithId("lotteryTime"));
              //console.log(lotteryTime, now - lotteryRoundDuration/1000);
              if(currentContenders == 0) {
                //console.log("winner, no more contenders!");
                this.shared.setRole("master");
                finish();
              }
              else {
                //console.log("winning, but have contenders", currentContenders);
                currentContenders = 0;
              }
            }
          }, this);
          
          checkRollInterval = global.setInterval(checkRoll, lotteryRoundDuration);
        }, this),
        masterCheckInterval: 10000
      };
    }
    
    this.lastMessageId = opt.id || opt.msgId;
    this.reconnect = typeof opt.reconnect == "undefined" ? true : opt.reconnect;
    this.reconnectTimeout = opt.reconnectTimeout || 1000;
    
    
    var saveConnectionState;
    if(!opt.reconnect) {
      saveConnectionState = function() {};
    }
    else {
      var index = "NchanSubscriber:" + url + ":lastMessageId";
      var storage;
      if(opt.reconnect == "persist") {
        storage = ("localStorage" in global) && global.localStorage;
        if(!storage)
          throw "can't use reconnect: 'persist' option: localStorage not available";
      }
      else if(opt.reconnect == "session") {
        storage = ("sessionStorage" in global) && global.sessionStorage;
        if(!storage)
          throw "can't use reconnect: 'session' option: sessionStorage not available";
      }
      else {
        throw "invalid 'reconnect' option value " + opt.reconnect;
      }
      saveConnectionState = ughbind(function(msgid) {
        if(this.shared && this.shared.role == "slave") return;
        storage.setItem(index, msgid);
      }, this);
      this.lastMessageId = storage.getItem(index);
    }
    
    var onUnloadEvent = ughbind(function() {
      if(this.running && this.connected) {
        this.stop();
      }
      if(this.shared && this.shared.role == "master") {
        this.shared.setWithId("status", "disconnected");
      }
    }, this);
    global.addEventListener("beforeunload", onUnloadEvent, false);
    // swap `beforeunload` to `unload` after DOM is loaded
    global.addEventListener("DOMContentLoaded", function() {
      global.removeEventListener("beforeunload", onUnloadEvent, false);
      global.addEventListener("unload", onUnloadEvent, false);
    }, false);
    
    
    var notifySharedSubscribers;
    if(this.shared) {
      notifySharedSubscribers = ughbind(function(name, data) {
        if(this.shared.role != "master") {
          return;
        }
        
        if(name == "message") {
          this.shared.set("msg:id", data[1] && data[1].id || "");
          this.shared.set("msg:content-type", data[1] && data[1]["content-type"] || "");
          this.shared.set("msg", data[0]);
        }
        else if(name == "error") {
          //TODO 
        }
        else if(name == "connecting") {
          this.shared.setWithId("status", "connecting");
        }
        else if(name == "connect") {
          this.shared.setWithId("status", "connected");
        }
        else if(name == "reconnect") {
          this.shared.setWithId("status", "reconnecting");
        }
        else if(name == "disconnect") {
          this.shared.setWithId("status", "disconnected");
        }
      }, this);
    }
    else {
      notifySharedSubscribers = function(){};
    }
    
    var restartTimeoutIndex;
    var stopHandler = ughbind(function() {
      if(!restartTimeoutIndex && this.running && this.reconnect && !this.transport.reconnecting && !this.transport.doNotReconnect) {
        //console.log("stopHAndler reconnect plz", this.running, this.reconnect);
        notifySharedSubscribers("reconnect");
        restartTimeoutIndex = global.setTimeout(ughbind(function() {
          restartTimeoutIndex = null;
          this.stop();
          this.start();
        }, this), this.reconnectTimeout);
      }
      else {
        notifySharedSubscribers("disconnect");
      }
    }, this);
    
    this.on("message", function msg(msg, meta) {
      this.lastMessageId=meta.id;
      if(meta.id) {
        saveConnectionState(meta.id);
      }
      notifySharedSubscribers("message", [msg, meta]);
      //console.log(msg, meta);
    });
    this.on("error", function fail(code, text) {
      stopHandler(code, text);
      notifySharedSubscribers("error", [code, text]);
      //console.log("failure", code, text);
    });
    this.on("connect", function() {
      this.connected = true;
      notifySharedSubscribers("connect");
    });
    this.on("__disconnect", function fail(code, text) {
      this.connected = false;
      this.emit("disconnect", code, text);
      stopHandler(code, text);
      //console.log("__disconnect", code, text);
    });
  }

  Emitter(NchanSubscriber.prototype);

  var defaultTransportOptions = function() {
    var opt = {
      url: null,
      msgid: null,
      headers : {}
    };
    for(var n in NchanSubscriber.prototype.SubscriberClass) {
      if(n != "__slave") {
        opt[n]={};
      }
    }
    return opt;
  };
  
  NchanSubscriber.prototype.initializeTransport = function(possibleTransports) {
    if(possibleTransports) {
      this.desiredTransport = possibleTransports;
    }
    if(this.shared && this.shared.role == "slave") {
      this.transport = new this.SubscriberClass["__slave"](ughbind(this.emit, this)); //try it
    }
    else {
      var tryInitializeTransport = ughbind(function(name) {
        if(!this.SubscriberClass[name]) {
          throw "unknown subscriber type " + name;
        }
        try {
          this.transport = new this.SubscriberClass[name](ughbind(this.emit, this)); //try it
          return this.transport;
        } catch(err) { /*meh...*/ }
      }, this);
      
      var i;
      if(this.desiredTransport) {
        for(i=0; i<this.desiredTransport.length; i++) {
          if(tryInitializeTransport(this.desiredTransport[i])) {
            break;
          }
        }
      }
      else {
        for(i in this.SubscriberClass) {
          if (this.SubscriberClass.hasOwnProperty(i) && i[0] != "_" && tryInitializeTransport(i)) {
            break;
          }
        }
      }
    }
    if(! this.transport) {
      throw "can't use any transport type";
    }
  };

  var storageEventListener;

  NchanSubscriber.prototype.start = function() {
    if(this.running)
      throw "Can't start NchanSubscriber, it's already started.";
    
    this.starting = true;
    
    if(this.shared) {
      if(sharedSubscriberTable[this.url] && sharedSubscriberTable[this.url] != this) {
        throw "Only 1 shared subscriber allowed per url per window/tab.";
      }
      sharedSubscriberTable[this.url] = this;
      
      if(!this.shared.role) {
        var status = this.shared.getWithId("status");
        storageEventListener = ughbind(function(ev) {
          if(this.shared.matchEventKeyWithId(ev, "status")) {
            var newValue = this.shared.stripIdFromVal(ev.newValue);
            if(newValue == "disconnected") {
              if(this.shared.role == "slave") {
                //play the promotion lottery
                //console.log(this.url, "status changed to disconnected, maybepromotetomaster", ev.newValue, ev.oldValue);
                this.shared.maybePromoteToMaster();
              }
              else if(this.shared.role == "master") {
                //do nothing
                //console.log(this.url, "current role is master, do nothing?...");
              }
            }
          }
          else if(this.shared.role == "master" && this.shared.matchEventKeyWithId(ev, "master:created") && ev.newValue) {
            //a new master has arrived. demote to slave.
            this.shared.demoteToSlave();
          }
        }, this);
        global.addEventListener("storage", storageEventListener);
        if(status == "disconnected") {
          //console.log(this.url, "status == disconnected, maybepromotetomaster");
          this.shared.maybePromoteToMaster();
        }
        else {
          this.shared.setRole(status ? "slave" : "master");
          this.initializeTransport();
        }
      }
      
      if(this.shared.role == "master") {
        this.shared.setWithId("status", "connecting");
        this.transport.listen(this.url, this.lastMessageId);
        this.running = true;
        delete this.starting;
        
        //master checkin interval
        this.shared.masterIntervalCheckID = global.setInterval(ughbind(function() {
          this.shared.setWithId("master:lastSeen", new Date().getTime() / 1000);
        }, this), this.shared.masterCheckInterval * 0.8);
      }
      else if(this.shared.role == "slave") {
        this.transport.listen(this.url, this.shared);
        this.running = true;
        delete this.starting;
        
        //slave check if master is around
        this.shared.masterIntervalCheckID = global.setInterval(ughbind(function() {
          var lastCheckin = parseFloat(this.shared.getWithId("master:lastSeen"));
          if(!lastCheckin || lastCheckin < (new Date().getTime() / 1000) - this.shared.masterCheckInterval / 1000) {
            //master hasn't checked in for too long. assume it's gone.
            this.shared.maybePromoteToMaster();
          }
        }, this), this.shared.masterCheckInterval);
      }
    }
    else {
      if(!this.transport) {
        this.initializeTransport();
      }
      this.transport.listen(this.url, this.lastMessageId);
      this.running = true;
      delete this.starting;
    }
    return this;
  };

  NchanSubscriber.prototype.stop = function() {
    if(!this.running)
      throw "Can't stop NchanSubscriber, it's not running.";
    
    this.running = false;
    if(storageEventListener) {
      global.removeEventListener("storage", storageEventListener);
    }
    this.transport.cancel();
    if(this.shared) {
      delete sharedSubscriberTable[this.url];
      if(this.shared.masterIntervalCheckID) {
        clearInterval(this.shared.masterIntervalCheckID);
        delete this.shared.masterIntervalCheckID;
      }
    }
    return this;
  };

  function addLastMsgIdToQueryString(url, msgid) {
    if(msgid) {
      var m = url.match(/(\?.*)$/);
      url += (m ? "&" : "?") + "last_event_id=" + encodeURIComponent(msgid);
    }
    return url;
  }

  NchanSubscriber.prototype.SubscriberClass = {
    "websocket": (function() {
      function WSWrapper(emit) {
        WebSocket;
        this.emit = emit;
        this.name = "websocket";
        this.opt = defaultTransportOptions()
        this.opt.headers["Sec-WebSocket-Protocol"]="ws+meta.nchan"
      };

      WSWrapper.prototype.setup = function() {
        this.emit("transportSetup", this.opt, this.name);
        var count = 0;
        var property;
        for ( property in this.opt.headers ) count++;
        if (count != 1 && "Sec-WebSocket-Protocol" in this.opt.headers) {
          throw "WebSocket only supports one header; Sec-WebSocket-Protocol";
        }
      };

      WSWrapper.prototype.websocketizeURL = function(url) {
        var m = url.match(/^((\w+:)?\/\/([^/]+))?(\/)?(.*)/);
        var protocol = m[2];
        var host = m[3];
        var absolute = m[4];
        var path = m[5];
        
        var loc;
        if(typeof window == "object") {
          loc = window.location;
        }
        else if(typeof document == "object") {
          loc = document.location;
        }
        
        if(!protocol && loc) {
          protocol = loc.protocol;
        }
        if(protocol == "https:") {
          protocol = "wss:";
        }
        else if(protocol == "http:") {
          protocol = "ws:";
        }
        else if(protocol != "ws:") {
          protocol = "wss:"; //default setting: secure, unless "ws:" explicitly specified
        }
        
        if(!host && loc) {
          host = loc.host;
        }
        
        if(!absolute) {
          path = loc ? loc.pathname.match(/(.*\/)[^/]*/)[1] + path : "/" + path;
        }
        else {
          path = "/" + path;
        }
        
        return protocol + "//" + host + path;
      };
      
      WSWrapper.prototype.listen = function(url, msgid) {
        if(this.listener) {
          throw "websocket already listening";
        }
        this.opt.url = url;
        this.opt.msgid = msgid;
        this.setup();
        url = this.websocketizeURL(this.opt.url);
        url = addLastMsgIdToQueryString(url, this.opt.msgid);
        //console.log(url);
        this.listener = new WebSocket(url, this.opt.headers["Sec-WebSocket-Protocol"]);
        var l = this.listener;
        this.emit("transportNativeCreated", l, this.name);
        l.onmessage = ughbind(function(evt) {
          if (evt.data instanceof Blob) {
            //extract header, preserve rest of blob.
            //let's assume the header ends in the first 255 chars
            var headerSlice = evt.data.slice(0, 255);
            var reader = new FileReader();
            reader.addEventListener("loadend", ughbind(function() {
              var m = reader.result.match(/^id: (.*)\n(content-type: (.*)\n)?\n/m);
              this.emit("message", evt.data.slice(m[0].length), {"id": m[1], "content-type": m[3]});
            }, this));
            reader.readAsText(headerSlice)
          } else {
            var m = evt.data.match(/^id: (.*)\n(content-type: (.*)\n)?\n/m);
            this.emit("message", evt.data.substr(m[0].length), {"id": m[1], "content-type": m[3]});
          }
        }, this);
        
        l.onopen = ughbind(function(evt) {
          this.emit("connect", evt);
          //console.log("connect", evt);
        }, this);
        
        l.onerror = ughbind(function(evt) {
          //console.log("error", evt);
          this.emit("error", evt, l);
          delete this.listener;
        }, this);
        
        l.onclose = ughbind(function(evt) {
          this.emit("__disconnect", evt);
          delete this.listener;
        }, this);
      };
      
      WSWrapper.prototype.cancel = function() {
        if(this.listener) {
          this.emit("transportNativeBeforeDestroy", this.listener, this.name);
          this.listener.close();
          delete this.listener;
        }
      };
      
      return WSWrapper;
    })(),
  
    "eventsource": (function() {
      function ESWrapper(emit) {
        EventSource;
        this.emit = emit;
        this.name = "eventsource";
        this.opt = defaultTransportOptions();
        this.opt.eventsource.withCredentials = false;
      }

      ESWrapper.prototype.setup = function() {
        this.emit("transportSetup", this.opt, this.name);
        var count = 0;
        var property;
        for ( property in this.opt.headers ) count++;
        if (count != 0) {
          throw "EventSource does not support headers";
        }
      };

      ESWrapper.prototype.listen= function(url, msgid) {
        if(this.listener) {
          throw "there's a ES listener running already";
        }
        this.opt.url = url;
        this.opt.msgid = msgid;
        this.setup();
        url = addLastMsgIdToQueryString(this.opt.url, this.opt.msgid);
        this.listener = new EventSource(url, this.opt.eventsource);
        var l = this.listener;
        this.emit("transportNativeCreated", l, this.name);
        l.onmessage = ughbind(function(evt){
          //console.log("message", evt);
          this.emit("message", evt.data, {id: evt.lastEventId});
        }, this);
        
        l.onopen = ughbind(function(evt) {
          this.reconnecting = false;
          //console.log("connect", evt);
          this.emit("connect", evt);
        }, this);
        
        l.onerror = ughbind(function(evt) {
          //EventSource will try to reconnect by itself
          //console.log("onerror", this.listener.readyState, evt);
          if(this.listener.readyState == EventSource.CONNECTING && !this.reconnecting) {
            if(!this.reconnecting) {
              this.reconnecting = true;
              this.emit("__disconnect", evt);
            }
          }
          else {
            this.emit("__disconnect", evt);
            //console.log('other __disconnect', evt);
          }
        }, this);
      };
      
      ESWrapper.prototype.cancel= function() {
        if(this.listener) {
          this.emit("transportNativeBeforeDestroy", this.listener, this.name);
          this.listener.close();
          delete this.listener;
        }
      };
      
      return ESWrapper;
    })(),
    
    "longpoll": (function () {
      function Longpoll(emit) {
        this.pollingRequest = null;
        this.nextRequestTimer = null;
        this.longPollStartTime = null;
        this.maxLongPollTime = 5*60*1000; //5 minutes
        this.emit = emit;
        this.name = "longpoll";
        this.opt = defaultTransportOptions();
        this.opt.longpoll.pollDelay = 0;
      }

      Longpoll.prototype.setup = function() {
        this.emit("transportSetup", this.opt, this.name);
        var count = 0;
        var property;
        for ( property in this.opt.headers ) count++;
      };

      Longpoll.prototype.listen = function(url, msgid) {
        if(this.req) {
          throw "already listening";
        }
        this.opt.url = url;
        this.opt.msgid = msgid;
        if(msgid) {
          this.opt.headers["Etag"] = msgid;
        }
        this.setup();

        var setHeader = ughbind(function(incoming, name) {
          if(incoming) { this.opt.headers[name]= incoming; }
        }, this);

        this.pollingRequest = ughbind(function() {
          if (this.req) {
            this.emit("transportNativeBeforeDestroy", this.req, this.name);
          }
          this.nextRequestTimer = null;
          this.reqStartTime = new Date().getTime();
          this.req = nanoajax.ajax({url: this.opt.url, headers: this.opt.headers}, requestCallback);
          this.emit("transportNativeCreated", this.req, this.name);
        }, this);
        var  requestCallback;
        requestCallback = ughbind(function (code, response_text, req) {
          setHeader(req.getResponseHeader("Last-Modified"), "If-Modified-Since");
          setHeader(req.getResponseHeader("Etag"), "If-None-Match");
          
          if(code >= 200 && code <= 210) {
            //legit reply
            var content_type = req.getResponseHeader("Content-Type");
            if (!this.parseMultipartMixedMessage(content_type, response_text, req)) {
              this.emit("message", response_text || "", {"content-type": content_type, "id": this.msgIdFromResponseHeaders(req)});
            }
            
            if (this.req) { //this check is needed because stop() may have been called in the message callback
              if (this.opt.longpoll.pollDelay == 0) {
                this.pollingRequest();
              } else {
                this.nextRequestTimer = global.setTimeout(this.pollingRequest, this.opt.longpoll.pollDelay);
              }
            }
          }
          else if((code == 0 && response_text == "Error" && req.readyState == 4) || (code === null && response_text != "Abort")) {
            //console.log("abort!!!");
            this.emit("__disconnect", code || 0, response_text);
            this.cancel();
          }
          else if(code !== null) {
            //HTTP error
            this.emit("error", code, response_text);
            this.cancel();
          }
          else {
            //don't care about abortions 
            this.cancel();
            this.emit("__disconnect");
            //console.log("abort!");
          }
        }, this);
        
        this.pollingRequest();
        this.emit("connect");
        
        return this;
      };
      
      Longpoll.prototype.parseMultipartMixedMessage = function(content_type, text, req) {
        var m = content_type && content_type.match(/^multipart\/mixed;\s+boundary=(.*)$/);
        if(!m) { 
          return false;
        }
        var boundary = m[1];
        
        var msgs = text.split("--" + boundary);
        if(msgs[0] != "" || !msgs[msgs.length-1].match(/--\r?\n/)) { throw "weird multipart/mixed split"; }
        
        msgs = msgs.slice(1, -1);
        for(var i in msgs) {
          m = msgs[i].match(/^(.*)\r?\n\r?\n([\s\S]*)\r?\n$/m);
          var hdrs = m[1].split("\n");
          
          var meta = {};
          for(var j in hdrs) {
            var hdr = hdrs[j].match(/^([^:]+):\s+(.*)/);
            if(hdr && hdr[1] == "Content-Type") {
              meta["content-type"] = hdr[2];
            }
          }
          
          if(i == msgs.length - 1) {
            meta["id"] = this.msgIdFromResponseHeaders(req);
          }
          this.emit("message", m[2], meta);
        }
        return true;
      };
      
      Longpoll.prototype.msgIdFromResponseHeaders = function(req) {
        var lastModified, etag;
        lastModified = req.getResponseHeader("Last-Modified");
        etag = req.getResponseHeader("Etag");
        if(lastModified) {
          return "" + Date.parse(lastModified)/1000 + ":" + (etag || "0");
        }
        else if(etag) {
          return etag;
        }
        else {
          return null;
        }
      };
      
      Longpoll.prototype.cancel = function() {
        if(this.req) {
          this.emit("transportNativeBeforeDestroy", this.req, this.name);
          this.req.abort();
          delete this.req;
        }
        this.cancelPendingPollRequest();
        return this; 
      };

      Longpoll.prototype.cancelPendingPollRequest = function() {
        if (this.nextRequestTimer) {
          global.clearTimeout(this.nextRequestTimer);
          this.nextRequestTimer = null;
        }
      };

      return Longpoll;
    })(),
    
    "__slave": (function() {
      function LocalStoreSlaveTransport(emit) {
        this.emit = emit;
        this.doNotReconnect = true;
        this.shared = null;
        this.name = "__slave";
        this.opt = defaultTransportOptions();
      }

      LocalStoreSlaveTransport.prototype.setup = function() {
        this.emit("transportSetup", this.opt, this.name);
        var count = 0;
        var property;
        for ( property in this.opt.headers ) count++;
        if (count != 0) {
          throw "__slave does not support headers";
        }
      };

      LocalStoreSlaveTransport.prototype.listen = function(url, shared) {
        this.shared = shared;
        this.opt.url = url;  
        this.setup();
        this.statusChangeChecker = ughbind(function(ev) {
          if(this.shared.matchEventKey(ev, "msg")) {
            var msgId = this.shared.get("msg:id");
            var contentType = this.shared.get("msg:content-type");
            var msg = this.shared.get("msg");
            this.emit("message", msg, {"id": msgId == "" ? undefined : msgId, "content-type": contentType == "" ? undefined : contentType});
          }
        }, this);
        global.addEventListener("storage", this.statusChangeChecker);
        //this.emit("transportNativeCreated", this, this.name);
      };
        
      LocalStoreSlaveTransport.prototype.cancel = function() {
        global.removeEventListener("storage", this.statusChangeChecker);
      };
      
      return LocalStoreSlaveTransport;
    })()

  };

  return NchanSubscriber;
});
(function() {
  window.EventEmitter = (function(_this) {
    return function() {
      var emit, events, subscribe, unsubscribe;
      events = {};
      subscribe = function(eventName, fn) {
        events[eventName] || (events[eventName] = []);
        return events[eventName].push(fn);
      };
      unsubscribe = function(eventName, fn) {
        return events[eventName] = (events[eventName] || []).filter(function(eventCallback) {
          return fn !== eventCallback;
        });
      };
      emit = function(eventName, data) {
        return (events[eventName] || []).forEach(function(callback) {
          return callback.call(null, data);
        });
      };
      return {
        subscribe: subscribe,
        unsubscribe: unsubscribe,
        events: events,
        emit: emit
      };
    };
  })(this);

}).call(this);
(function() {
  window.MessageStreamingEventManager = (function(_this) {
    return function(subscriberSource) {
      var _isHealthChecker, init, isOpen, isStarting, onclose, onerror, onhealth, onmessage, onopen, start, starting, stop, subscriber;
      starting = false;
      subscriber = null;
      _isHealthChecker = function(message, metadata) {
        return metadata['content-type'] === 'text/plain' && message === 'OK';
      };
      init = function(url) {
        return subscriber = new subscriberSource(url, {
          subscriber: 'websocket',
          reconnect: 'session',
          shared: false
        });
      };
      start = function() {
        starting = true;
        return subscriber.start();
      };
      stop = function() {
        if (subscriber && subscriber.running && subscriber.connected) {
          subscriber.onclose = function() {
            return {};
          };
          subscriber.onerror = function() {
            return {};
          };
          subscriber.onmessage = function() {
            return {};
          };
          subscriber.onhealth = function() {
            return {};
          };
          return subscriber.stop();
        }
      };
      isOpen = function() {
        return !!(subscriber != null ? subscriber.connected : void 0);
      };
      isStarting = function() {
        return !!(subscriber != null ? subscriber.starting : void 0) || starting;
      };
      onopen = function(handler) {
        return subscriber.on('connect', function(message) {
          starting = false;
          return handler(message);
        });
      };
      onhealth = function(handler) {
        return subscriber.on('message', function(message, metadata) {
          if (_isHealthChecker(message, metadata)) {
            return handler(message);
          }
        });
      };
      onmessage = function(handler) {
        return subscriber.on('message', function(message, metadata) {
          if (!_isHealthChecker(message, metadata)) {
            return handler(message);
          }
        });
      };
      onerror = function(handler) {
        return subscriber.on('error', handler);
      };
      onclose = function(handler) {
        return subscriber.on('disconnect', handler);
      };
      return {
        init: init,
        start: start,
        stop: stop,
        isOpen: isOpen,
        isStarting: isStarting,
        onopen: onopen,
        onhealth: onhealth,
        onmessage: onmessage,
        onerror: onerror,
        onclose: onclose
      };
    };
  })(this);

  window.MessageStreaming = (function(_this) {
    return function(arg) {
      var _channel, _emitterSubscribe, _setChannel, _startEventManager, _stopEventManager, debugManager, emitter, eventManager, isOpen, isStarting, navigationMonitor, onclose, onerror, onhealth, onmessage, onopen, start, stop, stopListener;
      eventManager = arg.eventManager, navigationMonitor = arg.navigationMonitor, emitter = arg.emitter, debugManager = arg.debugManager;
      _channel = null;
      _setChannel = function(value) {
        return _channel = value;
      };
      isOpen = eventManager.isOpen;
      isStarting = eventManager.isStarting;
      stopListener = function(eventName, callback) {
        return emitter.unsubscribe(eventName, callback);
      };
      _emitterSubscribe = function(event) {
        return function(handler) {
          stopListener(event, handler);
          return emitter.subscribe(event, handler);
        };
      };
      onopen = _emitterSubscribe('onopen');
      onmessage = _emitterSubscribe('onmessage');
      onhealth = _emitterSubscribe('onhealth');
      onerror = _emitterSubscribe('onerror');
      onclose = _emitterSubscribe('onclose');
      _startEventManager = function() {
        if (isStarting() || isOpen()) {
          return;
        }
        eventManager.init(_channel);
        eventManager.onopen(function(event) {
          debugManager.green('%c MessageStreaming Connection: Open ', "Timestamp: " + (new Date().toISOString()), {
            event: event
          });
          return emitter.emit('onopen', event);
        });
        eventManager.onmessage(function(event) {
          debugManager.blue('%c MessageStreaming Message Received ', "Timestamp: " + (new Date().toISOString()), {
            event: event
          });
          return emitter.emit('onmessage', event);
        });
        eventManager.onhealth(function(event) {
          debugManager.yellow('%c MessageStreaming Health Check ', "Timestamp: " + (new Date().toISOString()));
          return emitter.emit('onhealth', event);
        });
        eventManager.onerror(function(event) {
          debugManager.red('%c MessageStreaming Connection: Error ', "Timestamp: " + (new Date().toISOString()), {
            event: event
          });
          return emitter.emit('onerror', event);
        });
        eventManager.onclose(function(event) {
          debugManager.orange('%c MessageStreaming Connection: Closed ', "Timestamp: " + (new Date().toISOString()), {
            event: event
          });
          return emitter.emit('onclose', event);
        });
        return eventManager.start();
      };
      _stopEventManager = function() {
        return eventManager.stop();
      };
      start = function(channel) {
        _setChannel(channel);
        _startEventManager();
        return navigationMonitor.on(_startEventManager, _stopEventManager);
      };
      stop = function() {
        _stopEventManager();
        return navigationMonitor.off(_startEventManager, _stopEventManager);
      };
      return {
        start: start,
        stop: stop,
        stopListener: stopListener,
        onopen: onopen,
        onmessage: onmessage,
        onhealth: onhealth,
        onerror: onerror,
        onclose: onclose,
        isOpen: isOpen,
        isStarting: isStarting
      };
    };
  })(this);

}).call(this);
(function() {
  window.MessageStreamingUnavailablePopupConstants = {
    HEALTH_CHECK_INTERVAL: 60000,
    CHECK_CHANNEL_INTERVAL: 10000,
    RETRY_COUNT: 10,
    POPUP_STATUS_KEY: 'MessageStreaming:PopupStatus',
    WS_CLOSE_NORMAL: 1000,
    WS_CLOSE_ABNORMAL: 1006
  };

  window.MessageStreamingDates = (function(_this) {
    return function(arg) {
      var date, datediff, inPast, now, since;
      date = arg.date;
      now = function() {
        return new date;
      };
      inPast = function(datetime) {
        return datetime <= now();
      };
      since = function(minutes) {
        return now().setMinutes(now().getMinutes() + minutes);
      };
      datediff = function(datetime1, datetime2) {
        return datetime1.getTime() - datetime2.getTime();
      };
      return {
        now: now,
        inPast: inPast,
        since: since,
        datediff: datediff
      };
    };
  })(this);

  window.MessageStreamingUnavailablePopupStorage = (function(_this) {
    return function(storageLayer, constants) {
      var _getMessageStreamingPopupStatus, isMessageStreamingPopupStatusShowed, isMessageStreamingPopupStatusShowing, removeMessageStreamingPopupStatus, setMessageStreamingPopupStatus;
      _getMessageStreamingPopupStatus = function() {
        return storageLayer.getItem(constants.POPUP_STATUS_KEY);
      };
      isMessageStreamingPopupStatusShowed = function() {
        return _getMessageStreamingPopupStatus() === 'showed';
      };
      isMessageStreamingPopupStatusShowing = function() {
        return _getMessageStreamingPopupStatus() === 'showing';
      };
      setMessageStreamingPopupStatus = function(status) {
        return storageLayer.setItem(constants.POPUP_STATUS_KEY, status);
      };
      removeMessageStreamingPopupStatus = function() {
        return storageLayer.removeItem(constants.POPUP_STATUS_KEY);
      };
      return {
        setMessageStreamingPopupStatus: setMessageStreamingPopupStatus,
        isMessageStreamingPopupStatusShowed: isMessageStreamingPopupStatusShowed,
        isMessageStreamingPopupStatusShowing: isMessageStreamingPopupStatusShowing,
        removeMessageStreamingPopupStatus: removeMessageStreamingPopupStatus
      };
    };
  })(this);

  window.MessageStreamingHealthChecker = (function(_this) {
    return function(arg) {
      var _attempts, _checkChannel, _checkChannelHandler, _connecting, _isMessageStreamingUnavailable, _lastHealthCheckTime, _resetLastHealthCheck, _resetRetryAttempts, constants, date, onConnect, onMessage, startConnection, stopConnection, stopMessage, timer;
      constants = arg.constants, date = arg.date, timer = arg.timer;
      _attempts = 0;
      _connecting = false;
      _checkChannelHandler = null;
      _lastHealthCheckTime = date.now();
      _resetLastHealthCheck = function() {
        return _lastHealthCheckTime = date.now();
      };
      _resetRetryAttempts = function() {
        return _attempts = 0;
      };
      _isMessageStreamingUnavailable = function() {
        return date.datediff(date.now(), _lastHealthCheckTime) > constants.HEALTH_CHECK_INTERVAL;
      };
      _checkChannel = function(callback) {
        if (_isMessageStreamingUnavailable()) {
          _attempts += 1;
        }
        if (_attempts >= constants.RETRY_COUNT) {
          console.debug('MessageStreamingHealthChecker.checkChannel', {
            attempts: _attempts,
            lastHealthCheckTime: _lastHealthCheckTime,
            current: date.now()
          });
          callback.call(null);
          return timer.clearInterval(_checkChannelHandler);
        }
      };
      onMessage = function(handler) {
        _resetRetryAttempts();
        _resetLastHealthCheck();
        if (_checkChannelHandler) {
          timer.clearInterval(_checkChannelHandler);
        }
        return _checkChannelHandler = timer.setInterval((function() {
          return _checkChannel(handler);
        }), constants.CHECK_CHANNEL_INTERVAL);
      };
      onConnect = function(handler) {
        if (_connecting) {
          handler();
          return stopConnection();
        }
      };
      startConnection = function() {
        return _connecting = true;
      };
      stopConnection = function() {
        return _connecting = false;
      };
      stopMessage = function() {
        return timer.clearInterval(_checkChannelHandler);
      };
      return {
        startConnection: startConnection,
        onConnect: onConnect,
        onMessage: onMessage,
        stopConnection: stopConnection,
        stopMessage: stopMessage
      };
    };
  })(this);

  window.MessageStreamingUnavailablePopupTimer = (function(_this) {
    return function(arg) {
      var clearIntervalFn, clearTimeoutFn, setIntervalFn, setTimeoutFn;
      setIntervalFn = arg.setIntervalFn, clearIntervalFn = arg.clearIntervalFn, setTimeoutFn = arg.setTimeoutFn, clearTimeoutFn = arg.clearTimeoutFn;
      return {
        setInterval: function(callback, milliseconds) {
          return setIntervalFn(callback, milliseconds);
        },
        clearInterval: function(intervalId) {
          return clearIntervalFn(intervalId);
        },
        setTimeout: function(callback, milliseconds) {
          return setTimeoutFn(callback, milliseconds);
        },
        clearTimeout: function(timeoutId) {
          return clearTimeoutFn(timeoutId);
        }
      };
    };
  })(this);

  window.MessageStreamingUnavailablePopupDom = (function(_this) {
    return function(jQuery, locationLayer) {
      var _on, magnificPopupClose, reloadPage, showModal;
      _on = function(element, events, handler) {
        return jQuery(element).on(events, handler);
      };
      showModal = function(options) {
        return jQuery(options.element).modal(options.settings).modal('show');
      };
      magnificPopupClose = function() {
        return jQuery.magnificPopup.proto.close();
      };
      reloadPage = function() {
        return locationLayer.reload();
      };
      return {
        on: _on,
        showModal: showModal,
        magnificPopupClose: magnificPopupClose,
        reloadPage: reloadPage
      };
    };
  })(this);

  window.MessageStreamingUnavailablePopupElements = (function(_this) {
    return function() {
      var popupTemplate;
      popupTemplate = function(title, body) {
        return "<div class='ui modal' id='messageStreamingUnavailablePopup'>\n  <div class='header'>" + title + "</div>\n  <div class='content'>\n    " + body + "\n  </div>\n  <div class='actions'>\n    <div class='ui primary ok button'>OK</div>\n  </div>\n</div>";
      };
      return {
        popupTemplate: popupTemplate,
        cancelButton: '#messageStreamingUnavailablePopup .ok.button'
      };
    };
  })(this);

  window.MessageStreamingUnavailablePopup = (function(_this) {
    return function(arg) {
      var _addEventListener, _checkConnection, _onclose, _onerror, _onhealth, _onopen, _refreshPage, _removeEventListener, _resetPopupShowedStatus, _showPopup, constants, dom, elements, healthChecker, messageStreaming, navigationMonitor, reconnecting, start, stop, storage, translate;
      dom = arg.dom, elements = arg.elements, messageStreaming = arg.messageStreaming, translate = arg.translate, constants = arg.constants, healthChecker = arg.healthChecker, navigationMonitor = arg.navigationMonitor, storage = arg.storage;
      reconnecting = false;
      _resetPopupShowedStatus = function() {
        if (storage.isMessageStreamingPopupStatusShowed()) {
          storage.removeMessageStreamingPopupStatus();
        }
        if (storage.isMessageStreamingPopupStatusShowing()) {
          return storage.setMessageStreamingPopupStatus('showed');
        }
      };
      _refreshPage = function() {
        dom.magnificPopupClose();
        dom.reloadPage();
        return true;
      };
      _showPopup = function() {
        if (!storage.isMessageStreamingPopupStatusShowed()) {
          storage.setMessageStreamingPopupStatus('showing');
          dom.showModal({
            element: elements.popupTemplate(translate.t('message_streaming_unavailable.title'), translate.t('message_streaming_unavailable.body_html')),
            settings: {
              closable: false,
              dimmerSettings: {
                className: {
                  pageDimmer: 'message-streaming page top'
                }
              }
            }
          });
          return dom.on(elements.cancelButton, 'click', _refreshPage);
        }
      };
      _checkConnection = function() {
        if (!messageStreaming.isOpen()) {
          return _showPopup();
        }
      };
      _onhealth = function() {
        healthChecker.onMessage(_showPopup);
        return true;
      };
      _onopen = function(event) {
        _resetPopupShowedStatus();
        healthChecker.stopConnection();
        if (!reconnecting) {
          healthChecker.onMessage(_showPopup);
        }
        reconnecting = false;
        return true;
      };
      _onclose = function(event) {
        if (event.code === constants.WS_CLOSE_NORMAL) {
          healthChecker.stopMessage();
        }
        if (event.code === constants.WS_CLOSE_ABNORMAL) {
          healthChecker.onConnect(_showPopup);
        }
        return true;
      };
      _onerror = function(event) {
        reconnecting = true;
        return true;
      };
      _removeEventListener = function() {
        messageStreaming.stopListener('onopen', _onopen);
        messageStreaming.stopListener('onhealth', _onhealth);
        messageStreaming.stopListener('onmessage', _onhealth);
        messageStreaming.stopListener('onerror', _onerror);
        messageStreaming.stopListener('onclose', _onclose);
        healthChecker.stopMessage();
        healthChecker.stopConnection();
        return true;
      };
      _addEventListener = function() {
        messageStreaming.onopen(_onopen);
        messageStreaming.onhealth(_onhealth);
        messageStreaming.onmessage(_onhealth);
        messageStreaming.onclose(_onclose);
        messageStreaming.onerror(_onerror);
        healthChecker.startConnection();
        return true;
      };
      start = function() {
        _resetPopupShowedStatus();
        _addEventListener();
        navigationMonitor.on(_addEventListener, _removeEventListener);
        return true;
      };
      stop = function() {
        _removeEventListener();
        navigationMonitor.off(_addEventListener, _removeEventListener);
        return true;
      };
      return {
        start: start,
        stop: stop
      };
    };
  })(this);

}).call(this);
(function() {
  window.PageNavigationMonitor = (function(_this) {
    return function(jquery, myWindow, emitter) {
      var _checkLeaveTabHandler, _getCurrentUrl, _initUrl, _isPageEntered, _isPageLeaved, _off, _on, _previousUrl, _setPreviousUrl, start, stop;
      _initUrl = null;
      _previousUrl = null;
      _getCurrentUrl = function() {
        return myWindow.location.href.split('#')[0];
      };
      _isPageLeaved = function() {
        return _previousUrl === _initUrl && _initUrl !== _getCurrentUrl();
      };
      _isPageEntered = function() {
        return _previousUrl !== _initUrl && _initUrl === _getCurrentUrl();
      };
      _setPreviousUrl = function(url) {
        return _previousUrl = url;
      };
      _checkLeaveTabHandler = function() {
        if (_isPageEntered()) {
          emitter.emit('onenterpage');
        }
        if (_isPageLeaved()) {
          emitter.emit('onleavepage');
        }
        return _setPreviousUrl(_getCurrentUrl());
      };
      _on = function(callbackEnter, callbackLeave) {
        emitter.subscribe('onenterpage', callbackEnter);
        return emitter.subscribe('onleavepage', callbackLeave);
      };
      _off = function(callbackEnter, callbackLeave) {
        emitter.unsubscribe('onenterpage', callbackEnter);
        return emitter.unsubscribe('onleavepage', callbackLeave);
      };
      start = function() {
        _initUrl = _getCurrentUrl();
        _setPreviousUrl(_initUrl);
        return jquery(myWindow).on('popstate', _checkLeaveTabHandler);
      };
      stop = function() {
        return jquery(myWindow).off('popstate', _checkLeaveTabHandler);
      };
      return {
        start: start,
        stop: stop,
        on: _on,
        off: _off
      };
    };
  })(this);

}).call(this);
(function() {
  window.RunParallelUIUpdate = (function(_this) {
    return function(promiseHandler, setTimeoutHandler) {
      var _timedPromise, _timedPromises, processRecordsParallel;
      _timedPromise = function(object, handler) {
        return new promiseHandler(function(resolve) {
          return setTimeoutHandler(function() {
            handler(object);
            return resolve(object);
          }, 0);
        });
      };
      _timedPromises = function(array, handler) {
        return array.flatMap(function(object) {
          return _timedPromise(object, handler);
        });
      };
      processRecordsParallel = function(array, handler) {
        return promiseHandler.all(_timedPromises(array, handler));
      };
      return {
        processRecordsParallel: processRecordsParallel
      };
    };
  })(this);

}).call(this);
(function() {
  window.BillingEventDomManipulator = (function(_this) {
    return function(elements, documentLayer) {
      var _buildProgreesBar, _emptyElementContent, _getDataAttribute, _querySelector, _querySelectorAll, _replaceActions, _replaceStatus, _replaceValue, _setDataAttribute, _setProgressPercent, _toggleDisabledState, _updateElementContent, _updateElementStyleWidth, _updateElementTextContent, _updateProgressBar, filter, isVisibleDOMElement, refreshSearch, removeDOMElement, updateActionsDOMElement, updateDOMElement;
      _querySelectorAll = function(selectors) {
        return documentLayer.querySelectorAll(selectors);
      };
      _querySelector = function(selectors) {
        return documentLayer.querySelector(selectors);
      };
      _updateElementContent = function(selectors, content) {
        var ref;
        return (ref = _querySelector(selectors)) != null ? ref.innerHTML = content : void 0;
      };
      _emptyElementContent = function(selectors, content) {
        return _querySelector(selectors).innerHTML = '';
      };
      _setDataAttribute = function(selectors, name, value) {
        return _querySelector(selectors).dataset[name] = value;
      };
      _getDataAttribute = function(selectors, name) {
        return _querySelector(selectors).dataset[name];
      };
      _buildProgreesBar = function(record) {
        if (!_querySelector(elements.billingEventProgress(record))) {
          return _updateElementContent(elements.billingEventActions(record), elements.progressBarTemplate(record.progress));
        }
      };
      _updateElementTextContent = function(selectors, text) {
        return _querySelector(selectors).innerText = text;
      };
      _updateElementStyleWidth = function(selectors, width) {
        return _querySelector(selectors).style.width = width;
      };
      _setProgressPercent = function(record) {
        _setDataAttribute(elements.billingEventProgress(record), 'percent', record.progress);
        _updateElementStyleWidth(elements.billingEventProgressBar(record), record.progress + "%");
        return _updateElementTextContent(elements.billingEventProgressLabel(record), record.progress + "%");
      };
      _updateProgressBar = function(record) {
        _buildProgreesBar(record);
        return _setProgressPercent(record);
      };
      _toggleDisabledState = function(record) {
        return _querySelector(elements.billingEvent(record)).classList.toggle('disabled', record.isTransitState);
      };
      _replaceStatus = function(record) {
        return _updateElementContent(elements.billingEventStatus(record), elements.billingEventStatusTemplate(record.status, !record.isTransitState && record.isError));
      };
      _replaceValue = function(record) {
        return _updateElementContent(elements.billingEventValue(record), record.value);
      };
      _replaceActions = function(record) {
        if (record.isDeleting) {
          return _emptyElementContent(elements.billingEventActions(record));
        }
        if (record.showProgressBar) {
          return _updateProgressBar(record);
        }
      };
      filter = function(elements, callback) {
        var element, i, len, results;
        results = [];
        for (i = 0, len = elements.length; i < len; i++) {
          element = elements[i];
          if (callback(element)) {
            results.push(element);
          }
        }
        return results;
      };
      refreshSearch = function() {
        return _querySelector(elements.applySearchFilters).click();
      };
      isVisibleDOMElement = function(record) {
        return !!_querySelector(elements.billingEvent(record));
      };
      removeDOMElement = function(record) {
        var ref;
        return (ref = _querySelector(elements.billingEvent(record))) != null ? ref.remove() : void 0;
      };
      updateDOMElement = function(record) {
        _toggleDisabledState(record);
        _replaceStatus(record);
        _replaceValue(record);
        return _replaceActions(record);
      };
      updateActionsDOMElement = function(record, content) {
        return _updateElementContent(elements.billingEventActions(record), content);
      };
      return {
        filter: filter,
        refreshSearch: refreshSearch,
        isVisibleDOMElement: isVisibleDOMElement,
        removeDOMElement: removeDOMElement,
        updateDOMElement: updateDOMElement,
        updateActionsDOMElement: updateActionsDOMElement
      };
    };
  })(this);

}).call(this);
// I18n.js
// =======
//
// This small library provides the Rails I18n API on the Javascript.
// You don't actually have to use Rails (or even Ruby) to use I18n.js.
// Just make sure you export all translations in an object like this:
//
//     I18n.translations.en = {
//       hello: "Hello World"
//     };
//
// See tests for specific formatting like numbers and dates.
//

// Using UMD pattern from
// https://github.com/umdjs/umd#regular-module
// `returnExports.js` version
;(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define("i18n", function(){ return factory(root);});
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(root);
  } else {
    // Browser globals (root is window)
    root.I18n = factory(root);
  }
}(this, function(global) {
  "use strict";

  // Use previously defined object if exists in current scope
  var I18n = global && global.I18n || {};

  // Just cache the Array#slice function.
  var slice = Array.prototype.slice;

  // Apply number padding.
  var padding = function(number) {
    return ("0" + number.toString()).substr(-2);
  };

  // Improved toFixed number rounding function with support for unprecise floating points
  // JavaScript's standard toFixed function does not round certain numbers correctly (for example 0.105 with precision 2).
  var toFixed = function(number, precision) {
    return decimalAdjust('round', number, -precision).toFixed(precision);
  };

  // Is a given variable an object?
  // Borrowed from Underscore.js
  var isObject = function(obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object'
  };

  var isFunction = function(func) {
    var type = typeof func;
    return type === 'function'
  };

  // Check if value is different than undefined and null;
  var isSet = function(value) {
    return typeof(value) !== 'undefined' && value !== null;
  };

  // Is a given value an array?
  // Borrowed from Underscore.js
  var isArray = function(val) {
    if (Array.isArray) {
      return Array.isArray(val);
    }
    return Object.prototype.toString.call(val) === '[object Array]';
  };

  var isString = function(val) {
    return typeof val === 'string' || Object.prototype.toString.call(val) === '[object String]';
  };

  var isNumber = function(val) {
    return typeof val === 'number' || Object.prototype.toString.call(val) === '[object Number]';
  };

  var isBoolean = function(val) {
    return val === true || val === false;
  };

  var isNull = function(val) {
    return val === null;
  };

  var decimalAdjust = function(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  var lazyEvaluate = function(message, scope) {
    if (isFunction(message)) {
      return message(scope);
    } else {
      return message;
    }
  }

  var merge = function (dest, obj) {
    var key, value;
    for (key in obj) if (obj.hasOwnProperty(key)) {
      value = obj[key];
      if (isString(value) || isNumber(value) || isBoolean(value) || isArray(value) || isNull(value)) {
        dest[key] = value;
      } else {
        if (dest[key] == null) dest[key] = {};
        merge(dest[key], value);
      }
    }
    return dest;
  };

  // Set default days/months translations.
  var DATE = {
      day_names: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    , abbr_day_names: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
    , month_names: [null, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    , abbr_month_names: [null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    , meridian: ["AM", "PM"]
  };

  // Set default number format.
  var NUMBER_FORMAT = {
      precision: 3
    , separator: "."
    , delimiter: ","
    , strip_insignificant_zeros: false
  };

  // Set default currency format.
  var CURRENCY_FORMAT = {
      unit: "$"
    , precision: 2
    , format: "%u%n"
    , sign_first: true
    , delimiter: ","
    , separator: "."
  };

  // Set default percentage format.
  var PERCENTAGE_FORMAT = {
      unit: "%"
    , precision: 3
    , format: "%n%u"
    , separator: "."
    , delimiter: ""
  };

  // Set default size units.
  var SIZE_UNITS = [null, "kb", "mb", "gb", "tb"];

  // Other default options
  var DEFAULT_OPTIONS = {
    // Set default locale. This locale will be used when fallback is enabled and
    // the translation doesn't exist in a particular locale.
      defaultLocale: "en"
    // Set the current locale to `en`.
    , locale: "en"
    // Set the translation key separator.
    , defaultSeparator: "."
    // Set the placeholder format. Accepts `{{placeholder}}` and `%{placeholder}`.
    , placeholder: /(?:\{\{|%\{)(.*?)(?:\}\}?)/gm
    // Set if engine should fallback to the default locale when a translation
    // is missing.
    , fallbacks: false
    // Set the default translation object.
    , translations: {}
    // Set missing translation behavior. 'message' will display a message
    // that the translation is missing, 'guess' will try to guess the string
    , missingBehaviour: 'message'
    // if you use missingBehaviour with 'message', but want to know that the
    // string is actually missing for testing purposes, you can prefix the
    // guessed string by setting the value here. By default, no prefix!
    , missingTranslationPrefix: ''
  };

  // Set default locale. This locale will be used when fallback is enabled and
  // the translation doesn't exist in a particular locale.
  I18n.reset = function() {
    var key;
    for (key in DEFAULT_OPTIONS) {
      this[key] = DEFAULT_OPTIONS[key];
    }
  };

  // Much like `reset`, but only assign options if not already assigned
  I18n.initializeOptions = function() {
    var key;
    for (key in DEFAULT_OPTIONS) if (!isSet(this[key])) {
      this[key] = DEFAULT_OPTIONS[key];
    }
  };
  I18n.initializeOptions();

  // Return a list of all locales that must be tried before returning the
  // missing translation message. By default, this will consider the inline option,
  // current locale and fallback locale.
  //
  //     I18n.locales.get("de-DE");
  //     // ["de-DE", "de", "en"]
  //
  // You can define custom rules for any locale. Just make sure you return a array
  // containing all locales.
  //
  //     // Default the Wookie locale to English.
  //     I18n.locales["wk"] = function(locale) {
  //       return ["en"];
  //     };
  //
  I18n.locales = {};

  // Retrieve locales based on inline locale, current locale or default to
  // I18n's detection.
  I18n.locales.get = function(locale) {
    var result = this[locale] || this[I18n.locale] || this["default"];

    if (isFunction(result)) {
      result = result(locale);
    }

    if (isArray(result) === false) {
      result = [result];
    }

    return result;
  };

  // The default locale list.
  I18n.locales["default"] = function(locale) {
    var locales = []
      , list = []
    ;

    // Handle the inline locale option that can be provided to
    // the `I18n.t` options.
    if (locale) {
      locales.push(locale);
    }

    // Add the current locale to the list.
    if (!locale && I18n.locale) {
      locales.push(I18n.locale);
    }

    // Add the default locale if fallback strategy is enabled.
    if (I18n.fallbacks && I18n.defaultLocale) {
      locales.push(I18n.defaultLocale);
    }

    // Locale code format 1:
    // According to RFC4646 (http://www.ietf.org/rfc/rfc4646.txt)
    // language codes for Traditional Chinese should be `zh-Hant`
    //
    // But due to backward compatibility
    // We use older version of IETF language tag
    // @see http://www.w3.org/TR/html401/struct/dirlang.html
    // @see http://en.wikipedia.org/wiki/IETF_language_tag
    //
    // Format: `language-code = primary-code ( "-" subcode )*`
    //
    // primary-code uses ISO639-1
    // @see http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
    // @see http://www.iso.org/iso/home/standards/language_codes.htm
    //
    // subcode uses ISO 3166-1 alpha-2
    // @see http://en.wikipedia.org/wiki/ISO_3166
    // @see http://www.iso.org/iso/country_codes.htm
    //
    // @note
    //   subcode can be in upper case or lower case
    //   defining it in upper case is a convention only


    // Locale code format 2:
    // Format: `code = primary-code ( "-" region-code )*`
    // primary-code uses ISO 639-1
    // script-code uses ISO 15924
    // region-code uses ISO 3166-1 alpha-2
    // Example: zh-Hant-TW, en-HK, zh-Hant-CN
    //
    // It is similar to RFC4646 (or actually the same),
    // but seems to be limited to language, script, region

    // Compute each locale with its country code.
    // So this will return an array containing
    // `de-DE` and `de`
    // or
    // `zh-hans-tw`, `zh-hans`, `zh`
    // locales.
    locales.forEach(function(locale) {
      var localeParts = locale.split("-");
      var firstFallback = null;
      var secondFallback = null;
      if (localeParts.length === 3) {
        firstFallback = [
          localeParts[0],
          localeParts[1]
        ].join("-");
        secondFallback = localeParts[0];
      }
      else if (localeParts.length === 2) {
        firstFallback = localeParts[0];
      }

      if (list.indexOf(locale) === -1) {
        list.push(locale);
      }

      if (! I18n.fallbacks) {
        return;
      }

      [
        firstFallback,
        secondFallback
      ].forEach(function(nullableFallbackLocale) {
        // We don't want null values
        if (typeof nullableFallbackLocale === "undefined") { return; }
        if (nullableFallbackLocale === null) { return; }
        // We don't want duplicate values
        //
        // Comparing with `locale` first is faster than
        // checking whether value's presence in the list
        if (nullableFallbackLocale === locale) { return; }
        if (list.indexOf(nullableFallbackLocale) !== -1) { return; }

        list.push(nullableFallbackLocale);
      });
    });

    // No locales set? English it is.
    if (!locales.length) {
      locales.push("en");
    }

    return list;
  };

  // Hold pluralization rules.
  I18n.pluralization = {};

  // Return the pluralizer for a specific locale.
  // If no specify locale is found, then I18n's default will be used.
  I18n.pluralization.get = function(locale) {
    return this[locale] || this[I18n.locale] || this["default"];
  };

  // The default pluralizer rule.
  // It detects the `zero`, `one`, and `other` scopes.
  I18n.pluralization["default"] = function(count) {
    switch (count) {
      case 0: return ["zero", "other"];
      case 1: return ["one"];
      default: return ["other"];
    }
  };

  // Return current locale. If no locale has been set, then
  // the current locale will be the default locale.
  I18n.currentLocale = function() {
    return this.locale || this.defaultLocale;
  };

  // Check if value is different than undefined and null;
  I18n.isSet = isSet;

  // Find and process the translation using the provided scope and options.
  // This is used internally by some functions and should not be used as an
  // public API.
  I18n.lookup = function(scope, options) {
    options = options || {}

    var locales = this.locales.get(options.locale).slice()
      , locale
      , scopes
      , fullScope
      , translations
    ;

    fullScope = this.getFullScope(scope, options);

    while (locales.length) {
      locale = locales.shift();
      scopes = fullScope.split(this.defaultSeparator);
      translations = this.translations[locale];

      if (!translations) {
        continue;
      }
      while (scopes.length) {
        translations = translations[scopes.shift()];

        if (translations === undefined || translations === null) {
          break;
        }
      }

      if (translations !== undefined && translations !== null) {
        return translations;
      }
    }

    if (isSet(options.defaultValue)) {
      return lazyEvaluate(options.defaultValue, scope);
    }
  };

  // lookup pluralization rule key into translations
  I18n.pluralizationLookupWithoutFallback = function(count, locale, translations) {
    var pluralizer = this.pluralization.get(locale)
      , pluralizerKeys = pluralizer(count)
      , pluralizerKey
      , message;

    if (isObject(translations)) {
      while (pluralizerKeys.length) {
        pluralizerKey = pluralizerKeys.shift();
        if (isSet(translations[pluralizerKey])) {
          message = translations[pluralizerKey];
          break;
        }
      }
    }

    return message;
  };

  // Lookup dedicated to pluralization
  I18n.pluralizationLookup = function(count, scope, options) {
    options = options || {}
    var locales = this.locales.get(options.locale).slice()
      , locale
      , scopes
      , translations
      , message
    ;
    scope = this.getFullScope(scope, options);

    while (locales.length) {
      locale = locales.shift();
      scopes = scope.split(this.defaultSeparator);
      translations = this.translations[locale];

      if (!translations) {
        continue;
      }

      while (scopes.length) {
        translations = translations[scopes.shift()];
        if (!isObject(translations)) {
          break;
        }
        if (scopes.length == 0) {
          message = this.pluralizationLookupWithoutFallback(count, locale, translations);
        }
      }
      if (message != null && message != undefined) {
        break;
      }
    }

    if (message == null || message == undefined) {
      if (isSet(options.defaultValue)) {
        if (isObject(options.defaultValue)) {
          message = this.pluralizationLookupWithoutFallback(count, options.locale, options.defaultValue);
        } else {
          message = options.defaultValue;
        }
        translations = options.defaultValue;
      }
    }

    return { message: message, translations: translations };
  };

  // Rails changed the way the meridian is stored.
  // It started with `date.meridian` returning an array,
  // then it switched to `time.am` and `time.pm`.
  // This function abstracts this difference and returns
  // the correct meridian or the default value when none is provided.
  I18n.meridian = function() {
    var time = this.lookup("time");
    var date = this.lookup("date");

    if (time && time.am && time.pm) {
      return [time.am, time.pm];
    } else if (date && date.meridian) {
      return date.meridian;
    } else {
      return DATE.meridian;
    }
  };

  // Merge serveral hash options, checking if value is set before
  // overwriting any value. The precedence is from left to right.
  //
  //     I18n.prepareOptions({name: "John Doe"}, {name: "Mary Doe", role: "user"});
  //     #=> {name: "John Doe", role: "user"}
  //
  I18n.prepareOptions = function() {
    var args = slice.call(arguments)
      , options = {}
      , subject
    ;

    while (args.length) {
      subject = args.shift();

      if (typeof(subject) != "object") {
        continue;
      }

      for (var attr in subject) {
        if (!subject.hasOwnProperty(attr)) {
          continue;
        }

        if (isSet(options[attr])) {
          continue;
        }

        options[attr] = subject[attr];
      }
    }

    return options;
  };

  // Generate a list of translation options for default fallbacks.
  // `defaultValue` is also deleted from options as it is returned as part of
  // the translationOptions array.
  I18n.createTranslationOptions = function(scope, options) {
    var translationOptions = [{scope: scope}];

    // Defaults should be an array of hashes containing either
    // fallback scopes or messages
    if (isSet(options.defaults)) {
      translationOptions = translationOptions.concat(options.defaults);
    }

    // Maintain support for defaultValue. Since it is always a message
    // insert it in to the translation options as such.
    if (isSet(options.defaultValue)) {
      translationOptions.push({ message: options.defaultValue });
    }

    return translationOptions;
  };

  // Translate the given scope with the provided options.
  I18n.translate = function(scope, options) {
    options = options || {}

    var translationOptions = this.createTranslationOptions(scope, options);

    var translation;

    var optionsWithoutDefault = this.prepareOptions(options)
    delete optionsWithoutDefault.defaultValue

    // Iterate through the translation options until a translation
    // or message is found.
    var translationFound =
      translationOptions.some(function(translationOption) {
        if (isSet(translationOption.scope)) {
          translation = this.lookup(translationOption.scope, optionsWithoutDefault);
        } else if (isSet(translationOption.message)) {
          translation = lazyEvaluate(translationOption.message, scope);
        }

        if (translation !== undefined && translation !== null) {
          return true;
        }
      }, this);

    if (!translationFound) {
      return this.missingTranslation(scope, options);
    }

    if (typeof(translation) === "string") {
      translation = this.interpolate(translation, options);
    } else if (isArray(translation)) {
      translation = translation.map(function(t) {
        return (typeof(t) === "string" ? this.interpolate(t, options) : t);
      }, this);
    } else if (isObject(translation) && isSet(options.count)) {
      translation = this.pluralize(options.count, scope, options);
    }

    return translation;
  };

  // This function interpolates the all variables in the given message.
  I18n.interpolate = function(message, options) {
    if (message === null) {
      return message;
    }

    options = options || {}
    var matches = message.match(this.placeholder)
      , placeholder
      , value
      , name
      , regex
    ;

    if (!matches) {
      return message;
    }

    var value;

    while (matches.length) {
      placeholder = matches.shift();
      name = placeholder.replace(this.placeholder, "$1");

      if (isSet(options[name])) {
        value = options[name].toString().replace(/\$/gm, "_#$#_");
      } else if (name in options) {
        value = this.nullPlaceholder(placeholder, message, options);
      } else {
        value = this.missingPlaceholder(placeholder, message, options);
      }

      regex = new RegExp(placeholder.replace(/\{/gm, "\\{").replace(/\}/gm, "\\}"));
      message = message.replace(regex, value);
    }

    return message.replace(/_#\$#_/g, "$");
  };

  // Pluralize the given scope using the `count` value.
  // The pluralized translation may have other placeholders,
  // which will be retrieved from `options`.
  I18n.pluralize = function(count, scope, options) {
    options = this.prepareOptions({count: String(count)}, options)
    var pluralizer, message, result;

    result = this.pluralizationLookup(count, scope, options);
    if (result.translations == undefined || result.translations == null) {
      return this.missingTranslation(scope, options);
    }

    if (result.message != undefined && result.message != null) {
      return this.interpolate(result.message, options);
    }
    else {
      pluralizer = this.pluralization.get(options.locale);
      return this.missingTranslation(scope + '.' + pluralizer(count)[0], options);
    }
  };

  // Return a missing translation message for the given parameters.
  I18n.missingTranslation = function(scope, options) {
    //guess intended string
    if(this.missingBehaviour == 'guess'){
      //get only the last portion of the scope
      var s = scope.split('.').slice(-1)[0];
      //replace underscore with space && camelcase with space and lowercase letter
      return (this.missingTranslationPrefix.length > 0 ? this.missingTranslationPrefix : '') +
          s.replace('_',' ').replace(/([a-z])([A-Z])/g,
          function(match, p1, p2) {return p1 + ' ' + p2.toLowerCase()} );
    }

    var localeForTranslation = (options != null && options.locale != null) ? options.locale : this.currentLocale();
    var fullScope           = this.getFullScope(scope, options);
    var fullScopeWithLocale = [localeForTranslation, fullScope].join(this.defaultSeparator);

    return '[missing "' + fullScopeWithLocale + '" translation]';
  };

  // Return a missing placeholder message for given parameters
  I18n.missingPlaceholder = function(placeholder, message, options) {
    return "[missing " + placeholder + " value]";
  };

  I18n.nullPlaceholder = function() {
    return I18n.missingPlaceholder.apply(I18n, arguments);
  };

  // Format number using localization rules.
  // The options will be retrieved from the `number.format` scope.
  // If this isn't present, then the following options will be used:
  //
  // - `precision`: `3`
  // - `separator`: `"."`
  // - `delimiter`: `","`
  // - `strip_insignificant_zeros`: `false`
  //
  // You can also override these options by providing the `options` argument.
  //
  I18n.toNumber = function(number, options) {
    options = this.prepareOptions(
        options
      , this.lookup("number.format")
      , NUMBER_FORMAT
    );

    var negative = number < 0
      , string = toFixed(Math.abs(number), options.precision).toString()
      , parts = string.split(".")
      , precision
      , buffer = []
      , formattedNumber
      , format = options.format || "%n"
      , sign = negative ? "-" : ""
    ;

    number = parts[0];
    precision = parts[1];

    while (number.length > 0) {
      buffer.unshift(number.substr(Math.max(0, number.length - 3), 3));
      number = number.substr(0, number.length -3);
    }

    formattedNumber = buffer.join(options.delimiter);

    if (options.strip_insignificant_zeros && precision) {
      precision = precision.replace(/0+$/, "");
    }

    if (options.precision > 0 && precision) {
      formattedNumber += options.separator + precision;
    }

    if (options.sign_first) {
      format = "%s" + format;
    }
    else {
      format = format.replace("%n", "%s%n");
    }

    formattedNumber = format
      .replace("%u", options.unit)
      .replace("%n", formattedNumber)
      .replace("%s", sign)
    ;

    return formattedNumber;
  };

  // Format currency with localization rules.
  // The options will be retrieved from the `number.currency.format` and
  // `number.format` scopes, in that order.
  //
  // Any missing option will be retrieved from the `I18n.toNumber` defaults and
  // the following options:
  //
  // - `unit`: `"$"`
  // - `precision`: `2`
  // - `format`: `"%u%n"`
  // - `delimiter`: `","`
  // - `separator`: `"."`
  //
  // You can also override these options by providing the `options` argument.
  //
  I18n.toCurrency = function(number, options) {
    options = this.prepareOptions(
        options
      , this.lookup("number.currency.format")
      , this.lookup("number.format")
      , CURRENCY_FORMAT
    );

    return this.toNumber(number, options);
  };

  // Localize several values.
  // You can provide the following scopes: `currency`, `number`, or `percentage`.
  // If you provide a scope that matches the `/^(date|time)/` regular expression
  // then the `value` will be converted by using the `I18n.toTime` function.
  //
  // It will default to the value's `toString` function.
  //
  I18n.localize = function(scope, value, options) {
    options || (options = {});

    switch (scope) {
      case "currency":
        return this.toCurrency(value);
      case "number":
        scope = this.lookup("number.format");
        return this.toNumber(value, scope);
      case "percentage":
        return this.toPercentage(value);
      default:
        var localizedValue;

        if (scope.match(/^(date|time)/)) {
          localizedValue = this.toTime(scope, value);
        } else {
          localizedValue = value.toString();
        }

        return this.interpolate(localizedValue, options);
    }
  };

  // Parse a given `date` string into a JavaScript Date object.
  // This function is time zone aware.
  //
  // The following string formats are recognized:
  //
  //    yyyy-mm-dd
  //    yyyy-mm-dd[ T]hh:mm::ss
  //    yyyy-mm-dd[ T]hh:mm::ss
  //    yyyy-mm-dd[ T]hh:mm::ssZ
  //    yyyy-mm-dd[ T]hh:mm::ss+0000
  //    yyyy-mm-dd[ T]hh:mm::ss+00:00
  //    yyyy-mm-dd[ T]hh:mm::ss.123Z
  //
  I18n.parseDate = function(date) {
    var matches, convertedDate, fraction;
    // we have a date, so just return it.
    if (typeof(date) == "object") {
      return date;
    };

    matches = date.toString().match(/(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2})([\.,]\d{1,3})?)?(Z|\+00:?00)?/);

    if (matches) {
      for (var i = 1; i <= 6; i++) {
        matches[i] = parseInt(matches[i], 10) || 0;
      }

      // month starts on 0
      matches[2] -= 1;

      fraction = matches[7] ? 1000 * ("0" + matches[7]) : null;

      if (matches[8]) {
        convertedDate = new Date(Date.UTC(matches[1], matches[2], matches[3], matches[4], matches[5], matches[6], fraction));
      } else {
        convertedDate = new Date(matches[1], matches[2], matches[3], matches[4], matches[5], matches[6], fraction);
      }
    } else if (typeof(date) == "number") {
      // UNIX timestamp
      convertedDate = new Date();
      convertedDate.setTime(date);
    } else if (date.match(/([A-Z][a-z]{2}) ([A-Z][a-z]{2}) (\d+) (\d+:\d+:\d+) ([+-]\d+) (\d+)/)) {
      // This format `Wed Jul 20 13:03:39 +0000 2011` is parsed by
      // webkit/firefox, but not by IE, so we must parse it manually.
      convertedDate = new Date();
      convertedDate.setTime(Date.parse([
        RegExp.$1, RegExp.$2, RegExp.$3, RegExp.$6, RegExp.$4, RegExp.$5
      ].join(" ")));
    } else if (date.match(/\d+ \d+:\d+:\d+ [+-]\d+ \d+/)) {
      // a valid javascript format with timezone info
      convertedDate = new Date();
      convertedDate.setTime(Date.parse(date));
    } else {
      // an arbitrary javascript string
      convertedDate = new Date();
      convertedDate.setTime(Date.parse(date));
    }

    return convertedDate;
  };

  // Formats time according to the directives in the given format string.
  // The directives begins with a percent (%) character. Any text not listed as a
  // directive will be passed through to the output string.
  //
  // The accepted formats are:
  //
  //     %a  - The abbreviated weekday name (Sun)
  //     %A  - The full weekday name (Sunday)
  //     %b  - The abbreviated month name (Jan)
  //     %B  - The full month name (January)
  //     %c  - The preferred local date and time representation
  //     %d  - Day of the month (01..31)
  //     %-d - Day of the month (1..31)
  //     %H  - Hour of the day, 24-hour clock (00..23)
  //     %-H - Hour of the day, 24-hour clock (0..23)
  //     %I  - Hour of the day, 12-hour clock (01..12)
  //     %-I - Hour of the day, 12-hour clock (1..12)
  //     %m  - Month of the year (01..12)
  //     %-m - Month of the year (1..12)
  //     %M  - Minute of the hour (00..59)
  //     %-M - Minute of the hour (0..59)
  //     %p  - Meridian indicator (AM  or  PM)
  //     %S  - Second of the minute (00..60)
  //     %-S - Second of the minute (0..60)
  //     %w  - Day of the week (Sunday is 0, 0..6)
  //     %y  - Year without a century (00..99)
  //     %-y - Year without a century (0..99)
  //     %Y  - Year with century
  //     %z  - Timezone offset (+0545)
  //
  I18n.strftime = function(date, format) {
    var options = this.lookup("date")
      , meridianOptions = I18n.meridian()
    ;

    if (!options) {
      options = {};
    }

    options = this.prepareOptions(options, DATE);

    if (isNaN(date.getTime())) {
      throw new Error('I18n.strftime() requires a valid date object, but received an invalid date.');
    }

    var weekDay = date.getDay()
      , day = date.getDate()
      , year = date.getFullYear()
      , month = date.getMonth() + 1
      , hour = date.getHours()
      , hour12 = hour
      , meridian = hour > 11 ? 1 : 0
      , secs = date.getSeconds()
      , mins = date.getMinutes()
      , offset = date.getTimezoneOffset()
      , absOffsetHours = Math.floor(Math.abs(offset / 60))
      , absOffsetMinutes = Math.abs(offset) - (absOffsetHours * 60)
      , timezoneoffset = (offset > 0 ? "-" : "+") +
          (absOffsetHours.toString().length < 2 ? "0" + absOffsetHours : absOffsetHours) +
          (absOffsetMinutes.toString().length < 2 ? "0" + absOffsetMinutes : absOffsetMinutes)
    ;

    if (hour12 > 12) {
      hour12 = hour12 - 12;
    } else if (hour12 === 0) {
      hour12 = 12;
    }

    format = format.replace("%a", options.abbr_day_names[weekDay]);
    format = format.replace("%A", options.day_names[weekDay]);
    format = format.replace("%b", options.abbr_month_names[month]);
    format = format.replace("%B", options.month_names[month]);
    format = format.replace("%d", padding(day));
    format = format.replace("%e", day);
    format = format.replace("%-d", day);
    format = format.replace("%H", padding(hour));
    format = format.replace("%-H", hour);
    format = format.replace("%I", padding(hour12));
    format = format.replace("%-I", hour12);
    format = format.replace("%m", padding(month));
    format = format.replace("%-m", month);
    format = format.replace("%M", padding(mins));
    format = format.replace("%-M", mins);
    format = format.replace("%p", meridianOptions[meridian]);
    format = format.replace("%S", padding(secs));
    format = format.replace("%-S", secs);
    format = format.replace("%w", weekDay);
    format = format.replace("%y", padding(year));
    format = format.replace("%-y", padding(year).replace(/^0+/, ""));
    format = format.replace("%Y", year);
    format = format.replace("%z", timezoneoffset);

    return format;
  };

  // Convert the given dateString into a formatted date.
  I18n.toTime = function(scope, dateString) {
    var date = this.parseDate(dateString)
      , format = this.lookup(scope)
    ;

    if (date.toString().match(/invalid/i)) {
      return date.toString();
    }

    if (!format) {
      return date.toString();
    }

    return this.strftime(date, format);
  };

  // Convert a number into a formatted percentage value.
  I18n.toPercentage = function(number, options) {
    options = this.prepareOptions(
        options
      , this.lookup("number.percentage.format")
      , this.lookup("number.format")
      , PERCENTAGE_FORMAT
    );

    return this.toNumber(number, options);
  };

  // Convert a number into a readable size representation.
  I18n.toHumanSize = function(number, options) {
    var kb = 1024
      , size = number
      , iterations = 0
      , unit
      , precision
    ;

    while (size >= kb && iterations < 4) {
      size = size / kb;
      iterations += 1;
    }

    if (iterations === 0) {
      unit = this.t("number.human.storage_units.units.byte", {count: size});
      precision = 0;
    } else {
      unit = this.t("number.human.storage_units.units." + SIZE_UNITS[iterations]);
      precision = (size - Math.floor(size) === 0) ? 0 : 1;
    }

    options = this.prepareOptions(
        options
      , {unit: unit, precision: precision, format: "%n%u", delimiter: ""}
    );

    return this.toNumber(size, options);
  };

  I18n.getFullScope = function(scope, options) {
    options = options || {}

    // Deal with the scope as an array.
    if (isArray(scope)) {
      scope = scope.join(this.defaultSeparator);
    }

    // Deal with the scope option provided through the second argument.
    //
    //    I18n.t('hello', {scope: 'greetings'});
    //
    if (options.scope) {
      scope = [options.scope, scope].join(this.defaultSeparator);
    }

    return scope;
  };
  /**
   * Merge obj1 with obj2 (shallow merge), without modifying inputs
   * @param {Object} obj1
   * @param {Object} obj2
   * @returns {Object} Merged values of obj1 and obj2
   *
   * In order to support ES3, `Object.prototype.hasOwnProperty.call` is used
   * Idea is from:
   * https://stackoverflow.com/questions/8157700/object-has-no-hasownproperty-method-i-e-its-undefined-ie8
   */
  I18n.extend = function ( obj1, obj2 ) {
    if (typeof(obj1) === "undefined" && typeof(obj2) === "undefined") {
      return {};
    }
    return merge(obj1, obj2);
  };

  // Set aliases, so we can save some typing.
  I18n.t = I18n.translate;
  I18n.l = I18n.localize;
  I18n.p = I18n.pluralize;

  return I18n;
}));
I18n.translations || (I18n.translations = {});
I18n.translations["en"] = I18n.extend((I18n.translations["en"] || {}), {"js":{"frontend":{"billing":{"bulk_revalidate_confirm":"You are about to revalidate all selected billing files.\nClick OK to continue.\n","buttons":{"create_billing_event":"Create Billing Event","create_billing_event_filter":"Create from Filter","save_draft":"Save Draft","save_draft_filter":"Save Draft from Filter"},"change_review_charges_params_confirm":"You are making changes to the existing parameters.\nWould you like to load charges with the new parameters?\n","charges_loader":"Loading %{current} of %{total} charges...","close_warning_html":"Please do not close the window in order to monitor the progress of the job. Once it is done, you will see a Close option at the bottom.\u003cbr/\u003e\nIf you choose to close it now, the work will continue in the background, but you will not be informed of the progress..\n","create_files_and_invoices_confirm":"You are about to create billing files and invoices for all selected billing events.\nClick OK to create these files.\n","delete_draft_pending_confirm":"Are you sure you want to remove this draft event?","delete_pending_confirm":"Are you sure you want to delete this billing event? This can not be undone, and poses the possibility of billing for the same item twice.","loading_charges":"Loading Charges...","maximum_events_html":"You can revalidate up to %{maximum} events at a time and your current selection exceeds that number. Please adjust your selection and try again.\n","message_streaming_unavailable":{"body_html":"\u003cp\u003eWe have been notified and we are working on fixing it but in the meantime, we cannot show the progress of your action, which continues to run in the background without interruption.\nPlease click “OK” and then refresh the page periodically to get updates on the progress.\u003c/p\u003e\n\u003cp\u003eWe apologize for the inconvenience. Feel free to contact iLab Support if you have any additional questions.\u003c/p\u003e          \n","title":"An error occurred with the real-time progress updates."},"minimum_events_html":"Please select at least one record.","no_charges":"No Charges","statuses":{"billing_errors":"Billing Errors","billing_initiated":"Billing Initiated","deleting":"Deleting...","draft":"Draft","file_sent":"File Sent","pending_review":"Pending Review","processing":"Processing...","processing_error":"Processing Error","revalidating":"Revalidating..."}}}}});
(function() {
  window.BillingTranslationModule = (function(_this) {
    return function(i18nLayer) {
      var t;
      t = function(key, options) {
        options = Object.assign({}, {
          scope: 'js.frontend.billing'
        }, options || {});
        return i18nLayer.t(key, options);
      };
      return {
        t: t
      };
    };
  })(this);

}).call(this);
(function() {
  window.BillingEventDeserializer = (function(_this) {
    return function(data) {
      var _isEventTypeEql, isDeleting, isError, isProcessing, isProcessingError, isProgressComplete, isRevalidating, isTransitState, progress, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, showProgressBar;
      _isEventTypeEql = function(eventType) {
        return data.event_type === eventType;
      };
      progress = parseInt(((ref = data.args) != null ? ref.progress : void 0) || 0);
      isDeleting = ((ref1 = data.args) != null ? ref1.deleting : void 0) || false;
      isProcessing = (ref2 = data.args) != null ? ref2.processing : void 0;
      isRevalidating = (ref3 = data.args) != null ? ref3.revalidating : void 0;
      isTransitState = isProcessing || isRevalidating || isDeleting;
      isProcessingError = ((ref4 = data.args) != null ? ref4.processing_error : void 0) || false;
      isError = isProcessingError || ((ref5 = data.args) != null ? ref5.billing_errors : void 0) || false;
      isProgressComplete = progress === 100;
      showProgressBar = isProcessing || isRevalidating || false;
      return {
        objectClass: data.class_object,
        id: (ref6 = data.args) != null ? ref6.id : void 0,
        coreId: (ref7 = data.args) != null ? ref7.core_id : void 0,
        status: (ref8 = data.args) != null ? ref8.status : void 0,
        value: ((ref9 = data.args) != null ? ref9.value : void 0) || '',
        progress: progress,
        isUpdated: _isEventTypeEql('updated'),
        isDeleted: _isEventTypeEql('deleted'),
        isCreated: _isEventTypeEql('created'),
        isTransitState: isTransitState,
        isProcessingError: isProcessingError,
        isDeleting: isDeleting,
        isError: isError,
        isProgressComplete: isProgressComplete,
        showProgressBar: showProgressBar
      };
    };
  })(this);

}).call(this);
(function() {
  window.BillingTrackChangesXhr = (function(_this) {
    return function(jqueryLayer) {
      var _abortRequest, _addRequest, _removeRequest, loadActions, xhrPool;
      xhrPool = {};
      _addRequest = function(id, jqXHR) {
        return xhrPool[id] = jqXHR;
      };
      _removeRequest = function(id) {
        return delete xhrPool[id];
      };
      _abortRequest = function(id) {
        var jqXHR;
        jqXHR = xhrPool[id];
        if (jqXHR) {
          jqXHR.abort();
          return _removeRequest(id);
        }
      };
      loadActions = function(record, options, callback) {
        _abortRequest(record.id);
        return jqueryLayer.ajax({
          url: "/billing/" + record.id + "/load_actions",
          data: {
            is_core_page: options != null ? options.isCorePage : void 0
          },
          method: 'GET',
          beforeSend: (function(_this) {
            return function(jqXHR) {
              _addRequest(record.id, jqXHR);
              return callback(record, '');
            };
          })(this),
          success: (function(_this) {
            return function(responseText) {
              return callback(record, responseText);
            };
          })(this),
          complete: (function(_this) {
            return function(jqXHR) {
              return _removeRequest(record.id);
            };
          })(this)
        });
      };
      return {
        loadActions: loadActions
      };
    };
  })(this);

  window.BillingTrackChangesElements = (function(_this) {
    return function() {
      var billingEvent, billingEventStatusTemplate, billingEvents, progressBarTemplate;
      billingEvent = function(arg) {
        var id;
        id = arg.id;
        return "#billing_event_row_" + id;
      };
      billingEvents = function(records) {
        return records.map(function(record) {
          return billingEvent(record);
        });
      };
      billingEventStatusTemplate = function(content, error) {
        var classes;
        classes = error ? 'error' : '';
        return "<span class='" + classes + "'>" + content + "</span>";
      };
      progressBarTemplate = function(percent) {
        return "<div class='ui small indicating active progress' data-percent='" + percent + "'>\n  <div class='bar' style='transition-duration: 300ms;width: " + percent + "%;'></div>\n  <div class='label'>" + percent + "%</div>\n</div>";
      };
      return {
        billingEvent: billingEvent,
        billingEvents: billingEvents,
        progressBarTemplate: progressBarTemplate,
        billingEventStatusTemplate: billingEventStatusTemplate,
        billingEventStatus: function(record) {
          return (billingEvent(record)) + " .extended_status";
        },
        billingEventValue: function(record) {
          return (billingEvent(record)) + " .stats";
        },
        billingEventActions: function(record) {
          return (billingEvent(record)) + " .actions";
        },
        applySearchFilters: '.billingevents_search #apply_filters',
        billingEventProgress: function(record) {
          return (billingEvent(record)) + " .progress";
        },
        billingEventProgressBar: function(record) {
          return (billingEvent(record)) + " .progress .bar";
        },
        billingEventProgressLabel: function(record) {
          return (billingEvent(record)) + " .progress .label";
        },
        allBillingEventProgress: '.search_result_entry .progress'
      };
    };
  })(this);

  window.BillingTrackChanges = (function(_this) {
    return function(arg) {
      var _deletedRecords, _deserializedData, _hasCreatedRecords, _isCorePage, _onmessage, _parseArray, _processRecords, _setIsCorePage, _updateDOMElement, _updatedRecords, _visibleRecords, debugManager, deserializer, dom, isCorePage, jsonLayer, messageStreaming, promiseHandler, start, stop, xhrHandler;
      dom = arg.dom, messageStreaming = arg.messageStreaming, promiseHandler = arg.promiseHandler, deserializer = arg.deserializer, isCorePage = arg.isCorePage, xhrHandler = arg.xhrHandler, jsonLayer = arg.jsonLayer, debugManager = arg.debugManager;
      _isCorePage = false;
      _setIsCorePage = function(value) {
        return _isCorePage = value;
      };
      _parseArray = function(string) {
        return jsonLayer.parse(string) || [];
      };
      _deserializedData = function(data) {
        return _parseArray(data).map(function(record) {
          return deserializer(record);
        });
      };
      _hasCreatedRecords = function(records) {
        return !!dom.filter(records, function(record) {
          return record.isCreated && !dom.isVisibleDOMElement(record);
        }).length;
      };
      _visibleRecords = function(records) {
        return dom.filter(records, function(record) {
          return dom.isVisibleDOMElement(record);
        });
      };
      _updatedRecords = function(records) {
        return dom.filter(records, function(record) {
          return record.isUpdated;
        });
      };
      _deletedRecords = function(records) {
        return dom.filter(records, function(record) {
          return record.isDeleted;
        });
      };
      _updateDOMElement = function(record) {
        dom.updateDOMElement(record);
        if (!record.isTransitState) {
          return xhrHandler.loadActions(record, {
            isCorePage: _isCorePage
          }, dom.updateActionsDOMElement);
        }
      };
      _processRecords = function(records) {
        var visibleRecords;
        if (_hasCreatedRecords(records)) {
          return dom.refreshSearch();
        }
        visibleRecords = _visibleRecords(records);
        promiseHandler.processRecordsParallel(_deletedRecords(visibleRecords), function(record) {
          return dom.removeDOMElement(record);
        });
        return promiseHandler.processRecordsParallel(_updatedRecords(visibleRecords), function(record) {
          return _updateDOMElement(record);
        });
      };
      _onmessage = function(data) {
        debugManager.blue('%c BillingTrackChanges Message Received ', {
          _isCorePage: _isCorePage,
          deserialisedData: _deserializedData(data)
        });
        return _processRecords(_deserializedData(data));
      };
      start = function(arg1) {
        var isCorePage;
        isCorePage = arg1.isCorePage;
        _setIsCorePage(isCorePage);
        return messageStreaming.onmessage(_onmessage);
      };
      stop = function() {
        return messageStreaming.stopListener('onmessage', _onmessage);
      };
      return {
        start: start,
        stop: stop
      };
    };
  })(this);

}).call(this);
(function() {
  var date, elements, emitter, eventManager, messageStreamingPopupConstants, setupBillingTrackChanges, setupMessageStreaming, timer, translate;

  messageStreamingPopupConstants = window.MessageStreamingUnavailablePopupConstants;

  translate = window.BillingTranslationModule(I18n);

  date = window.MessageStreamingDates({
    date: Date
  });

  eventManager = window.MessageStreamingEventManager(NchanSubscriber);

  elements = window.BillingTrackChangesElements({
    translate: translate
  });

  emitter = new window.EventEmitter();

  timer = window.MessageStreamingUnavailablePopupTimer({
    setIntervalFn: window.setInterval,
    clearIntervalFn: window.clearInterval,
    setTimeoutFn: window.setTimeout,
    clearTimeoutFn: window.clearTimeout
  });

  setupMessageStreaming = function() {
    window.navigationMonitor = window.PageNavigationMonitor($j, window, emitter);
    window.messageStreaming = window.MessageStreaming({
      eventManager: eventManager,
      emitter: emitter,
      navigationMonitor: window.navigationMonitor,
      debugManager: window.debugManager
    });
    return window.messageStreamingPopup = window.MessageStreamingUnavailablePopup({
      messageStreaming: window.messageStreaming,
      translate: translate,
      healthChecker: window.MessageStreamingHealthChecker({
        date: date,
        timer: timer,
        constants: messageStreamingPopupConstants
      }),
      navigationMonitor: window.navigationMonitor,
      constants: messageStreamingPopupConstants,
      storage: window.MessageStreamingUnavailablePopupStorage(window.sessionStorage, messageStreamingPopupConstants),
      dom: window.MessageStreamingUnavailablePopupDom($j, window.location),
      elements: window.MessageStreamingUnavailablePopupElements()
    });
  };

  setupBillingTrackChanges = function() {
    return window.billingTrackChanges = window.BillingTrackChanges({
      messageStreaming: window.messageStreaming,
      dom: window.BillingEventDomManipulator(elements, document),
      promiseHandler: window.RunParallelUIUpdate(Promise, window.setTimeout),
      deserializer: window.BillingEventDeserializer,
      xhrHandler: window.BillingTrackChangesXhr($j),
      jsonLayer: JSON,
      debugManager: window.debugManager
    });
  };

  $j(function() {
    setupMessageStreaming();
    setupBillingTrackChanges();
    $j("body").on("click", ".message.closable .close.icon", function() {
      $j('.message.closable').fadeOut("slow");
      return false;
    });
    $j("body").on("click", "#show-billing-event-revalidate-modal", function() {
      return $j('#billing-event-revalidate').modal('show');
    });
    $j("body").on("click", "#billing-event-revalidate-submit", function(event) {
      $j(this).addClass("loading");
      $j(this).closest("form").submit();
      return true;
    });
    $j("body").on("click", "#show-email-billing-event-summaries-modal", function() {
      return $j('#email-billing-event-summaries').modal('show');
    });
    return $j("body").on("click", "#show-invoice-email-notification-modal", function(ev) {
      var modalEl;
      modalEl = $j('#invoice-email-notification-modal');
      console.dir(ev);
      return $j.get({
        url: $j(ev.target).data('load-path'),
        data: {
          semantic: 'true'
        },
        success: function(data) {
          modalEl.find('.content').html(data);
          return modalEl.modal({
            observeChanges: true
          }).modal('show');
        },
        dataType: 'html'
      });
    });
  });

}).call(this);



I18n.translations || (I18n.translations = {});
I18n.translations["en"] = I18n.extend((I18n.translations["en"] || {}), {"js":{"people_search":{"additional_contacts":"(%{count} additional contacts)","loader_text":"Please wait until the page is fully loaded...","select_all_title":"Email will be sent to all %{count} people."}}});
(function() {
  var PeopleSendEmails;

  $j.fn.extend({
    uniqueSerialize: function() {
      var returnData;
      returnData = {};
      $j.each(this.serializeObject(), function(key, value) {
        return returnData[key] = typeof value.unique === 'function' ? value.unique() : value;
      });
      return jQuery.param(returnData);
    }
  });

  $j(function() {
    var _appendToUserList, _getPersonObject, getRecipientInputs, getRecipientsCount, hasPeopleSearch, hasPeopleSearchSearch, hasPeopleSearchTabbedIndex, hasPeopleSearchTabbedSearch, peopleSendEmails;
    $j(' .people_search #search_controls > form').livequery(function() {
      if (!($j('#sel_all_ppl').length > 0)) {
        return $j(this).append('<input id="people_across_pages" name="people_across_pages" type="hidden" value="0">');
      }
    });
    $j('#sel_all_ppl').live('click', function() {
      var count;
      if ('0' === $j('#people_across_pages').val()) {
        $j('#people_across_pages').val('1');
        $j(this).text('Click to uncheck.');
        count = $j(' .people_search #header_message').text().match(/of (\d+) /)[1];
        $j(this).closest('span').html('Selected all ' + count + ' results.').append(this);
        peopleSendEmails.selectAllPages();
        Tipped.refresh('*');
      } else {
        $j('#people_across_pages').val('0');
        $j(this).closest('span').remove();
        $j('#select_all_people').trigger('click');
        peopleSendEmails.unselectAllPages();
        Tipped.refresh('*');
      }
      return false;
    });
    $j('#people_bulk_actions_link').live('click', function() {
      $j('#people_bulk_actions').toggle(300);
      if ($j(this).text() === '>>') {
        $j(this).text('<< Bulk Actions');
      } else {
        $j(this).text('>>');
      }
      return false;
    });
    $j(' .people_search .search_result_entry.header').livequery(function() {
      if ($j(' .people_search .search_result_entry.header').length) {
        if (!$j('#select_all_people').length) {
          return $j(' .people_search .search_result_entry.header').append('<input class="mark_user" id="select_all_people" type="checkbox" style="float:right;" >');
        }
      }
    });
    $j('#select_all_people').live('click', function() {
      var access_request_list_insert, checkboxes;
      window.selected_user_ids || (window.selected_user_ids = []);
      access_request_list_insert = '';
      if ($j(this).prop('checked')) {
        checkboxes = $j(' .indicators :checkbox');
        checkboxes.each(function() {
          var email, id, name;
          $j(this).prop('checked', true);
          id = $j(this).attr('value');
          name = $j(this).parents('.search_result_entry').find('.full_name').html();
          email = $j(this).parents('.search_result_entry').find('.email').html();
          window.selected_user_ids.push(id);
          return access_request_list_insert += window.people_get_insert_element(id, name, email);
        });
        _appendToUserList(document.getElementById('selected_users_list_for_access_request'), access_request_list_insert);
        peopleSendEmails.selectAll(checkboxes.map(function() {
          return _getPersonObject(this);
        }).get());
        $j(' .people_search #header_message').append('<span>Selected all results on this page.<a id="sel_all_ppl">Click to select all results</a></span>');
      } else {
        window.selected_user_ids = [];
        $j('#people_across_pages').val('0');
        $j(' .people_search #header_message > span').remove();
        $j('#select_all_people').val(0);
        Tipped.refresh('*');
        $j(' .indicators :checkbox').each(function(index) {
          return $j(this).prop('checked', false);
        });
        window.people_search_userlists_remove_all();
        peopleSendEmails.unselectAll();
      }
      return window.people_search_userlists_tipped_refresh();
    });
    getRecipientInputs = (function(_this) {
      return function(form) {
        return form.find('input[name="persons[]"]:checked, input[name="email[send_to][]"]:checked');
      };
    })(this);
    getRecipientsCount = (function(_this) {
      return function(form) {
        return getRecipientInputs(form).map(function() {
          return this.value;
        }).get().unique().length;
      };
    })(this);
    $j(' .email_submit_button').live('click', function() {
      var data, editor_id, form, number_of_recipients, self, split_arr;
      self = $j(this);
      form = self.parents('form');
      editor_id = form.find('.email_body').first().attr('id');
      tinyMCE.EditorManager.get(editor_id).save();
      data = form.uniqueSerialize();
      if (self.closest('.email_content').find('.email_subject').val().length < 10) {
        alert('Subject should be at least 10 characters long.');
        return false;
      }
      if (self.closest('.email_content').find('.email_body').val().length < 25) {
        alert('Message should be at least 25 characters long.');
        return false;
      }
      number_of_recipients = getRecipientsCount(form);
      if (form.find('#email_all_people').text()) {
        number_of_recipients = form.find('#email_all_people').text().match(/all (\d+) people/)[1];
      }
      if (number_of_recipients === 0) {
        alert('Please select at least one recipient.');
        return false;
      }
      split_arr = $j(' .people_search #search_controls > form ').attr('action').split('?');
      data += '&' + split_arr[split_arr.length - 1];
      if ('1' === $j('#people_across_pages').val()) {
        data += '&' + $j(' .people_search #search_controls > form ').serialize();
      }
      if (peopleSendEmails.onlyAdministration) {
        data += "&only_administration=true";
      }
      if (peopleSendEmails.copyAdministration) {
        data += "&copy_administration=true";
      }
      $j('#are_you_sure_question').html('Are you sure you want to send an email to ' + number_of_recipients + ' recipient(s)?');
      $j("#email_confirmation_dialog").dialog({
        resizable: false,
        width: 600,
        modal: true,
        buttons: [
          {
            text: 'Cancel',
            click: function() {
              return $j(this).dialog('destroy');
            }
          }, {
            text: 'Send Email',
            click: function() {
              return $j.ajax(form.attr('action'), {
                type: 'POST',
                data: data,
                beforeSend: (function(_this) {
                  return function() {
                    self.next().show();
                    return self.hide();
                  };
                })(this),
                complete: (function(_this) {
                  return function() {
                    $j(_this).dialog('destroy');
                    Tipped.hide('*');
                    alert('Your message has been sent!');
                    self.next().hide();
                    return self.show();
                  };
                })(this)
              });
            }
          }
        ]
      });
      return false;
    });
    $j(' .remove_from_trained').live('click', function() {
      $j.ajax($j(this).attr('url'), {
        type: 'POST'
      });
      $j(this).parents('.equipment_info').fadeOut('slow', function() {
        $j(this).parent('.equipment_info').remove();
        return Tipped.refresh('*');
      });
      return false;
    });
    $j(' .user_equipment_training .add_as_trained_link').live('click', function() {
      $j.ajax($j(this).attr('url'), {
        type: 'POST',
        complete: (function(_this) {
          return function(response) {
            var container;
            container = $j(_this).parents('.add_as_trained').prev();
            container.prepend(response.responseText);
            container.children(':first-child').hide();
            container.children(':first-child').fadeIn('slow');
            return $j(_this).parents('.equipment_info').fadeOut('slow', function() {
              $j(this).parent('.equipment_info').remove();
              return Tipped.refresh('*');
            });
          };
        })(this)
      });
      return false;
    });
    $j(' .find_equipment').live('click', function() {
      var form;
      form = $j(this).parents('form');
      $j.ajax(form.attr('action'), {
        type: 'GET',
        data: form.serializeArray(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            $j(_this).show();
            $j(_this).parents('form').next().html(response.responseText);
            return Tipped.refresh('*');
          };
        })(this)
      });
      return false;
    });
    $j(' .search_form form').live('submit', function() {
      var form, submit;
      form = $j(this);
      submit = $j(this).find('.find_equipment');
      $j.ajax(form.attr('action'), {
        type: 'GET',
        data: form.serializeArray(),
        beforeSend: (function(_this) {
          return function() {
            submit.next().show();
            return submit.hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            submit.next().hide();
            submit.show();
            form.next().html(response.responseText);
            return Tipped.refresh('*');
          };
        })(this)
      });
      return false;
    });
    $j(' .process_access_request, .process_multiple_access_requests').live('click', function() {
      var form, update_type;
      showSpinner(this);
      form = $j(this).parents('form');
      update_type = $j(this).attr('class').replace('process_access_request', '');
      update_type = update_type.replace('process_multiple_access_requests', '');
      update_type = update_type.trim();
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize() + '&update_type=' + update_type,
        complete: (function(_this) {
          return function() {
            hideSpinner(_this);
            if (('approve' === update_type) || ('reject' === update_type)) {
              return $j(_this).parents('.request_info_wrapper').fadeOut('slow', function() {
                return Tipped.refresh('*');
              });
            }
          };
        })(this)
      });
      return false;
    });
    $j(' .generate_access_request').live('click', function() {
      var form;
      form = $j(this).parents('form');
      $j.ajax(form.attr('action'), {
        type: 'GET',
        data: form.serializeArray(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            $j(_this).show();
            if ($j(_this).parents('form').next().length) {
              $j(_this).parents('form').next().remove();
            }
            $j(_this).parents('form').after('<div class="request_info_wrapper">' + response.responseText + '</div>');
            return Tipped.refresh('*');
          };
        })(this)
      });
      return false;
    });
    $j(' #equipment_training_form .add_as_trained_link').live('click', function() {
      var asset_id, form;
      form = $j('#selected_users_list_for_equipment_training');
      asset_id = $j(this).attr('url').split('?').slice(-1)[0];
      if (form.find('input:checked').length > 0) {
        $j.ajax(form.data('url') + '?' + asset_id, {
          type: 'POST',
          dataType: 'script',
          data: form.find('input:checked').serializeArray(),
          complete: (function(_this) {
            return function(response) {
              $j('#training_added_for').show();
              $j('#training_added_for .results').append(response.responseText);
              $j(_this).parents('.equipment_info').fadeOut('slow', function() {
                $j(this).parent('.equipment_info').remove();
                return Tipped.refresh('*');
              });
              return Tipped.refresh('*');
            };
          })(this)
        });
      } else {
        form.children(' .warning').remove();
        form.append('<span class="warning" style="color:red;">Select at least one person.</span>');
        Tipped.refresh('*');
      }
      return false;
    });
    $j(' .generate_access_requests').live('click', function() {
      var form;
      form = $j(this).parents('form');
      if (form.find('input:checked').length > 0) {
        form.find(' .warning').remove();
        $j.ajax(form.attr('action'), {
          type: 'POST',
          dataType: 'script',
          data: form.serializeArray(),
          beforeSend: (function(_this) {
            return function() {
              $j(_this).next().show();
              return $j(_this).hide();
            };
          })(this),
          complete: (function(_this) {
            return function(response) {
              $j('#selected_users_list_for_access_request').html('');
              $j('#access_requests_header').show();
              $j('#access_requests_list').show();
              $j('#access_requests_list').html(response.responseText);
              $j(_this).next().hide();
              $j(_this).show();
              return Tipped.refresh('*');
            };
          })(this)
        });
      } else {
        form.children(' .warning').remove();
        $j('#access_requests_header').hide();
        $j('#access_requests_list').hide();
        form.append('<span class="warning" style="color:red;">Select at least one person.</span>');
        Tipped.refresh('*');
      }
      return false;
    });
    window.people_search_userlists_tipped_refresh = function() {
      return Tipped.refresh('#add_access_requests', '#equipment_training_form');
    };
    window.people_get_insert_element = function(id, name, email) {
      return '<tr id="person_' + id + '" class="person_entry"> <td><input type="checkbox" checked="checked" value="' + id + '" name="persons[]"><span>' + name + '(' + email + ')</span></td> <td><a href="#" style="float:right" onclick="$j(this).parent().parent().remove();return false;"><img src="/images/delete.png"></a></td> </tr>';
    };
    window.people_search_userlists_append = function(id, name, email) {
      var list2;
      list2 = $j('#selected_users_list_for_access_request');
      return list2.append(window.people_get_insert_element(id, name, email));
    };
    window.people_search_userlists_remove_all = function() {
      $j('#selected_users_list_for_access_request').html('');
      return window.people_search_userlists_tipped_refresh();
    };
    window.people_search_userlists_remove = function(id) {
      $j('#email_people_form #person_' + id).remove();
      $j('#access_requests_form #person_' + id).remove();
      $j('#equipment_training_form #person_' + id).remove();
      return window.people_search_userlists_tipped_refresh();
    };
    _appendToUserList = function(node, userListHTML) {
      if (node) {
        return node.innerHTML += userListHTML;
      }
    };
    _getPersonObject = function(node) {
      return {
        id: $j(node).attr('value'),
        name: $j(node).parents('.search_result_entry').find('.full_name').text().trim(),
        email: $j(node).parents('.search_result_entry').find('.email').text().trim(),
        administrators: $j(node).parents('.search_result_entry').data('administrators')
      };
    };
    window.selected_user_ids = [];
    $j(' .indicators :checkbox').live('change', function() {
      var email, id, name;
      $j('#people_across_pages').val('0');
      $j(' .people_search #header_message > span').remove();
      $j('#select_all_people').prop('checked', '');
      $j('#selected_users_list').show();
      Tipped.refresh('*');
      if ($j(this).prop('checked')) {
        id = $j(this).attr('value');
        name = $j(this).parents('.search_result_entry').find('.full_name').html();
        email = $j(this).parents('.search_result_entry').find('.email').html();
        window.selected_user_ids.push(id);
        window.people_search_userlists_append(id, name, email);
        peopleSendEmails.select(_getPersonObject(this));
      } else {
        id = $j(this).attr('value');
        $j('#email_people_form #person_' + id).remove();
        $j('#access_requests_form #person_' + id).remove();
        window.selected_user_ids.splice(window.selected_user_ids.indexOf(id), 1);
        peopleSendEmails.unselect(_getPersonObject(this));
      }
      return window.people_search_userlists_tipped_refresh();
    });
    $j('#people_to_csv_dialog').livequery(function() {
      return $j(this).magnificPopup({
        type: 'inline',
        preloader: false,
        modal: true,
        callbacks: {
          open: function() {
            $j('.mfp-content').width('40%');
            $j('#people_to_csv_form .criteria_fields .datepicker').datepicker();
            $j('#people_to_csv_form .cancel.button').on('click', function() {
              return $j.magnificPopup.close();
            });
            return $j('#people_to_csv_form input[type=radio]').on('change', function() {
              return $j('#people_to_csv_form .criteria_fields').toggle($j('#export_by_criteria_radio').prop('checked'));
            });
          },
          close: function() {
            return $j('.mfp-content').width('100%');
          }
        }
      });
    });
    $j('#people_to_csv_form .export.button').live('click', function(event) {
      var data, filters_form, href;
      filters_form = $j(' .searcher_base.people_search').data('searcher_base').filtersForm;
      data = filters_form.serializeArray();
      data.push({
        name: 'selected_users_ids',
        value: window.selected_user_ids
      });
      data = data.concat($j('#people_to_csv_form form').serializeArray());
      href = ($j('#people_to_csv_dialog').attr("url")) + "&" + ($j.param(data));
      window.open(href, '_blank');
      return false;
    });
    $j(' .mark_user').livequery(function() {
      if (window.selected_user_ids.indexOf($j(this).attr('value')) >= 0) {
        $j(this).prop('checked', true);
        return true;
      }
    }, function() {
      return true;
    });
    $j(' #review_facilities_usage').live('click', function() {
      var id, options, type, url;
      options = $j(this).parents('form').serializeArray();
      id = options[options.length - 2]['value'];
      type = options[options.length - 1]['value'];
      if ('equipment' === type) {
        url = "/equipment/message_customers/?service_center_id=" + id;
      } else {
        url = "/service_center/message_customers/" + id;
      }
      window.location.href = url;
      return false;
    });
    $j('.profile_information_popup').live('click', function() {
      $j.ajax('/people_search/profile_magnifico_popup', {
        method: 'GET',
        data: {
          id: $j(this).data('profile_id'),
          entry_type: $j(this).data('entry_type'),
          member_profile_id: $j(this).data('member_profile_id')
        },
        beforeSend: (function(_this) {
          return function() {
            return showSpinner(_this);
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            var height;
            hideSpinner(_this);
            if ($j(_this).data('tipped')) {
              return Tipped.create($j(_this), response.responseText, {
                hideOn: false,
                closeButton: true
              });
            } else {
              $j.magnificPopup.open({
                alignTop: false,
                overflowY: 'auto',
                items: {
                  src: response.responseText,
                  type: 'inline'
                }
              });
              return height = $j(window).height() * 0.9;
            }
          };
        })(this)
      });
      return false;
    });
    $j('.lab_information_form').live('click', function() {
      $j.ajax('/people_search/lab_popup_form', {
        method: 'POST',
        data: {
          id: $j(this).data('lab_id'),
          entry_type: $j(this).data('entry_type')
        },
        complete: (function(_this) {
          return function(response) {
            var height;
            $j.magnificPopup.open({
              alignTop: false,
              overflowY: 'auto',
              items: {
                src: response.responseText,
                type: 'inline'
              }
            });
            return height = $j(window).height() * 0.9;
          };
        })(this)
      });
      return false;
    });
    $j('.toggle-handler').live('click', function() {
      $j(this).parent().find('.' + $j(this).data('togglable')).slideToggle();
      if ($j(this).text() === 'Hide managers') {
        $j(this).text('Show managers');
      } else {
        $j(this).text('Hide managers');
      }
      return false;
    });
    hasPeopleSearch = (function(_this) {
      return function(url) {
        return url.indexOf('/people_search') >= 0;
      };
    })(this);
    hasPeopleSearchSearch = (function(_this) {
      return function(url) {
        return url.indexOf('/people_search/search') >= 0;
      };
    })(this);
    hasPeopleSearchTabbedIndex = (function(_this) {
      return function(url) {
        return url.indexOf('/people_search/tabbed_index') >= 0;
      };
    })(this);
    hasPeopleSearchTabbedSearch = (function(_this) {
      return function(url) {
        return url.indexOf('/people_search/tabbed_search') >= 0;
      };
    })(this);
    peopleSendEmails = PeopleSendEmails();
    if (peopleSendEmails) {
      if (hasPeopleSearch(window.location.pathname)) {
        peopleSendEmails.init();
        return $j(document).ajaxComplete(function(event, request, settings) {
          if (hasPeopleSearchSearch(settings.url)) {
            return peopleSendEmails.init();
          }
        });
      } else {
        return $j(document).ajaxComplete(function(event, request, settings) {
          if (hasPeopleSearchTabbedIndex(settings.url) || hasPeopleSearchTabbedSearch(settings.url)) {
            return peopleSendEmails.init();
          }
        });
      }
    }
  });

  PeopleSendEmails = (function(_this) {
    return function() {
      var _buildAllpeopleTitle, _buildChildrenTable, _buildLoaderText, _buildPersonRow, _buildPersonRows, _clearSelectedUsersListTable, _emailAllPeople, _emailCopyAdministration, _emailOnlyAdministration, _groupByAdministrator, _handleCopyAdministartors, _handleOnlyAdministartors, _isAcrossPages, _loadAdministrators, _loadAdministratorsParams, _loaderAdministrations, _onSuccessfullLoad, _peopleSearchForm, _presentAdministrators, _refreshTipped, _resetAdministratorsList, _resetPeopleList, _selectedUsersListTable, _sendEmailAdministartionWarning, _sendEmailsForm, _switchEmailAllPeople, _switchWarning, _totalPeopleCount, _updateAllpeopleTitle, _updateNumberAdditionalContactsTitle, _updatePeopleTable, administrators, copyAdministration, init, onlyAdministration, people, select, selectAll, selectAllPages, unselect, unselectAll, unselectAllPages;
      people = [];
      administrators = [];
      copyAdministration = false;
      onlyAdministration = false;
      init = function() {
        _loadAdministrators();
        _emailOnlyAdministration().off('click').on('click', _handleOnlyAdministartors);
        return _emailCopyAdministration().off('click').on('click', _handleCopyAdministartors);
      };
      select = function(inPerson) {
        people.push(inPerson);
        return _updatePeopleTable();
      };
      unselect = function(inPerson) {
        var index, record;
        for (index in people) {
          record = people[index];
          if (record.id === inPerson.id) {
            people.splice(index, 1);
          }
        }
        return _updatePeopleTable();
      };
      selectAll = function(inPeople) {
        Array.prototype.push.apply(people, inPeople);
        return _updatePeopleTable();
      };
      unselectAll = function() {
        _resetPeopleList();
        _resetAdministratorsList();
        return _updatePeopleTable();
      };
      selectAllPages = function() {
        return _updatePeopleTable();
      };
      unselectAllPages = function() {
        return unselectAll();
      };
      _handleOnlyAdministartors = function(event) {
        copyAdministration = false;
        onlyAdministration = event.target.checked;
        _updatePeopleTable();
        return _emailCopyAdministration().prop('checked', false);
      };
      _handleCopyAdministartors = function(event) {
        copyAdministration = event.target.checked;
        onlyAdministration = false;
        _updatePeopleTable();
        return _emailOnlyAdministration().prop('checked', false);
      };
      _peopleSearchForm = function() {
        return $j('.people_search #search_controls > form');
      };
      _loadAdministratorsParams = function() {
        var data, splitArr;
        data = _peopleSearchForm().serialize();
        splitArr = _peopleSearchForm().attr('action').split('?').slice(1).join('&');
        if (splitArr.length) {
          data += "&" + splitArr;
        }
        return data;
      };
      _onSuccessfullLoad = function(data) {
        _loaderAdministrations().remove();
        _buildAllpeopleTitle(data.count);
        _switchEmailAllPeople(_isAcrossPages());
        return _updatePeopleTable();
      };
      _loadAdministrators = function() {
        _buildLoaderText();
        return $j.ajax({
          url: '/people_search/load_administrators',
          data: _loadAdministratorsParams(),
          success: _onSuccessfullLoad,
          dataType: 'json'
        });
      };
      _sendEmailsForm = function() {
        return $j('#email_people_form');
      };
      _emailOnlyAdministration = function() {
        return _sendEmailsForm().find('.email_only_administration');
      };
      _emailCopyAdministration = function() {
        return _sendEmailsForm().find('.email_copy_administration');
      };
      _updatePeopleTable = function() {
        _switchWarning(copyAdministration || onlyAdministration);
        _switchEmailAllPeople(_isAcrossPages());
        _clearSelectedUsersListTable();
        if (_isAcrossPages()) {
          _updateAllpeopleTitle({
            includeAdministrators: copyAdministration,
            onlyAdministrators: onlyAdministration
          });
        } else {
          administrators = _groupByAdministrator(people);
          _buildPersonRows({
            includeAdministrators: copyAdministration,
            onlyAdministrators: onlyAdministration
          });
        }
        _updateNumberAdditionalContactsTitle();
        return _refreshTipped();
      };
      _buildPersonRows = function(options) {
        var fragment, table;
        if (options == null) {
          options = {};
        }
        table = _selectedUsersListTable()[0];
        table.innerHTML = '';
        fragment = document.createDocumentFragment();
        if (!options.includeAdministrators && !options.onlyAdministrators) {
          people.forEach(function(record) {
            return fragment.appendChild(_buildPersonRow(record));
          });
        }
        if (options.includeAdministrators) {
          administrators.forEach(function(record) {
            return fragment.appendChild(_buildPersonRow(record, true));
          });
        }
        if (options.onlyAdministrators) {
          _presentAdministrators().forEach(function(record) {
            return fragment.appendChild(_buildPersonRow(record));
          });
        }
        return table.appendChild(fragment);
      };
      _buildPersonRow = function(person, buildChildrenList) {
        var childrenTable, labels, trElement;
        if (buildChildrenList == null) {
          buildChildrenList = false;
        }
        trElement = document.createElement('tr');
        trElement.className = 'person_entry';
        trElement.id = "person_" + person.id;
        childrenTable = person.isAdmin && buildChildrenList ? _buildChildrenTable(person.people).outerHTML : '';
        if (person.id >= 0) {
          labels = person.isAdmin ? '<div class="ui label">Administrator</div>' : '';
          trElement.innerHTML += "<td><input type='checkbox' checked='checked' value='" + person.id + "' name='persons[]'><span>" + person.name + " (" + person.email + ") " + labels + "</span>" + childrenTable + "</td>";
        } else {
          trElement.innerHTML += "<td><span>" + person.name + "</span>" + childrenTable + "</td>";
        }
        return trElement;
      };
      _buildChildrenTable = function(children) {
        var fragment, tableElement;
        tableElement = document.createElement('table');
        tableElement.className = 'persons';
        fragment = document.createDocumentFragment();
        children.forEach(function(record) {
          return fragment.appendChild(_buildPersonRow(record));
        });
        tableElement.appendChild(fragment);
        return tableElement;
      };
      _selectedUsersListTable = function() {
        return _sendEmailsForm().find('table#selected_users_list');
      };
      _clearSelectedUsersListTable = function() {
        return _selectedUsersListTable().html('');
      };
      _presentAdministrators = function() {
        return administrators.filter(function(person) {
          return person.id >= 0;
        });
      };
      _groupByAdministrator = function(inPeople) {
        var administrator, i, index, j, len, len1, person, ref, tempAdministartors;
        tempAdministartors = [];
        for (i = 0, len = inPeople.length; i < len; i++) {
          person = inPeople[i];
          if (!person.administrators.length) {
            person.administrators.push({
              id: -1,
              name: 'No administrators',
              email: null,
              isAdmin: true,
              people: [person]
            });
          }
          ref = person.administrators;
          for (j = 0, len1 = ref.length; j < len1; j++) {
            administrator = ref[j];
            index = tempAdministartors.findIndex(function(record) {
              return record.id === administrator.id;
            });
            if (index >= 0) {
              tempAdministartors[index].people.push(person);
            } else {
              tempAdministartors.push(Object.assign(administrator, {
                isAdmin: true,
                people: [person]
              }));
            }
          }
        }
        return tempAdministartors;
      };
      _resetPeopleList = function() {
        return people.length = 0;
      };
      _resetAdministratorsList = function() {
        return administrators.length = 0;
      };
      _isAcrossPages = function() {
        return $j('#people_across_pages').val() === '1';
      };
      _switchEmailAllPeople = function(hideOrShow) {
        if (hideOrShow) {
          _sendEmailsForm().find('.userlist').addClass('all');
          return _emailAllPeople().show();
        } else {
          _sendEmailsForm().find('.userlist').removeClass('all');
          _emailAllPeople().hide();
          return _loaderAdministrations().hide();
        }
      };
      _buildLoaderText = function() {
        return _selectedUsersListTable().before("<div id='loader_administrations'>" + (I18n.t('js.people_search.loader_text')) + "</div>");
      };
      _loaderAdministrations = function() {
        return _sendEmailsForm().find('#loader_administrations');
      };
      _emailAllPeople = function() {
        return _sendEmailsForm().find('#email_all_people');
      };
      _sendEmailAdministartionWarning = function() {
        return _sendEmailsForm().find('#send_email_administartion_warning');
      };
      _switchWarning = function(hideOrShow) {
        if (hideOrShow) {
          return _sendEmailAdministartionWarning().show();
        } else {
          return _sendEmailAdministartionWarning().hide();
        }
      };
      _buildAllpeopleTitle = function(count) {
        return _selectedUsersListTable().before("<div id='email_all_people' data-administrators-count='" + count + "'></div>");
      };
      _totalPeopleCount = function() {
        return parseInt($j('.people_search #header_message').text().match(/of (\d+) /)[1]);
      };
      _refreshTipped = function() {
        return Tipped.refresh('#email_people');
      };
      _updateAllpeopleTitle = function(options) {
        var administratorsCount, count;
        if (options == null) {
          options = {};
        }
        if (_emailAllPeople().length > 0) {
          count = _totalPeopleCount();
          administratorsCount = _emailAllPeople().data('administratorsCount');
          if (options.includeAdministrators) {
            count += administratorsCount;
          }
          if (options.onlyAdministrators) {
            count = administratorsCount;
          }
          return _emailAllPeople().text(I18n.t('js.people_search.select_all_title', {
            count: count
          }));
        } else {
          return _loaderAdministrations().show();
        }
      };
      _updateNumberAdditionalContactsTitle = function() {
        var checkbox, count;
        count = _isAcrossPages() && _emailAllPeople().length > 0 ? _emailAllPeople().data('administratorsCount') : _presentAdministrators().length;
        checkbox = _sendEmailsForm().find('.email_copy_administration');
        return checkbox.parent().find('.number_of_contacts').text(I18n.t('js.people_search.additional_contacts', {
          count: count
        }));
      };
      return {
        init: init,
        select: select,
        unselect: unselect,
        selectAll: selectAll,
        unselectAll: unselectAll,
        selectAllPages: selectAllPages,
        unselectAllPages: unselectAllPages,
        copyAdministration: copyAdministration,
        onlyAdministration: onlyAdministration
      };
    };
  })(this);

}).call(this);
jQuery(function() {
  function adjustSidebarHeight(event, heightInfo) {
    var height = $j('#top_nav').height();
    if(heightInfo) {
      height = heightInfo.newHeight;
    }
    var sideBar = document.getElementById('left_menu_sidebar');
    sideBar.style.setProperty('top', height + 'px');
    sideBar.style.setProperty('height', 'calc(100% - ' + height +'px)', 'important');
  }
  function adjustStickyHeight(event, heightInfo) {
    $j('.ui.sticky').each(function() {
      var element = $j(this);
      var newOffset = element.sticky('setting', 'offset') + heightInfo.heightDiff;
      element.sticky('setting', 'offset', newOffset).sticky('refresh');
    });
  }
  function createPopups() {
    Tipped.setDefaultSkin('light');

    var hideOnSettings = [
      {element: 'tooltip', event: 'mouseleave'},
      {element: 'self', event: 'mouseleave'}
    ];

    Tipped.create('#favorites_popup_item', 'favorites_popup_content', {
      inline: true,
      hook: {target: 'rightmiddle', tooltip: 'lefttop'},
      hideOn: hideOnSettings
    });

    var popup_items = document.getElementsByClassName('left_menu_popup');
    for (var i = 0; i < popup_items.length; i++) {
      var item = $j(popup_items[i]);
      var offsetX = 0;
      if ($j(item.data('offset-x')).length > 0) {
        offsetX = item.data('offset-x');
      }
      Tipped.create(item.uniqueId(), item.data('flyoutUrl'), {
        ajax: true,
        hook: {target: 'rightmiddle', tooltip: 'lefttop'},
        hideOn: hideOnSettings,
        maxWidth: 800,
        offset: {x: offsetX}
      });
    }
  }

  setTimeout(function() {
    $j('.messages_container .ui.message').fadeOut();
  }, 12000);

  var keepNavOpen = false;   // set to true for dev testing only!

  if($j('#left_menu_btn').length) {
   $j('#help_btn.leave_feedback_link').popup({
      popup: $j('#feedback_form'),
      on: 'click',
      onShow: function() {
        return $j('#feedback_form').html("<div class='ui text loader active'></div>");
      },
      onHide: function() {
        return $j('#feedback_form').html('');
      }
    });

    if (!keepNavOpen) {
      // close sidebar if the user clicks in an iframe
      $j(window).on('blur', function () {
        if ($j('#left_menu_sidebar').sidebar('is open')) {
          $j('#left_menu_sidebar').sidebar('hide');
        }
      });
    }

    $j('.pusher').css('padding-top', $j('#top_nav').height());

    if ($j('.system_annoucement').length) {
      var topNav = $j('#top_nav');
      var oldTopNavHeight = topNav.height();

      $j('#top_nav').on('top_nav:heightChanged', adjustSidebarHeight);
      $j('#top_nav').on('top_nav:heightChanged', adjustStickyHeight);

      function checkTopNavHeight() {
        var topNavHeight = topNav.height();
        var heightDiff = topNavHeight - oldTopNavHeight;
        if(heightDiff != 0) {
          oldTopNavHeight = topNavHeight;
          $j('.pusher').css('padding-top', topNavHeight);
          $j('#top_nav').trigger('top_nav:heightChanged', {
            newHeight: topNavHeight,
            heightDiff: heightDiff
          });
        }
      }

      $j('.annoucement_close').on('click', function(e) {
        var self = this;
        $j.post('/upcoming_layout/annoucement_closed', { reset_key: $j(self).data('reset-key') });
        $j(self).parent('div.system-banner').addClass('hidden');
        checkTopNavHeight();
        $j(window).off('.topNavResize');
      });
      $j(window).on('resize.topNavResize', checkTopNavHeight);
    }

    $j('#left_menu_sidebar').sidebar( {
      dimPage: false,
      closeable: !keepNavOpen,
      onVisible: function() {
        adjustSidebarHeight();
        $j('#left_menu_btn').addClass('darken background');
      },
      onShow: function() {
        $j('.pushable').addClass('show_horizontal_scrollbar');
        $j('.ui.sticky').each(function() {
          $j(this).sticky('refresh');
        });
        focusLeftMenuItem()
      },
      onHide: function() {
        $j('#left_menu_btn').removeClass('darken background');
        $j('.pushable').removeClass('show_horizontal_scrollbar');
      },
      onHidden: function() {
        $j('.ui.sticky').each(function() {
          $j(this).sticky('refresh');
        });
      }
    }).sidebar('attach events', '#left_menu_btn');

    // start loading the left nav as early as we can so it can (usually) be finished rendering by the time the user actually clicks the button to show it
    $j('#left_menu_btn').on('mouseenter focus', function () {
      if ($j('.left_main_menu_wrapper').length === 0) {
        $j.get({
          url: '/upcoming_layout/left_navigation',
          dataType: 'html'
        }).done(function(response) {
          $j('#left_menu_sidebar').html(response);
          createPopups();
          focusLeftMenuItem();
          setShiftTabClickHandler();
        });
      }
    });

    $j('#left_menu_btn').click(function() {
      if ($j('#hamburger').popup('is visible')) {
        $j('#hamburger').popup('hide');
        $j.post('/upcoming_layout/left_nav_clicked');
      }
    });

    $j('#hamburger').popup({
          position: 'bottom left',
          transition: 'fade',
          hideOnScroll: false,
          inline: true,
          on: 'manual',
          offset: -7,
          content: 'Click here to access the left navigation'
    });
    if ($j('#hamburger').hasClass('show-training-popup')) {
        $j('#hamburger').popup('show');
    }
  }

  // Shared method to show or hide the top nav and footer.
  // show: true to show elements, false to hide them (move them off-screen)
  $j.setHeaderAndFooterVisible = function (show) {
    var selector_array = ['#top_nav', '.profiler-results', '.ilab_footer'];
    var className = 'movedFromScreen';
    for (var i = 0; i < selector_array.length; i++) {
      $j(selector_array[i]).each(function () {
        if (show && (!scheduler || !scheduler.expanded))    // never restore the top nav & footer if the calendar is full-screen
          $j(this).removeClass(className);
        else
          $j(this).addClass(className);
      });
    }
  }

  // Accessibility navigation code
  var _sidebarIconSelector = '#left_menu_btn'
  var _firstItemSelector = '.left_main_menu .item a:first'

  $j(_sidebarIconSelector).keypress(function(e){
    if (e.key !== 'Enter') {
      return;
    }

    $j(this).click() // trigger click on Enter keypress
  });

  function focusLeftMenuItem() {
    $j(_firstItemSelector).focus()
  }

  function setShiftTabClickHandler() {
    var element = $j(_firstItemSelector)
    element.on('keydown blur', _onKeyDownHandler);
  }

  function _onKeyDownHandler(event) {
    if (!_isShiftTabKey(event)) {
      return;
    }

    $j(_sidebarIconSelector).focus();
    return false
  }

  function _isShiftTabKey(event) {
    return event.shiftKey && event.key === 'Tab';
  }
});
// AjaxQ jQuery Plugin
// Copyright (c) 2012 Foliotek Inc.
// MIT License
// https://github.com/Foliotek/ajaxq

(function($) {

    var queues = {};
    var activeReqs = {};

    // Register an $.ajaxq function, which follows the $.ajax interface, but allows a queue name which will force only one request per queue to fire.
    $.ajaxq = function(qname, opts) {

        if (typeof opts === "undefined") {
            throw ("AjaxQ: queue name is not provided");
        }

        // Will return a Deferred promise object extended with success/error/callback, so that this function matches the interface of $.ajax
        var deferred = $.Deferred(),
            promise = deferred.promise();

        promise.success = promise.done;
        promise.error = promise.fail;
        promise.complete = promise.always;

        // Create a deep copy of the arguments, and enqueue this request.
        var clonedOptions = $.extend(true, {}, opts);
        enqueue(function() {
            // Send off the ajax request now that the item has been removed from the queue
            var jqXHR = $.ajax.apply(window, [clonedOptions]);

            // Notify the returned deferred object with the correct context when the jqXHR is done or fails
            // Note that 'always' will automatically be fired once one of these are called: http://api.jquery.com/category/deferred-object/.
            jqXHR.done(function() {
                deferred.resolve.apply(this, arguments);
            });
            jqXHR.fail(function() {
                deferred.reject.apply(this, arguments);
            });

            jqXHR.always(dequeue); // make sure to dequeue the next request AFTER the done and fail callbacks are fired
            return jqXHR;
        });

        return promise;


        // If there is no queue, create an empty one and instantly process this item.
        // Otherwise, just add this item onto it for later processing.
        function enqueue(cb) {
            if (!queues[qname]) {
                queues[qname] = [];
                var xhr = cb();
                activeReqs[qname] = xhr;
            }
            else {
                queues[qname].push(cb);
            }
        }

        // Remove the next callback from the queue and fire it off.
        // If the queue was empty (this was the last item), delete it from memory so the next one can be instantly processed.
        function dequeue() {
            if (!queues[qname]) {
                return;
            }
            var nextCallback = queues[qname].shift();
            if (nextCallback) {
                var xhr = nextCallback();
                activeReqs[qname] = xhr;
            }
            else {
                delete queues[qname];
                delete activeReqs[qname];
            }
        }
    };

    // Register a $.postq and $.getq method to provide shortcuts for $.get and $.post
    // Copied from jQuery source to make sure the functions share the same defaults as $.get and $.post.
    $.each( [ "getq", "postq" ], function( i, method ) {
        $[ method ] = function( qname, url, data, callback, type ) {

            if ( $.isFunction( data ) ) {
                type = type || callback;
                callback = data;
                data = undefined;
            }

            return $.ajaxq(qname, {
                type: method === "postq" ? "post" : "get",
                url: url,
                data: data,
                success: callback,
                dataType: type
            });
        };
    });

    var isQueueRunning = function(qname) {
        return queues.hasOwnProperty(qname);
    };

    var isAnyQueueRunning = function() {
        for (var i in queues) {
            if (isQueueRunning(i)) return true;
        }
        return false;
    };

    $.ajaxq.isRunning = function(qname) {
        if (qname) return isQueueRunning(qname);
        else return isAnyQueueRunning();
    };

    $.ajaxq.getActiveRequest = function(qname) {
        if (!qname) throw ("AjaxQ: queue name is required");

        return activeReqs[qname];
    };

    $.ajaxq.abort = function(qname) {
        if (!qname) throw ("AjaxQ: queue name is required");

        var current = $.ajaxq.getActiveRequest(qname);
        delete queues[qname];
        delete activeReqs[qname];
        if (current) current.abort();
    };

    $.ajaxq.clear = function(qname) {
        if (!qname) {
            for (var i in queues) {
                if (queues.hasOwnProperty(i)) {
                    queues[i] = [];
                }
            }
        }
        else {
            if (queues[qname]) {
                queues[qname] = [];
            }
        }
    };

})(jQuery);
(function() {
  var move_list_element;

  $j(function() {
    var is_valid_selector, sticky_tabs;
    $j(document).on('focusin', function(e) {
      if ($j(e.target).closest('.mce-window').length) {
        e.stopImmediatePropagation();
      }
      return true;
    });
    window.non_char_keys = [13, 38, 40, 37, 39, 27, 17, 18, 9, 16, 20, 91, 93, 36, 35, 45, 33, 34, 144, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 145, 19, 0];
    window.magnific = function(content) {
      $j.magnificPopup.open({
        closeBtnInside: false,
        showCloseBtn: true,
        closeOnBgClick: true,
        closeOnContentClick: false,
        items: {
          src: content
        }
      });
      return true;
    };
    $j.magnificPopup.instance._onFocusIn = function(e) {
      if ($j(e.target).hasClass('select2-input')) {
        return true;
      }
      return $j.magnificPopup.proto._onFocusIn.call(this, e);
    };
    $j('.message:not(.no_auto_init) .close').live('click', function() {
      return $j(this).closest('.message').fadeOut();
    });
    $j('.with_popup').popup();
    $j('.with_popup').live('click', function() {
      return $j(this).popup('hide');
    });
    $j(document).ajaxSuccess(function() {
      return $j('.with_popup').popup();
    });
    $j('input[data-table_filter]').livequery(function() {
      $j(this).on('keyup', function(e) {
        var parent, table_loader;
        console.log(e.which);
        if (window.non_char_keys.indexOf(e.which) < 0) {
          parent = $j(this).parents('.ui.input');
          table_loader = parent.parent().find('.table_loader');
          $j.ajaxq.abort("table_filtering");
          return $j.ajaxq('table_filtering', {
            url: $j(this).data('path'),
            dataType: 'script',
            data: {
              q: $j(this).val()
            },
            beforeSend: function() {
              parent.addClass('loading');
              return table_loader.addClass('active');
            },
            complete: function() {
              parent.removeClass('loading');
              return table_loader.removeClass('active');
            },
            error: function() {
              parent.removeClass('loading');
              return table_loader.removeClass('active');
            }
          });
        }
      });
      return true;
    });
    $j('a[data-remote="true"]').livequery(function() {
      $j(this).on('ajax:before', function() {
        return $j(this).addClass('loading');
      });
      $j(this).on('ajax:complete', function() {
        return $j(this).removeClass('loading');
      });
      return true;
    });
    $j('form[data-remote="true"]').livequery(function() {
      $j(this).submit(function() {
        if ($j(this).find('.field.error').length === 0) {
          return $j(this).addClass('loading');
        }
      });
      return true;
    });
    if ($j('html.legacy-page').length === 0) {
      $j('.tabs_menu .item').live('click', function() {
        $j('.tab_load_dimmer').addClass('active');
        $j(this).parent().children().removeClass('active');
        return $j(this).addClass('active');
      });
      $j(document).pjax('a[data-pjax]', '.main_content');
      $j(document).on('pjax:timeout', function() {
        return false;
      });
      $j(document).on('pjax:send', function() {
        return $j('.tab_load_dimmer').addClass('active');
      });
      sticky_tabs = function() {
        return $j('#horizontal_tabs_wrapper').sticky({
          offset: $j('#top_nav').height()
        });
      };
      sticky_tabs();
      $j(document).on('pjax:complete', function() {
        $j('.tab_load_dimmer').removeClass('active');
        $j('.main_content_wrapper').height('auto');
        return sticky_tabs();
      });
      $j('.main_content').on('pjax:popstate', function(event) {
        var path, tab_to_activate;
        path = window.location.pathname;
        tab_to_activate = $j('.tabs_menu a[href="' + path + '"]');
        $j('.tabs_menu a').removeClass('active');
        return tab_to_activate.addClass('active');
      });
    }
    $j('.institution_semantic_add_department_link').live('click', function() {
      var data, name;
      name = $j('#new_department_name').val().replace(/^\s+|\s+$/g, "");
      $j(this).addClass('loading');
      if (confirm("Are you sure you would like to create a new department?")) {
        data = {
          name: name
        };
        $j.ajax($j(this).attr('href'), {
          type: 'GET',
          data: data,
          success: $j(this).removeClass('loading')
        });
      } else {
        $j(this).removeClass('loading');
      }
      return false;
    });
    $j('input.live_search_cores').livequery(function() {
      var url;
      url = $j('.live_search_cores').data('url');
      return $j(this).select2({
        placeholder: "Start typing a name...",
        minimumInputLength: 2,
        width: 'element',
        ajax: {
          url: url,
          type: 'GET',
          dataType: "json",
          data: function(term) {
            return {
              term: term
            };
          },
          results: function(data) {
            return {
              results: data
            };
          }
        },
        escapeMarkup: function(m) {
          return m;
        },
        dropdownAutoWidth: true
      });
    });
    $j('input.live_search_members').livequery(function() {
      var url;
      url = $j('.live_search_members').data('url');
      return $j(this).select2({
        placeholder: "Start typing a name...",
        minimumInputLength: 2,
        width: 'element',
        ajax: {
          url: url,
          type: 'GET',
          dataType: "json",
          data: function(term) {
            return {
              members_searchtext: term
            };
          },
          results: function(data) {
            return {
              results: data
            };
          }
        },
        escapeMarkup: function(m) {
          return m;
        },
        dropdownAutoWidth: true
      });
    });
    $j('input.live_search_institution').livequery(function() {
      var url;
      url = $j('.live_search_institution').data('url');
      return $j(this).select2({
        placeholder: "Start typing a name...",
        minimumInputLength: 2,
        width: 'element',
        ajax: {
          url: url,
          type: 'GET',
          dataType: "json",
          data: function(term) {
            return {
              term: term
            };
          },
          results: function(data) {
            return {
              results: data
            };
          }
        },
        escapeMarkup: function(m) {
          return m;
        },
        dropdownAutoWidth: true
      });
    });
    $j('input#live_search_groups').livequery(function() {
      return $j(this).select2({
        placeholder: "Start typing a group name...",
        minimumInputLength: 2,
        ajax: {
          url: "/live_search/labs",
          dataType: "json",
          data: function(term) {
            return {
              q: term
            };
          },
          results: function(data) {
            return {
              results: data
            };
          }
        },
        escapeMarkup: function(m) {
          return m;
        },
        dropdownAutoWidth: true
      });
    });
    $j('input#live_search_institutions').livequery(function() {
      return $j(this).select2({
        placeholder: "Start typing an institution name...",
        minimumInputLength: 2,
        ajax: {
          url: "/live_search/institutions_live_search",
          dataType: "json",
          data: function(term) {
            return {
              term: term
            };
          },
          results: function(data) {
            return {
              results: data
            };
          }
        },
        escapeMarkup: function(m) {
          return m;
        },
        dropdownAutoWidth: true
      });
    });
    $j('input.live_search_members').live("change", function(e) {
      $j('.invite_form').show();
      return $j('#recipient_profile_id').val(e.val);
    });
    $j('input.live_search_pi').live("change", function(e) {
      return $j('#lab_admin_id').val(e.val);
    });
    $j('.add_attachment_link').live('click', function() {
      var attachment_field;
      attachment_field = '<div class="field"> <input id="reaction_attachments_" name="reaction[attachments][]" type="file"> </div>';
      return $j('#reaction_form .attachments_list').append(attachment_field);
    });
    $j('#reaction_form').live('submit', function(ev) {
      if (!$j(this).form().form('validate_form')) {
        ev.preventDefault();
        return false;
      }
      $j('#reaction_form_submit').attr('disabled', 'disabled');
      $j('#feedback_spinner').show();
      return $j('#feedback_blank').hide();
    });
    $j('input.live_search_labs').livequery(function() {
      var url;
      url = $j('.live_search_labs').data('url');
      return $j(this).select2({
        placeholder: "Start typing...",
        minimumInputLength: 2,
        id: 'value',
        width: 'element',
        ajax: {
          url: url,
          type: 'GET',
          dataType: "json",
          data: function(term) {
            return {
              term: term
            };
          },
          results: function(data) {
            return {
              results: data
            };
          }
        },
        escapeMarkup: function(m) {
          return m;
        },
        formatResult: function(item) {
          return item['label'];
        },
        formatSelection: function(item) {
          return item['label'];
        },
        dropdownAutoWidth: true
      });
    });
    $j('input.live_search_labs').live("change", function(e) {
      return $j('#lab_profile_id').val(e.val);
    });
    $j('#tax_reasons_for_exemptions').livequery(function() {
      var help_text;
      help_text = 'Type a reason and press Enter';
      return $j(this).select2({
        tags: [],
        placeholder: help_text,
        formatNoMatches: function() {
          return help_text;
        },
        width: '100%'
      }).on("change", function(e) {
        return Tipped.refresh('*');
      });
    });
    $j('#tax_applicable_to_payment_options').livequery(function() {
      var help_text;
      help_text = 'Select options';
      return $j(this).select2({
        width: '100%',
        placeholder: help_text,
        formatNoMatches: function() {
          return '';
        }
      });
    });
    $j('#tax_applicable_to_price_types').livequery(function() {
      var help_text;
      help_text = 'Select price types';
      return $j(this).select2({
        width: '100%',
        placeholder: help_text,
        formatNoMatches: function() {
          return '';
        }
      });
    });
    $j('#tax_start_date, #tax_end_date').livequery(function() {
      return $j(this).datetimepicker({
        timepicker: false,
        scrollInput: false
      });
    });
    $j('.global_search .menu .item').live('click', function() {
      return $j('#which_universe').val($j(this).attr('value'));
    });
    is_valid_selector = function(selector) {
      var element;
      try {
        element = $j(selector);
        return element.length > 0;
      } catch (error) {
        return false;
      }
    };
    $j('a[href*="#"]').live('click', function(event) {
      var scrollPos;
      if (is_valid_selector(this.hash)) {
        event.preventDefault();
        scrollPos = $j(this.hash).offset().top - $j('#top_nav').height() - 75;
        $j('html,body').animate({
          scrollTop: scrollPos
        }, 250);
        return false;
      } else {
        return true;
      }
    });
    $j('.delete_core').live('click', function() {
      var row;
      row = $j(this).parent().parent();
      row.remove();
      return false;
    });
    $j('#non_ilab_cores_form_submit').live('click', function() {
      return showSpinner($j(this));
    });
    $j('.add_core').live('click', function() {
      var html;
      html = $j('#empty_row').children().first().html();
      $j('#non_ilab_cores_table tr:last').after(html);
      return false;
    });
    $j("#save_partners").live('click', function() {
      var value_array;
      value_array = [];
      $j("#partner_institutions_list option").each(function() {
        return value_array.push($j(this).attr('value'));
      });
      $j.post('/institutions/save_partner_institutions', {
        id: $j('#institution_id').attr('value'),
        partners: value_array
      }, function(data) {
        $j('.institutions_list_container').parent().prepend("<div id='save_partner_alert' class='ui success message' id=''> <i class='close icon'></i> " + "<div class='header'> Your changes successfully Saved. </div> " + "</div>");
        return setTimeout(function() {
          return $j('#save_partner_alert').remove();
        }, 3000);
      });
      return false;
    });
    $j(" .ui.simple_submit").live("click", function() {
      var data, form;
      if ($j(this).attr('disabled')) {
        return false;
      } else {
        form = $j(this).parents('form');
        form.find('.ui.error.message').hide();
        if ($j(this)[0].hasAttribute('data-validate')) {
          if (!form.form('is valid')) {
            form.form('validate form');
            form.find('.ui.error.message').show();
            return false;
          }
        }
        data = form.serialize().replace(/\&_method=\w*/, '');
        $j.ajax(form.attr('action'), {
          type: 'POST',
          data: data,
          beforeSend: (function(_this) {
            return function(xhr) {
              xhr.setRequestHeader("Accept", "text/javascript");
              return $j(_this).addClass('loading');
            };
          })(this),
          complete: (function(_this) {
            return function(response) {
              return $j(_this).removeClass('loading');
            };
          })(this)
        });
        return false;
      }
    });
    $j("#move_left").live('click', function() {
      move_list_element($j("#other_institutions_list > option:selected"), $j("#partner_institutions_list"));
      return false;
    });
    $j("#move_right").live('click', function() {
      return move_list_element($j("#partner_institutions_list > option:selected"), $j("#other_institutions_list"));
    });
    return false;
  });

  move_list_element = function(source, target) {
    return $j(source).filter('option:selected').each(function() {
      $j(this).removeAttr("selected");
      return $j(this).remove().appendTo($j(target));
    });
  };

}).call(this);
/*!
 * jQuery-runner - v2.3.3 - 2014-08-06
 * https://github.com/jylauril/jquery-runner/
 * Copyright (c) 2014 Jyrki Laurila <https://github.com/jylauril>
 */

(function(){var a,b,c,d,e,f,g,h,i;if(c={version:"2.3.3",name:"jQuery-runner"},g=this.jQuery||this.Zepto||this.$,!g||!g.fn)throw new Error("["+c.name+"] jQuery or jQuery-like library is required for this plugin to work");e={},d=function(a){return(10>a?"0":"")+a},i=1,f=function(){return"runner"+i++},h=function(a,b){return a["r"+b]||a["webkitR"+b]||a["mozR"+b]||a["msR"+b]||function(a){return setTimeout(a,30)}}(this,"equestAnimationFrame"),b=function(a,b){var c,e,f,g,h,i,j,k,l,m,n;for(b=b||{},k=[36e5,6e4,1e3,10],i=["",":",":","."],h="",g="",f=b.milliseconds,e=k.length,l=0,0>a&&(a=Math.abs(a),h="-"),c=m=0,n=k.length;n>m;c=++m)j=k[c],l=0,a>=j&&(l=Math.floor(a/j),a-=l*j),(l||c>1||g)&&(c!==e-1||f)&&(g+=(g?i[c]:"")+d(l));return h+g},a=function(){function a(b,c,d){var h;return this instanceof a?(this.items=b,h=this.id=f(),this.settings=g.extend({},this.settings,c),e[h]=this,b.each(function(a,b){g(b).data("runner",h)}),this.value(this.settings.startAt),void((d||this.settings.autostart)&&this.start())):new a(b,c,d)}return a.prototype.running=!1,a.prototype.updating=!1,a.prototype.finished=!1,a.prototype.interval=null,a.prototype.total=0,a.prototype.lastTime=0,a.prototype.startTime=0,a.prototype.lastLap=0,a.prototype.lapTime=0,a.prototype.settings={autostart:!1,countdown:!1,stopAt:null,startAt:0,milliseconds:!0,format:null},a.prototype.value=function(a){this.items.each(function(b){return function(c,d){var e;c=g(d),e=c.is("input")?"val":"text",c[e](b.format(a))}}(this))},a.prototype.format=function(a){var c;return c=this.settings.format,(c=g.isFunction(c)?c:b)(a,this.settings)},a.prototype.update=function(){var a,b,c,d,e;this.updating||(this.updating=!0,c=this.settings,e=g.now(),d=c.stopAt,a=c.countdown,b=e-this.lastTime,this.lastTime=e,a?this.total-=b:this.total+=b,null!==d&&(a&&this.total<=d||!a&&this.total>=d)&&(this.total=d,this.finished=!0,this.stop(),this.fire("runnerFinish")),this.value(this.total),this.updating=!1)},a.prototype.fire=function(a){this.items.trigger(a,this.info())},a.prototype.start=function(){var a;this.running||(this.running=!0,(!this.startTime||this.finished)&&this.reset(),this.lastTime=g.now(),a=function(b){return function(){b.running&&(b.update(),h(a))}}(this),h(a),this.fire("runnerStart"))},a.prototype.stop=function(){this.running&&(this.running=!1,this.update(),this.fire("runnerStop"))},a.prototype.toggle=function(){this.running?this.stop():this.start()},a.prototype.lap=function(){var a,b;return b=this.lastTime,a=b-this.lapTime,this.settings.countdown&&(a=-a),(this.running||a)&&(this.lastLap=a,this.lapTime=b),b=this.format(this.lastLap),this.fire("runnerLap"),b},a.prototype.reset=function(a){var b;a&&this.stop(),b=g.now(),"number"!=typeof this.settings.startAt||this.settings.countdown||(b-=this.settings.startAt),this.startTime=this.lapTime=this.lastTime=b,this.total=this.settings.startAt,this.value(this.total),this.finished=!1,this.fire("runnerReset")},a.prototype.info=function(){var a;return a=this.lastLap||0,{running:this.running,finished:this.finished,time:this.total,formattedTime:this.format(this.total),startTime:this.startTime,lapTime:a,formattedLapTime:this.format(a),settings:this.settings}},a}(),g.fn.runner=function(b,d,f){var h,i;switch(b||(b="init"),"object"==typeof b&&(f=d,d=b,b="init"),h=this.data("runner"),i=h?e[h]:!1,b){case"init":new a(this,d,f);break;case"info":if(i)return i.info();break;case"reset":i&&i.reset(d);break;case"lap":if(i)return i.lap();break;case"start":case"stop":case"toggle":if(i)return i[b]();break;case"version":return c.version;default:g.error("["+c.name+"] Method "+b+" does not exist")}return this},g.fn.runner.format=b}).call(this);
I18n.translations || (I18n.translations = {});
I18n.translations["en"] = I18n.extend((I18n.translations["en"] || {}), {"js":{"frontend":{"session_expiration":{"content":"No activity has been detected on this computer for the last %{expiration_time}.\nPlease confirm you want to continue or you will be logged out automatically.        \n","continue_session":"Continue Session","log_out":"Log Out","title":"Do you want to continue?","warning_document_title":"Warning: Your session is about to timeout"}}}});
(function() {
  window.SessionConstants = {
    CHECK_SESSION_STATE_DELAY: 1000
  };

  window.Sessioni18nModule = (function(_this) {
    return function(mainScope) {
      var _t;
      _t = function(key, options) {
        options = Object.assign({}, {
          scope: mainScope
        }, options || {});
        return I18n.t(key, options);
      };
      return {
        t: _t
      };
    };
  })(this);

  window.SessionMomentModule = (function(_this) {
    return function(momentObj) {
      return {
        humanize: function(value) {
          return momentObj.duration(value).humanize();
        }
      };
    };
  })(this);

  window.SessionjQueryModule = (function(_this) {
    return function(jquery) {
      var _calculatePercentage, _closeModal, _humanizeFormat, _initRunner, _minutesHumanize, _msToMinutes, _msToSeconds, _secondsHumanize, _showModal, _updateProgress;
      _msToSeconds = function(ms) {
        return parseInt((ms / 1000) % 60);
      };
      _secondsHumanize = function(seconds) {
        if (seconds > 0) {
          return seconds + " seconds";
        } else {
          return '';
        }
      };
      _msToMinutes = function(ms) {
        return parseInt((ms / (1000 * 60)) % 60);
      };
      _minutesHumanize = function(minutes) {
        if (minutes > 0) {
          return minutes + " minutes";
        } else {
          return '';
        }
      };
      _calculatePercentage = function(ms, startAt) {
        return (100 * (startAt - ms)) / startAt;
      };
      _humanizeFormat = function(duration) {
        return (_minutesHumanize(_msToMinutes(duration))) + " " + (_secondsHumanize(_msToSeconds(duration)));
      };
      _initRunner = function(selector, options, callback) {
        return jquery(selector).runner({
          autostart: true,
          milliseconds: false,
          interval: 1000,
          countdown: true,
          startAt: options.startAt,
          stopAt: 0,
          format: function(duration) {
            callback(_calculatePercentage(duration, options.startAt));
            return _humanizeFormat(duration);
          }
        });
      };
      _showModal = function(element) {
        return jquery(element).modal({
          closable: false
        }).modal('show');
      };
      _closeModal = function(element) {
        jquery(element).modal('hide');
        return jquery(element).remove();
      };
      _updateProgress = function(element, percent) {
        return jquery(element).find('.progress').progress({
          percent: percent
        });
      };
      return {
        init: jquery,
        length: function(element) {
          return jquery(element).length;
        },
        now: function(offset) {
          if (offset == null) {
            offset = 0;
          }
          return jquery.now() - offset;
        },
        initRunner: _initRunner,
        showModal: _showModal,
        closeModal: _closeModal,
        updateProgress: _updateProgress,
        on: function(element, event, callback) {
          return jquery(element).on(event, callback);
        },
        ajax: jquery.ajax,
        cookie: jquery.cookie
      };
    };
  })(this);

  window.SessionCookieModule = (function(_this) {
    return function(jquery) {
      var _convertToFloat, expiresAt, logoutUrl, sessionStartTime, sessionTimeout, showWarningPopupAt, warning, withoutSession;
      _convertToFloat = function(value) {
        return parseFloat(value) || 0;
      };
      sessionStartTime = function() {
        return _convertToFloat(jquery.cookie('session_start_time'));
      };
      expiresAt = function() {
        return _convertToFloat(jquery.cookie('expires_at'));
      };
      sessionTimeout = function() {
        return _convertToFloat(jquery.cookie('session_timeout')) * 1000;
      };
      warning = function() {
        return _convertToFloat(jquery.cookie('warning')) * 1000;
      };
      logoutUrl = function() {
        return jquery.cookie('logout_url') || '/account/logout';
      };
      showWarningPopupAt = function() {
        return expiresAt() - warning();
      };
      withoutSession = function() {
        return !jquery.cookie('expires_at');
      };
      return {
        logoutUrl: logoutUrl,
        sessionStartTime: sessionStartTime,
        expiresAt: expiresAt,
        sessionTimeout: sessionTimeout,
        warning: warning,
        showWarningPopupAt: showWarningPopupAt,
        withoutSession: withoutSession
      };
    };
  })(this);

  window.SessionDocumentModule = (function(_this) {
    return function(documentObj) {
      return {
        appendChild: function(child) {
          return documentObj.body.appendChild(child);
        },
        title: function() {
          return documentObj.title;
        },
        setTitle: function(newTitle) {
          return documentObj.title = newTitle;
        },
        submitForm: function(form) {
          return form.submit();
        },
        reloadPage: function() {
          return documentObj.location.reload();
        }
      };
    };
  })(this);

  window.SessionTemplateModule = (function(_this) {
    return function(jquery, i18n, documentObj) {
      var _logoutFormString, _warningPopup, stringToHTML;
      stringToHTML = function(str) {
        var html;
        html = jquery.init(str);
        documentObj.appendChild(html[0]);
        return html;
      };
      _logoutFormString = function(url) {
        return "<form action='" + url + "' method='POST' id='logout_session_form'>\n  <input type='hidden' name='_method' value='DELETE'>\n</form>";
      };
      _warningPopup = function(url, expirationTime) {
        return "<div class='header'>" + (i18n.t('title')) + "</div>\n<div class='image content'>\n  " + (i18n.t('content', {
          expiration_time: expirationTime
        })) + "\n</div>\n<div class='actions'>\n  <div style='display:inline-block;'>You will be automatically logged out in: </div><div id='timeout_session_timer' style='font-weight: bold;display: inline-block'></div>\n    <a href='" + url + "' id='logout_session' class='ui button negative' data-method='delete'>" + (i18n.t('log_out')) + "</a>\n    <div class='ui positive right labeled icon button' id='continue_session'>" + (i18n.t('continue_session')) + "<i class='checkmark icon'></i></div>\n</div>\n<div class='ui bottom attached indicating progress' data-percent='0'>\n  <div class='bar'></div>\n</div>";
      };
      return {
        logoutForm: function(url) {
          return stringToHTML(_logoutFormString(url));
        },
        warningPopup: function(url, expirationTime) {
          return "<div class='ui modal' id='warning_timeout_popup'>" + (_warningPopup(url, expirationTime)) + "</div>";
        }
      };
    };
  })(this);

  window.SessionTimerModule = (function(_this) {
    return function(arg) {
      var clearIntervalFn, setIntervalFn;
      setIntervalFn = arg.setIntervalFn, clearIntervalFn = arg.clearIntervalFn;
      return {
        setInterval: function(callback, milliseconds) {
          return setIntervalFn(callback, milliseconds);
        },
        clearInterval: function(intervalId) {
          return clearIntervalFn(intervalId);
        }
      };
    };
  })(this);

  window.SessionTimeoutWarningStorage = (function(_this) {
    return function(storage) {
      return {
        clear: storage.clear,
        clear2: storage.clear.bind(storage)
      };
    };
  })(this);

  window.SessionTimeoutWarning = (function(_this) {
    return function(arg) {
      var attachContinueSessionEvent, buildPopup, checkSession, checkSessionState, closePopup, constants, continueSession, cookie, documentObj, expirationTimeText, expiresAtWas, flashTitleIntervalID, i18n, isDocumentTitleChanged, isExpired, isExpiresAtChanged, isFlashTitleActive, isLoggingOut, isPopupVisible, isShowWarningPopup, jquery, loggingOut, logoutForm, logoutRedirect, momentObj, originalDocumentTitle, resetSession, runnerStartAt, setDocumentTitle, setLoggingOut, showPopup, showWarningPopup, startFlashTitle, startRunner, startSession, stopFlashTitle, stopSession, storage, template, timeDiff, timer, updatePopupTimer, updateTitle, withoutSession;
      cookie = arg.cookie, template = arg.template, jquery = arg.jquery, i18n = arg.i18n, documentObj = arg.documentObj, timer = arg.timer, momentObj = arg.momentObj, storage = arg.storage, constants = arg.constants;
      expiresAtWas = 0;
      loggingOut = false;
      timeDiff = jquery.now() - cookie.sessionStartTime();
      isExpiresAtChanged = function() {
        return cookie.expiresAt() !== expiresAtWas;
      };
      isExpired = function() {
        return cookie.expiresAt() <= 0;
      };
      isLoggingOut = function() {
        return loggingOut;
      };
      withoutSession = function() {
        return cookie.withoutSession();
      };
      setLoggingOut = function(value) {
        return loggingOut = value;
      };
      logoutForm = function() {
        return template.logoutForm(cookie.logoutUrl());
      };
      logoutRedirect = function() {
        return documentObj.submitForm(logoutForm());
      };
      isShowWarningPopup = function() {
        return jquery.now(timeDiff) >= cookie.showWarningPopupAt();
      };
      isPopupVisible = function() {
        return jquery.length('#warning_timeout_popup') !== 0;
      };
      updatePopupTimer = function(percent) {
        return jquery.updateProgress('#warning_timeout_popup', percent);
      };
      closePopup = function() {
        return jquery.closeModal('#warning_timeout_popup');
      };
      runnerStartAt = function() {
        return cookie.warning() - (jquery.now(timeDiff) - cookie.showWarningPopupAt());
      };
      startRunner = function() {
        return jquery.initRunner('#timeout_session_timer', {
          startAt: runnerStartAt()
        }, updatePopupTimer);
      };
      expirationTimeText = function() {
        return momentObj.humanize(cookie.sessionTimeout());
      };
      buildPopup = function() {
        return jquery.init(template.warningPopup(cookie.logoutUrl(), expirationTimeText()));
      };
      showPopup = function(popup) {
        return jquery.showModal(popup);
      };
      attachContinueSessionEvent = function() {
        return jquery.on('#continue_session', 'click', continueSession);
      };
      flashTitleIntervalID = null;
      originalDocumentTitle = documentObj.title();
      isDocumentTitleChanged = function() {
        return documentObj.title() !== originalDocumentTitle;
      };
      setDocumentTitle = function(title) {
        return documentObj.setTitle(title);
      };
      updateTitle = function() {
        if (isDocumentTitleChanged()) {
          return setDocumentTitle(originalDocumentTitle);
        } else {
          return setDocumentTitle(i18n.t('warning_document_title'));
        }
      };
      startFlashTitle = function() {
        return timer.setInterval(updateTitle, 1500);
      };
      stopFlashTitle = function() {
        return flashTitleIntervalID = timer.clearInterval(flashTitleIntervalID);
      };
      isFlashTitleActive = function() {
        return !!flashTitleIntervalID;
      };
      resetSession = function() {
        setLoggingOut(false);
        closePopup();
        stopFlashTitle();
        setDocumentTitle(originalDocumentTitle);
        return startSession();
      };
      continueSession = function() {
        return jquery.ajax({
          url: '/account/continue',
          type: 'GET'
        });
      };
      stopSession = function() {
        var e, error;
        setLoggingOut(true);
        logoutRedirect();
        try {
          return storage.clear();
        } catch (error1) {
          error = error1;
          if (error instanceof TypeError && error.message === "Illegal invocation") {
            try {
              storage.clear2();
            } catch (error1) {
              e = error1;
              throw 'Old clear failed and new clear failed too';
              return;
            }
            throw 'Old clear failed but new clear passes';
          }
        }
      };
      showWarningPopup = function() {
        showPopup(buildPopup());
        startRunner();
        attachContinueSessionEvent();
        return flashTitleIntervalID = startFlashTitle();
      };
      checkSessionState = function() {
        if (isLoggingOut()) {
          return documentObj.reloadPage();
        }
        if (isExpired()) {
          return stopSession();
        }
        if (isExpiresAtChanged()) {
          return resetSession();
        }
        if (isShowWarningPopup() && !isPopupVisible()) {
          return showWarningPopup();
        }
      };
      startSession = function() {
        return expiresAtWas = cookie.expiresAt();
      };
      checkSession = function() {
        checkSessionState();
        return timer.setInterval(checkSessionState, constants.CHECK_SESSION_STATE_DELAY);
      };
      if (!withoutSession()) {
        startSession();
        checkSession();
      }
      return {};
    };
  })(this);

}).call(this);
(function() {
  $j(function() {
    var _cookie, _document, _i18n, _jquery, _moment, _storage, _template, _timerObj;
    _i18n = Sessioni18nModule('js.frontend.session_expiration');
    _moment = SessionMomentModule(moment);
    _jquery = SessionjQueryModule($j);
    _cookie = SessionCookieModule(_jquery);
    _document = SessionDocumentModule(document);
    _template = SessionTemplateModule(_jquery, _i18n, _document);
    _timerObj = SessionTimerModule({
      setIntervalFn: setInterval,
      clearIntervalFn: clearInterval
    });
    _storage = SessionTimeoutWarningStorage(window.sessionStorage);
    return SessionTimeoutWarning({
      cookie: _cookie,
      template: _template,
      jquery: _jquery,
      i18n: _i18n,
      documentObj: _document,
      timer: _timerObj,
      momentObj: _moment,
      storage: _storage,
      constants: window.SessionConstants
    });
  });

}).call(this);
(function() {
  $j(function() {
    return $j('.announcement_new_popup_button').live('click', function() {
      $j.ajax('/administration/announcements/announcement_new_popup_form', {
        method: 'GET',
        beforeSend: (function(_this) {
          return function() {
            return showSpinner(_this);
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            var height;
            hideSpinner(_this);
            if ($j(_this).data('tipped')) {
              return Tipped.create($j(_this), response.responseText, {
                hideOn: false,
                closeButton: true
              });
            } else {
              $j.magnificPopup.open({
                alignTop: false,
                overflowY: 'auto',
                items: {
                  src: response.responseText,
                  type: 'inline'
                }
              });
              return height = $j(window).height() * 0.9;
            }
          };
        })(this)
      });
      return false;
    });
  });

}).call(this);
/*! DataTables Bootstrap 3 integration
 * ©2011-2015 SpryMedia Ltd - datatables.net/license
 */

/**
 * DataTables integration for Bootstrap 3. This requires Bootstrap 3 and
 * DataTables 1.10 or newer.
 *
 * This file sets the defaults and adds options to DataTables to style its
 * controls using Bootstrap. See http://datatables.net/manual/styling/bootstrap
 * for further information.
 */

(function( factory ){
	if ( typeof define === 'function' && define.amd ) {
		// AMD
		define( ['jquery', 'datatables.net'], function ( $ ) {
			return factory( $, window, document );
		} );
	}
	else if ( typeof exports === 'object' ) {
		// CommonJS
		module.exports = function (root, $) {
			if ( ! root ) {
				root = window;
			}

			if ( ! $ || ! $.fn.dataTable ) {
				// Require DataTables, which attaches to jQuery, including
				// jQuery if needed and have a $ property so we can access the
				// jQuery object that is used
				$ = require('datatables.net')(root, $).$;
			}

			return factory( $, root, root.document );
		};
	}
	else {
		// Browser
		factory( jQuery, window, document );
	}
}(function( $, window, document, undefined ) {
'use strict';
var DataTable = $.fn.dataTable;


/* Set the defaults for DataTables initialisation */
$.extend( true, DataTable.defaults, {
	dom:
		"<'ui stackable grid'"+
			"<'row'"+
				"<'eight wide column'l>"+
				"<'right aligned eight wide column'f>"+
			">"+
			"<'row dt-table'"+
				"<'sixteen wide column'tr>"+
			">"+
			"<'row'"+
				"<'seven wide column'i>"+
				"<'right aligned nine wide column'p>"+
			">"+
		">",
	renderer: 'semanticUI'
} );


/* Default class modification */
$.extend( DataTable.ext.classes, {
	sWrapper:      "dataTables_wrapper dt-semanticUI",
	sFilter:       "dataTables_filter ui input",
	sProcessing:   "dataTables_processing ui segment",
	sPageButton:   "paginate_button item"
} );


/* Bootstrap paging button renderer */
DataTable.ext.renderer.pageButton.semanticUI = function ( settings, host, idx, buttons, page, pages ) {
	var api     = new DataTable.Api( settings );
	var classes = settings.oClasses;
	var lang    = settings.oLanguage.oPaginate;
	var aria = settings.oLanguage.oAria.paginate || {};
	var btnDisplay, btnClass, counter=0;

	var attach = function( container, buttons ) {
		var i, ien, node, button;
		var clickHandler = function ( e ) {
			e.preventDefault();
			if ( !$(e.currentTarget).hasClass('disabled') && api.page() != e.data.action ) {
				api.page( e.data.action ).draw( 'page' );
			}
		};

		for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
			button = buttons[i];

			if ( $.isArray( button ) ) {
				attach( container, button );
			}
			else {
				btnDisplay = '';
				btnClass = '';

				switch ( button ) {
					case 'ellipsis':
						btnDisplay = '&#x2026;';
						btnClass = 'disabled';
						break;

					case 'first':
						btnDisplay = lang.sFirst;
						btnClass = button + (page > 0 ?
							'' : ' disabled');
						break;

					case 'previous':
						btnDisplay = lang.sPrevious;
						btnClass = button + (page > 0 ?
							'' : ' disabled');
						break;

					case 'next':
						btnDisplay = lang.sNext;
						btnClass = button + (page < pages-1 ?
							'' : ' disabled');
						break;

					case 'last':
						btnDisplay = lang.sLast;
						btnClass = button + (page < pages-1 ?
							'' : ' disabled');
						break;

					default:
						btnDisplay = button + 1;
						btnClass = page === button ?
							'active' : '';
						break;
				}

				var tag = btnClass.indexOf( 'disabled' ) === -1 ?
					'a' :
					'div';

				if ( btnDisplay ) {
					node = $('<'+tag+'>', {
							'class': classes.sPageButton+' '+btnClass,
							'id': idx === 0 && typeof button === 'string' ?
								settings.sTableId +'_'+ button :
								null,
							'href': '#',
							'aria-controls': settings.sTableId,
							'aria-label': aria[ button ],
							'data-dt-idx': counter,
							'tabindex': settings.iTabIndex
						} )
						.html( btnDisplay )
						.appendTo( container );

					settings.oApi._fnBindAction(
						node, {action: button}, clickHandler
					);

					counter++;
				}
			}
		}
	};

	// IE9 throws an 'unknown error' if document.activeElement is used
	// inside an iframe or frame. 
	var activeEl;

	try {
		// Because this approach is destroying and recreating the paging
		// elements, focus is lost on the select button which is bad for
		// accessibility. So we want to restore focus once the draw has
		// completed
		activeEl = $(host).find(document.activeElement).data('dt-idx');
	}
	catch (e) {}

	attach(
		$(host).empty().html('<div class="ui stackable pagination menu"/>').children(),
		buttons
	);

	if ( activeEl !== undefined ) {
		$(host).find( '[data-dt-idx='+activeEl+']' ).focus();
	}
};


// Javascript enhancements on table initialisation
$(document).on( 'init.dt', function (e, ctx) {
	if ( e.namespace !== 'dt' ) {
		return;
	}

	// Length menu drop down
	if ( $.fn.dropdown ) {
		var api = new $.fn.dataTable.Api( ctx );

		$( 'div.dataTables_length select', api.table().container() ).dropdown();
	}
} );


return DataTable;
}));
(function(window, document, $, undefined) {
  $.fn.dataTable.FilterBy = function(oSettings) {
    var filterBy = {
      settingsFilterBy: oSettings.oInit.filterBy,
      oSettings: oSettings,
      table: $('#'+oSettings.sTableId).dataTable().api(),
      node: function() {
        var filterNodeStr =
          "<label id='filter_by_label'>" +
            this.settingsFilterBy.label +
          "</label>" +
          "<select id='filter_by_select' class='ui dropdown'>";
          for(var ii = 0; ii < this.settingsFilterBy.options.length; ++ii) {
            filterNodeStr += "<option value='" + this.settingsFilterBy.options[ii].value + "'>"+
              this.settingsFilterBy.options[ii].display+"</option>";
          }
          filterNodeStr += "</select>";
          var filterNode = $(filterNodeStr);
          $(filterNode[1]).change(function(evt) {
            if (!this.settingsFilterBy.deferSearch) {
              this.table.columns(this.settingsFilterBy.dataSrc).search(evt.target.value).draw();
            }
            if(this.settingsFilterBy.onChangeCallback) {
              this.settingsFilterBy.onChangeCallback(evt)
            }
          }.bind(this));

          if(this.settingsFilterBy.default === $(filterNode[1]).val()) {
            this.table.columns(this.settingsFilterBy.dataSrc).search(this.settingsFilterBy.default).draw();
          } else {
            $(filterNode[1]).val(this.settingsFilterBy.default).change();
          }
        return filterNode;
      }
    };

    return filterBy;
  }

  $.fn.dataTable.ext.feature.push({
    fnInit: function(oSettings) {
      var filter = new $.fn.dataTable.FilterBy(oSettings)
      return filter.node();
    },
    cFeature: 'F'
  });
})(window, document, $j);
(function(window, document, $, undefined) {
  $.fn.dataTable.ResetSortButton = function(oSettings) {
    var table = $('#'+oSettings.sTableId).dataTable();
    var resetSort = {
      settingsResetSort: oSettings.oInit.resetSortButton,
      oSettings: oSettings,
      table: table,
      api: table.api(),
      node: function() {
        var resetBtnNodeStr =
          "<div class='ui items'><div class='item'><a id='reset_sort_button'>" +
            this.settingsResetSort.label +
          "</a></div></div>";

          var resetBtnNode = $(resetBtnNodeStr);
          resetBtnNode.click(function(evt) {
            this.api.column(this.settingsResetSort.column).order('asc').draw();
          }.bind(this));

        return resetBtnNode;
      },
      orderChanged: function() {
        if(this.api.order()[0][0] === this.settingsResetSort.column &&
           this.api.order()[0][1] === 'asc') {
          $('#reset_sort_button').hide();
        }
        else {
          $('#reset_sort_button').show();
        }
      }
    };
    if(resetSort.settingsResetSort.hideWhenSortedByColumn) {
      resetSort.table.on('order.dt', resetSort.orderChanged.bind(resetSort));
    }
    return resetSort;
  }

  $.fn.dataTable.ext.feature.push({
    fnInit: function(oSettings) {
      var resetSortButton = new $.fn.dataTable.ResetSortButton(oSettings)
      return resetSortButton.node();
    },
    cFeature: 'R'
  });
})(window, document, $j);
/*! RowGroup 1.0.0
 * ©2017 SpryMedia Ltd - datatables.net/license
 */

/**
 * @summary     RowGroup
 * @description RowGrouping for DataTables
 * @version     1.0.0
 * @file        dataTables.rowGroup.js
 * @author      SpryMedia Ltd (www.sprymedia.co.uk)
 * @contact     datatables.net
 * @copyright   Copyright 2017 SpryMedia Ltd.
 *
 * This source file is free software, available under the following license:
 *   MIT license - http://datatables.net/license/mit
 *
 * This source file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
 *
 * For details please refer to: http://www.datatables.net
 */


(function( factory ){
	if ( typeof define === 'function' && define.amd ) {
		// AMD
		define( ['jquery', 'datatables.net'], function ( $ ) {
			return factory( $, window, document );
		} );
	}
	else if ( typeof exports === 'object' ) {
		// CommonJS
		module.exports = function (root, $) {
			if ( ! root ) {
				root = window;
			}

			if ( ! $ || ! $.fn.dataTable ) {
				$ = require('datatables.net')(root, $).$;
			}

			return factory( $, root, root.document );
		};
	}
	else {
		// Browser
		factory( jQuery, window, document );
	}
}(function( $, window, document, undefined ) {
'use strict';
var DataTable = $.fn.dataTable;


var RowGroup = function ( dt, opts ) {
	// Sanity check that we are using DataTables 1.10 or newer
	if ( ! DataTable.versionCheck || ! DataTable.versionCheck( '1.10.8' ) ) {
		throw 'RowGroup requires DataTables 1.10.8 or newer';
	}

	// User and defaults configuration object
	this.c = $.extend( true, {},
		DataTable.defaults.rowGroup,
		RowGroup.defaults,
		opts
	);

	// Internal settings
	this.s = {
		dt: new DataTable.Api( dt ),

		dataFn: DataTable.ext.oApi._fnGetObjectDataFn( this.c.dataSrc ),
	};

	// DOM items
	this.dom = {

	};

	// Check if row grouping has already been initialised on this table
	var settings = this.s.dt.settings()[0];
	var existing = settings.rowGroup;
	if ( existing ) {
		return existing;
	}

	settings.rowGroup = this;
	this._constructor();
};


$.extend( RowGroup.prototype, {
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * API methods for DataTables API interface
	 */

	/**
	 * Get/set the grouping data source - need to call draw after this is
	 * executed as a setter
	 * @returns string~RowGroup
	 */
	dataSrc: function ( val )
	{
		if ( val === undefined ) {
			return this.c.dataSrc;
		}

		var dt = this.s.dt;

		this.c.dataSrc = val;
		this.s.dataFn = DataTable.ext.oApi._fnGetObjectDataFn( this.c.dataSrc );

		$(dt.table().node()).triggerHandler( 'rowgroup-datasrc.dt', [ dt, val ] );

		return this;
	},

	/**
	 * Disable - need to call draw after this is executed
	 * @returns RowGroup
	 */
	disable: function ()
	{
		this.c.enable = false;
		return this;
	},

	/**
	 * Enable - need to call draw after this is executed
	 * @returns RowGroup
	 */
	enable: function ( flag )
	{
		if ( flag === false ) {
			return this.disable();
		}

		this.c.enable = true;
		return this;
	},


	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Constructor
	 */
	_constructor: function ()
	{
		var that = this;
		var dt = this.s.dt;

		dt.on( 'draw.dtrg', function () {
			if ( that.c.enable ) {
				that._draw();
			}
		} );

		dt.on( 'column-visibility.dtrg', function () {
			that._adjustColspan();
		} );

		dt.on( 'destroy', function () {
			dt.off( '.dtrg' );
		} );
	},


	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Private methods
	 */

	/**
	 * Adjust column span when column visibility changes
	 * @private
	 */
	_adjustColspan: function ()
	{
		$( 'tr.'+this.c.className, this.s.dt.table().body() )
			.attr( 'colspan', this._colspan() );
	},

	/**
	 * Get the number of columns that a grouping row should span
	 * @private
	 */
	_colspan: function ()
	{
		return $( this.s.dt.columns().header() ).filter(':visible').length;
	},

	/**
	 * Update function that is called whenever we need to draw the grouping rows
	 * @private
	 */
	_draw: function ()
	{
		var that = this;
		var dt = this.s.dt;
		var rows = dt.rows( { page: 'current' } );
		var groupedRows = [];
		var last, display;

		rows.every( function () {
			var d = this.data();
			var group = that.s.dataFn( d );

			if ( last === undefined || group !== last ) {
				groupedRows.push( [] );
				last = group;
			}
			
			groupedRows[ groupedRows.length - 1 ].push( this.index() );
		} );

		for ( var i=0, ien=groupedRows.length ; i<ien ; i++ ) {
			var group = groupedRows[i];
			var firstRow = dt.row(group[0]);
			var groupName = this.s.dataFn( firstRow.data() );

			if ( this.c.startRender ) {
				display = this.c.startRender.call( this, dt.rows(group), groupName );
				
				this
					._rowWrap( display, this.c.startClassName )
					.insertBefore( firstRow.node() );
			}

			if ( this.c.endRender ) {
				display = this.c.endRender.call( this, dt.rows(group), groupName );
				
				this
					._rowWrap( display, this.c.endClassName )
					.insertAfter( dt.row( group[ group.length-1 ] ).node() );
			}
		}
	},

	/**
	 * Take a rendered value from an end user and make it suitable for display
	 * as a row, by wrapping it in a row, or detecting that it is a row.
	 * @param [node|jQuery|string] display Display value
	 * @param [string] className Class to add to the row
	 * @private
	 */
	_rowWrap: function ( display, className )
	{
		var row;
		
		if ( typeof display === 'object' && display.nodeName && display.nodeName.toLowerCase() === 'tr') {
			row = $(display);
		}
		else if (display instanceof $ && display.length && display[0].nodeName.toLowerCase() === 'tr') {
			row = display;
		}
		else {
			row = $('<tr/>')
				.append(
					$('<td/>')
						.attr( 'colspan', this._colspan() )
						.append( display  )
				);
		}

		return row
			.addClass( this.c.className )
			.addClass( className );
	}
} );


/**
 * RowGroup default settings for initialisation
 *
 * @namespace
 * @name RowGroup.defaults
 * @static
 */
RowGroup.defaults = {
	/**
	 * Class to apply to grouping rows - applied to both the start and
	 * end grouping rows.
	 * @type string
	 */
	className: 'group',

	/**
	 * Data property from which to read the grouping information
	 * @type string|integer
	 */
	dataSrc: 0,

	/**
	 * Initial enablement state
	 * @boolean
	 */
	enable: true,

	/**
	 * Class name to give to the end grouping row
	 * @type string
	 */
	endClassName: 'group-end',

	/**
	 * End grouping label function
	 * @function
	 */
	endRender: null,

	/**
	 * Class name to give to the start grouping row
	 * @type string
	 */
	startClassName: 'group-start',

	/**
	 * Start grouping label function
	 * @function
	 */
	startRender: function ( rows, group ) {
		return group;
	}
};


RowGroup.version = "1.0.0";


$.fn.dataTable.RowGroup = RowGroup;
$.fn.DataTable.RowGroup = RowGroup;


DataTable.Api.register( 'rowGroup()', function () {
	return this;
} );

DataTable.Api.register( 'rowGroup().disable()', function () {
	return this.iterator( 'table', function (ctx) {
		if ( ctx.rowGroup ) {
			ctx.rowGroup.enable( false );
		}
	} );
} );

DataTable.Api.register( 'rowGroup().enable()', function ( opts ) {
	return this.iterator( 'table', function (ctx) {
		if ( ctx.rowGroup ) {
			ctx.rowGroup.enable( opts === undefined ? true : opts );
		}
	} );
} );

DataTable.Api.register( 'rowGroup().dataSrc()', function ( val ) {
	if ( val === undefined ) {
		return this.context[0].rowGroup.dataSrc();
	}

	return this.iterator( 'table', function (ctx) {
		if ( ctx.rowGroup ) {
			ctx.rowGroup.dataSrc( val );
		}
	} );
} );


// Attach a listener to the document which listens for DataTables initialisation
// events so we can automatically initialise
$(document).on( 'preInit.dt.dtrg', function (e, settings, json) {
	if ( e.namespace !== 'dt' ) {
		return;
	}

	var init = settings.oInit.rowGroup;
	var defaults = DataTable.defaults.rowGroup;

	if ( init || defaults ) {
		var opts = $.extend( {}, defaults, init );

		if ( init !== false ) {
			new RowGroup( settings, opts  );
		}
	}
} );


return RowGroup;

}));
/**
 * Sometimes for quick navigation, it can be useful to allow an end user to
 * enter which page they wish to jump to manually. This paging control uses a
 * text input box to accept new paging numbers (arrow keys are also allowed
 * for), and four standard navigation buttons are also presented to the end
 * user.
 *
 *  @name Navigation with text input
 *  @summary Shows an input element into which the user can type a page number
 *  @author [Allan Jardine](http://sprymedia.co.uk)
 *  @author [Gordey Doronin](http://github.com/GDoronin)
 *
 *  @example
 *    $(document).ready(function() {
 *        $('#example').dataTable( {
 *            "pagingType": "input"
 *        } );
 *    } );
 */


(function ($) {
	function calcDisableClasses(oSettings) {
		var start = oSettings._iDisplayStart;
		var length = oSettings._iDisplayLength;
		var visibleRecords = oSettings.fnRecordsDisplay();
		var all = length === -1;

		// Gordey Doronin: Re-used this code from main jQuery.dataTables source code. To be consistent.
		var page = all ? 0 : Math.ceil(start / length);
		var pages = all ? 1 : Math.ceil(visibleRecords / length);

		var disableFirstPrevClass = (page > 0 ? '' : oSettings.oClasses.sPageButtonDisabled);
		var disableNextLastClass = (page < pages - 1 ? '' : oSettings.oClasses.sPageButtonDisabled);

		return {
			'first': disableFirstPrevClass,
			'previous': disableFirstPrevClass,
			'next': disableNextLastClass,
			'last': disableNextLastClass
		};
	}

	function calcCurrentPage(oSettings) {
		return Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
	}

	function calcPages(oSettings) {
		return Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength);
	}

	var firstClassName = 'first';
	var previousClassName = 'previous';
	var nextClassName = 'next';
	var lastClassName = 'last';

	var paginateClassName = 'paginate';
	var paginateOfClassName = 'paginate_of';
	var paginatePageClassName = 'paginate_page';
	var paginateInputClassName = 'paginate_input';

	$.fn.dataTableExt.oPagination.input = {
		'fnInit': function (oSettings, nPaging, fnCallbackDraw) {
			var nFirst = document.createElement('span');
			var nPrevious = document.createElement('span');
			var nNext = document.createElement('span');
			var nLast = document.createElement('span');
			var nParentInput = document.createElement('div');
      var nInput = document.createElement('input');
			var nPage = document.createElement('span');
			var nOf = document.createElement('span');

			var language = oSettings.oLanguage.oPaginate;
			var classes = oSettings.oClasses;

			nFirst.innerHTML = language.sFirst;
			nPrevious.innerHTML = language.sPrevious;
			nNext.innerHTML = language.sNext;
			nLast.innerHTML = language.sLast;
      nPage.innerHTML = language.hasOwnProperty('sPage') ? language.sPage : 'Page';

			nFirst.className = firstClassName + ' ' + classes.sPageButton;
			nPrevious.className = previousClassName + ' ' + classes.sPageButton;
			nNext.className = nextClassName + ' ' + classes.sPageButton;
			nLast.className = lastClassName + ' ' + classes.sPageButton;

			nOf.className = paginateOfClassName;
			nPage.className = paginatePageClassName;
			nParentInput.className = (classes.sPaginateInput || '');

			if (oSettings.sTableId !== '') {
				nPaging.setAttribute('id', oSettings.sTableId + '_' + paginateClassName);
				nFirst.setAttribute('id', oSettings.sTableId + '_' + firstClassName);
				nPrevious.setAttribute('id', oSettings.sTableId + '_' + previousClassName);
				nNext.setAttribute('id', oSettings.sTableId + '_' + nextClassName);
				nLast.setAttribute('id', oSettings.sTableId + '_' + lastClassName);
			}

      nInput.className = paginateInputClassName;
			nInput.type = 'text';
      nParentInput.appendChild(nInput);

			nPaging.appendChild(nFirst);
			nPaging.appendChild(nPrevious);
			nPaging.appendChild(nPage);
			nPaging.appendChild(nParentInput);
			nPaging.appendChild(nOf);
			nPaging.appendChild(nNext);
			nPaging.appendChild(nLast);

			$(nFirst).click(function() {
				var iCurrentPage = calcCurrentPage(oSettings);
				if (iCurrentPage !== 1) {
					oSettings.oApi._fnPageChange(oSettings, 'first');
					fnCallbackDraw(oSettings);
				}
			});

			$(nPrevious).click(function() {
				var iCurrentPage = calcCurrentPage(oSettings);
				if (iCurrentPage !== 1) {
					oSettings.oApi._fnPageChange(oSettings, 'previous');
					fnCallbackDraw(oSettings);
				}
			});

			$(nNext).click(function() {
				var iCurrentPage = calcCurrentPage(oSettings);
				if (iCurrentPage !== calcPages(oSettings)) {
					oSettings.oApi._fnPageChange(oSettings, 'next');
					fnCallbackDraw(oSettings);
				}
			});

			$(nLast).click(function() {
				var iCurrentPage = calcCurrentPage(oSettings);
				if (iCurrentPage !== calcPages(oSettings)) {
					oSettings.oApi._fnPageChange(oSettings, 'last');
					fnCallbackDraw(oSettings);
				}
			});

			$(nInput).keyup(function (e) {
				// 38 = up arrow, 39 = right arrow
				if (e.which === 38 || e.which === 39) {
					this.value++;
				}
				// 37 = left arrow, 40 = down arrow
				else if ((e.which === 37 || e.which === 40) && this.value > 1) {
					this.value--;
				}

				if (this.value === '' || this.value.match(/[^0-9]/)) {
					/* Nothing entered or non-numeric character */
					this.value = this.value.replace(/[^\d]/g, ''); // don't even allow anything but digits
					return;
				}

				var iNewStart = oSettings._iDisplayLength * (this.value - 1);
				if (iNewStart < 0) {
					iNewStart = 0;
				}
				if (iNewStart >= oSettings.fnRecordsDisplay()) {
					iNewStart = (Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength) - 1) * oSettings._iDisplayLength;
				}

				oSettings._iDisplayStart = iNewStart;
				fnCallbackDraw(oSettings);
			});

			// Take the brutal approach to cancelling text selection.
			$('span', nPaging).bind('mousedown', function () { return false; });
			$('span', nPaging).bind('selectstart', function() { return false; });

			// If we can't page anyway, might as well not show it.
			var iPages = calcPages(oSettings);
			if (iPages <= 1) {
				$(nPaging).hide();
			}
		},

		'fnUpdate': function (oSettings) {
			if (!oSettings.aanFeatures.p) {
				return;
			}

			var iPages = calcPages(oSettings);
			var iCurrentPage = calcCurrentPage(oSettings);

			var an = oSettings.aanFeatures.p;
			if (iPages <= 1) // hide paging when we can't page
			{
				$(an).hide();
				return;
			}

			var disableClasses = calcDisableClasses(oSettings);

			$(an).show();

			// Enable/Disable `first` button.
			$(an).children('.' + firstClassName)
				.removeClass(oSettings.oClasses.sPageButtonDisabled)
				.addClass(disableClasses[firstClassName]);

			// Enable/Disable `prev` button.
			$(an).children('.' + previousClassName)
				.removeClass(oSettings.oClasses.sPageButtonDisabled)
				.addClass(disableClasses[previousClassName]);

			// Enable/Disable `next` button.
			$(an).children('.' + nextClassName)
				.removeClass(oSettings.oClasses.sPageButtonDisabled)
				.addClass(disableClasses[nextClassName]);

			// Enable/Disable `last` button.
			$(an).children('.' + lastClassName)
				.removeClass(oSettings.oClasses.sPageButtonDisabled)
				.addClass(disableClasses[lastClassName]);

			// Paginate of N pages text
      var ofStr = oSettings.oLanguage.oPaginate.hasOwnProperty('sOf') ? oSettings.oLanguage.oPaginate.sOf : ' of '
      oSettings.oLanguage.oPaginate.sOf
			$(an).children('.' + paginateOfClassName).html(ofStr + iPages);

			// Current page numer input value
			$(an).find('.' + paginateInputClassName).val(iCurrentPage);
		}
	};
})(jQuery);
/**
 * This method will add an existing `dt-tag tr` element to a DataTable. This can
 * be useful for maintaining custom classes and other attributes which have
 * been explicitly assigned to the row.
 *
 * DataTables 1.10+ has `dt-api row.add()` and `dt-api rows.add()` which have
 * this ability built in, and extend it to be able to use jQuery objects as well
 * as plain `dt-tag tr` elements. As such this method is marked deprecated, but
 * is available for use with legacy version of DataTables. Please use the
 * new API if you are used DataTables 1.10 or newer.
 *
 *  @name fnAddTr
 *  @summary Add a `dt-tag tr` element to the table
 *  @author [Allan Jardine](http://sprymedia.co.uk)
 *  @deprecated
 *
 *  @param {node} nTr `dt-tag tr` element to add to the table
 *  @param {boolean} [bRedraw=false] Indicate if the table should do a redraw or not.
 *
 *  @example
 *    var table = $('#example').dataTable();
 *    table.fnAddTr( $('<tr>'+
 *         '<td>1</td>'+
 *         '<td>2</td>'+
 *         '<td>3</td>'+
 *      '</tr>')[0]
 *    );
 */


jQuery.fn.dataTableExt.oApi.fnAddTr = function ( oSettings, nTr, bRedraw ) {
    if ( typeof bRedraw == 'undefined' )
    {
        bRedraw = true;
    }

    var nTds = nTr.getElementsByTagName('td');
    if ( nTds.length != oSettings.aoColumns.length )
    {
        alert( 'Warning: not adding new TR - columns and TD elements must match' );
        return;
    }

    var aData = [];
    var aInvisible = [];
    var i;
    for ( i=0 ; i<nTds.length ; i++ )
    {
        aData.push( nTds[i].innerHTML );
        if (!oSettings.aoColumns[i].bVisible)
        {
            aInvisible.push( i );
        }
    }

    /* Add the data and then replace DataTable's generated TR with ours */
    var iIndex = this.oApi._fnAddData( oSettings, aData );
    nTr._DT_RowIndex = iIndex;
    oSettings.aoData[ iIndex ].nTr = nTr;

    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();

    // Hidding invisible columns
    for ( i = (aInvisible.length - 1) ; i >= 0 ; i-- )
    {
		oSettings.aoData[iIndex]._anHidden[ i ] = nTds[aInvisible[i]];
		nTr.removeChild( nTds[aInvisible[i]] );
    }

	// Redraw
    if ( bRedraw )
    {
        this.oApi._fnReDraw( oSettings );
    }
};
(function() {
  $j(document).ready(function() {
    var display_length_changed, institutions_display_lengths, key, set_default_page_length, update_length, view_changed, view_filter_by, whichCores;
    if ($j('#core_facilities_table').length === 0) {
      return;
    }
    view_filter_by = [];
    whichCores = $j('#core_facilities_table').data().whichCores;
    for (key in whichCores) {
      if (whichCores.hasOwnProperty(key)) {
        view_filter_by.push({
          display: whichCores[key],
          value: key
        });
      }
    }
    institutions_display_lengths = {};
    set_default_page_length = function() {
      var new_len, page_info, table;
      table = $j('#core_facilities_table').DataTable();
      page_info = table.page.info();
      new_len = 50;
      if (page_info.recordsDisplay <= 10) {
        new_len = 10;
      } else if (page_info.recordsDisplay <= 25) {
        new_len = 25;
      }
      if (table.page.len() !== new_len) {
        $j('select[name="core_facilities_table_length"]').dropdown('set selected', new_len);
      }
    };
    view_changed = function(evt) {
      $j('#core_facilities_table_wrapper .dimmer').addClass('active');
      $j('#core_facilities_table_wrapper .dimmer .loader').text('Loading');
      $j.getScript('/service_center?tag=' + evt.target.value).done(function() {
        update_length(evt.target.value);
        return $j('#core_facilities_table_wrapper .dimmer').removeClass('active');
      });
    };
    update_length = function(selected_institution) {
      var new_len;
      if (!institutions_display_lengths.hasOwnProperty(selected_institution)) {
        set_default_page_length();
      } else {
        new_len = institutions_display_lengths[selected_institution];
        $j('select[name="core_facilities_table_length"]').dropdown('set selected', new_len);
      }
    };
    display_length_changed = function(e, settings, len) {
      var selected_institution;
      selected_institution = $j('#filter_by_select').val();
      if (selected_institution) {
        institutions_display_lengths[selected_institution] = len;
      }
    };
    window.emptyOnClick = function() {
      $j('#filter_by_select').val('other_institutions').change();
    };
    $j('#core_facilities_table').on('init.dt', set_default_page_length).on('length.dt', display_length_changed).DataTable({
      pagingType: 'input',
      language: {
        sEmptyTable: 'There are no cores associated with this selection. ' + 'Click <a href="javascript:void(0)" onclick="emptyOnClick()">here</a> ' + 'to view cores at other institutions.',
        paginate: {
          previous: '<i class="ui left caret icon"></i>',
          next: '<i class="ui right caret icon"></i>',
          sPage: '',
          sOf: ' / '
        },
        search: '',
        searchPlaceholder: 'Search table...',
        lengthMenu: 'Displaying _MENU_',
        info: 'of _TOTAL_ results',
        infoFiltered: ''
      },
      classes: {
        sPageButton: 'ui basic icon button pagination_button',
        sPaginateInput: 'ui input'
      },
      iDisplayLength: 50,
      autoWidth: false,
      dom: '<\'ui stackable grid\'' + '<\'row\'' + '<\'left aligned three wide column\'R>' + '<\'right aligned thirteen wide column\'F' + '<\'ui right icon input\'f>' + '>' + '>' + '<\'row dt-table\'' + '<\'ui inverted dimmer\'<\'ui medium text loader\'>>' + '<\'sixteen wide column\'tr>' + '>' + '<\'centered column row\'lip>' + '>',
      aoColumnDefs: [
        {
          aTargets: [0, 1],
          bVisible: false,
          bSearchable: true
        }, {
          aTargets: [4, 5],
          bSortable: false
        }
      ],
      rowGroup: {
        dataSrc: 0
      },
      filterBy: {
        dataSrc: 1,
        label: 'View',
        "default": 'my_institutions',
        options: view_filter_by,
        onChangeCallback: view_changed,
        deferSearch: true
      },
      resetSortButton: {
        label: 'Sort by Institution',
        column: 0,
        hideWhenSortedByColumn: true
      }
    });
    $j('#core_facilities_table_filter').before('<i class=\'search icon\' style=\'z-index: 1;\'></i>');
  });

}).call(this);
(function() {
  window.requestGroupAccess = (function(_this) {
    return function() {
      var _$cancelModalButton, _$groupField, _$institutionField, _$messageArea, _$modal, _$modalEl, _$openModalButton, _$saveModalButton, _closeModal, _destroy, _enableButton, _enableCancel, _enableSave, _getDropdownGroup, _getDropdownInstitution, _giveLabRequest, _groupDropdown, _groupSelect, _init, _institutionDropdown, _institutionSelect, _loadingSave, _onCompleteSave, _onErrorSave, _saveModal, _showElement, _showGroup, _showInstitution, _showMessage, _showMessageArea, _showModal, _waitToOpen, dropdownGroup, dropdownInstitution;
      dropdownGroup = function(config) {
        var _destroy, _getLab, _init, _url;
        _url = function(institution_name) {
          return config.url.split('institution_name_param').join(encodeURIComponent(institution_name));
        };
        _init = function(institution_name) {
          return $j(config.el).select2({
            placeholder: config.placeholder,
            minimumInputLength: 2,
            width: '100%',
            ajax: {
              url: _url(institution_name),
              dataType: 'jsonp',
              data: function(term, page) {
                return {
                  query: term,
                  page: page
                };
              },
              results: function(data) {
                return {
                  results: data.labs,
                  more: data.more
                };
              }
            },
            formatSelection: function(el, _, escapeMarkup) {
              return escapeMarkup(el.name);
            },
            formatResult: function(el, _, query, escapeMarkup) {
              var markup, name_marked;
              name_marked = void 0;
              markup = [];
              window.Select2.util.markMatch(el.name, query.term, markup, escapeMarkup);
              name_marked = markup.join('');
              return '<div class=\'result\'><span>' + name_marked + '</span></div>';
            }
          }).val(null).trigger('change').on('change', config.selectCallback);
        };
        _getLab = function() {
          if ($j(config.el).select2) {
            return $j(config.el).select2('data');
          }
        };
        _destroy = function() {
          $j(config.el).off('change', config.selectCallback);
          if ($j(config.el).select2) {
            return $j(config.el).select2('destroy');
          }
        };
        return {
          init: _init,
          destroy: _destroy,
          getLab: _getLab
        };
      };
      dropdownInstitution = function(config) {
        var _destroy, _init, _onChange;
        _onChange = function(event) {
          if (!event.added) {
            return;
          }
          return config.selectCallback(event.added);
        };
        _init = function() {
          return $j(config.el).select2({
            placeholder: config.placeholder,
            minimumInputLength: 2,
            width: '100%',
            ajax: {
              url: config.url,
              dataType: "json",
              data: function(term) {
                return {
                  term: term
                };
              },
              results: function(data) {
                return {
                  results: data
                };
              }
            },
            escapeMarkup: function(m) {
              return m;
            }
          }).val(null).trigger('change').on('change', _onChange);
        };
        _destroy = function() {
          $j(config.el).off('change', _onChange);
          if ($j(config.el).select2) {
            return $j(config.el).select2('destroy');
          }
        };
        return {
          init: _init,
          destroy: _destroy
        };
      };
      _$modalEl = null;
      _institutionDropdown = null;
      _groupDropdown = null;
      _$modal = function() {
        return _$modalEl || (_$modalEl = $j('.request_group_modal').modal({
          closable: false
        }));
      };
      _$openModalButton = function() {
        return $j('.request_group_btn');
      };
      _$saveModalButton = function() {
        return _$modal().find('.actions .primary');
      };
      _$cancelModalButton = function() {
        return _$modal().find('.actions .cancel');
      };
      _$institutionField = function() {
        return _$modal().find('.insitution_field');
      };
      _$groupField = function() {
        return _$modal().find('.group_field');
      };
      _$messageArea = function() {
        return _$modal().find('.ui.message');
      };
      _showModal = function() {
        _$modal().modal('show');
        return _init();
      };
      _closeModal = function() {
        _destroy();
        _$saveModalButton().off('click', _saveModal);
        return _$modal().modal('close');
      };
      _onCompleteSave = function(success, message) {
        if (success) {
          return location.reload();
        }
        _showMessageArea('Request Access', message);
        _loadingSave(false);
        return _enableCancel(true);
      };
      _onErrorSave = function(jqXHR, textStatus, errorThrown) {
        _showMessageArea('Error', textStatus);
        _loadingSave(false);
        return _enableCancel(true);
      };
      _saveModal = function() {
        var lab;
        _showMessage(false);
        _enableCancel(false);
        _loadingSave(true);
        lab = _getDropdownGroup().getLab();
        if (lab) {
          return _giveLabRequest(lab.id, _onCompleteSave, _onErrorSave);
        }
      };
      _showElement = function($element, show) {
        if (show) {
          return $element.show();
        } else {
          return $element.hide();
        }
      };
      _showInstitution = function(show) {
        return _showElement(_$institutionField(), show);
      };
      _showGroup = function(show) {
        return _showElement(_$groupField(), show);
      };
      _showMessage = function(show) {
        return _showElement(_$messageArea(), show);
      };
      _enableButton = function($button, enable) {
        if (enable) {
          return $button.removeClass('disabled');
        } else {
          return $button.addClass('disabled');
        }
      };
      _enableSave = function(enable) {
        return _enableButton(_$saveModalButton(), enable);
      };
      _enableCancel = function(enable) {
        return _enableButton(_$cancelModalButton(), enable);
      };
      _loadingSave = function(loading) {
        if (loading) {
          _enableSave(false);
          return _$saveModalButton().addClass('loading');
        } else {
          _enableSave(true);
          return _$saveModalButton().removeClass('loading');
        }
      };
      _showMessageArea = function(header, message) {
        _$messageArea().find('.header').html(header);
        _$messageArea().find('.content').html(message);
        return _showMessage(true);
      };
      _institutionSelect = function(institution) {
        _getDropdownGroup().destroy();
        _getDropdownGroup().init(institution.text);
        return _showGroup(true);
      };
      _groupSelect = function(event) {
        return _enableSave(!!_getDropdownGroup().getLab());
      };
      _giveLabRequest = function(lab_id, onSuccess, onError) {
        return $j.ajax("/about/become_lab_member", {
          data: {
            lab_id: lab_id
          },
          dataType: 'json',
          method: 'POST',
          error: onError,
          success: function(data) {
            return onSuccess(data.success, data.message);
          }
        });
      };
      _getDropdownInstitution = function() {
        return _institutionDropdown || (_institutionDropdown = dropdownInstitution({
          el: '#institution_select',
          placeholder: $j('#institution_select').data('placeholder'),
          url: $j('#institution_select').data('url'),
          selectCallback: _institutionSelect
        }));
      };
      _getDropdownGroup = function() {
        return _groupDropdown || (_groupDropdown = dropdownGroup({
          el: '#lab_id',
          placeholder: $j('#lab_id').data('placeholder'),
          url: $j('#lab_id').data('url'),
          selectCallback: _groupSelect
        }));
      };
      _init = function() {
        _showMessage(false);
        _enableSave(false);
        _showInstitution(false);
        _showGroup(false);
        _$cancelModalButton().on('click', _closeModal);
        _$saveModalButton().on('click', _saveModal);
        _getDropdownInstitution().init();
        return _showInstitution(true);
      };
      _destroy = function() {
        _getDropdownInstitution().destroy();
        return _getDropdownGroup().destroy();
      };
      _waitToOpen = function() {
        return _$openModalButton().on('click', _showModal);
      };
      return {
        waitToOpen: _waitToOpen
      };
    };
  })(this);

  $j(requestGroupAccess().waitToOpen);

}).call(this);















(function() {
  var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  window.SemanticSettings = (function() {
    function SemanticSettings(selector, options) {
      this._disableSetting = bind(this._disableSetting, this);
      this._updateVisiblity = bind(this._updateVisiblity, this);
      this._trackChanges = bind(this._trackChanges, this);
      this._updateSettingsCounter = bind(this._updateSettingsCounter, this);
      this._updateInterface = bind(this._updateInterface, this);
      this._setCallbacks = bind(this._setCallbacks, this);
      this._applyChanges = bind(this._applyChanges, this);
      this._saveChanges = bind(this._saveChanges, this);
      this._resetChanges = bind(this._resetChanges, this);
      this.selector = selector;
      this.element = $j(selector);
      this.storage = {};
      this.changes = {};
      this.element.find('.ui.settings.row').map((function(_this) {
        return function(el, row) {
          var settingName;
          row = $j(row);
          settingName = row.data('name');
          _this.storage[settingName] = {
            'id': row.attr('id'),
            'restore': row.find('input[type=text],input[type=checkbox], select, textarea').data('restore'),
            'showIf': row.data('show-if'),
            'hideIf': row.data('hide-if'),
            'checkbox': row.find('input[type=checkbox]').size() > 0,
            'visiblity': true
          };
          if (_this.storage[settingName]['checkbox']) {
            return _this.storage[settingName]['value'] = row.find('input[type=checkbox]').prop('checked');
          } else {
            return _this.storage[settingName]['value'] = row.find('input[type=text], select, textarea').val();
          }
        };
      })(this));
      this.initialize();
      this.search = new SemanticSettingsSearch('#search-wrapper');
    }

    SemanticSettings.prototype.initialize = function() {
      this.element.find(' select.select2').select2({
        width: 'resolve',
        placeholder: "Please select..."
      });
      this.element.find(' .checkbox').checkbox();
      this.element.find(' .colorpicker').each(function() {
        return new jscolor.color(document.getElementById($j(this).attr('id')));
      });
      this.element.find('.tinymce').each(function() {
        unsetTextareaToTinyMCE($j(this).attr('id'));
        return setTextareaToTinyMCE($j(this).attr('id'));
      });
      $j('#left-menu-fixed').sticky({
        context: this.selector,
        offset: $j('#top_nav').height() + $j('#horizontal_tabs_wrapper').height() + 10
      });
      this.element.find('.semantic_popup').popup({
        inline: true,
        delay: {
          show: 800,
          hide: 0
        }
      });
      this._setCallbacks();
      return this._updateVisiblity();
    };

    SemanticSettings.prototype._resetChanges = function() {
      var el, name, ref, value;
      ref = this.changes;
      for (name in ref) {
        value = ref[name];
        el = $j('#settings_' + name);
        if (el.prop('tagName') === 'INPUT' && el.prop('type') === 'checkbox') {
          if (this.storage[name]['restore']) {
            el.parent().checkbox('check');
          } else {
            el.parent().checkbox('uncheck');
          }
        } else {
          el.val(this.storage[name]['restore']);
          if (el.hasClass('tinymce')) {
            tinyMCE.get(el.attr('id')).setContent(this.storage[name]['restore']);
          }
        }
      }
      this.element.find('select.select2').each(function() {
        return $j(this).select2('val', $j(this).val());
      });
      this.element.find('.updated').removeClass('updated');
      this._updateInterface();
      return false;
    };

    SemanticSettings.prototype._saveChanges = function() {
      this.element.find('.setting_save_dimmer').addClass('active');
      showSpinner(this.element.find('#settings-apply-action'));
      $j.ajax($j('#edit_settings').prop('action'), {
        data: {
          'settings': this.changes
        },
        method: 'PUT',
        dataType: 'script',
        complete: (function(_this) {
          return function() {
            _this._applyChanges();
            _this.element.find('.setting_save_dimmer').removeClass('active');
            hideSpinner(_this.element.find('#settings-apply-action'));
            return _this._updateInterface();
          };
        })(this)
      });
      return false;
    };

    SemanticSettings.prototype._applyChanges = function() {
      var name, ref, value;
      ref = this.changes;
      for (name in ref) {
        value = ref[name];
        this.storage[name]['restore'] = value;
      }
      return this.element.find('.updated').removeClass('updated');
    };

    SemanticSettings.prototype._setCallbacks = function() {
      this.element.on('click', '#settings-reset-action', this._resetChanges);
      this.element.on('click', '#settings-apply-action', this._saveChanges);
      this.element.find('#settings-wrapper').on('change', 'input[type=text],input[type=checkbox], select, textarea', this._trackChanges);
      return true;
    };

    SemanticSettings.prototype._updateInterface = function() {
      this._updateSettingsCounter();
      this._updateVisiblity();
      return true;
    };

    SemanticSettings.prototype._updateSettingsCounter = function() {
      var count;
      count = this.element.find('.updated').size();
      if (count > 0) {
        $j('#settings-actions .button').removeClass('disabled');
        if ($j('#settings-actions-box').css('visibility') === "hidden") {
          $j('#settings-actions-box').transition('slide up');
        }
      } else {
        $j('#settings-actions .button').addClass('disabled');
        $j('#settings-actions-box').transition('slide up');
      }
      this.element.find('#total_updated_counter').text(count);
      return true;
    };

    SemanticSettings.prototype._trackChanges = function(event) {
      var el, label_el, name, restore, val;
      el = event.currentTarget;
      name = $j(el).prop('id').replace('settings_', '');
      if (this.storage[name]['checkbox']) {
        val = $j(el).prop('checked');
      } else {
        val = $j(el).val();
      }
      restore = this.storage[name]['restore'];
      this.storage[name]['value'] = val;
      label_el = $j('#' + $j(el).prop('id') + '_label');
      if ((this.storage[name]['checkbox'] && restore == $j(el).prop('checked')) || restore == val) {
        label_el.removeClass('updated');
        delete this.changes[name];
      } else {
        this.changes[name] = val;
        label_el.addClass('updated');
      }
      this._updateInterface();
      return true;
    };

    SemanticSettings.prototype._updateVisiblity = function() {
      var ancestor_value, dependency, name, options, ref, visibility;
      ref = this.storage;
      for (name in ref) {
        options = ref[name];
        if (this.storage[name]['showIf'] || this.storage[name]['hideIf']) {
          dependency = this.storage[(this.storage[name]['showIf'] || this.storage[name]['hideIf']).replace('?', '')];
          if (dependency) {
            if (dependency['checkbox']) {
              ancestor_value = dependency['value'];
            } else {
              ancestor_value = dependency['value'] !== void 0;
            }
            if (this.storage[name]['showIf']) {
              visibility = ancestor_value;
            }
            if (this.storage[name]['hideIf']) {
              visibility = !ancestor_value;
            }
            this.storage[name]['visiblity'] = visibility;
            if (!visibility) {
              $j('#' + this.storage[name]['id']).find('.dimmer').addClass('active zindex10');
            } else {
              $j('#' + this.storage[name]['id']).find('.dimmer').removeClass('active');
            }
          }
        }
      }
      return true;
    };

    SemanticSettings.prototype._disableSetting = function() {};

    true;

    return SemanticSettings;

  })();

  window.SemanticSettingsSearch = (function() {
    function SemanticSettingsSearch(selector) {
      this.selector = selector;
      this.intialize();
    }

    SemanticSettingsSearch.prototype.intialize = function() {
      return $j(this.selector).search({
        duration: 100,
        source: eval($j('#settings-input').data('source')),
        searchFields: ['title', 'description'],
        searchFullText: false,
        type: 'nonranked',
        onSelect: function(result, response) {
          var setting;
          setting = $j("#settings_" + result['setting'] + '_row');
          $j("html, body").animate({
            scrollTop: setting.offset().top - 200
          }, 1000);
          setting.scrollTop(1000);
          setting.effect("highlight", {}, 2000);
          $j('#search-settings').search('hide results');
          $j('#settings-input').val('');
          return true;
        }
      });
    };

    $j.fn.search.settings.regExp.beginsWith = '\\b';

    $j.fn.search.settings.templates.nonranked = function(response) {
      var highlight, sortedResults, val;
      sortedResults = response.results.sort(function(a, b) {
        if (a.rank > b.rank) {
          return 1;
        } else if (a.rank < b.rank) {
          return -1;
        } else {
          return 0;
        }
      });
      val = $j('#settings-input').val();
      highlight = $j('<div>').append($j('<span>').addClass('highlighted').text(val)).html();
      return $j.map(sortedResults, function(item) {
        return $j('<div>').append($j('<a>').addClass('result').append($j('<div>').addClass('content').append($j('<div>').addClass('title').html(item.title.replace(val, highlight)), $j('<div>').addClass('description').html(item.description.replace(val, highlight))))).html();
      });
    };

    return SemanticSettingsSearch;

  })();

  $j(function() {
    return $j('#semantic-settings').livequery(function() {
      return window.semanticSettings = new SemanticSettings('#semantic-settings');
    });
  });

}).call(this);
function popup_window(urlstr) {
  //www.google.com/NuPAGE lds sample buffer site:invitrogen.com
  window.newwindow = window.open(urlstr,'status',
                                 'height=800,width=800,status=no');
  return false;
}

/* currently hard_coded for expecting a checkbox id of 'history_line_item_XX' where XX is the id... eventually will factor out */
// 3-Aug-2018: this method appears to no longer be used -- see page `/requisition/manage_requested` for where it would be used.
function highlight_row(checkbox) {
  var tr;
  if (document.getElementById) {
      this_line_item = checkbox.id.split('_');
      this_line_item_id = this_line_item[3];
      tr = eval("document.getElementById(\"line_item_" + this_line_item_id + "\")");
      /*var tr = eval("document.getElementById(\"history_line_item_23\")");*/
      //window.alert(this_line_item);
   } else {
      return;
   }

   if (tr.style) {
      if (checkbox.checked) {
         checkbox.checked = true;
         tr.style.backgroundColor = "#FFF298";
      } else {
         checkbox.checked = false;
         tr.style.backgroundColor = "white";
      }
   }
}

function hideStatus(line_item){
  var lid = line_item.data('lid');

  if ($j("#save_status_icon_" + lid)){
    $j("#save_status_icon_" + lid).replaceWith("&nbsp;");
    return true;
  } else {
    return false;
  }
}

function toggleSelectedLineItem(cb){
  li_array = cb.id.split('_');
  li_id = li_array.pop();
  unloaded = Array();

  if (cb.checked) {
    $j("#line_item_" + li_id).find(".line_item").each( function(index, y){
			$j(y).addClass('selected');
		});
  } else {
    $j("#line_item_" + li_id).find(".line_item").each( function(index, y){
			$j(y).removeClass('selected');
		});
  }
}

function expandLineItem(ids, options) {
    li_array = ids.split(',');
    unloaded = Array();

    for (var i=0;i < li_array.length;i++){
      id=li_array[i];
      li = $j("#line_item_" + id);
      if ($j("#line_item_expansion_" + id).length < 1){
        unloaded.push(id);
      } else {
        $j("#line_item_expansion_" + id).show();
        $j("#collapse_" + id).show();
        $j("#expand_" + id).hide();
        if (options.js_callback){
          options.js_callback();
        }
      }
      li.addClass('open');
    }

    if (unloaded.length > 0) {
      for (i=0;i < unloaded.length;i++){
        $j("#expansion_spinner_" + unloaded[i]).show();
        $j("#expand_" + unloaded[i]).hide();
      }

      mr_active = $j("#managed_requested_items").length

      $j.ajax({
        url:'/line_item/load_expansion',
        async:true,
        dataType: 'script',
        complete:options.js_callback,
        data:"ids="+unloaded.join(",")+"&mr_active="+mr_active+"&"+options.orig_render})
    }

}

function toggleLineItem(ids, orig_render) {
    li_array = ids.split(',');
    unloaded = Array();

    for (var i=0;i < li_array.length;i++){
      id=li_array[i];
      if ($j("#expanded_line_item_line_" + id).is(':visible')) {
        collapseLineItem($j('#line_item_'+id));
      } else {
        expandLineItem(ids, orig_render);
      }
    }
}

function expandServiceItem(ids, sc_id, orig_render) {
    var li_array = ids.split(',');
    var unloaded = Array();

    for (var i=0;i < li_array.length;i++){
      var id = li_array[i];
      var li = $j("#service_item_" + id);
      if (!$j("#service_item_expansion_" + id).length){
        unloaded.push(id);
      } else {
        $j("#service_item_expansion_" + id).show();
        $j("#collapse_si_" + id).show();
        $j("#expand_si_" + id).hide();
      }
      li.addClass('open');
    }

    if (unloaded.length > 0) {
      for (var i=0;i < unloaded.length;i++){
        $j("#expansion_si_spinner_" + unloaded[i]).show();
        $j("#expand_si_" + unloaded[i]).hide();
      }
      $j.ajax('/service_item/load_expansion', {
        type: "GET",
        data: "ids=" + unloaded.join(",") + "&" + "sc_id=" + sc_id + "&" + orig_render
      });
    }

}

function expandDepartmentFund(ids, department_id , orig_render) {
    var li_array = ids.split(',');
    var unloaded = Array();

    for (var i=0;i < li_array.length;i++){
      var id = li_array[i];
      var li = $j("#department_fund_" + id);
      if (!$j("#department_fund_expansion_" + id).length){
        unloaded.push(id);
      } else {
        $j("#department_fund_expansion_" + id).show();
        $j("#collapse_df_" + id).show();
        $j("#expand_df_" + id).hide();
      }
      li.addClass('open');
    }

    if (unloaded.length > 0) {
      for (var i=0;i < unloaded.length;i++){
        $j("#expansion_df_spinner_" + unloaded[i]).show();
        $j("#expand_df_" + unloaded[i]).hide();
      }
      $j.ajax('/department_funds/load_expansion', {
        type: "POST",
        data: "ids=" + unloaded.join(",")+ "&" + "department_id=" + department_id + "&" + orig_render
      });
    }

}

function runAllForCol(service_id, attachment_id, orig_render, sid) {
  $j.ajax('/service_run/run_all_in_attachment_for_service',{
    type: 'GET',
    data: "asset_id="+service_id+"&attachment_id="+attachment_id+"&"+orig_render,
    beforeSend: function(){
      $j('#'+sid).show();
    },
    complete: function(){
     $j('#'+sid).hide();
    }
  });
}

function showSpinnerFor(service_id, attachment_id) {
    $j('#run_all_for_attachment_' + attachment_id + '_and_service_' + service_id).hide();
    $j('#run_all_spinner_for_attachment_' + attachment_id + '_and_service_' + service_id).show();
}

function hideSpinnerFor(service_id, attachment_id) {
    $j('#run_all_spinner_for_attachment_' + attachment_id + '_and_service_' + service_id).hide();
    $j('#run_all_for_attachment_' + attachment_id + '_and_service_' + service_id).show();
}

function moveRowToAvailableServices(elem, att_id)
{
    sel_table = $j('#selected_svcs_for_attachment_'+att_id);
    avail_table = $j('#remaining_svcs_for_attachment_'+att_id);
    link = '<a href="javascript:" onclick="moveRowToSelectedServices($j(this).parent(\'tr\'), '+att_id+')"><img src="/images/add.png" alt="add service"/></a>'
    $j(elem).find('a:first-child').replaceWith(link);
    avail_table.append(elem);
}


function moveRowToSelectedServices(elem, att_id)
{
    sel_table = $j('#selected_svcs_for_attachment_'+att_id);
    avail_table = $j('#remaining_svcs_for_attachment_'+att_id);
    link = '<a href="javascript:" onclick="moveRowToAvailableServices($j(this).parent(\'tr\'), '+att_id+')"><img src="/images/delete.png" alt="add service"/></a>'
    $j(elem).find('a:first-child').replaceWith(link);
    sel_table.append(elem);
}

function expandServiceRun(id, orig_render) {
   $j('#expand_sr_' + id).hide();
   dr = $j("#data_row_line_" + id);
   cell_context = dr.find('td:first-child');

   var bgColor = "#FFFCD8";
   $j.ajax('/service_run/load_expansion',{
    type: 'GET',
    data: "data_row_id="+id+"&"+orig_render,
    complete: function() {
      cell_context.css({backgroundColor:bgColor,borderBottom:'1px solid '+bgColor})
      $j('#expand_sr_' + id).hide();
    },
    beforeSend: function() {
      $j("#expansion_sr_spinner_" + id).show();
    }
   });
}

function collapseServiceRun(dr_id) {
    $j('#service_runs_for_'+dr_id).prev('tr').find('td').each(function(index, el){
      $j(el).css({borderBottom:'1px solid #C0C0C0'});
    });
    $j("#service_runs_for_" + dr_id).remove();
    $j("#collapse_sr_" + dr_id).hide();
    $j("#expand_sr_" + dr_id).parent('td').css({backgroundColor:"#FFFFFF"});
    $j("#expand_sr_" + dr_id).show();
}
// PS: stopped here
function incrementSpinnerDataRowCount(){
    $j('span.data_row_count').each(function(index, el){
      $j(el).html(parseInt(el.innerHTML) + 1);
    });
}

function decrementSpinnerDataRowCount(){
   $j('span.data_row_count').each(function(index, el){
      $j(el).html(parseInt(el.innerHTML) - 1);
   });
}

function collapseServiceItem(li) {
    li_array = li.attr('id').split('_');
    li_id = li_array.pop();

    Tipped.hide("#service_item_expansion_"+li_id+" .tipped_target");
    $j("#service_item_expansion_" + li_id).hide();
    $j("#collapse_si_" + li_id).hide();
    $j("#expand_si_" + li_id).show();
    Tipped.refresh('*');

    li.removeClass('open');
}

function collapseDepartmentFund(li) {
    li_array = li.attr('id').split('_');
    li_id = li_array.pop();

    Tipped.hide("#service_item_expansion_"+li_id+" .tipped_target");
    $j("#department_fund_expansion_" + li_id).hide();
    $j("#collapse_df_" + li_id).hide();
    $j("#expand_df_" + li_id).show();
    Tipped.refresh('*');

    li.removeClass('open');
}

function collapseLineItem(li) {
    li_array = li.attr('id').split('_');
    li_id = li_array.pop();

    $j("#line_item_expansion_" + li_id).hide();
    $j("#collapse_" + li_id).hide();
    $j("#expand_" + li_id).show();


    li.removeClass('open');
}

function collapseLineItemMaster(mli) {
    $j(' .child_recurrence_item_'+mli).hide();
    $j('#collapse_master_'+mli).hide();
    $j('#expand_master_'+mli).show();
}

function expandLineItemMaster (mli){
    $j('#expand_master_'+mli).hide();
    $j('#collapse_master_'+mli).show();
    $j(' .child_recurrence_item_'+mli).show();
}

function collapseAnimalOrder(order) {
    $j("#animal_order_expansion_" + order).hide();
    $j("#collapse_" + order).hide();
    $j("#expand_" + order).show();

    $j("animal_order_" + order).removeClass('open');
}

function expandAnimalOrder(order){
    $j("#collapse_" + order).show();
    $j("#expand_" + order).hide();
    $j('#animal_order_expansion_'+order).show()

    $j('#animal_order_' + order).addClass('open')
}


function rollOverHighlight(row,on) {

  var tr = row;
  split_tr_id = tr.id.split('_');
  this_line_item_id = split_tr_id[3];
  var checkbox = eval("document.getElementById(\"line_item_checkbox_" + this_line_item_id + "\")");

  off_color = (checkbox.checked)? "#fff298" : "white";

  row.style.backgroundColor=(!on)? off_color : "#efe";
}

/* currently hard_coded for expecting a checkbox id of 'history_line_item_XX' where XX is the id... eventually will factor out */
function highlight_tr_row(this_tr_row) {
   if (document.getElementById) {
      var tr = this_tr_row;
      split_tr_id = tr.id.split('_');
      this_line_item_id = split_tr_id[3];
      //window.alert(tr.id);
      var checkbox = eval("document.getElementById(\"line_item_checkbox_" + this_line_item_id + "\")");
      if (checkbox.checked) {
        checkbox.checked = false;
        tr.style.backgroundColor = "white";
      } else {
        checkbox.checked = true;
        tr.style.backgroundColor = "#FFF298";
      }

   } else {
      return;
   }
}

function highlight_table_row(tr_div_id, new_color) {
   if (document.getElementById) {
      var tr = eval("document.getElementById(\"" + tr_div_id + "\")");
      tr.style.backgroundColor = new_color;
   } else {
      return;
   }
}

/* currently hard_coded for expecting a checkbox id of 'history_line_item_XX' where XX is the id... eventually will factor out */
function highlight_tr_row_with_id(tr_id) {
   if (document.getElementById) {
      var tr = eval("document.getElementById(\"line_item_" + tr_id + "\")");
      var checkbox = eval("document.getElementById(\"line_item_checkbox_" + tr_id + "\")");
      if (checkbox.checked) {
        checkbox.checked = false;
        tr.style.backgroundColor = "white";
      } else {
        checkbox.checked = true;
        tr.style.backgroundColor = "#FFF298";
      }

   } else {
      return;
   }
}

//http://somethingscripted.wordpress.com/2006/11/14/new-blog-bonus-javascript-snippet/
//<% cancel_note_text_id = "cancel_note_" + history_line_item.id.to_s %>
//<input type="text" name="cancelled_note" id="<%= cancel_note_text_id %>" onfocus="textChange('<%= cancel_note_text_id %>', 'enter cancel note here');" onblur="textChange('<%= cancel_note_text_id %>', 'enter cancel note here');" value="enter cancel note here" />
function textChange(elementID, defaultText)
{
   var element = document.getElementById(elementID);

   if(element.value == defaultText)
   {
      element.value = "";
   }
   else if(element.value == "")
   {
      element.value = defaultText;
   }
}

    function sortTableBy(sortColumn, columnHeaders, controller, action_name) {
      var direction;

      //columnHeaders = ["created_at_integer", "product_name", "owner_name", "quantity", "extended_price", "status"];
      $j('#spinner_description').html("Sorting");
      $j('#filter_spinner').show();

      for (var i = 0; i < columnHeaders.length; i++) {

        //window.alert(columnHeaders[i]);

        if (columnHeaders[i].length > 0) {

          sort_header_direction_span_name = "#sort_" + columnHeaders[i] + "_direction";
          sort_header_direction_image_name = "#sort_" + columnHeaders[i] + "_direction_image";
          sort_header_th = "#th_" + columnHeaders[i];

          if (columnHeaders[i] == sortColumn) {
            current_direction = $j(sort_header_direction_span_name).html();

            if (current_direction == "ASC") {
              direction = "DESC";
              image_name = "&#9660;";
            } else {
              direction = "ASC";
              image_name = "&#9650;";
            }

            $j(sort_header_th).css('background', "#CBEB98;");
            $j(sort_header_direction_span_name).html(direction);
            $j(sort_header_direction_image_name).html(image_name);
            $j('#filter_sort_category').val(sortColumn);// + "_sort";
            $j('#filter_sort_direction').val(direction);

          } else {
            // turn off arrows on other headers

            $j(sort_header_th).css('background', "#fff;");
            $j(sort_header_direction_span_name).html('');
            $j(sort_header_direction_image_name).html('');

          }
        }


      }

      var controller_action_url = "/" + controller + "/" + action_name;

      $j.ajax( controller_action_url, {
        type: 'GET',
        data: $j('#form_filter_options input').serializeArray()
      });

    }

    // Checks or unchecks checkboxes for use specifically with the filtering stuff
    function checkUncheckAllLink(divName, checked, controller, action_name) {
      var theForm = document.getElementById(divName), z = 0;
      theForm = theForm.getElementsByTagName("input");

      var controller_action_url = "/" + controller + "/" + action_name;

      for (var i = 0; i < theForm.length; i++) {
        myType = theForm[i].getAttribute("type");
        if (myType == "checkbox") {
          theForm[i].checked = checked;
        }
      }

      $j('#spinner_description').html('Filtering');

      $j('#filter_spinner').show();
      $j.ajax({url: controller_action_url, data: $j('#form_filter_options').serialize(), type: 'POST'});

    }

    // A generic version of checking or unchecking all check boxes
    function ToggleCheckBoxes(divName, checked) {
      var theForm = document.getElementById(divName), z = 0;
      theForm = theForm.getElementsByTagName("input");
      for (var i = 0; i < theForm.length; i++) {
        myType = theForm[i].getAttribute("type");
        if (myType == "checkbox") {
          theForm[i].checked = checked;
        }
      }
    }


    // A generic version of checking or unchecking all check boxes
    function ToggleRadioButton(divName, checked) {
      var theForm = document.getElementById(divName), z = 0;
      theForm = theForm.getElementsByTagName("input");
      for (var i = 0; i < theForm.length; i++) {
        myType = theForm[i].getAttribute("type");
        myValue = theForm[i].getAttribute("value");
        if (myType == "radio" && myValue == checked) {
          theForm[i].checked = true;
        }
      }
    }

    // Enables or disables checkboxes
    function DisableAllLink(divName, disabled, controller, action_name) {
      var theForm = document.getElementById(divName), z = 0;
      theForm = theForm.getElementsByTagName("input");

      var controller_action_url = "/" + controller + "/" + action_name;

      for (var i = 0; i < theForm.length; i++) {
        myType = theForm[i].getAttribute("type");
        if (myType == "checkbox") {
          theForm[i].disabled = disabled;
        }
      }

      $j('#spinner_description').html("Filtering");

      $j('#filter_spinner').show();
      $j.ajax({url: controller_action_url, data: $j('#form_filter_options').serialize(), type: 'POST'});
    }

    function simpleToggle(target_id, key){
      var target = $j(target_id);
      if (key.checked)
        target.show();
      else
        target.hide();
    }

    // Toggles if divs are hidden or not can also just tell it to turn it on
    function ToggleDiv(divName, onofftoggle){
        var elem, vis;
        if( document.getElementById ) // this is the way the standards work
            elem = document.getElementById( divName );
        else if( document.all ) // this is the way old msie versions work
            elem = document.all[divName];
        else if( document.layers ) // this is the way nn4 works
            elem = document.layers[divName];
        vis = elem.style;
        // if the style.display value is blank we try to figure it out here
        if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
            vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'':'none';

        if( onofftoggle=='toggle' || onofftoggle=='')
            vis.display = (vis.display==''||vis.display=='block')?'none':'';
        else if( onofftoggle=='on')
            vis.display = '';
        else if( onofftoggle=='off')
            vis.display = 'none';
    }

    // if they check email box, we should check the ilab inbox checkbox
    // if they uncheck the ilab inbox checkbox, we will uncheck the email checkbox
    function validateNotificationPreferences(pref_type, notification_id) {

      email_checkbox = $j("#email_preference_" + notification_id)
      ilabinbox_checkbox = $j("#commage_preference_" + notification_id)


      // checked the email box
      if (pref_type == "e") {
        if (email_checkbox.is(':checked')) {
          $j(ilabinbox_checkbox).prop('checked', true)
        }
        if (!(ilabinbox_checkbox.is(':checked'))) {
          $j(email_checkbox).prop('checked', false)
        }
      } else {
      // checked the ilab inbox box
        if (!(ilabinbox_checkbox.is(':checked'))) {
          $j(email_checkbox).prop('checked', false)
        }
      }


    }

    function checkUncheckAll(divName, checked) {
      var theForm = document.getElementById(divName), z = 0;
      theForm = theForm.getElementsByTagName("input");

      for (var i = 0; i < theForm.length; i++) {
        myType = theForm[i].getAttribute("type");
        if (myType == "checkbox") {
          theForm[i].checked = checked; //removed on 2007-10-18 (SG); highlight_row does this for us..
          highlight_row(theForm[i]);
        }
      }

    }

    function checkJustOneInSet(myDOMid, divName, controller, action_name) {
      var theForm = document.getElementById(divName), z = 0;
      theForm = theForm.getElementsByTagName("input");

      $j('#spinner_description').html("Filtering");

      for (var i = 0; i < theForm.length; i++) {
        myType = theForm[i].getAttribute("type");
        if ((myType == "checkbox")){

          myName = theForm[i].getAttribute("id");
          if (myDOMid == theForm[i].getAttribute("id")) {
            theForm[i].checked = 1;
          } else {
            theForm[i].checked = 0;
          }

        }
      }
      $j('#filter_spinner').show();

      var controller_action_url = "/" + controller + "/" + action_name;
      $j.ajax({url: controller_action_url, data: $j('#form_filter_options').serialize(), type: 'POST'});
    }

    function selectCustomDateRange(divName, selectName, select_value){
      var theForm = document.getElementById(divName), z = 0;
      theForm = theForm.getElementsByTagName("select");
      //window.alert(selectName);
      for (var i = 0; i < theForm.length; i++) {

        myName = theForm[i].getAttribute("id");
        //window.alert(myName);
        if (myName == selectName) {
          theForm[i].selectedIndex = select_value;
        }
      }
    }

    function setDaySpan(date_index, flag) {

        var day_span = 0;
        if (flag > 0) {
          day_span = date_index - $j('#filter_index_min').html() + 1;
          $j('#span_day_range').val(day_span + " days");
          $j('#filter_index_max').val(date_index);
        } else {
          day_span = $j('#filter_index_max').html() - date_index + 1;
          $j('#span_day_range').html(day_span + " days");
          $j('#filter_index_min').html(date_index);
        }
     }

    function changeDateSlider(minDayValue, maxDayValue){
      $j('#min_date_handle').css('left', minDayValue + "px;");
      $j('#max_date_handle').css('left', maxDayValue + "px;");
    }

    function onChangeDateSlider(v, min_max_flag, url_controller, url_action) {


      if (min_max_flag > 0) { // then we changed the right slider
        //selectCustomDateRange('filter_date_panel', 'filter_dates_range', 3);
        $j('#print_max_date').html(''+returndatestr(v, 1));
        $j('#filter_dates_max').val(''+returndatestr(v, 0));
      } else {
        $j('#print_min_date').html(''+returndatestr(v, 1));
        $j('#filter_dates_min').val(''+returndatestr(v, 0));
      }
      setDaySpan(v, min_max_flag);

      $j('#spinner_description').html("Filtering");
      $j('#filter_spinner').show();

      var controller_action_url = "/" + url_controller + "/" + action_name;
      $j.ajax({url: controller_action_url, data: $j('#form_filter_options').serialize(), type: 'POST'});
      return false;
    }

      //mutliple submit button disable
   function toggleSubmitButton(btnId, makeActive, submitLabel)
   {
      var submitBtn = document.getElementById(btnId);

      if (makeActive) {
        submitBtn.disabled = false;
        submitBtn.value = submitLabel;
      } else {
        submitBtn.disabled = true;
        submitBtn.value = 'Submitting';
      }
   }

function stripNonNum(str) {
  return str.replace(/[^0-9.]/g, '');
}

function checkDefaultContacts() {
  problemCompanies = []; // Problem companies have no default contact and multiple contacts
  warningCompanies = []; // Warning companies have no default contact and only one contact

  // Get lab contact tables, exclude add contact and public contact tables
  labContactTables = $j('#contacts_panel').find('table[id ^= list_contact_div_]:not([id $= -1])');

  labContactTables.each(function (index, table) {
    var $contactRows = $j(table).find('tr:visible');
    var companyNames = $contactRows
      .map(function(index, row) { return $j(row).attr('company');})
      .toArray()
      .filter(function(company, index, array) {
        return array.indexOf(company) === index; // Ensure array elements are unique.
      });

    companyNames.forEach(function (companyName) {
      var companyContactRows = $contactRows.filter("[company='" + companyName + "']");

      if (!companyContactRows.filter("[default='true']").length) {
        if (companyContactRows.length == 1) {
          warningCompanies.push(companyName);
        } else {
          problemCompanies.push(companyName);
        }
      }
    });
  });

  if (problemCompanies.length) {
    if (problemCompanies.length > 1) {
      alert('Problem with contacts for: ' + problemCompanies.join(', ') + '.  These companies have multiple contacts without any contact marked as the default.  Click the company names to mark default contacts for use in PDF templates.');
    } else {
      alert('Problem with contacts for ' + problemCompanies.join(', ') + '.  This company has multiple contacts without any contact marked as the default.  Click the company name to mark a default contact for use in PDF templates.');
    }
    return false;
  } else {
    return true;
  }
}

/* currently hard coded for asset menu */
function highlight_element(new_asset_category) {
   if (document.getElementById) {
      var this_span = eval("document.getElementById(\"cb_add_" + new_asset_category + "\")");
      var checkbox = eval("document.getElementById(\"checkboxes_" + new_asset_category + "\")");

      if (checkbox.checked) {
        checkbox.checked = true;
        this_span.style.backgroundColor = "#ffffdd";
        $j('#container_' + new_asset_category).show();
        $j('#add_' + new_asset_category).show();
        $j("#add_" + new_asset_category + "_twisty").html("&#9660;");
        $j('html, body').animate({ scrollTop: $j("#container_" + new_asset_category).offset().top}, 2000);
      } else {
        checkbox.checked = false;
        this_span.style.backgroundColor = "#FFFFFF";
      }

   } else {
      return;
   }
}

/* OBSOLETE INVENTORY CODE */
function expandInstance(ids, options) {
  li_array = ids.split(',');
  unloaded = Array();

  for (var i=0;i < li_array.length;i++){
    id=li_array[i];
    li = $j("#instance_" + id);
    if ($j("#instance_expansion_" + id).length === 0){
      unloaded.push(id);
    } else {
      $j("#instance_expansion_" + id).show();
      $j("#collapse_" + id).show();
      $j("#expand_" + id).hide();
      if (options.js_callback){
        options.js_callback();
      }
    }
    li.addClass('open');
  }

  if (unloaded.length > 0) {
    for (var i=0;i < unloaded.length;i++){
      $j("#expansion_spinner_" + unloaded[i]).show();
      $j("#expand_" + unloaded[i]).hide();
    }
    $j.ajax({url: '/instance/load_expansion', data: "ids="+unloaded.join(",")+"&"+options.orig_render, type: 'POST', complete: options.js_callback});
  }
}

function collapseInstance(li) {
    li_array = li.attr('id').split('_');
    li_id = li_array.pop();

    $j("#instance_expansion_" + li_id).hide();
    $j("#collapse_" + li_id).hide();
    $j("#expand_" + li_id).show();


    li.removeClass('open');
}

function toggleInstance(li) {
    li_array = li.attr('id').split('_');
    li_id = li_array.pop();

    if ($j("#expanded_instance_" + li_id).is(':visible')) {
      $j("#expanded_instance_" + li_id).hide();
      $j("#collapse_" + li_id).hide();
      $j("#expand_" + li_id).show();
      li.removeClass('open');
    } else {
      $j("#expanded_instance_" + li_id).show();
      $j("#collapse_" + li_id).show();
      $j("#expand_" + li_id).hide();

      li.addClass('open');
    }

    return true;
}

function process(id) {
  var $process = $j("#" + id + "_process");
  var $save = $j("#" + id + "_save");
  var $cancel = $j("#" + id + "_cancel");

  if ($process.length) {$process.show();}

  if ($save.length) {
    $save.addClass('disabled').prop('disabled', 'disabled');
    $save.attr("onclickdisabled", $save.attr("onclick"));
    $save.attr("onclick", "")
    $save.attr("hrefdisabled", $save.attr("href"));
    $save.attr("href", "#")
  }

  if ($cancel.length) {
    $cancel.addClass('disabled').prop('disabled', 'disabled');
    $cancel.attr("onclickdisabled", $cancel.attr("onclick"));
    $cancel.attr("onclick", "")
    $cancel.attr("hrefdisabled", $cancel.attr("href"));
    $cancel.attr("href", "#")
  }

  return true;
}

function unprocess(id) {
  var $process = $j("#" + id + "_process");
  var $save = $j("#" + id + "_save");
  var $cancel = $j("#" + id + "_cancel");

  if ($process.length) {$process.hide();}

  if ($save.length) {
    $save.removeClass('disabled').prop('disabled', false);
    $save.attr("onclick", $save.attr("onclickdisabled"));
    $save.attr("href", $save.attr("hrefdisabled"));
  }

  if ($cancel.length) {
    $cancel.removeClass('disabled').prop('disabled', false);
    $cancel.attr("onclick", $cancel.attr("onclickdisabled"));
    $cancel.attr("href", $cancel.attr("hrefdisabled"));
  }

  return true;
}

var new_sc_contact_num = 8;

function add_sc_contact_on_new() {
	var new_row = $j('#sc_contact_1').html();
	new_sc_contact_num += 1;
	new_row = "<tr id='sc_contact_"+ new_sc_contact_num + "'>" + new_row + "</tr>";
	$j('#sc_contacts').append(new_row);

	var row = $j("#sc_contact_"+ new_sc_contact_num);
	row.children(".name").attr('name', "contact["+new_sc_contact_num+"][name]");
	row.children(".role").attr('name', "contact["+new_sc_contact_num+"][role]");
	row.children(".phone").attr('name', "contact["+new_sc_contact_num+"][phone]");
	row.children(".email").attr('name', "contact["+new_sc_contact_num+"][email]");
	row.children(".location").attr('name', "contact["+new_sc_contact_num+"][location]");

	row.addClass("hide_add_button");

	return true;
}

function remove_sc_contact_on_new(obj) {
	obj.remove();
}

function checkSCForm(form){
	success = true;
  var a = null;
  $j(form).find('.required').each(function(){
    a = $j(this)
    $j(this).find('input, textarea').each(function(){

      if($j(this).prop("tagName")=="TEXTAREA"){
        $j(this).val(tinyMCE.get($j(this).attr('id')).getContent())
      }
      if($j(this).val()==""){
        a.addClass('error');
        success = false
      } else {
        a.removeClass('error')
      }
    })
  })

	if (success) {$j('#create_service_center_save').attr("disabled", "true");}

	return success;
}

function checkSPTForm(form){
	success = true;

	$j(form).find('.required').each( function(index, s){
		$j(s).find('input, textarea, select').each( function(index, y){
			if (y.val()){
				$j(s).removeClass('error');
			} else {
				$j(s).addClass('error');
				success = false;
			}
    });
  });

	return success;
}

function updateSPTPrices(){
  var running_total;
  var new_tot;
  var price_types_on_page = Array();
  $j("[id^='price_type_value']").each(function (index, s){
      $j(s).val('0');
      price_types_on_page.push(s.id.split("_").pop());
    }
  );

  $j("[id^='price_type_warning']").each( function (index, s){$j(s).hide();} );

  $j('prices').each(function(index, p) {
    for(a=0;a<price_types_on_page.length;++a) {
      var $p = $j(p);
      var i = price_types_on_page[a];
      var q;
      var quantity;
      var val = $p.attr(String(i));
      if (val){
        if (q= $p.attr("q"))
          quantity = Number(q);
        else
          quantity = 1;
        val = Number(val) * quantity;
        running_total = $j('#price_type_value_'+i).val();
        new_tot = CurrencyFormatted(Number(val) + Number(running_total));
        $j('#price_type_value_'+i).val(new_tot);
      } else {
        $j('#price_type_warning_'+i).show();
      }
    }
  });

  for(a=0;a<price_types_on_page.length;++a){
    i = price_types_on_page[a];
    running_total = $j('#price_type_value_'+i).val();
    running_total = parseFloat(running_total) || 0;

    if ($j('#select_retainer_type').val() == "1"){
      new_tot = (parseFloat($j('#other_costs').val() || 0) * 0.01) * running_total + running_total;
    } else {
      new_tot = parseFloat($j('#other_costs').val() || 0) + running_total;
    }
    new_tot = CurrencyFormatted(new_tot);
    $j('#price_type_value_'+i).val(new_tot);
  }
}

function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) {i = 0.00;}
	var minus = '';
	if(i < 0) {minus = '-';}
	i = Math.abs(i);
	i = Math.round(i*100 + .001) / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) {s += '.00';}
	if(s.indexOf('.') == (s.length - 2)) {s += '0';}
	s = minus + s;
	return s;
}

function findPos(obj){
  var posX = obj.offsetLeft;
  var posY = obj.offsetTop;
  while(obj.offsetParent){
  posX=posX+obj.offsetParent.offsetLeft;
  posY=posY+obj.offsetParent.offsetTop;
  if(obj==document.getElementsByTagName('body')[0]){break}
  else{obj=obj.offsetParent;}
  }
  return [posX,posY]
}

function setPos(to, from){
  var to_pos = findPos(to);
  $j(from).css({
    top: to_pos[1]+'px',
    left: to_pos[0]-55+'px'
  });
}

//http://www.jacklmoore.com/notes/rounding-in-javascript/
//https://stackoverflow.com/a/18358056/666053
function round(value, decimals) {
    return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

function updateNewSIPrices(div){
  const $div = $j('#' + div);
  var running_total = 0;
  var extended_cost = 0;
  var val = 0;
  var qty = 0;

  if ($div.length){
    $div.find('.ilab_price').each(function(index, p) {
      val = parseFloat($j(p).attr('cart_price'));
      mult = parseFloat($j(p).attr('multiplier'));
      tax_amount = parseFloat($j(p).attr('unit_tax_amount'));
      if ( $j(p).closest(".line_item").find(".quantity").length ) {
        qty = parseFloat($j(p).closest(".line_item").find(".quantity").val() || $j(p).closest(".line_item").find(".quantity").html());
      }
      else {
        qty = 0
      }

      extended_cost = val*qty*mult;
      extended_cost += tax_amount * qty * mult;

      if (extended_cost){
        running_total += round(extended_cost, 2 );
      }
    });

    if($j('#new_service_item_form #events_total').length){
      running_total += parseFloat($j('#new_service_item_form #events_total').val())
    }
    $j('.special_request_item').each(function() {
      var total_price = parseFloat($j('td[id^=line_total]', this).data('totalPrice'));
      running_total += total_price;
    });

    if ($j('#select_retainer_type_new_si').length){
      if ($j('#select_retainer_type_new_si').val() == "1"){
        new_tot = (parseFloat($j('#other_costs_new_si').val() || 0) * 0.01) * running_total + running_total;
        $j('#percentage_symbol_sign').show();
        $j('#currency_symbol_sign').hide();
      } else {
        new_tot = parseFloat($j('#other_costs_new_si').val()) + running_total;
        $j('#currency_symbol_sign').show();
        $j('#percentage_symbol_sign').hide();
      }

    } else {
      new_tot = running_total;
    }

    new_tot = CurrencyFormatted(new_tot)

    var $projected_cost_input = $j("[name='service_item[projected_cost]']");
    if ($projected_cost_input.length && $projected_cost_input.val() !== new_tot){
      $projected_cost_input.val(new_tot);
    }
  }
}

function addInput(to_div, display_name, input_name, value){
  new_element = "<div class='location clearright' style='margin:2px;padding:2px;'>";
  new_element += display_name;
  new_element += "<img style='float:right;' src='/images/delete.png' onclick='$j(this).parent().remove();' />";
  new_element += "<input type='hidden' name='"+input_name+"' value='"+value+"' />";
  new_element += "</div>";

  new $j('#' + to_div).append(new_element);
  return true;
}

function getSelectedOptionDisplayText(select_box){
  return select_box.find('option:selected').text();
}

function updateServiceItemTotalSelectedPrice(from, to) {
  elements_with_price_attr = $j(from).find("[id^='line_item_checkbox_']");
  total = 0;
  elements_with_price_attr.each( function (index, s) {
    if (s.checked){
     total += parseFloat($j(s).attr('price'));
    }
  });
  $j(to).html(CurrencyFormatted(total));
}

function createSpinner() {
  return $j('<img class="spinner" src="/images/spinner_arrow_spin.gif" />');
}

$j(document).ready( function() {
  // the element in which we will observe all clicks and capture
  // ones originating from pagination links
  var container = $j(document.body)

  if (container.length) {
    var img = new Image;
    img.src = '/images/spinner.gif';

    container.on('click', function(e) {
      var el = $j(e.target);
      if (el.is('.pagination.ajax a')) {
        var paginate_div = el.parent('.pagination');

        other_params="";
        if (paginate_div.attr('submit')){
          form = $j("#" + paginate_div.attr('submit')).find('form');

          // e.g. "utf8=%E2%9C%93&filters%5Bwhen%5D=all&filters%5Bwhat%5D=all&filters%5Bwho%5D=all&filters%5Bstatus%5D=all&commit=Filter!"
          other_params = form.serialize();
        }

        method_pass = 'get';
        if (paginate_div.attr('method_pass')){
          method_pass = paginate_div.attr('method_pass');
        }

        loaded_string="";
        if (paginate_div.attr('loaded')){
          loaded_string = paginate_div.attr('loaded');
        }

        loading_string="";
        if (paginate_div.attr('loading')){
          loading_string = paginate_div.attr('loading');
        }

        update_div="";
        if (paginate_div.attr('update')){
          update_div = paginate_div.attr('update');
        }

        spinner = createSpinner();
        paginate_div.append(spinner);

        spinner = $j(spinner);

        // hack for semantic ui paginator. do not show preloader
        if(paginate_div.hasClass('ui')) {
          spinner.hide();
        }

        if (update_div){
          $j.ajax({url: el.attr('href'),
                  data: other_params,
                  type: method_pass,
                  beforeSend: function(){eval(loading_string);},
                  complete: function(resp){spinner.hide();$j('#'+update_div).html(resp.responseText);}
                });
        }else{
          $j.ajax({url: el.attr('href'),
                  data: other_params,
                  dataType: 'script',
                  type: method_pass,
                  beforeSend: function(){eval(loading_string);},
                  complete: function(resp){spinner.hide();eval(loaded_string);}
                });
        }

        e.stopPropagation();
        e.preventDefault();
      }
    })
  }

  $j('a.lightview')
    .filter(function(index, el) { return $j(el).attr('href').match(/\.(gif|jpg|jpeg|tiff|png)$/i) })
    .each(function(index, el) {
      $j(el).magnificPopup({
        type:'image',
        closeMarkup: '<button class="ui mfp-close"></button>'
      })
    });
})

function ehsLocTip(){
   $j(".ehs_loc_sel").each(
      function(index, s){
         var form = $j(s).parent('form');
         var id = form.attr('id').substr(form.id.lastIndexOf("_") + 1);

         var instance_ids_input = new Array();
         instance_ids_input = form.find('[type="hidden"][name="instance_ids"]');

         var instance_ids = new Array();
         instance_ids = $j(instance_ids_input).val().split(',');

         $j(s).on('click',function() {
            $j.ajax({
              url: '/location/quick_update_select',
              data: {instance_id: instance_ids[0], is_ehs: true, show_delete:false},
              dataType: 'script',
              success: function(result) {
                  $j('#location_selector').html(result);
              }
            });

            locsel.setLocation(this.offset().top - 5, this.offset().left + 50);
            $j('#instance_ids_list').val(instance_ids.join(","));

            if ($j('#id_tag').length) {
              $j('#id_tag').val(id);
            } else {
              $j('#instance_ids_list').insertAfter("<input id=\"id_tag\" type=\"hidden\" value="+id+"></input>");
            }
            locsel.show();
         });
      }
   );
}

function cart_line_item_destination_location(){
   $j(".li_destination_location").each(
      function(index, s){
      var id = s.id
      s.on('click',function() {
        $j.ajax({
          url: '/location/quick_update_select',
          data: {root: true, show_delete:false, is_cart: true},
          dataType: 'script',
          success: function(result) {
              $j('#location_selector').html(result);
          }
        });
         locsel.setLocation(this.offset().top - 5, this.offset().left + 50);

         if ($j('#id_tag').length) {
          $j('#id_tag').val(id);
         }
         else {
          $j('#instance_ids_list').insertAfter("<input id=\"id_tag\" type=\"hidden\" value="+id+"></input>");
         }

         locsel.show();
      });
      }
   );
}

function checkedInstanceIds(){
  checked = Array();
  $j(".instance_checkboxes").each( function(s){
    if ($j(s).prop('checked')){
      checked.push($j(s).attr('instance_id'));
    }
  });
  return checked;
}

function uncheckAll(class_name){
  $j("."+class_name).prop('checked', false);
  afterCheckSelectedInstance();
  return true;
}

function toggleSelectedInstance(cb){
  li_array = cb.id.split('_');
  li_id = li_array.pop();

  if (cb.checked) {
    $j("#instance_" + li_id).addClass('selected');
  } else {
    $j("#instance_" + li_id).removeClass('selected');
  }
  afterCheckSelectedInstance();
}

function afterCheckSelectedInstance(){
  var instance_location_input = $j("#instance_ids_list");
  if (instance_location_input.length) {
    instance_location_input.val(checkedInstanceIds().join(","));
    inventory_size = (checkedInstanceIds().length > 0) ? checkedInstanceIds().length : 1;
    $j('#instance_list').html("You are changing the location for " + inventory_size + " pieces of inventory.");
  }
}

function setiLabNotice(notice_text){
  $j('#ilab_notice_text').html(notice_text);
  $j('#ilab_notice').slideDown();
  setTimeout("hideiLabNotice()", 12000);
  return false;
}

function hideiLabNotice(){
  $j('#ilab_notice').slideUp();
  $j('#ilab_notice').hide();
  return false;
}

$j(document).ready( function() {
  $j(".advanced_text_editor").each( function(index, e){
	  setTextareaToTinyMCE(e.id);
  });
});

$j(document).on("submit", function(event) {
  $j(event.target).find(".advanced_text_editor").each( function(index, e){
    unsetTextareaToTinyMCE(e.id);
  });
});

function toggle_product_search_facet(el){
  cb = el.select('input').first();
  if (!cb.checked){
    cb.checked = true;
    el.addClass('landing_facet_selected');
  } else {
    cb.checked = false;
    el.removeClass('landing_facet_selected');
  }
  return true;
}

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}

$j(document).ready( function() {
  if ($j('#order_by_input').length && $j('#order_by_input_display').length) {
    $j('#order_by_input_display').val( $j('#order_by_input').val() );
  }
});

function submitServiceItemSearch(){
  spinner = new Element('img', {src: '/images/spinner_arrow_spin.gif', 'class': 'spinner'});
  $j.ajax({url: '/service_item/search', type: 'POST', data: $j('#service_items_filter_panel').serialize(), complete: function(){spinner.hide();} });
}

function observeCustomForm(cfid, template_fields){
  customFormObserver(cfid, template_fields);
	$j("#custom_form_"+cfid+"_fields").find('input,textarea,select').change(function(form, value) {customFormObserver(cfid, template_fields)});
}

function customFormEvaluateOr(showif, template_fields){
  var result = false;
  var show_if_conditions = showif.split('||')
  $j.each(show_if_conditions, function(index, condition) {
   if (condition.indexOf('&&')>0){
     if (customFormEvaluateAnd(condition, template_fields)){
       result = true;
     }
   } else {
     var pieces = condition.split('=');
     if (pieces.length > 1) {
       var field_name = pieces[0].trim();
       var field_value = pieces[1].trim();
       for (var i = 0; i < template_fields.length; i++) {
         if ((template_fields[i].identifier == field_name) && (template_fields[i].value.indexOf(field_value) >= 0)) {
           result = true;
           break;
         }
       }
     }
   }
  });
  return result;
}

function customFormEvaluateAnd(showif, template_fields){
  var results = [];
  var show_if_conditions = showif.split('&&');
  $j.each(show_if_conditions, function(index, condition) {
          if (condition.split('=').length < 2) {return;} // ignore broken condition!
          var field_name = condition.split('=')[0].trim();
          var field_value = condition.split('=')[1].trim();

          for (var i=0; i<template_fields.length; i++){
              if (template_fields[i].identifier == field_name){
                  if (template_fields[i].value.indexOf(field_value)>=0){
                      results.push(true);
                  } else {
                      results.push(false);
                  }
              }
          }
        });

   if ((results.length == showif.split('&&').length) && results.every(function (val) { return val === true; })) {
    return true;
  } else {
    return false;
  }
}

function buildTemplateFieldValues(cfid,template_fields)
{
    for(var i=0; i<template_fields.length; i++){
        template_fields[i].value = [];
        if ( $j('#cf_'+cfid+'_template_fields_'+i).length) {
          var tf_values = $j('#cf_'+cfid+'_template_fields_'+i).find('[name^="template_fields['+i+'][value]"]');
          tf_values.each(function(index, tf_value){
              if ((tf_values.length == 1 && tf_value.type != 'checkbox') || tf_value.checked){
                  template_fields[i].value.push(tf_value.value.trim())
              }
          });
        }
    }
    return template_fields
}

function customFormObserver(cfid, template_fields){
  template_fields = buildTemplateFieldValues(cfid, template_fields);

  for(var i=0; i<template_fields.length; i++){
    if (template_fields[i].show_if){
        if (customFormEvaluateOr(template_fields[i].show_if,template_fields)){
            $j('#cf_'+cfid+'_template_fields_'+i).show();
            rerenderHandsontable($j('#cf_'+cfid+'_template_fields_'+i));
            if($j('#cf_sub_'+cfid+'_template_fields_'+i).length){
                $j('#cf_sub_'+cfid+'_template_fields_'+i).show();
                rerenderHandsontable($j('#cf_sub_'+cfid+'_template_fields_'+i));
            }
        } else {
            if ($j('#cf_'+cfid+'_template_fields_'+i).length) {
              $j('#cf_'+cfid+'_template_fields_'+i).hide();}
            if($j('#cf_sub_'+cfid+'_template_fields_'+i).length){
                $j('#cf_sub_'+cfid+'_template_fields_'+i).hide();
            }
        }
    }
  }
}

// ReRender Handsontable, because it doesn't render when parent is hidden
function rerenderHandsontable(object){
  $j(object).find('.data_table_custom_form.handsontable').each(function(){
    if ($j(this).data('handsontable')) { $j(this).data('handsontable').render() }
  })
}

function limitText(limitField, limitCount, limitNum) {
              if (limitField.value.length > limitNum) {
                limitField.value = limitField.value.substring(0, limitNum);
              } else {
                limitCount.value = limitNum - limitField.value.length;
              }
          }

function getBarcodePrintQueryString(){
    var instances_str = ""
    $j(".instance_checkboxes").each(function(index, ele){
      if ($j(ele).is(':checked')) {
        inst_id = $j(ele).attr('id').match(/\d+$/);
        if (instances_str != "")
          instances_str += "&";
        instances_str += "instance_checkbox["+inst_id+"]=1";
      }
    });
    return instances_str;
}

function sortReportingTable (handle, column_type) {
  var table = handle.parentNode.parentNode.parentNode.parentNode;
  var row = handle.parentNode.parentNode;

  column_index = [].indexOf.call(row.childNodes, handle.parentNode);

  table.sortHistory = table.sortHistory || {};
  var direction = (table.sortHistory[column_index] || -1) * -1;
  table.sortHistory[column_index] = direction;

  for (var i=0; i<row.childNodes.length; i++) {
    var sortLink = row.childNodes[i].childNodes[0];
    sortLink.originalHeader = sortLink.originalHeader || sortLink.innerHTML;
    sortLink.arrowHeader = '';
    sortLink.innerHTML = sortLink.originalHeader + sortLink.arrowHeader;
  }

  if (direction == 1)
    handle.arrowHeader = " &uarr;";
  else
    handle.arrowHeader = " &darr;";

  handle.innerHTML = handle.originalHeader + handle.arrowHeader;

  if (column_type === 'string') {
    sort_func = function (r1, r2) {
      var s1 = r1.childNodes[0].innerHTML;
      var s2 = r2.childNodes[0].innerHTML;
      return s1.localeCompare(s2) * direction;
    }
  } else {
    sort_func = function (r1, r2) {
      var v1 = parseFloat(r1.childNodes[column_index].innerHTML.replace(/[,$%]/g, ''));
      var v2 = parseFloat(r2.childNodes[column_index].innerHTML.replace(/[,$%]/g, ''));

      return ((v2||0) - (v1||0)) * direction;
    }
  }

  // var toBeEvald = '';
  // while (true) {

  //   toBeEvald = prompt('Enter code to be evaluated', toBeEvald);
  //   if (toBeEvald === 'quit') break;

  //   try {
  //     alert(eval(toBeEvald));
  //   } catch (e) {
  //     alert(e.message);
  //   }
  // }

  var rows = table.childNodes[0].childNodes;

  var recordRows = [];
  for(var i=0; i<rows.length; i++) {
    recordRows.push(rows[i]);
  }

  var sortedRows = recordRows.slice(1, -1).sort(sort_func);

  var tbody = table.childNodes[0];

  for(var i=0; i < sortedRows.length; i++) {
    var row = sortedRows[i];
    tbody.removeChild(row);
  }

  for(var i=0; i < sortedRows.length; i++) {
    var row = sortedRows[i];
    row.className = (i%2) ? 'odd' : 'even'

    tbody.insertBefore(row, tbody.lastChild);
  }
}

function expandDataRows(customForm, attachmentId, sid){
    outerDiv = $j('#import_data_row_table_' + attachmentId);

    if($j('#expansion_section_for_' + attachmentId).length){
        outerDiv.show();
        $j('#show_data_row_table_'+ attachmentId).hide();
        $j('#hide_data_row_table_'+ attachmentId).show();
    }
    else {
      $j.ajax( '/custom_form/load_import_expansion', {
        type: 'GET',
        data: "id="+customForm+"&attachment_id="+attachmentId,
        beforeSend: function(){
          $j('#'+sid).show();
        },
        complete: function(){
          $j('#show_data_row_table_'+ attachmentId).hide();
          $j('#'+sid).hide();
          $j('#hide_data_row_table_'+ attachmentId).show();
        }
      }
     );
    }
}

function collapseDataRows(attachmentId)
{
    outerDiv = $j('#import_data_row_table_' + attachmentId);
    outerDiv.hide();
}

function addServiceCustomForm(service_id, service_name, att_id, id){
  $j.ajax('/custom_form/add_selected_service', {
    method: 'post',
    data: "s_id="+service_id+"&s_name="+encodeURIComponent(service_name)+"&att_id="+att_id+"&id="+id+"&addable_type=custom_form",
    complete: function(response){
      //eval(response.responseText)
    }
  })
 }


function removeServiceCustomForm(service_id, att_id, id, lid) {
  $j.ajax('/custom_form/remove_selected_service', {
    method: 'post',
    data: "s_id="+service_id+"&att_id="+att_id+"&lid="+lid+"&id="+id+"&addable_type=custom_form",
    complete: function(response){
      //eval(response.responseText)
    }
  })
}


function addServiceCustomFormTemplate(service_id, service_name, elem){
    field_number = $j(elem).closest('div[id^=available_ser]').find('input').attr('name').match(/[\d\.]+/g)[0];
    index = $j('#list_of_pruned_available_services_'+field_number).children().length;
    if($j("#selected_" + service_id +"_field_" + field_number).length){
        return;
    }
    $j.ajax('/custom_form/add_selected_service', {
      method: 'post',
      data: "s_id="+service_id+"&s_name="+encodeURIComponent(service_name)+"&index="+index+"&field_number="+field_number+"&addable_type=custom_form_template",
      complete: function(response){
        //eval(response.responseText)
      }
    })
}

function removeServiceCustomFormTemplate(service_id, elem) {
    var field_number = $j(elem).closest('div[id^=available_ser]').find('input').attr('name').match(/[\d\.]+/g)[0];
    $j("#selected_" + service_id +"_field_" + field_number).remove();
    Tipped.refresh('*');
}

//What value is selected for rname in the context of parent element
function value_of_radio(parent, rname) {
  parent_el = $j(parent);
  all_radios = parent_el.find('input[name="'+rname+'"]');
  var selected = null;
  all_radios.each(function(index, rad){
    if(rad.checked){
      selected=rad.value;
    }
  });
  return selected;
}

function warn_if_not_selected(parent,rname,things_name) {
  if(value_of_radio(parent,rname)==null){
    alert('Please select one of the '+things_name+' before clicking submit');
    return false;
  }else{
    return true;
  }
}

function findFieldNumber(row) {
  var input = $j(row).find('input[name^=template_fields]')[0];
  return $j(input).attr('name').match(/[\d\.]+/g)[0];
}


function toggleElementsWithIds(ids){
    ids.forEach(function(item){$j(item).toggle()});
}

function updateQuantityOnLineItem(elem, id, currency_symbol) {
  if (elem.val() != elem.attr('quantity'))
  {
    qty_input_id = 'line_item_'+id+'_quantity'
    input = $j('#' + qty_input_id)
    viewing_service_center_id = input.attr('viewing_service_center_id')

    $j.ajax({
      url:'/line_item/update_line_item_quantity/'+id,
      type:"POST",
      async:true,
      data:input.serialize() + '&viewing_service_center_id=' + viewing_service_center_id,
      beforeSend: function() {
        lockLineItem(id)
        showSpinner('#' + qty_input_id)
      },
      complete: function() {
        unlockLineItem(id)
        hideSpinner('#' + qty_input_id)
      },
      error: function() {
        unlockLineItem(id)
        hideSpinner('#' + qty_input_id)
      }
    })

    return false;
  }
}

function lockLineItem(id) {
  elem = $j('#line_item_' + id + ' tr.line_item')
  elem.css('pointer-events', 'none')
  elem.addClass('disabled')
  elem.find('select').prop('disabled', true)
}

function unlockLineItem(id) {
  elem = $j('#line_item_' + id + ' tr.line_item')
  elem.css('pointer-events', 'auto')
  elem.removeClass('disabled')
  elem.find('select').prop('disabled', false)
}

function updateCartPriceOnLineItem(elem, id, currency_symbol) {
  cartPrice = elem.val();
  elem.prevAll('price').attr('cart_price', cartPrice);
  $j('#line_item_'+id+'_price').text(currency_symbol + CurrencyFormatted(Number(cartPrice)));
  qty = $j('#line_item_'+id+'_quantity').val();
  totalPriceHtml = currency_symbol + CurrencyFormatted(Number(qty) * Number(cartPrice));
  $j('#line_item_extended_price_'+id).html(totalPriceHtml);
  input = $j('#line_item_'+id+'_cart_price')
  $j.ajax({
    url:'/line_item/update_cart_price/'+id,
    type:"POST",
    async:true,
    data:input.serialize(),
    beforeSend: function(){showSpinner('#line_item_'+id+'_quantity'+', #line_item_extended_price_'+id)},
    complete:   function(){hideSpinner('#line_item_'+id+'_quantity'+', #line_item_extended_price_'+id)}
  })

  return false;
}

function alertIncompleteCustomForm(){
    alert("There may be fields which you have not completed. Please review the forms carefully.");
}


function showHideConfigWizardRows(show, id)
{
    if (show){
        $j('#interaction_config_' +id).show();
        $j('#auth_config_'+ id).show();
        $j('#notes_config_'+ id).show();
    }
    else{
        $j('#interaction_config_' +id).hide();
        $j('#auth_config_'+ id).hide();
        $j('#notes_config_'+ id).hide();
    }
    Tipped.refresh('*');

}

function showHideInteractionRows(show, id) {
  if (show){
    $j('#interaction_config_' +id).show();
  }
  else {
    $j('#interaction_config_' +id).hide();
    $j('#interaction_config_' +id + ' input').prop('checked', false);
  }
  Tipped.refresh('*')
}

function drawLineChart(container, title, data, yTitle, xLabels, step, unit, animate, stacktype, parse_dates, grid_display){
    step = (typeof step !== 'undefined' ? step : 1);
    unit = (typeof unit !== 'undefined' ? unit : {prefix: '', suffix: ''});
    animate = (typeof animate !== 'undefined' ? animate : true);
    stacktype = (typeof stacktype !== 'undefined' ? stacktype : 'none');
    parse_dates = (typeof parse_dates !== 'undefined' ? parse_dates : false);
    grid_display = (typeof grid_display !== 'undefined' ? grid_display : 0.15);

    var plot = { series: { enableMouseTracking: false, shadow: false, animation: false } }

    var chart = AmCharts.makeChart(container, {
      "type": "serial",
      "theme": "light",
      "valueAxes": [
        {
          "title": yTitle,
          "stackType": stacktype,
          "gridAlpha": grid_display
        }
      ],

      "sequencedAnimation": false,
      "startDuration": 0,
      "categoryField": "category",
      "dataDateFormat": "MM/DD/YYYY",
      "categoryAxis": {
        "parseDates": parse_dates,
        "gridAlpha": grid_display
      },
      "legend": {
        "useGraphSettings": true,
        "horizontalGap": 10,
        "borderAlpha": 0.1,
        "maxColumns": 1,
        "position": "right",
      },
      "graphs": xLabels,
      "chartCursor": {
          "pan": true,
          // "valueLineEnabled": true,
          // "valueBalloonEnabled": true,
          "categoryBalloonEnabled": true,
          "cursorAlpha":0,
          "cursorColor":"#258cbb",
          "valueLineAlpha":0.2
      },
      "dataProvider": data});



}


function drawStackedBarChart(container, title, data, yTitle, xLabels, step, unit, showTotals, column_totals, animate, stack, parse_dates, grid_display, title_y_axis_val){


    title = (typeof title_y_axis_val !== 'undefined' ? { text: title, floating: true, y: title_y_axis_val }: { text: title } );


    var chart = AmCharts.makeChart(container, {
      "type": "serial",
      "theme": "light",
      "valueAxes": [
        {
          "title": yTitle,
          "stackType": "regular",
          "gridAlpha": grid_display
        }
      ],
      "categoryField": "category",
      "dataDateFormat": "MM/DD/YYYY",
      "startDuration": 0,
      "categoryAxis": {
        "parseDates": parse_dates,
        "gridAlpha": grid_display,
        "autoRotateAngle": 45,
        "autoRotateCount": 10
      },
      "legend": {
        "useGraphSettings": true,
        "horizontalGap": 10,
        "borderAlpha": 0.1,
        "maxColumns": 1,
        "position": "right",
        "labelWidth": 150
      },
      "graphs": xLabels,
      "chartCursor": {
          "pan": true,
          "valueLineEnabled": true,
          "valueLineBalloonEnabled": true,
          "cursorAlpha":1,
          "cursorColor":"#258cbb",
          "limitToGraph":"g1",
          "valueLineAlpha":0.2
      },
      "dataProvider": data});
}

function drawPieChart(container, title, data, unit, series, showPercentages, showTotal, animate, convert_to_bar_chart,
                      yTitle, xLabels, hideLabelPercent){
    unit = (typeof unit !== 'undefined' ? unit : {prefix: '', suffix: ''});
    animate = (typeof animate !== 'undefined' ? animate : true);

    if (convert_to_bar_chart) {
        // Sometimes we want to show a bar chart instead of a pie chart so that
        // negative values can be included.
        drawStackedBarChart(container, title, data, yTitle, xLabels, 1, unit, false, false, animate);

    } else {

        var chart = AmCharts.makeChart(container, {
          "type": "pie",
          "theme": "light",
          "dataProvider": data,
          "valueField": "value",
          "titleField": "label",
          "startDuration": 0,
          "groupPercent": 2,
          "hideLabelsPercent": hideLabelPercent,
          "groupedTitle": 'Other (< 2%)',
          "balloon":{
            "fixedPosition":true
          },
          "export": {
            "enabled": true
          }
        } );

    }
}

var hasOwnProperty = null;
if ( Object.prototype.hasOwnProperty ) {
    hasOwnProperty = function(obj, prop){
        return obj.hasOwnProperty(prop);
    }
}else{
		hasOwnProperty = function(obj, prop){
			var proto = obj._proto_ || obj.constructor.prototype;
			return (prop in obj) &&
					(!(prop in proto) || proto[prop] !== obj[prop]);
		}
}

var arrange_equipment = function(){
    var ids = [];
    $j(' .equipment-checkbox').each(function(){
      var val =$j(this).val();
      if ($j(this).attr('checked') != 'checked')
        $j(' .eq-'+val+':not(.equipment-checkbox)').hide();
    });
  };

/* for Reservations tab */
$j(function(){
  var toggle_equipment = function(el, eq_id){
    $j(' .eq-'+eq_id+':not(.equipment-checkbox)').toggle(el.checked);
    for(var i =0; i< equipment_list.length; i++)
      if (equipment_list[i].id == eq_id){
          equipment_list[i].checked = el.checked;
      }
    $j('#last_page_table').fixedHeaderTable('show');
  };

  $j('#print_reservations_link').live('click', function() {
    var href = this.href;
    var href = href.split('&equipment')[0];
    var param = '&list_only=true';
    var equipment_string = '';
    $j(' .equipment-checkbox:checked').each(function(){
        equipment_string = equipment_string + '&equipment[]=' + $j(this).val();
    });
    if ($j('#print_list_only:checked').length > 0)
      {href = href + param;}
    else
      {href = href.replace(param,'');}
    href = href + equipment_string;
    $j(this).attr('href', href);
    return true;
  });



  $j(' .equipment-checkbox').live('change', function(){
      var eq_id = $j(this).val();
      toggle_equipment(this,eq_id)
      return true;
  });



  $j('#hide_free_equipment').live('click', function(){
    var ids = [];
    $j(' .equipment-checkbox').each(function(){
      ids.push($j(this).val());
    });
    $j('#last_page_table td.busy').each(function(){
      var pattern = /eq-(\d+)/g;
      var class_name = $j(this).attr('class');
      var match = pattern.exec(class_name);
      var index_of = ids.indexOf(match[1])
      if(index_of >= 0)
        ids.splice(index_of,1);
    });
    for(i=0; i< ids.length ;i++ )
    {
      if($j('td.eq-'+ids[i]+':not(.free)').length == 0){
        $j(' .eq-'+ids[i]+':not([type="checkbox"])').hide();
        $j(' .eq-'+ids[i]+'[type="checkbox"]').attr('checked',false);
      }
        for(var j = 0; j <equipment_list.length; j++)
        {
          eq = equipment_list[j];
          if(eq.id == parseInt(ids[i])){
            equipment_list[j]['checked'] = false;
          }
        }

    }
    // console.log(ids);
    $j('#last_page_table').fixedHeaderTable('show');

    // IS: hack to fix issue
    // when cloned header does change its height
    // and the original doesn't
    // most likely it's `fixedHeaderTable` bug
    $j('#last_page_table tr:first th:first').height($j('.fht-table tr:first th:first').height());

    return false;
  });

  $j('#eq_list_by_category').live('click', function(){
    render_equipment_list_by_category(equipment_list);
  });

  $j('#eq_list_alphabetically').live('click', function(){
    render_equipment_list_alphabetically(equipment_list);
  });

});

  var get_eq_span = function(eq){
        var input, span;
          input = $j('<input>')
                      .attr({
                        type: 'checkbox',
                        'class': "equipment-checkbox eq-"+eq.id,
                        value: eq.id,
                        name: "resource_ids[]"
                        });
          if (eq.checked) {input.attr('checked', 'checked');}

          span = $j('<span>').attr('class', 'equipment-span').html(eq.name);
          span.prepend(input)
          return span;
  };
  var set_equipment_list= function(eqs){equipment_list = eqs};
  var render_equipment_list_alphabetically = function(eqs) {
    $j.cookie("eq_list_alpha", '1');
    $j('#eq_list_wrapper').html('');
    eqs = eqs.sort(function(a,b){
      return a['name'].toUpperCase().localeCompare(b['name'].toUpperCase())
    })
    for(var i=0; i< eqs.length; i++){
      var span =  get_eq_span(eqs[i]);
      $j('#eq_list_wrapper').append(span);
    }
    $j('#eq_list_wrapper').fadeIn();
  };
  var render_equipment_list_by_category = function(eqs){
    $j.cookie("eq_list_alpha", '0');
    $j('#eq_list_wrapper').html('');
    var grouped_list = {};
    for(i=0; i< eqs.length; i++){
      var eq = eqs[i];
      if(grouped_list[eq.category] == null){
        grouped_list[eq.category] = $j('<div>').attr('style', 'clear:both');
        var checkbox =$j('<input type="checkbox" class="group-checkbox" checked="checked">');
        grouped_list[eq.category].append($j('<h4>').text(" "+eq.category).prepend(checkbox.change(function(){
          $j(this).parent().parent().find('.equipment-checkbox').prop('checked', $j(this).prop('checked')).each(function(){
            el = $j(this)
            eq_id = $j(this).val();
            $j(' .eq-'+eq_id+':not(.equipment-checkbox)').toggle(!!el.prop('checked'));
            for(var i =0; i< equipment_list.length; i++)
              if (equipment_list[i]['id'] == eq_id){
                  equipment_list[i]['checked'] = el.checked;
              }
            $j('#last_page_table').fixedHeaderTable('show');
          })

        })));
      }
      var span =  get_eq_span(eq);
      grouped_list[eq.category].append(span);
    }

    for (var i in grouped_list)
      $j('#eq_list_wrapper').append(grouped_list[i]);
    $j('#eq_list_wrapper').fadeIn();

    $j('.group-checkbox').each(function(){
      if ($j(this).parent().parent().find('.equipment-checkbox:not(:checked)').size() > 0)
        $j(this).removeAttr('checked','checked');
    });
  };
  var render_equipment_list = function(eqs){
    // console.log($j.cookie("eq_list_alpha"))
    if ($j.cookie("eq_list_alpha")=='0')
      render_equipment_list_by_category(eqs);
    else
      render_equipment_list_alphabetically(eqs);
  };


/* This is for equipment edit view. Override enter button behaviour on trained users search */
$j(document).ready(function() {
  $j(window).keydown(function(event){
    if(event.keyCode == 13) {
      if (event.target.id == 'trained_searchtext'){
        event.preventDefault();
        $j('#trained_button').trigger('click');
        return false;
      }
    }
  });
});

(function( $ ) {
    $.widget( "ui.combobox", {
        _create: function() {
            var input,
                that = this,
                wasOpen = false,
                select = this.element.hide(),
                selected = select.children( ":selected" ),
                value = selected.val() ? selected.text() : "",
                wrapper = this.wrapper = $( "<span>" )
                    .addClass( "ui-combobox" )
                    .insertAfter( select );
            function removeIfInvalid( element ) {
                var value = $( element ).val(),
                    matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( value ) + "$", "i" ),
                    valid = false;
                select.children( "option" ).each(function() {
                    if ( $( this ).text().match( matcher ) ) {
                        this.selected = valid = true;
                        return false;
                    }
                });
                if ( !valid ) {
// remove invalid value, as it didn't match anything
                    $( element )
                        .val( "" )
                        .attr( "title", value + " didn't match any item" )
                        .tooltip( "open" );
                    select.val( "" );
                    setTimeout(function() {
                        input.tooltip( "close" ).attr( "title", "" );
                    }, 2500 );
                    input.data( "ui-autocomplete" ).term = "";
                }
            }
            input = $( "<input>" )
                .appendTo( wrapper )
                .val( value )
                .attr( "title", "" )
                .addClass( "ui-state-default ui-combobox-input" )
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: function( request, response ) {
                        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                        response( select.children( "option" ).map(function() {
                            var text = $( this ).text();
                            if ( this.value && ( !request.term || matcher.test(text) ) )
                                return {
                                    label: text.replace(
                                        new RegExp(
                                            "(?![^&;]+;)(?!<[^<>]*)(" +
                                                $.ui.autocomplete.escapeRegex(request.term) +
                                                ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                        ), "<strong>$1</strong>" ),
                                    value: text,
                                    option: this
                                };
                        }) );
                    },
                    select: function( event, ui ) {
                        ui.item.option.selected = true;
                        var selected_option = $(ui.item.option)
                        var id = selected_option.val();
                        var name = selected_option.data('name');
                        var email = selected_option.data('email');

                        var root_element = selected_option.closest('.control-line');
                        root_element.data('name', name);
                        root_element.data('id', id);
                        root_element.data('email', email);

                        root_element.find('.add_button_user_notify').focus();

                        that._trigger( "selected", event, {
                            item: ui.item.option
                        });
                    },
                    change: function( event, ui ) {
                        if ( !ui.item ) {
                            removeIfInvalid( this );
                        }
                    }
                })
                .addClass( "ui-widget ui-widget-content ui-corner-left" );
            input.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li>" )
                    .append( "<a>" + item.label + "</a>" )
                    .appendTo( ul );
            };
            $( "<a>" )
                .attr( "tabIndex", -1 )
                .attr( "title", "Show All Items" )
                .tooltip()
                .appendTo( wrapper )
                .button({
                    icons: {
                        primary: "ui-icon-triangle-1-s"
                    },
                    text: false
                })
                .removeClass( "ui-corner-all" )
                .addClass( "ui-corner-right ui-combobox-toggle" )
                .mousedown(function() {
                    wasOpen = input.autocomplete( "widget" ).is( ":visible" );
                })
                .click(function() {
                    input.focus();
// close if already visible
                    if ( wasOpen ) {
                        return;
                    }
// pass empty string as value to search for, displaying all results
                    input.autocomplete( "search", "" );
                });
            input.tooltip({
                tooltipClass: "ui-state-highlight"
            });
        },
        _destroy: function() {
            this.wrapper.remove();
            this.element.show();
        }
    });
})( jQuery );

$j(function() {
  // This ensures we do a redirect after any AJAX request if the user was logged out.
  // See comments in AuthenticatedSystem#access_denied.
  $j(document).ajaxComplete(function(ev, xhr, settings) {
    var redirect_location = xhr.getResponseHeader('REDIRECT_LOCATION');
    if (redirect_location) {
      window.location.replace(redirect_location);
    }
  });
});

window.onbeforeunload = function() {
  var warn = $j(".warn-on-leave:visible").length > 0;
  return warn ? '' : undefined;
}
;
(function() {
  var StatefulJob,
    slice = [].slice;

  StatefulJob = (function() {
    function StatefulJob(url, timeout) {
      if (timeout == null) {
        timeout = 1000;
      }
      this.url = url;
      this.timeout = timeout;
      this.callbacks = {};
    }

    StatefulJob.prototype.on = function(type, callback) {
      this.register_callbacks(type, callback);
      return this;
    };

    StatefulJob.prototype.poll = function() {
      var self;
      self = this;
      self.poll_function = function() {
        return setTimeout(function() {
          return $j.ajax({
            url: self.url,
            dataType: "json",
            success: function(data, status, xhr) {
              return self.handle_response(data, status, xhr);
            },
            error: function(xhr, status, error) {
              return self.invoke_callbacks("fail", xhr, status, {
                error: error
              });
            }
          });
        }, self.timeout);
      };
      self.poll_function();
      return this.invoke_callbacks("start");
    };

    StatefulJob.prototype.handle_response = function(data, status, xhr) {
      switch (data.status) {
        case "running":
          return this.poll_function();
        case "success":
          this.invoke_callbacks("success");
          break;
        case "error":
          if (data.error && data.error !== null) {
            this.invoke_callbacks("error", data.error);
          } else {
            this.invoke_callbacks("fail", status, xhr, data);
          }
          break;
        default:
          this.invoke_callbacks("fail", status, xhr, data);
      }
      return this.invoke_callbacks("done");
    };

    StatefulJob.prototype.invoke_callbacks = function() {
      var args, callback, event, i, len, ref, results;
      event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (this.callbacks[event]) {
        ref = this.callbacks[event];
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          callback = ref[i];
          results.push(callback.apply(null, args));
        }
        return results;
      }
    };

    StatefulJob.prototype.register_callbacks = function(event, callback) {
      if (!this.callbacks[event]) {
        this.callbacks[event] = [];
      }
      return this.callbacks[event].push(callback);
    };

    return StatefulJob;

  })();

  window.StatefulJob = StatefulJob;

}).call(this);
(function() {
  window.initPermissionLevelSelector = function(save_button, events) {
    var _anyPermissionLevelChecked, _enableSaveButton, _enableSavePermissionLevels, _fireRefresh, _hidePermissionLevels, _isPermissionTypeSelected, _permissionLevelsCheckbox, _permissionLevelsDefault, _permissionLevelsSelector, _permissionLevelsUpdated, _permissionTypeSelector, _permissionTypeValue, _selectDefaultLevels, _setPermissionLevelCheckbox, _showPermissionLevels, _updatePermissionLevelsPanel, _updateSaveButton, init;
    _permissionLevelsSelector = function() {
      return $j('.permission_levels');
    };
    _permissionLevelsCheckbox = function() {
      return _permissionLevelsSelector().find('input');
    };
    _permissionLevelsDefault = function() {
      return _permissionLevelsSelector().data('default-levels');
    };
    _setPermissionLevelCheckbox = function(id, checked) {
      return $j("#permission_level_" + id).prop('checked', checked);
    };
    _permissionTypeSelector = function() {
      return $j('#permission_levels_selector .permission_type input');
    };
    _permissionTypeValue = function() {
      return _permissionTypeSelector().closest(':checked').val();
    };
    _anyPermissionLevelChecked = function() {
      return _permissionLevelsCheckbox().is(':checked');
    };
    _isPermissionTypeSelected = function() {
      return _permissionTypeValue() === 'selected';
    };
    _fireRefresh = function() {
      if (events && events.onRefresh) {
        return events.onRefresh();
      }
    };
    _enableSavePermissionLevels = function() {
      if (!_isPermissionTypeSelected()) {
        return true;
      }
      return _anyPermissionLevelChecked();
    };
    _enableSaveButton = function(enable) {
      if (enable) {
        return $j(save_button).removeClass('disabled');
      } else {
        return $j(save_button).addClass('disabled');
      }
    };
    _updateSaveButton = function() {
      return _enableSaveButton(_enableSavePermissionLevels());
    };
    _permissionLevelsUpdated = function() {
      _updateSaveButton();
      return _fireRefresh();
    };
    _showPermissionLevels = function() {
      return _permissionLevelsSelector().slideDown(_permissionLevelsUpdated);
    };
    _hidePermissionLevels = function() {
      return _permissionLevelsSelector().slideUp(_permissionLevelsUpdated);
    };
    _updatePermissionLevelsPanel = function() {
      if (_isPermissionTypeSelected()) {
        return _showPermissionLevels();
      } else {
        return _hidePermissionLevels();
      }
    };
    _selectDefaultLevels = function() {
      var i, j, len, ref, results;
      if (!_permissionLevelsDefault()) {
        return;
      }
      ref = _permissionLevelsDefault();
      results = [];
      for (j = 0, len = ref.length; j < len; j++) {
        i = ref[j];
        results.push(_setPermissionLevelCheckbox(i, true));
      }
      return results;
    };
    init = function() {
      _permissionTypeSelector().live('change', _updatePermissionLevelsPanel);
      _permissionLevelsCheckbox().live('change', _updateSaveButton);
      return _selectDefaultLevels();
    };
    return init;
  };

}).call(this);



$j('#asset_allow_to_add_only_selected_charges, #how_do_you_charge_for_scans').live('change', function(){
  linked_charges = $j('#asset_allow_to_add_only_selected_charges').is(':checked');
  scan_charges = $j('#how_do_you_charge_for_scans').val() == 'service';
  if(linked_charges || scan_charges)
    $j('#related_charges').show();
  if(linked_charges)
    $j('#related_charges .linked_charges').show();
  else
    $j('#related_charges .linked_charges').hide();
  if (scan_charges)
    $j('#related_charges .scan_charges').show();
  else
    $j('#related_charges .scan_charges').hide();

  if(!(linked_charges || scan_charges))
    $j('#related_charges').hide();
});

$j('#warn_when_longer_than_scheduled').live('change', function(){
  var longer_warning =  $j('#warn_when_longer_than_scheduled').attr('value');
  if(longer_warning == 'true')
    $j('#significantly_longer_inputs').show();
  else
    $j('#significantly_longer_inputs').hide();
});

$j('#warn_when_shorter_than_scheduled').live('change', function(){
  var longer_warning =  $j('#warn_when_shorter_than_scheduled').attr('value');
  if(longer_warning == 'true')
    $j('#significantly_shorter_inputs').show();
  else
    $j('#significantly_shorter_inputs').hide();
});


//MK: I imagine at some point we should encapsulate all calendar functionality that way?
window.iLabScheduling = {
  now_with_offset: function(equipment_offset){
    browser_now = new Date();
    browser_offset = browser_now.getTimezoneOffset(); //minutes BEFORE UTC
    difference = browser_offset - equipment_offset;
    return $j.now() + 60*1000*difference; //JS works in ms, while offset is in minutes
  },
  setup_time_zone_correction: function(a_scheduler, offset){
    iLabScheduling.the_scheduler = a_scheduler;
    iLabScheduling.the_offset = offset;
    iLabScheduling.the_scheduler.config.now_date = iLabScheduling.now_with_offset(iLabScheduling.the_offset);
    iLabScheduling.time_zone_timer = window.setInterval(function() {
      if(iLabScheduling.the_scheduler && iLabScheduling.the_offset){
        iLabScheduling.the_scheduler.config.now_date = iLabScheduling.now_with_offset(iLabScheduling.the_offset);
      }
    }, 30000);
  }
};

$j('#asset_trained_users_track_trained_users').live('change', function(){
  $j('#trained_users_detail, #accessability_event_inputs_trained').toggle();
});

$j('#asset_trained_users_only_trained').live('change', function(){
  $j('#accessability_event_inputs').toggle();
});

$j(' .centered_password_box #event_type').live('change', function () {
  if ($j.inArray($j('#event_type').val(), ['unavailable', 'availability']) != -1) {
    $j('#customer_select').hide();
    $j('.new_reservation_prompt .employee_new_next').show();
  }
  else {
    // Reset the form.
    $j('#customer_select').show();
    $j('#customer_select #owner_id').select2('data', '').trigger('change');
    $j('.new_reservation_prompt .employee_new_next').hide();
  }
});

$j(document).live("mfpClose", function(devent) {
  if ($j('#event_form .centered_password_box:visible').length > 0) {
    lightbox_open = false;
    var event_id = $j('#current_event_id').val();
    var e = scheduler.getEvent(event_id);
    if (e && (e.text == 'New event' || e.text == 'Validating...')){
      removeServiceEvent(false);
      scheduler.deleteEvent(event_id,false);
    }

    Tipped.remove('*');
    unbindConfirmClose();
  }
  return true;
});

function isNewEvent(){
  return $j('#current_event_new_or_updating').val() === 'new';
};

// IS: in use
function cancelServiceEvent(){
  if (isNewEvent()) { //if it's during a create, delete the event
    removeServiceEvent(false);
  } else { //if the cancel is during an update just get out of the form
    $j.bhPopup.hide();
  }
}

function removeServiceEventFromHomepage(cancelling, cancel_with_fee, managers_cancel_fee_action, adjustedFeeAmount, justification, event_id, asset_id, action){
  cancel_with_fee = cancel_with_fee || null;
  managers_cancel_fee_action = managers_cancel_fee_action || null;
  adjustedFeeAmount = adjustedFeeAmount || null;
  justification = justification || null;
  event_id = event_id || null;
  if (!asset_id && cancel_with_fee) {
    asset_id = cancel_with_fee.asset_id;
  }

  var params_object = {
    id: event_id,
    asset_id: asset_id,
    cancel_with_fee: cancel_with_fee,
    cancelling: cancelling,
    managers_cancel_fee_action: managers_cancel_fee_action,
    adjusted_fee_amount: adjustedFeeAmount,
    justification: justification,
  }


  $j.ajax({
    url: '/calendar_events/' + event_id,
    type: 'DELETE',
    async: true,
    data: $j.param(params_object),
    success: function(transport) {
      if(action == 'delete'){
        $j("#event_id_" + event_id).remove();
      }
      else{
        $j("#event_status_for_" + event_id).addClass('cancelled_event')
                                           .text('cancelled');

        $j("#event_id_" + event_id).find(".event_widget_cancel_button").remove();
      }

    }
  });

  return true;
}

// IS: in use
function removeServiceEvent(cancelling, cancel_with_fee, managers_cancel_fee_action, adjustedFeeAmount, justification){
  // E11 does not support default parameters.
  // This is an extension in ES6 in the JavaScript language that browser does not recognize.
  // http://kangax.github.io/compat-table/es6/
  cancel_with_fee = cancel_with_fee || null;
  managers_cancel_fee_action = managers_cancel_fee_action || null;
  adjustedFeeAmount = adjustedFeeAmount || null;
  justification = justification || null;

  $j.bhPopup.hide(true);
  var event_id = $j('#current_event_id').val();
  var devent = scheduler.getEvent(event_id);
  devent.text = 'Deleting...';
  devent.readonly = true;
  scheduler.updateEvent(devent.id);

  var params_object = new Object;
  params_object.id = devent.id;
  params_object.asset_id = devent.asset_id;
  params_object.equipment_id = devent.equipment_id;
  params_object.cancel_with_fee = cancel_with_fee
  params_object.cancelling = cancelling;
  params_object.managers_cancel_fee_action = managers_cancel_fee_action;
  params_object.adjusted_fee_amount = adjustedFeeAmount;
  params_object.justification = justification;
  params_object['!nativeeditor_status'] = "deleted";
  params_object.keep_recurrence = $j("form#recurrent-event-form input#detach_recurrent").val();

  $j.ajax({
    url: '/calendar_events/' + devent.id,
    type: 'DELETE',
    async: true,
    data: $j.param(params_object),
    success: function(transport) {
      var recurrent_event_id = $j("form#recurrent-event-form input#recurrent_event_id").val();
      var detachedFromSeries = ($j("form#recurrent-event-form input#detach_recurrent").val() === 'true');
      var shouldPoll = !detachedFromSeries && recurrent_event_id != undefined && recurrent_event_id.length > 0

      if (shouldPoll) {
        recurrentEventRemoveCallback(recurrent_event_id);
      }
      else {
        afterSaveCallback(transport);
      }
    },
    beforeSend: function() {
      blockAllButtons()
    },
    complete: function() {
      unblockAllButtons()
    }
  });

  return true;
}

// IS: in use
function resaveServiceEvent(event_id,params_object){
  $j.ajax({
    url: '/calendar_events/' + event_id,
    type: 'PUT',
    data: $j.param(params_object) + "&" + $j('#simple_split_form_' + event_id +' :input').serialize() + '&valid_override=true' ,

    beforeSend: function() {
      $j('#service_event_save_button').addClass('disabled');
    },

    complete: function() {
      $j('#service_event_save_button').removeClass('disabled');
    },

    success: function(transport) {
      afterSaveCallback(transport);
    }
  });
}

// returns permission type selected (maybe: all, no, selected)
var permissionType = function() {
  return $j('#permission_levels_selector .permission_type input:checked').val();
};

var isPermisionLevelsSelected = function() {
  return permissionType() === 'selected';
}

// returns the ids of the permission levels selected
var permissionIdSelected = function() {
  if (!isPermisionLevelsSelected()) {
    return [];
  }
  return $j(
    '#permission_levels_selector .permission_levels .checkbox input:checked'
  ).map(function () {
    return $j(this).val();
  }).get();
};

var anyPermissionLevelSelected = function() {
  return permissionIdSelected().length > 0;
}

// IS: in use
function saveSimpleServiceEvent(){
  var event_id = $j('#current_event_id').val();
  var devent = scheduler.getEvent(event_id);
  scheduler.updateEvent(devent.id);
  var is_new = devent.id > 2000000;
  devent.text = 'Saving...';

  var params_object = {
    id: devent.id,
    equipment_id: $j('#equipment_id').val()
  };

  if($j('#start_date').length){
    params_object.start_date = $j('#start_date').val();
  }
  if($j('#end_date').length){
    params_object.end_date = $j('#end_date').val();
  }

  // If permission type is selected, there should be permissionIds
  if (isPermisionLevelsSelected() && !anyPermissionLevelSelected()) {
    alert('You must select at least one permission level');
    return false;
  }

  params_object.permission_type = permissionType();
  params_object.permission_levels = permissionIdSelected();

  if(devent.event_type === 'availability'){
    params_object.orderable_item_id = $j('#orderable_item_id').val();
    if($j('#needs_confirmation').attr('checked')) {
      params_object.needs_confirmation = $j('#needs_confirmation').val();
    }else{
      params_object.needs_confirmation = 'false';
    }
  }else{
    params_object.cancel_overlapping = $j('#cancel_overlapping').prop('checked') || false;

    if($j('#notes').length){
      params_object.notes = $j('#notes').val();
    }
  }
  params_object.from_lightbox = true;

  if (devent['comment_ids'])   { params_object.comment_ids = devent['comment_ids'].join(); }
  params_object['!nativeeditor_status'] = is_new ? 'inserted' : 'updated';
  params_object.event_type = devent.event_type;
  params_object.owner_id = devent.owner_id;
  params_object.status = 'valid'
  params_object.asset_id = devent.asset_id;

  if($j('#event_custom_form').length) {
    data = $j('#event_custom_form').find('input, select, textarea').serialize() //copied from link_to_remote
    cust_serialized = "&" + data;
  }else{
    cust_serialized = '';
  }

  $j.ajax({
    url: '/calendar_events/' + devent.id,
    type: 'PUT',
    async: true,
    data: $j.param(params_object) + "&" + $j('#simple_split_form_' + devent.id +' :input').serialize() + cust_serialized + "&" + $j('#recurrent-event-form').serialize(),

    beforeSend: function() {
      blockAllButtons()
    },

    complete: function() {
      unblockAllButtons()
    },

    success: function(transport) {
      var handleRecurringEvent =
        $j('#recurrent-event-form input#is_recurrent').val() == 'true' &&
          $j("form#recurrent-event-form input#detach_recurrent").val() != 'true';

      if (handleRecurringEvent) {
        var is_error = $j(transport).find("action").attr("type") === "error";
        var recurrent_event_id = $j(transport).find("action").attr("recurrent_event_id");
        var error_message = $j(transport).find("action").text();

        recurrentEventCallback(recurrent_event_id, is_error, error_message);
      }
      else {
        afterSaveCallback(transport);
      }
    }
  });

  if (is_employee)
    $j.bhPopup.hide();

  disableSaveAndShowSpinner();

  return true;
}

var timeSaveButton = function () {
  return $j('.save_times');
};

var timeSaveButtonVisible = function () {
  return timeSaveButton().length;
};

var timeSaveButtonTimesType = function () {
  // e.g. scheduled, logged or billable - just show the first one if there are multiple
  return timeSaveButton().first().closest('tr').find('.title').text().toLowerCase();
};

// IS: in use
function preSaveServiceEvent(is_reservation) {
  if($j('#service_event_save_button').hasClass('disabled')) {
    return false;
  }

  if (is_reservation === undefined) {
    is_reservation = true;
  }

  var event_is_recurring = $j("form#recurrent-event-form input#has_recurrence_rule").val() == "true";
  var event_is_linked = $j("input#toggle_linked_reservations").prop('checked');
  var event_will_reccur = $j("form#recurrent-event-form input#is_recurrent").val() == 'true';
  var require_service_project = $j('#service_project_id').data('required');

  if ((event_is_recurring || event_will_reccur) && event_is_linked){
    alert('Linked reservations cannot be set-up on a recurring schedule.  Schedule each reservation individually if you want to also create a linked reservation.');
    return false;
  }

  if (require_service_project && parseInt($j('#service_project_id').val()) <= 0) {
    alert('This event must be linked to an ongoing project before you can save it. If you do not see a project in the drop-down, please contact your facility manager.');
    return false;
  }

  if (timeSaveButtonVisible()) {
    alert("You are modifying the " + timeSaveButtonTimesType() + " times.  Please click the 'Save' or 'Reset' button to resolve your changes before saving the event.");
    return false;
  }

  if (event_is_recurring) {
    var callback = function(value) {
      return function () {
        $j("#dialog-detach").dialog("destroy");
        $j("form#recurrent-event-form input#detach_recurrent").val(value);
        is_reservation == true ? saveServiceEvent() : saveSimpleServiceEvent();
      }
    };

    // Display a dialog if a recurring event is edited
    recurringDialog({
      "Only this event": callback(true),
      "This and all future events in this series": callback(false)
    });
  }
  else {
    is_reservation == true ? saveServiceEvent() : saveSimpleServiceEvent();
  }
}

var _cancelModal = function(event_id) {
  return $j('#custom_cancellation_modal_' + event_id);
};


function getCancellationFee(event, event_id, asset_id, from_ui){
  event.preventDefault();
  _cancelModal(event_id).show();

  var params_object = new Object;
  params_object.id = event_id;
  params_object.asset_id = asset_id;
  params_object.from_ui = from_ui;
  $j.ajax({
    url: '/calendar_events/' + event_id + '/cancellation_fee_amount',
    type: 'GET',
    data: $j.param(params_object),
    success: showCancellationFeeModal
  });
}

function getAdjustedCancellationFee(cancel_fee_data) {
  var feeAmount = cancel_fee_data.message.substring(1);
  var modal = _cancelModal(cancel_fee_data.event_id);

  modal.find('.adjust_fee_checkboxes').removeClass('hidden').show();
  modal.find('.fee_amount_input input').attr("placeholder", feeAmount);
}

function justificationSelected(event_id) {
  var modal = _cancelModal(event_id);
  if(!modal.find('.cancellation_charge_justification').val()) {

    modal.find('.error_message').removeClass('hidden').show().text('Please select a justification.');
    modal.find('.fee_amount_input > select').addClass('error');
    return false;
  }
  return true
}

function validateAdjustedFeeValue(adjustedFeeAmount, event_id) {
  var feeAmountRegEx = /^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
  var modal = _cancelModal(event_id);
  // Prevent submitting empty input
  if(adjustedFeeAmount.length == 0){

    modal.find('.error_message').removeClass('hidden').show().text('Please enter a cancellation fee amount.');
    modal.find('.fee_amount_input > input').addClass('error');
    return false;
  }
  // Ensure only 2 numbers after decimal and that its a valid number
  else if (!feeAmountRegEx.test(adjustedFeeAmount)) {
    modal.find('.error_message').removeClass('hidden').show().text('Please enter a valid cancellation fee amount.');

    modal.find('.fee_amount_input > input').addClass('error');
    return false;
  }
  return true;
}

function showCancellationFeeModal(cancel_fee_data) {
  var event_id = cancel_fee_data.event_id;
  var modal = _cancelModal(event_id);
  var closeButton = modal.find(".close_cancellation_modal");
  var comfirmButton = modal.find(".confirm_cancellation_fee");

  modal.find('.cancellation_fee_loading').hide();
  modal.find('.cancellation_fee_message').removeClass('hidden').show();
  modal.find('.fee_amount').text(cancel_fee_data.message);

  // unbind any previosly set click handlers
  closeButton.off('click');
  comfirmButton.off('click');

  // Allow core manager to adjust or waive cancellation fee

  if(modal.find('.adjust_fee_checkboxes').length > 0) {
    getAdjustedCancellationFee(cancel_fee_data);
  }

  // add event listener for cancel button
  closeButton.click(function(){
    modal.hide();
  });

  // add event listener for confirm button
  comfirmButton.click(function(event) {
    var managers_cancel_fee_action = modal.find('.confirm_cancellation_fee').data('managers_cancel_fee_action');
    if(managers_cancel_fee_action == 'adjust_fee') {

      var adjustedFeeAmount = modal.find('.fee_amount_input input').val();
      var justification = null;
      var justificationEl = modal.find('.cancellation_charge_justification');

      if(justificationEl.length > 0) {
        if (!justificationSelected(event_id)) {
          return false;
        }
        justification = justificationEl.val();
      }

      if (!validateAdjustedFeeValue(adjustedFeeAmount, event_id)) {
        return false;
      }
    }

    if (cancel_fee_data.from_ui == 'attributes_scheduler') {
      equipmentConfigurationsScheduler._deleteReservation($j('.cancel_reservation_button'), true, cancel_fee_data, managers_cancel_fee_action, adjustedFeeAmount, justification)
    }
    else if (cancel_fee_data.from_ui == 'configuration_reservations') {
      equipmentConfigurationsScheduler._deleteConfigReservation($j('.cancel_reservation_button'), true, cancel_fee_data, managers_cancel_fee_action, adjustedFeeAmount, justification)
    }
    else if (cancel_fee_data.from_ui == 'homepage') {
      preRemoveServiceEvent(true, cancel_fee_data, managers_cancel_fee_action, adjustedFeeAmount, justification, 'homepage');
    }
    else {
      preRemoveServiceEvent(true, cancel_fee_data, managers_cancel_fee_action, adjustedFeeAmount, justification);
    }
    modal.hide();
  });
}

// IS: in use
function preRemoveServiceEvent(cancel, cancel_with_fee, managers_cancel_fee_action, adjustedFeeAmount, justification, from_ui, event_id, asset_id) {
  // E11 does not support default parameters.
  // This is an extension in ES6 in the JavaScript language that browser does not recognize.
  // http://kangax.github.io/compat-table/es6/
  cancel_with_fee = cancel_with_fee || null;
  managers_cancel_fee_action = managers_cancel_fee_action || null;
  adjustedFeeAmount = adjustedFeeAmount || null;
  justification = justification || null;
  from_ui = from_ui || null;
  event_id = event_id || cancel_with_fee && cancel_with_fee.event_id || null;
  asset_id = asset_id || cancel_with_fee && cancel_with_fee.asset_id || null;

  var deleteWord = cancel ? 'cancel' : 'delete';

  if (!cancel_with_fee) {
    confirmText = 'Do you really want to ' + deleteWord + ' this event?';
    if (!confirm(confirmText)) {
      return false;
    }
  }

  var event_is_recurring = $j("form#recurrent-event-form input#has_recurrence_rule").val() == "true";

  if (event_is_recurring) {
    $j.bhPopup.hide();

    var callback = function(value) {
      return function () {
        $j("#dialog-detach").dialog("destroy");
        $j("form#recurrent-event-form input#detach_recurrent").val(value);
        removeServiceEvent(cancel, cancel_with_fee, managers_cancel_fee_action, adjustedFeeAmount, justification);
      }
    };

    var dialogButtons = {};

    if (cancel) {
      dialogButtons = {
        "Only cancel this event": callback(true),
        "Cancel this event and remove all future events in this series": callback(false)
      };
    }
    else {
      dialogButtons = {
        "Only this event": callback(true),
        "This and all future events in this series": callback(false)
      };
    }

    // Display a dialog is a recurring event is edited
    recurringDialog(dialogButtons);
  }
  else if (from_ui == 'homepage') {
    removeServiceEventFromHomepage(cancel, cancel_with_fee, managers_cancel_fee_action, adjustedFeeAmount, justification, event_id, asset_id, deleteWord);
  }
  else {
    removeServiceEvent(cancel, cancel_with_fee, managers_cancel_fee_action, adjustedFeeAmount, justification);
  }
}

function recurringDialog(dialogButtons) {
  $j("#dialog-detach").dialog({
    resizable: false,
    position: { my: 'bottom', at: 'center', of: $j("body"), within: $j('body') },
    width: 500,
    modal: true,
    buttons: dialogButtons
  });
}

// IS: in use
function saveServiceEvent() {
  var event_id = $j('#current_event_id').val();
  var devent = scheduler.getEvent(event_id);
  scheduler.updateEvent(devent.id);
  var is_new = devent.id > 2000000;
  devent.text = 'Saving...';

  var params_object = {
    id: devent.id,
    equipment_id: $j('#equipment_id').val()
  }
  if($j('#start_date').length) {
    params_object.start_date = $j('#start_date').val();
  }
  if($j('#end_date').length) {
    params_object.end_date = $j('#end_date').val();
  }

  if ($j('#service_project_id') && !$j('#service_project_id').attr('disabled')) {
    params_object.service_project_id = $j('#service_project_id').val();
  }

  params_object.from_lightbox = true;
  if (devent['confirm'])       { params_object.confirm = true; devent['confirm']=false;}//do it only once
  if (devent['approve'])       { params_object.approve = true; devent['approve']=false;}
  if (devent['verify'])        { params_object.verify  = true; devent['verify'] =false;}

  //AH 2012-07-26 -  Added this to pass through the value in the additional event subscriptions field - kind of funky cause set in jscript rather than passing though the form.
  if ($j('#additional_event_subscriptions').length) {
    params_object.additional_event_subscriptions = $j('#additional_event_subscriptions').val();
  }
  if (devent['comment_ids'])   { params_object.comment_ids = devent['comment_ids'].join(); }
  params_object['!nativeeditor_status'] = is_new ? 'inserted' : 'updated';
  params_object.event_type = devent.event_type;
  params_object.owner_id = devent.owner_id;
  params_object.group_profile_id = devent.group_profile_id;
  params_object.asset_id = devent.asset_id;
  params_object.notes = $j('#notes').val();
  params_object.notes_visibility = $j('#notes_visibility').val();
  params_object.copy_notes_to_li = $j('#copy_notes_to_li').prop('checked');
  params_object.study_id = $j('select#study_id').val();
  params_object.collaborator_profile_ids = $j('input[type="hidden"].collaborator_ids').val();

  var data = $j.param(params_object) + "&from_form=true";
  data += "&" + $j('#times_summary_wrapper :input').serialize();
  data += "&" + $j(' .event_availabilities :input').serialize();
  data += "&" + $j('#event_custom_form :input').serialize();
  data += "&" + $j('#simple_split_form_' + devent.id +' :input').serialize();
  data += "&" + $j('#recurrent-event-form').serialize();

  if ( $j("input#toggle_linked_reservations").prop('checked') ){
    var linked_data = $j('#linked-reservations :input');
    var selected_options = [];
    var disabled = $j('#linked-reservations').find(':input:disabled').removeAttr('disabled');
    // Only use checked options
    linked_data.each(function(idx, element) {
      if ( element.type === "checkbox" && element.checked ) {
        selected_options.push(element);
        if ( linked_data[idx + 1].type !== "checkbox" ) {
          selected_options.push(linked_data[idx + 1])
        }
      }
    });

    // Allows us to remove linked event
    if ( selected_options.length === 1 ) {
      data += "&" + linked_data.serialize();
    }else{
      data += "&" + $j(selected_options).serialize();
    }
    disabled.attr('disabled','disabled');
  }

  $j.ajax({
    url: '/calendar_events/' + devent.id,
    type: 'PUT',
    async: true,
    data: data,

    beforeSend: function() {
      blockAllButtons()
    },

    complete: function() {
      unblockAllButtons()
    },

    success: function(transport) {
      var handleRecurringEvent =
        $j('#recurrent-event-form input#is_recurrent').val() == 'true' &&
          $j("form#recurrent-event-form input#detach_recurrent").val() != 'true';

      if (handleRecurringEvent) {
        var is_error = $j(transport).find("action").attr("type") === "error";
        var recurrent_event_id = $j(transport).find("action").attr("recurrent_event_id");
        var error_message = $j(transport).find("action").text();

        recurrentEventCallback(recurrent_event_id, is_error, error_message);
      }
      else {
        afterSaveCallback(transport);
      }
    }
  });

  if (is_employee) {
    $j.bhPopup.hide();
  }

  disableSaveAndShowSpinner();

  return true;
}

// IS: in use
function saveAndConfirmServiceEvent(){
  var event_id = $j('#current_event_id').val();
  var devent = scheduler.getEvent(event_id);
  devent['confirm'] = true;
  devent['approve'] = true;
  return preSaveServiceEvent();
}

// IS: in use
function saveAndApproveServiceEvent(){
  var event_id = $j('#current_event_id').val();
  var devent = scheduler.getEvent(event_id);
  devent['approve'] = true;
  return preSaveServiceEvent();
}

// IS: in use
function saveAndVerifyServiceEvent(){
  var event_id = $j('#current_event_id').val();
  var devent = scheduler.getEvent(event_id);
  devent['verify'] = true;
  return preSaveServiceEvent();
}

// IS: in use
function serializeXmlNode(xmlNode) {
    // http://stackoverflow.com/questions/4916327/javascript-replacement-for-xmlserializer-serializetostring
    if (typeof window.XMLSerializer != "undefined") {
        return (new window.XMLSerializer()).serializeToString(xmlNode);
    } else if (typeof xmlNode.xml != "undefined") {
        return xmlNode.xml;
    }
    return "";
}

// process can be: 'create' or 'destroy'
function showRecurringNotifier(process) {
  $j("#recurring-notifier").removeClass("hidden");
  Spinners.create($j("#recurring-notifier").find(" .spinnable")).play();
}

function hideRecurringNotifier() {
  $j("#recurring-notifier").addClass("hidden");
  Spinners.get($j("#recurring-notifier").find(" .spinnable")).remove();
}


function _finishRecurrentEventRemoveCallback() {
  scheduler_refresh(false);
  unbindConfirmClose();
  alert("Reservations have been successfully removed.");
  hideRecurringNotifier();
}

function recurrentEventRemoveCallback(recurrent_event_id) {
  if (typeof recurrent_event_id === "string" && recurrent_event_id.length > 0) {
    var url = "/recurrent_events/" + recurrent_event_id + "/status";
    var job = new StatefulJob(url);

    job.on("start", function() {
      showRecurringNotifier('destroy');
    });

    job.on("success", _finishRecurrentEventRemoveCallback);

    job.on("fail", function(xhr) {
      if (xhr.status == 404) {
        _finishRecurrentEventRemoveCallback();
      }
      else {
        alert("Sorry, an error has occured. We have been notified about it and will fix it soon.");
      }
    });

    job.on("done", function() {
      hideRecurringNotifier();
    });

    job.poll();

    $j.bhPopup.hide();
    bindConfirmClose();
  }

  enableSaveAndHideSpinner();
}

// IS: in use
function recurrentEventCallback(recurrent_event_id, is_error, error_message) {
  if (typeof recurrent_event_id === "string" && recurrent_event_id.length > 0) {
    var url = "/recurrent_events/" + recurrent_event_id + "/status";
  }

  if (is_error) {
    alert(error_message);
    $j.bhPopup.show();
  }
  else {
    if (url !== undefined) {
      var job = new StatefulJob(url);
      var removeJob = function(recurrent_event_id) {
        $j.ajax({
          url: '/recurrent_events/' + recurrent_event_id,
          type: 'DELETE',
          dataType: 'json',

          success: function() {
            scheduler_refresh(false);
            unbindConfirmClose();
          }
        });
      };

      job.on("start", function() {
        showRecurringNotifier('create');
      });

      job.on("fail", function() {
        if (!window.navigatingAway) {
          alert("Sorry, an error has occured. We have been notified about it and will fix it soon.");
        } else {
          // Unset navigating away flag
          window.navigatingAway = false;
        }

      });

      job.on("error", function(error) {
        $j.ajax({
          type: "GET",
          url: "/recurrent_events/" + recurrent_event_id + "/is_overridable",
          dataType: "json",

          success: function(data) {
            if (data.overridable === true) {
              var resave = confirm(error.message + ' Do you want to proceed anyway?');
              if (resave === true) {
                $j.ajax({
                  type: "POST",
                  url: "/recurrent_events/" + recurrent_event_id + "/resave",
                  dataType: "json",

                  success: function(data) {
                    if (data.success === true) {
                      recurrentEventCallback(recurrent_event_id, false);
                    }
                    else {
                      alert("Error resaving recurring event!");
                    }
                  }
                });
              }
              else {
                removeJob(recurrent_event_id);
              }
            }
            else {
              alert(error.message);
              $j.bhPopup.show();
            }
          }
        });
      });

      job.on("success", function() {
        scheduler_refresh(false);
        alert("Reservations have been successfully saved!");
      });

      job.on("done", function() {
        unbindConfirmClose();
        hideRecurringNotifier();
      });

      job.poll();
    }

    $j.bhPopup.hide();
    bindSilentClose();
  }

  enableSaveAndHideSpinner();
}

// IS: in use
function afterSaveCallback(transport) {
  xml_string = serializeXmlNode(transport.documentElement)

  loader = new dtmlXMLLoaderObject(function(){});
  loader.loadXMLString(xml_string);

  var btag = loader.doXPath("//data/action")[0];
  var refresh_scheduler = updateEventFromXML(btag.getAttribute("sid"), btag.getAttribute("type"), btag.getAttribute("tid"), btag);

  if (refresh_scheduler) {
    scheduler_refresh(false);
  }

  enableSaveAndHideSpinner();
  unbindConfirmClose();
}

// IS: in use
function enableSaveAndHideSpinner() {
  var spinner = $j('#service_event_form_spinner');
  if (spinner) {
    spinner.hide();
  }
}

// IS: in use
function disableSaveAndShowSpinner() {
  var spinner = $j('#service_event_form_spinner');
  if (spinner) {
    spinner.show();
  }
}

// IS: in use
function replaceFormWithSpinner() {
  $j("#event_form").find('.centered_password_box').hide()
  $j('#event_loading_spinner').show()
  $j.magnificPopup.open({
    items: {
      src: "#event_form",
      type: "inline"
    }
  });

  return true
}

// IS: in use
function get_page_size() {
  var windowWidth, windowHeight;

  if (self.innerHeight) {	// all except Explorer
    if(document.documentElement.clientWidth){
      windowWidth = document.documentElement.clientWidth;
    } else {
      windowWidth = self.innerWidth;
    }
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }

  pageHeight = windowHeight;
  pageWidth = windowWidth;

  return [pageWidth,pageHeight];
}

// IS: in use
function bring_back_keynav(){
  scheduler.callEvent('onAfterLightbox', $j.map(scheduler.get_visible_events(), function(e){ return e.id }))
}

// IS: in use
function disable_scheduler_keynav(){
  scheduler.callEvent('onBeforeLightbox', $j.map(scheduler.get_visible_events(), function(e){ return e.id }))
}

// IS: in use
function actuallyShowBox(id) {
  if (id === undefined) {
    id = "#event_form";
  }

  $j.magnificPopup.open({
    items: {
      src: id,
      type: "inline"
    }
  });
  disable_scheduler_keynav();

  $j('.new_reservation_prompt #event_type').val('reservation');
  $j('.new_reservation_prompt #event_type').trigger('change');

  $j('#event_form').css('height', 'auto');
  $j("#event_form").find('canvas').hide();
  $j("#event_form").find('.centered_password_box').first().show();
}

// IS: in use
function loadForm(event_id, lab_selected) {
  var page_size = get_page_size();
  var devent = scheduler.getEvent(event_id);

  // TD: skip if event was deleted
  if (devent === undefined) {
    return false;
  }

  var is_new = (devent.owner_id == undefined);
  // IS: not a perfect guess
  var persisted = (devent.id < 1000000000000);

  if (lab_selected === undefined) {
    lab_selected = false;
  }

  $j('#current_event_id').val(devent.id);
  $j('#current_event_new_or_updating').val((!is_new) ? 'updating' : 'new');

  if(is_new && (is_multilab || is_employee)){
    actuallyShowBox();
    if (lab_selected === false && display_mode != 'availabilities') {
      return false;
    }
  }

  if (is_new && is_employee && display_mode != 'availabilities'){
    devent['comment_ids'] = [];
  }
  else {
    if (is_new && !is_employee && !is_multilab){
      devent['owner_id'] = current_user_id;
      devent['group_profile_id'] = singlelab;
    }

    var params_object = {};
    params_object.id = devent.id;
    params_object.equipment_id = devent.equipment_id;

    params_object.start_date = date_to_string(devent.start_date);
    params_object.end_date = date_to_string(devent.end_date);
    params_object.page_height = page_size[1];

    if (display_mode == 'availabilities') {
      params_object.event_type = 'availability';
    }
    else {
      params_object.event_type = devent.event_type;
    }

    params_object.owner_id = devent.owner_id;
    params_object.group_profile_id = devent.group_profile_id
    params_object.asset_id = asset_id;
    params_object.mode = display_mode;

    bindConfirmClose();

    // IS: we're checking in calendars#create if it's actually persisted
    if (!persisted) {
      $j.ajax({
        url: '/calendar_events',
        type: 'POST',
        dataType: 'script',
        data: $j.param(params_object),

        beforeSend: function() {
          replaceFormWithSpinner();
        },

        complete: function () {
          $j('#event_loading_spinner').hide();
          if ($j.magnificPopup.instance) {
            $j.magnificPopup.close();
          }
        },

        success: function() {
          if (window.ga) {
            // Include "create" in the URL we send to Google Analytics, to distinguish it from the index action.
            ga('send', 'pageview', '/calendar_events/create');
          }
        }
      });
    }
    else {
      var editEvent = function(event_id) {
        var url = '/calendar_events/' + event_id + '/edit';
        $j.ajax(url, {
          method: "GET",
          dataType: "script",
          data: $j.param(params_object),
          beforeSend: function(){
            replaceFormWithSpinner()
          },

          complete: function () {
            $j('#event_loading_spinner').hide()
            if($j.magnificPopup.instance){
              $j.magnificPopup.close()
            }
          },

          success: function() {
            if (window.ga) {
              ga('send', 'pageview', url);
            }
          }
        });
      }

      if (devent.has_linked_event === true) {
        if (confirm('This is a linked reservation that cannot be edited directly. Would you like to edit the parent reservation?')) {
          editEvent(devent.parent_event_id);
        }
        else {
          unbindConfirmClose();
        }
      }
      else {
        editEvent(devent.id);
      }
    }
  }
}

// IS: in use
function scheduler_refresh(toggle_relevant_schedules, callback) {
  if(typeof toggle_relevant_schedules == 'undefined'){
    toggle_relevant_schedules = true
  }

  scheduler.clearAll();
  add_assets = [];
  checkboxes = $j('input[type="checkbox"][name^="add_view_asset_"]');
  toggle     = $j("#toggle_relevant_schedule");

  if(toggle_relevant_schedules){
    toggle.data('checked', !toggle.data('checked'));
    checkboxes.prop('checked', toggle.data('checked'));
  }else{
    // Do not show the linked events by default
    toggle.data('checked', false);
    checkboxes.prop('checked', false);
  }

  // Toogle button
  if(toggle.data('checked')){
    toggle.text('hide other relevant schedules');
  }else{
    toggle.text('show other relevant schedules');
  }

  // Get all checked other relevant schedules
  add_assets = checkboxes.map(function(){ if(this.checked) return this.value; }).get();
  add_asset_add = (add_assets.length > 0) ? '&additional_assets='+add_assets.join('_') : '';

  if (typeof display_mode !== 'undefined' && display_mode === 'availabilities') {
    mode_add = "&show_availabilities=true";
  }
  else {
    mode_add = "";
  }

  for_configurations = $j(scheduler._obj).hasClass('equipment_attributes_scheduler') ? "&for_configurations=true" : '';
  skip_timeout = '&skip_session_timeout=true';

  // In old confirm usage, asset_id is an element, while in reservation
  // details, it's an int.  We need to pull the asset ID from the element
  // if that is in fact what it is.
  asset_id_val = isNaN(asset_id) ? $j(asset_id).val() : asset_id;
  scheduler.load("/calendar_events.json?asset_id="+asset_id_val+add_asset_add+mode_add+for_configurations+skip_timeout, 'json', function() {
    if (typeof callback === 'function') {
      callback();
    }
  });
}

// IS: in use
function multilabNewNextStep(){
  replaceFormWithSpinner();

  var devent = scheduler.getEvent($j('#current_event_id').val());
  devent['group_profile_id'] = $j('#group_profile_id').val();
  devent['owner_id'] = current_user_id;

  loadForm(devent.id, true);
  return true;
}

// IS: in use
function employeeNewNextStep() {
  var is_reservation = $j('#event_type').val() === 'reservation';
  var owner_present = $j('#owner_id').length > 0 && $j('#owner_id').val() !== '';
  var group_id_present = $j('#group_profile_id').length > 0 && $j('#group_profile_id').val() !== '';
  var reservation_invalid = is_reservation && (!owner_present || !group_id_present);

  if (reservation_invalid) {
    return false;
  }
  else {
    var devent = scheduler.getEvent($j('#current_event_id').val());
    devent.event_type = $j('#event_type').val();
    devent.owner_id = $j('#owner_id').val();

    if (is_reservation) {
      devent.group_profile_id = $j('#group_profile_id').val();
    }

    replaceFormWithSpinner();
    loadForm(devent.id);

    return false;
  }
}

// IS: in use
function updateEventFromXML(sid, action, tid, btag) {
  var event_id = action == 'inserted' ? sid : tid;
  var e = scheduler.getEvent(event_id);

  if (!is_employee && action != 'error')
    $j.bhPopup.hide();
  if (e){

    var start_date = btag.getAttribute("start_date").trim();
    var end_date = btag.getAttribute("end_date").trim();
    var equipment_id = btag.getAttribute("equipment_id").trim();

    if(e.text=='New event' && action=='error'){ //for all intents and purposes this event hasn't been created yet
      e.text = 'New event';
    }else{
      e.text = btag.getAttribute("text");
    }
    e.css_class = btag.getAttribute("css_class");

    if (start_date)    { scheduler.setEventStartDate(event_id, string_to_date(start_date)); }
    if (end_date)      { scheduler.setEventEndDate(event_id, string_to_date(end_date)); }
    if (equipment_id)  { e.equipment_id = equipment_id; }

    var linked_reservations_ids = btag.getAttribute('linked_reservations_ids');

    if (linked_reservations_ids) {
      linked_reservations_ids = JSON.parse(linked_reservations_ids);

      for (i = 0; i < linked_reservations_ids.length; ++i) {
        if (scheduler.getEvent(linked_reservations_ids[i]) !== undefined){
          if (start_date) { scheduler.setEventStartDate(linked_reservations_ids[i], string_to_date(start_date)); }
          if (end_date) { scheduler.setEventEndDate(linked_reservations_ids[i], string_to_date(end_date)); }
        }
      }
    }

    switch (action) {

      case 'error':
        if (btag.getAttribute('remove') == 'true')
          scheduler.deleteEvent(e.id, true);

        setiLabNotice("Your reservation has NOT been saved!");
        if(btag.getAttribute('qstring')){// this means it's overridable
          if(confirm(btag.firstChild.data+' Do you want to proceed anyway?')){
            var params_object = eval('('+btag.getAttribute('qstring')+')');
            resaveServiceEvent(e.id,params_object);
          }
        }else{
          alert(btag.firstChild.data);
        }
        break;

      case 'inserted':
        scheduler.changeEventId(sid,tid);
        setiLabNotice("Your reservation has been created!");
        break;

      case 'deleted':
        scheduler.deleteEvent(e.id, true);
        setiLabNotice("Your reservation has been deleted!");
        return false;
        break;

      case 'updated':
        setiLabNotice("Your reservation has been updated!");

        if (btag.getAttribute('with_cancelled') == 'true') {
          scheduler_refresh(false);
          return false;
        }

        break;
    }

    scheduler.updateEvent(e.id);

    if (btag.getAttribute('linked_reservations_ids') !== '[]') {
      $j('input[type="checkbox"][name^="add_view_asset_"]').attr("checked", true);

      // If there is reservations with unfilled custom form
      if (btag.getAttribute('invalid_linked_reservations') !== '[]') {
        var invalid_reservation = JSON.parse(btag.getAttribute('invalid_linked_reservations'))[0];

        scheduler_refresh(false, function() {
          loadForm(invalid_reservation, false, true);
        });
      }
      else {
        scheduler_refresh(false);
      }

      return false;
    }
  }

  return true;
}

// IS: in use by equipment_controller
function checkEquipmentPrice(input) {
  var row = $j(input).closest('.equipment_price');
  var value = $j(input).val();

  if (isNaN(parseFloat(value)) || !isFinite(value)) {
    row.addClass('disabled');
  }
  else {
    row.removeClass('disabled');
  }
}

$j(' .scan_price_checkbox').live('change', function(){
  fixSelectOiDropDowns()
})

// IS: in use in equipment CRUD
function fixSelectOiDropDowns(){
  opts = [];
  $j("input[id$='_supplier_catalog_number']").each( function (index, el){
    if ($j(el).parent('tr').find('.remove_input').val() =='0') {
      value = el.value;
      idd = "";
      if ($j(el).parent('tr').find("input[id$='_id']").last().length){
        idd = $j(el).parent('tr').find("input[id$='_id']").last().val();
      }
      if (idd === '') {
        idd = $j(el).parent('tr').find("input").last().attr('name').match(/[\d\.]+/g)[0];
      }
      $j(el).attr('oid', idd);
      opts.push([value, idd]);
    }
  });
  selectConfirmation($j('#reservations_confirmation_select'));
  return true;
}

// IS: in use in equipment CRUD
function removeRow(row_element){
  $j(row_element).hide();
  $j(row_element).find('.remove_input').val(1);
}

// IS: in use in equipment CRUD
function selectConfirmation(select){
  if(select.value=='select'){
    $j('.av_confirmation_toggle').each(function(index, ac){$j(ac).show();});
  }else{
    $j('.av_confirmation_toggle').each(function(index, ac){$j(ac).hide();});
  }
}

// IS: in use
function beforeNoChargeAddon(me, li_id){
    var old_value, _this = this;
    if ($j(me).data('require_justification') === true && $j(me).prop('checked')) {
      Tipped.setDefaultSkin("light");
      old_value = $j(me).data('value');
      $j(me).prop('checked', !$j(me).prop('checked'));
      $j(me).data('tipped-object', Tipped.create(me, '/line_item/charge_justification_options/' + li_id+'?status=not_billable&addon=true', {
        ajax: {
          async: false,
          cache: false,
          data: {
            tipped_ajax_request: true
          }
        },
        hideOn: false,
        showOn: false,
        closeButton: true,
        closeButtonSkin: 'light',
        containment: '#wrapper_main',
        onShow: function(content, element) {
          eval($j(element).data('callback'));
          return setTimeout(function() {
            return Tipped.refresh(element);
          }, 1000);
        },
        onHide: function(content, element) {
          return eval($j(element).data('hide-callback'));
        }
      }));
      Tipped.show(me);
      return false;
    } else {
      Tipped.remove(me);
      return no_charge_addon($j(me).prop('checked'), li_id, null);
    }
  };

// IS: in use
function no_charge_addon(no_charge, li_id, justification) {
  var checkbox_span = $j("#no_charge_check_" + li_id);
  var checkbox = $j("#nocharge_addon_check_" + li_id);
  //var no_charge = checkbox.prop("checked");

  $j.ajax("/service_event/addon_no_charge", {
    type: "POST",
    dataType: "script",
    data: {
      line_item_id: li_id,
      no_charge: no_charge,
      justification: justification
    },

    beforeSend: function() { showSpinner(checkbox_span); },
    complete: function() { hideSpinner(checkbox_span); }
  });
}

// IS: in use
function bindConfirmClose() {
  $j(window).on('beforeunload.confirmClose', function(){
    return "Warning! Navigating away from this page will cause you to lose any changes to this reservation.";
  });
}

function bindSilentClose() {
  $j(window).on('beforeunload', silentClose);
}

// IS: in use
function unbindConfirmClose() {
  $j(window).off('beforeunload.confirmClose');
  // Unset navigating away flag
  window.navigatingAway = false;
}

function silentClose(event) {
  event.preventDefault();
  // Set navigating away flag
  window.navigatingAway = true;
}

//From here on the functions should be jquery-based
//TODO all these things have to be removed from the global namespace (MK 2012-11-06)
//================================================================
// IS: in use
function adjust_scans(asset_id,event_id){
  req = $j.ajax({
    url: '/service_event/adjust_scans/'+asset_id,
    data: 'event_id=' + event_id + '&' + $j('#scans_details_' + event_id + ' :input').serialize(),
    beforeSend: function(){
      confirmUsage.hide_confirm_usage_event(event_id);
      Tipped.hide($j('#scans_details_'+event_id));
    },
    complete: function(){
      confirmUsage.show_confirm_usage_event(event_id);
      $j('#summary_spinner_wrapper_short_'+event_id+', #summary_spinner_short_'+event_id).hide();
    },
  });
}

function loadmask(selector){
  var obj = $j(selector)
  if(typeof(obj.attr('loadmask_id')) == 'undefined'){
    var offsets = obj.offset()
    var mask = $j('<div>').addClass('ilab_loadmask').css('top', offsets.top).css('left', offsets.left).css('width', obj.width()).css('height', obj.height())
    mask.append($j('<img src="/images/ajax-loader2.gif">').addClass('ilab_loadmask_spinner').css('margin', '20% 45%'))
    $j('body').append( mask)
    mask.uniqueId()
    obj.attr('loadmask_id', mask.attr('id'))
  } else {
    $j('#'+obj.attr('loadmask_id')).remove()
    obj.removeAttr('loadmask_id')
  }
}

// IS: in use
function events_around(id,table_id,the_object){
  loadmask('#service_request_event_form')
  req = $j.ajax({
      url: '/service/events_around/'+id,
      data: $j("#"+table_id+" :input").serialize()
    });
}

// IS: in use in equipment CRUD
function delete_equipment(id){
  var data = $j("#delete_"+id+"_fields :input").serialize();

  Tipped.hideAll();
  $j('#delete_button_'+id).hide();
  $j('#delete_spinner_'+id).show();

  $j.ajax({
    url: '/equipment/delete_instance/'+id,
    data: data,
    success: function(data){
      $j('#instance_inputs').html(data);
    },
    error: function(data){
      $j('#delete_button_'+id).show();
      $j('#delete_spinner_'+id).hide();
      alert(data.responseText);
    }
  });
}

// IS: in use in equipment CRUD
function recover_equipment(id,asset_id){
  Tipped.hideAll();
  $j('#recover_button').hide();
  $j('#recover_spinner').show();
  req = $j.ajax({
      url: '/equipment/recover_instance/'+id+'?asset_id='+asset_id,
      success: function(data){
        $j('#instance_inputs').html(data);
        $j('#recover_button').show();
        $j('#recover_spinner').hide();
      },
      error: function(data){
        $j('#recover_button').show();
        $j('#recover_spinner').hide();
        alert(data.responseText);
      }
    });
}

// unobtrusive behaviour attachment
$j('select.event_time_slot_select_short').livequery('change', function(){
  var _this = $j(this);
  var event_id = _this.data('event_id');
  var time_section_id = _this.data('timesection');
  var price_ids = {};

  price_ids[time_section_id] = _this.val();

  $j.ajax({
    url: '/service_event/save_time_sections',
    data: {
      event_id: event_id,
      time_sections: { price_ids: price_ids }
    },
    beforeSend: function() {
      confirmUsage.hide_confirm_usage_event(_this.data('event_id'));
    },
    complete: function() {
      confirmUsage.show_confirm_usage_event(_this.data('event_id'));
    }
  });
});

// unobtrusive behavior for studies on events
$j('.event_study_selector').find('#study_id').livequery('change', function(){
  var _this = $j(this);
  var study_id = _this.val()
  var data = {
    study_id: study_id
  }

  $j.ajax({
    url: "/studies/"+study_id+"/study_notes/display_simple_notes",
    type: 'GET',
    data: data,
    complete: function(response){
        var text = response.responseText || response
        $j('.event_study_selector').find('.event_study_notes').html(text);
      }
  })
});

// temporary function to get us started displaying event detials in other contexts.
function loadFormExt(event_id, lab_selected) {
  var page_size = get_page_size();


  var is_new = false; //(devent.owner_id == undefined);
  // IS: not a perfect guess
  var persisted = true //(devent.id < 1000000000000);

  if (lab_selected === undefined) {
    lab_selected = false;
  }

  $j('#current_event_id').val(event_id);

  $j.ajax('/calendar_events/' + event_id + '/edit?from_line_item=true', {
    method: "GET",
    dataType: "script",
    // data: $j.param(params_object),
    beforeSend: function(){
      replaceFormWithSpinner()
    },

    complete: function () {
      $j('#event_loading_spinner').hide()
      if($j.magnificPopup.instance){
        $j.magnificPopup.close()
      }
    }
  });
}

var scheduling_modal_buttons = ['service_event_cancel_button', 'delete_event', 'service_event_save_button', 'service_event_confirm_button', 'cancel_charges_btn'];

var buttonElement = function(id) {
  return $j('.buttons #' + id);
}

var setPointerEventsCss = function(element, value) {
  element.css('pointer-events', value);
}

var disableElement = function(element) {
  element.addClass('disabled')
  element.find('select').prop('disabled', true)
}

var enableElement = function(element) {
  element.removeClass('disabled')
  element.find('select').prop('disabled', false)
}

function blockAllButtons() {
  scheduling_modal_buttons.forEach(function(id) {
    elem = buttonElement(id)
    setPointerEventsCss(elem, 'none')
    disableElement(elem)
  })
}

function unblockAllButtons() {
  scheduling_modal_buttons.forEach(function(id) {
    elem = buttonElement(id)
    setPointerEventsCss(elem, 'auto')
    enableElement(elem)
  })
}

;
(function() {
  var quote_items_recalculation;

  $j(function() {
    var dateTimeChanged;
    $j("body").on("calendarChange", ".date_end_input", function() {
      $j(this).closest('.prices_block').find('.date_end_input').val($j(this).val());
      return true;
    });
    $j("body").on("calendarChange", ".date_start_input", function() {
      $j(this).closest('.prices_block').find('.date_start_input').val($j(this).val());
      return true;
    });
    $j('body').on('click', '.public_edc_check', function() {
      var asset_id, edc_id, is_public;
      asset_id = $j(this).data('asset_id');
      edc_id = $j(this).data('edc_id');
      is_public = $j(this).is(':checked');
      return $j.ajax('/equipment/set_default_charge_public', {
        type: 'POST',
        dataType: 'script',
        data: {
          asset_id: asset_id,
          edc_id: edc_id,
          is_public: is_public
        }
      });
    });
    $j("#create_equipment_save").live("click", function(event) {
      $j(this).attr("disabled", "disabled");
      $j(this).closest("form").submit();
      return true;
    });
    $j('a#edit-schedule-description').live('click', function(event) {
      var description_div, edit_div, self;
      event.preventDefault();
      self = $j(this);
      edit_div = $j("#description-edit");
      description_div = $j("#description");
      setTextareaToTinyMCE(edit_div.find("textarea.tiny-mce").prop("id"));
      edit_div.show();
      description_div.hide();
      return self.hide();
    });
    $j('a#save-schedule-description').live('click', function(event) {
      var description_div, edit_div, edit_link, form, self, textarea;
      event.preventDefault();
      self = $j(this);
      form = $j("#description-edit").find("form");
      edit_div = $j("#description-edit");
      description_div = $j("#description");
      textarea = edit_div.find("textarea.tiny-mce");
      edit_link = $j('a#edit-schedule-description');
      unsetTextareaToTinyMCE(textarea.prop("id"));
      return $j.ajax(form.prop("action"), {
        type: form.prop("method"),
        dataType: "json",
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            return showSpinner($j(edit_div));
          };
        })(this),
        success: (function(_this) {
          return function() {
            hideSpinner($j(edit_div));
            edit_div.hide();
            description_div.html(textarea.val()).show();
            textarea.html(textarea.val());
            return edit_link.show();
          };
        })(this)
      });
    });
    $j('a#cancel-schedule-description').live('click', function(event) {
      var description_div, edit_div, edit_link;
      event.preventDefault();
      edit_link = $j('a#edit-schedule-description');
      edit_div = $j("#description-edit");
      description_div = $j("#description");
      unsetTextareaToTinyMCE(edit_div.find("textarea.tiny-mce").prop("id"));
      edit_div.hide();
      description_div.show();
      return edit_link.show();
    });
    window.initTimeSummary = function(self) {
      var d, event_id, ref, time_summary;
      if (!self.attr('initialized')) {
        d = document.createElement('table');
        $j(d).attr('class', 'times_summary');
        event_id = (ref = self.attr('event_id')) != null ? ref : '';
        if (self.is(':checked')) {
          time_summary = $j('#availability_switcher_' + event_id).parent().find('.times_summary.regular').first();
          $j(d).attr('class', 'times_summary regular');
        } else {
          time_summary = $j('#availability_switcher_' + event_id).parent().find('.times_summary.overridden').first();
          $j(d).attr('class', 'times_summary overridden');
        }
        $j(d).html(time_summary.html());
        self.data('holder', d);
        time_summary.remove();
        Tipped.refresh("#show_event_availabilities_link_" + event_id);
        self.attr('initialized', true);
      }
      return true;
    };
    $j(' .change_equipment_availability').livequery(function() {
      return window.initTimeSummary($j(this));
    });
    window.toggleOverideAvailabilities = function(self) {
      var d, event_id, ref, time_summary;
      d = document.createElement('table');
      event_id = (ref = self.attr('event_id')) != null ? ref : '';
      if (self.is(':checked')) {
        time_summary = $j('#availability_switcher_' + event_id).parent().find('.times_summary.regular').first();
        $j(d).attr('class', 'times_summary regular');
      } else {
        time_summary = $j('#availability_switcher_' + event_id).parent().find('.times_summary.overridden').first();
        $j(d).attr('class', 'times_summary overridden');
      }
      time_summary.after(self.data('holder'));
      $j(d).html(time_summary.html());
      self.data('holder', d);
      time_summary.remove();
      Tipped.refresh("#show_event_availabilities_link_" + event_id);
      window.hide_split_form_of_no_charge();
      return true;
    };
    $j('.change_equipment_availability:not(.presentation)').live('change', function() {
      window.toggleOverideAvailabilities($j(this));
      if ($j(this).data('overridden') !== $j(this).is(':checked')) {
        $j(this).data('overridden', $j(this).is(':checked'));
        recalculateQuoteItems($j(this).attr('event_id'));
      }
      return true;
    });
    window.hide_split_form_of_no_charge = function() {
      var all_no_charge, no_charge;
      if ($j('.simple_split_form:first').attr('hide_allowed') === "true") {
        no_charge = $j.map($j(' .event_time_slot_select option:selected'), function(e) {
          return !!$j(e).text().match(/no charge/ig);
        });
        all_no_charge = !no_charge.includes(false) && $j('#event-add-on-charges-table tbody').length === 0;
        if (all_no_charge) {
          $j('#split_form_wrapper').prev().hide();
          $j('#split_form_wrapper').hide();
        } else {
          $j('#split_form_wrapper').prev().show();
          $j('#split_form_wrapper').show();
        }
      }
      return true;
    };
    $j(' .event_time_slot_select').livequery(function() {
      $j(this).closest('tr').css('background-color', $j(this).find('option:selected')[0].style.backgroundColor);
      return $j(this).change(function() {
        return window.hide_split_form_of_no_charge();
      });
    });
    $j('#event-details .equipment_dropdown').live('change', function() {
      var date_picker, time_picker;
      date_picker = $j('input.start.hasDatepicker');
      time_picker = $j('input.start.ui-timepicker-input');
      if ($j(this).hasClass('quick_event')) {
        return;
      }
      $j.ajax("/service_event/refresh_time_summaries", {
        beforeSend: function() {
          $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').show();
          return $j('#times_summary_wrapper').hide();
        },
        success: function() {
          $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').hide();
          return $j('#times_summary_wrapper').show();
        },
        data: {
          event_id: $j(this).attr('event_id'),
          start_date: ($j('#scheduled_start_date_date').val()) + " " + ($j('#scheduled_start_date_time').val()),
          end_date: ($j('#scheduled_end_date_date').val()) + " " + ($j('#scheduled_end_date_time').val())
        }
      });
      return true;
    });
    $j('.asset_line .asset_name').livequery(function() {
      $j(this).live('click', function() {
        var arrow, toggled_field;
        arrow = $j(this).find('span.toggle_asset');
        toggled_field = $j(this).find('input.toggled_hidden_field');
        if (arrow.html() === "▼") {
          arrow.html("►");
          toggled_field.val(false);
        } else {
          arrow.html("▼");
          toggled_field.val(true);
        }
        return $j(this).parent().next().toggle();
      });
      return false;
    });
    window.timeChangedCallback = function(element) {
      var $this;
      $this = $j(element);
      if (!($this.hasClass('quick_event') || $this.hasClass('non_reservation'))) {
        return $j.ajax("/service_event/refresh_time_summaries", {
          beforeSend: function() {
            $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').show();
            return $j('#times_summary_wrapper').hide();
          },
          success: function() {
            $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').hide();
            return $j('#times_summary_wrapper').show();
          },
          data: {
            event_id: $j('#current_event_id').val(),
            start_date: ($j('#scheduled_start_date_date').val()) + " " + ($j('#scheduled_start_date_time').val()),
            end_date: ($j('#scheduled_end_date_date').val()) + " " + ($j('#scheduled_end_date_time').val())
          }
        });
      }
    };
    $j(' .scheduled_time input').live('change', function() {
      if ($j(this).hasClass('override_asset_line_availabilities')) {
        return true;
      }
      return window.timeChangedCallback(this);
    });
    $j(' .summary_price_select').live('change', function() {
      var data, event_id;
      data = $j(' .summary_price_select').serializeArray();
      event_id = $j('input[name=current_event_id]').val();
      data.push({
        name: 'event_id',
        value: event_id
      });
      $j.ajax("/service_event/refresh_time_summaries", {
        beforeSend: function() {
          $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').show();
          return $j('#times_summary_wrapper').hide();
        },
        success: function() {
          $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').hide();
          return $j('#times_summary_wrapper').show();
        },
        data: data
      });
      return true;
    });
    $j('.event_time_slot_select:not(.presentation)').live('change', function() {
      $j(this).closest('tr').css('background-color', $j(this).find('option:selected')[0].style.backgroundColor);
      recalculateQuoteItems($j(this).data('event_id'));
      return true;
    });
    $j('#times_summary_wrapper').livequery(function() {
      $j.ajax("/service_event/refresh_time_summaries", {
        beforeSend: function() {
          return $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').show();
        },
        success: function() {
          return $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').hide();
        },
        data: {
          event_id: $j('#current_event_id').val()
        }
      });
      return true;
    });
    $j(' .times_summary_wrapper_short').livequery(function() {
      var event_id, timeout;
      event_id = $j(this).data('id');
      timeout = $j(this).data('delay');
      window.refreshTimeSummariesShort(event_id, timeout);
      return true;
    });
    $j(' .show_detailed_costs_link').live('click', function() {
      var event_id;
      event_id = $j(this).attr('event_id');
      Tipped.create(this, {
        ajax: {
          url: '/service_event/refresh_time_summaries',
          cache: false,
          type: 'post',
          data: {
            event_id: event_id,
            in_request_summary: true
          }
        },
        hook: "bottomright",
        showOn: 'click',
        hideOn: {
          element: 'self',
          event: 'click'
        },
        closeButton: true,
        closeButtonSkin: 'light',
        maxWidth: 800,
        fixed: true,
        target: 'barcodes_wrapper',
        onHide: function(content, element) {
          return Tipped.remove(element);
        },
        onShow: function(content, element) {
          eval($j(element).data('callback'));
          return setTimeout(function() {
            return Tipped.refresh(element);
          }, 1000);
        }
      });
      Tipped.show(this);
      return false;
    });
    $j(' .edit_times').live('click', function() {
      $j(this).parent().parent().find('span.edit').show();
      $j(this).parent().hide();
      return false;
    });
    $j(' .reset_times').live('click', function() {
      $j(this).parent().parent().find('.initial').each(function() {
        var id;
        id = $j(this).attr('id').replace('_initial', '');
        $j("#" + id).val($j(this).val());
        $j("#" + id + "_date").val($j(this).val().match(/^(.+) (.+)$/)[1]);
        $j("#" + id + "_time").val($j(this).val().match(/^(.+) (.+)$/)[2]);
        return $j("#" + id).attr('disabled', 'true');
      });
      $j(this).hide();
      return false;
    });
    dateTimeChanged = function(self) {
      var table;
      table = self.parents().find('table[event_id]');
      $j('#event_settings_global_end_time_changed').val('false');
      $j('#event_settings_global_time_changed').val('false');
      if (!self.hasClass('asset_only')) {
        if (self.attr('id') === 'event_end_date_time' || self.attr('id') === 'event_end_date_date') {
          $j('#event_settings_global_end_time_changed').val('true');
        }
        $j('#event_settings_global_time_changed').val('true');
      }
      events_around(table.attr('event_id'), table.attr('id'), this);
      return true;
    };
    $j('.quick_event.datepart, .quick_event.ui-timepicker-input').live('change', function() {
      return dateTimeChanged($j(this));
    });
    $j('select.equipment_availability').live('change', function() {
      var html, img, un;
      img = 'tick';
      if (!$j(this).find(":selected").attr('available')) {
        img = 'delete_org';
      }
      un = '';
      if (!$j(this).find(":selected").attr('available')) {
        un = 'not';
      }
      html = '<img src="/images/' + img + '.png"> (time ' + un + ' available)';
      $j(this).parent().next().html(html);
      return true;
    });
    $j("input.repeat-type-radio").live("click", function(event) {
      var input;
      input = $j(this);
      $j(".dhx-repeat").not(".hidden").addClass("hidden");
      $j("#repeat-type-" + (input.val())).removeClass("hidden");
      return true;
    });
    $j("input#toggle_linked_reservations").live("change", function(event) {
      var self, target;
      self = $j(this);
      target = $j('#linked-reservaions-body');
      if (self.prop("checked")) {
        return target.removeClass("hidden");
      } else {
        return target.addClass("hidden");
      }
    });
    $j("input#is_recurrent").live("change", function(event) {
      var self, target;
      self = $j(this);
      target = $j("#recurring-details-body");
      if (self.prop("checked")) {
        target.removeClass("hidden");
        $j("#recurrent-event-form input#is_recurrent").val(true);
        $j('#service_event_save_button').html('<img src="/images/fff_silk/error.png"/> Check availablility and save');
      } else {
        target.addClass("hidden");
        $j("#recurrent-event-form input#is_recurrent").val(false);
        $j('#service_event_save_button').html('<img src="/images/fff_silk/disk.png"/> Save Reservation');
      }
      return true;
    });
    $j(' .poor_match').livequery(function() {
      var inputs_selector, links_selector, msg;
      msg = 'Not allowed until you adjust owner and/or group.';
      inputs_selector = 'select, input:checkbox';
      links_selector = 'a, td.cu_selected, td.cu_unselected, img.tipped_target';
      $j(this).find(inputs_selector).not('.poor_match_enabled').attr('disabled', true).addClass('tipsy_tip').attr('title', msg);
      $j(this).find(links_selector).not('.poor_match_enabled').removeAttr('onclick').off('click').on('click', function() {
        return false;
      }).removeClass('tipped_target').addClass('strike tipsy_tip').attr('title', msg);
      return true;
    });
    true;
    $j('#service_events').livequery(function() {
      return $j(this).on('click', '.confirm_usage_delete_button', function() {
        var fail_handler, link;
        link = $j(this);
        if (!confirm(link.data('confirmMsg'))) {
          return false;
        }
        fail_handler = function() {
          return alert('A problem happened while deleting this event');
        };
        showSpinner(link);
        $j.ajax({
          url: link.attr('href'),
          type: 'DELETE',
          dataType: 'json'
        }).done(function(data) {
          if (data.mode === 'deleted') {
            return $j("#all_trs_" + (link.data('eventId'))).effect('fade');
          } else {
            return fail_handler();
          }
        }).fail(fail_handler).always(function() {
          return hideSpinner(link);
        });
        return false;
      });
    });
    return $j('input.j-validate-time').live('change', function(event) {
      var $this, parsedValue, value;
      $this = $j(this);
      value = $this.val();
      parsedValue = Date.parse(value);
      if (parsedValue && parsedValue.format($this.data('format')).replace(/^0/, '') === value.toUpperCase().trim().replace(' ', '').replace(/^0/, '')) {
        return true;
      } else {
        $this.val($this.prop('defaultValue'));
        return false;
      }
    });
  });

  window.refreshTimeSummariesShort = function(event_id, timeout) {
    var $selector;
    if (timeout == null) {
      timeout = 0;
    }
    $selector = "#summary_spinner_wrapper_short_" + event_id + ", #summary_spinner_short_" + event_id;
    $j($selector).show();
    setTimeout(function() {
      return $j.ajax("/service_event/refresh_time_summaries", {
        success: function() {
          return $j($selector).hide();
        },
        data: {
          event_id: event_id,
          short: 1
        }
      });
    }, timeout * 500);
    return false;
  };

  window.cancelUpdateDetails = function(event_id) {
    $j('#availabilities_' + event_id).html('');
    $j.ajax("/service_event/refresh_time_summaries", {
      beforeSend: function() {
        $j('#summary_spinner_wrapper_short_' + event_id + ', #summary_spinner_short_' + event_id).show();
        return $j('#times_summary_wrapper_short_' + event_id).html('');
      },
      success: function() {
        return $j('#summary_spinner_wrapper_short_' + event_id + ', #summary_spinner_short_' + event_id).hide();
      },
      data: {
        event_id: event_id,
        short: 1
      }
    });
    Tipped.hideAll();
    return false;
  };

  window.updateDetails = function(event_id) {
    var data;
    data = $j("#event_availabilities_wrapper_" + event_id + " :input").serializeArray();
    data.push({
      name: 'event_id',
      value: event_id
    });
    $j.ajax("/service_event/save_time_sections", {
      data: data,
      beforeSend: function() {
        return confirmUsage.hide_confirm_usage_event(event_id);
      },
      success: function(data) {
        return confirmUsage.show_confirm_usage_event(event_id);
      }
    });
    Tipped.hideAll();
    return true;
  };

  window.getEventAddOnChargesSum = function(event_id) {
    if ($j('#add_on_summary_charges_' + event_id).is(':visible')) {
      $j.ajax("/service_event/add_on_charges_sum/" + event_id, {
        method: 'GET',
        complete: (function(_this) {
          return function(response) {
            var sum;
            sum = parseFloat(response.responseText.slice(1, -1));
            $j('#add_on_summary_charges_' + event_id).html(response.responseText);
            if (sum > 0) {
              return $j('#charge_details_for_' + event_id).find('img').prop('src', '/images/add.png');
            } else {
              return $j('#charge_details_for_' + event_id).find('img').prop('src', '/images/grey_add.png');
            }
          };
        })(this)
      });
    }
    return false;
  };

  quote_items_recalculation = null;

  window.recalculateQuoteItems = function(event_id) {
    var data;
    if (event_id == null) {
      event_id = 0;
    }
    if (quote_items_recalculation && quote_items_recalculation.readyState !== 4) {
      quote_items_recalculation.abort();
    }
    data = $j(' .event_time_slot_select').serializeArray();
    data.push({
      name: 'event_id',
      value: event_id
    });
    data.push({
      name: 'expand_price_details',
      value: true
    });
    data.push({
      name: 'override_availabilities_toggled',
      value: $j('.change_equipment_availability').prop('checked')
    });
    quote_items_recalculation = $j.ajax("/service_event/refresh_time_summaries", {
      beforeSend: function() {
        return $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').show();
      },
      success: function() {
        return $j('#availabilities_calculation_spinner, #availabilities_calculation_spinner_wrapper').hide();
      },
      data: data
    });
    return true;
  };

}).call(this);
(function() {
  $j(function() {
    window.selected_add_event_availabilities = {};
    window.add_toggle_icon = function(item, show_it) {
      if (show_it) {
        $j(item).append('<span class="pluss_icon"> +</span>');
      } else {
        $j(item).find('.pluss_icon').remove();
      }
      return true;
    };
    $j('.toggable').livequery(function() {
      var container, show_plus;
      $j(this).css('cursor', 'pointer');
      container = $j(this).next();
      show_plus = !$j(this).hasClass('dashed');
      add_toggle_icon(this, container.css('display') === "none" && show_plus);
      return $j(this).live('click', function(e) {
        container.toggle();
        add_toggle_icon(this, container.css('display') === "none" && show_plus);
        return false;
      });
    });
    $j('.toggle_study_info').livequery(function() {
      return $j(this).live('click', function(e) {
        if ($j('.study_info').css('display') === 'none') {
          $j('.study_info').show();
          $j('#scan_form_wrapper').css('width', '100%');
          $j('.general_content').css('width', '50%');
          $j('.study_info').css('height', ($j('.general_content').height()) + "px");
        } else {
          $j('.study_info').hide();
          $j('#scan_form_wrapper').css('width', '55%');
          $j('.general_content').css('width', '100%');
        }
        return false;
      });
    });
    $j('.create_subject_link').livequery(function() {
      return $j(this).live('click', function(e) {
        e.preventDefault();
        $j.ajax($j(this).attr('href'), {
          method: 'GET',
          success: (function(_this) {
            return function(data, status, xhr) {
              return $j.magnificPopup.open({
                alignTop: false,
                overflowY: 'auto',
                items: {
                  src: data,
                  type: 'inline'
                }
              });
            };
          })(this),
          error: (function(_this) {
            return function(response) {
              return alert(response.responseText);
            };
          })(this)
        });
        return false;
      });
    });
    $j('.edit_subject_link').livequery(function() {
      return $j(this).live('click', function(e) {
        e.preventDefault();
        $j.ajax($j(this).attr('href'), {
          method: 'GET',
          success: (function(_this) {
            return function(data, status, xhr) {
              return $j.magnificPopup.open({
                alignTop: false,
                overflowY: 'auto',
                items: {
                  src: data,
                  type: 'inline'
                }
              });
            };
          })(this),
          error: (function(_this) {
            return function(response) {
              return alert(response.responseText);
            };
          })(this)
        });
        return false;
      });
    });
    $j('#subject_id').live('change', function(event) {
      return $j('#new_subject_form').toggle(event.val === "new");
    });
    $j("#new_service_item_form input[id='subject_id']:first").livequery(function() {
      return $j(this).select2({
        width: 300,
        minimumInputLength: 1,
        ajax: {
          url: $j(this).attr('url'),
          dataType: 'jsonp',
          data: function(term, page) {
            return {
              query: term
            };
          },
          results: function(data, page) {
            return {
              results: data.subjects
            };
          }
        },
        escapeMarkup: function(m) {
          return m;
        },
        containerCss: {
          'width': '100%'
        },
        dropdownCss: {
          'min-width': '760px'
        },
        formatSelection: function(el) {
          return el.name;
        },
        formatResult: function(el, container, query, escapeMarkup) {
          var date_of_birth, date_of_birth_marked, markup, name, name_marked, uid, uid_marked;
          name = el.name;
          uid = el.uid;
          date_of_birth = el.date_of_birth;
          markup = [];
          window.Select2.util.markMatch(name, query.term, markup, escapeMarkup);
          name_marked = markup.join('');
          markup = [];
          window.Select2.util.markMatch(uid, query.term, markup, escapeMarkup);
          uid_marked = markup.join('');
          markup = [];
          window.Select2.util.markMatch(date_of_birth, query.term, markup, escapeMarkup);
          date_of_birth_marked = markup.join('');
          return "<div class='result'> <span class='owner'>" + name_marked + "</span> <span class='group'>" + uid_marked + "</span> <span class='name'>" + date_of_birth_marked + "</span> </div>";
        }
      });
    });
    $j('.add_event_to_service').livequery(function() {
      return $j(this).live('click', function(e) {
        e.preventDefault();
        $j.ajax($j(this).attr('href'), {
          method: 'GET',
          success: (function(_this) {
            return function(data, status, xhr) {
              return $j.magnificPopup.open({
                alignTop: false,
                overflowY: 'auto',
                items: {
                  src: data,
                  type: 'inline'
                }
              });
            };
          })(this),
          error: (function(_this) {
            return function(response) {
              return alert(response.responseText);
            };
          })(this)
        });
        return false;
      });
    });
    $j('input#service_item_submitted_at').live('change', function(event) {
      var backdated, service_item_id, submitted_at;
      if (!$j('input#service_item_backdated').prop('checked')) {
        return true;
      }
      service_item_id = $j('input[name=service_item_id]').val();
      backdated = $j('input#service_item_backdated').prop('checked');
      submitted_at = $j(this).val();
      if (service_item_id !== void 0) {
        $j.ajax("/service_item/" + service_item_id + "/update_backdating", {
          type: 'POST',
          dataType: "script",
          data: {
            service_item: {
              backdated: backdated,
              submitted_at: submitted_at
            }
          }
        });
      }
      return false;
    });
    $j(' .search_form_without_submit_button').live("submit", function(event) {
      $j(this).find('.search_form_find_link').trigger('click');
      return false;
    });
    $j('#service_item_submitted_at').live('change', function(event) {
      return $j("#update_charges_purchased_on").effect("highlight", 3000);
    });
    $j('#service_item_completed_on').live('change', function(event) {
      return $j("#update_charges_completed_on").effect("highlight", 3000);
    });
    $j('#update-service-item-schedule-form input').live('change', function(event) {
      return $j('.update_service_item_schedule a').css('background-color', 'red');
    });
    $j(' .create_all_charges').live('click', function() {
      var data, id;
      data = [];
      $j.each($j(this).closest('.charges_header').parent().find('.form'), function(index, form) {
        return data.push($j(form).find('input, select, textarea').serializeArray());
      });
      id = $j(this).closest('.charges_header').parent().attr('id').match(/\d+/)[0];
      $j.ajax("/service_item/create_charges/" + id, {
        type: 'POST',
        data: {
          charges: data
        },
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            return $j(_this).show();
          };
        })(this)
      });
      return false;
    });
    $j(' .billing_status_control').live('change', function() {
      var selected;
      selected = $j(this).find('option:selected').val();
      $j(this).parent().parent().parent().find('.billing_status').val(selected);
      return false;
    });
    $j(' .work_status_control').live('change', function() {
      var selected;
      selected = $j(this).find('option:selected').val();
      $j(this).parent().parent().parent().find('.work_status').val(selected);
      return false;
    });
    $j(' .process_custom_form_field_charges').live('click', function() {
      var data, id;
      data = {
        instances: JSON.stringify($j(this).closest('tr').prev().find('.dataTable').data('handsontable').getData()),
        custom_form_id: $j(this).closest('table').attr('id').match(/\d+/)[0],
        field_number: $j(this).closest('tr').prev().find('.handsontable_value').attr('id').match(/\d+/)[0]
      };
      id = $j(this).closest('.azlist_table').attr('id').match(/\d+/)[0];
      $j(this).closest('tr').prev().find('[name*=processed]').val('true');
      $j.ajax("/service_item/custom_form_charges/" + id, {
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            $j(_this).prev().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            if (!$j(_this).hasClass('not_employee')) {
              $j(_this).closest('tr').next().find('td').html(response.responseText);
            }
            $j(_this).prev().hide();
            $j(_this).show();
            return Tipped.refresh($j(_this)[0]);
          };
        })(this)
      });
      return false;
    });
    $j(' .process_custom_form_charges').live('click', function() {
      var data, form, id;
      form = $j(this).closest('form');
      if (form.length) {
        data = {
          instances: JSON.stringify($j(this).closest('form').find('.handsontable').data('handsontable').getData()),
          asset_template_id: $j(this).closest('form').find('#_asset_template_id').val(),
          template_id: $j(this).closest('form').find('#asset_template_id').val()
        };
        id = $j(this).closest('form').attr('action').match(/\d+/)[0];
        $j.ajax("/service_item/process_charges/" + id, {
          type: 'POST',
          data: data,
          beforeSend: (function(_this) {
            return function() {
              $j(_this).prev().show();
              return $j(_this).hide();
            };
          })(this),
          complete: (function(_this) {
            return function(response) {
              $j(_this).closest('form').next().html(response.responseText);
              $j(_this).prev().hide();
              $j(_this).show();
              return Tipped.refresh($j(_this)[0]);
            };
          })(this)
        });
      }
      return false;
    });
    $j(" .toggle_services").live("click", function() {
      $j(this).parent().parent().parent().find('.services_plain').toggle();
      $j(this).parent().parent().parent().find('.services_by_cat').toggle();
      if ('Show alphabetically' === $j(this).html().trim()) {
        $j(this).html('Show by category');
      } else {
        $j(this).html('Show alphabetically');
      }
      $j(this).closest('.clearfix').find(' .add_service_show_all').show();
      Tipped.refresh('*');
      return false;
    });
    $j(" .toggle_categorized_services").live("click", function() {
      var container, elem, form, spinner;
      elem = $j(this);
      form = elem.closest('div').children('form');
      container = elem.closest('div').next();
      container.toggle();
      elem.prev().toggle();
      elem.prev().prev().toggle();
      if (container.children().length > 0) {
        Tipped.refresh('*');
      } else if (container.is(':visible')) {
        container.html('<div style="width:20px;height:20px"></div>');
        spinner = container.children().first();
        showSpinner(spinner);
        $j.get('/service/services_expand_category', form.serialize(), null, 'html').done(function(data) {
          hideSpinner(spinner);
          container.html(data);
          return Tipped.refresh('*');
        }).fail(function() {
          return hideSpinner(spinner);
        });
      }
      return false;
    });
    $j(" .live_search_as_link").live("click", function() {
      var form;
      form = $j(this).parents('form');
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            $j(_this).show();
            return Tipped.refresh('*');
          };
        })(this)
      });
      return false;
    });
    $j(" .add_service_show_all").live("click", function() {
      var form;
      form = $j(this).closest('form');
      form.find('input[name=search_query]').val('');
      form.find('.live_search_as_link').click();
      return false;
    });
    $j(" .add_service_show_all").live("click", function() {
      var form;
      form = $j(this).closest('form');
      form.find('input[name=search_query]').val('');
      form.find('.live_search_as_link').click();
      return false;
    });
    $j(" .add_line_item_button").live("click", function() {
      var advanced_settings_form, data, form, instance_ids;
      form = $j(this).parents('.form');
      data = form.find('input, select, textarea').serializeArray();
      data.push({
        name: 'price_id',
        value: $j(this).data('price_id')
      });
      if (form.find('#instance_ids').val() === "selection") {
        instance_ids = ($j("#service_item_service_rows_" + (form.find('#service_item_id').val()) + " input[type=checkbox].instance_checkboxes:checked").map(function() {
          return $j(this).val();
        })).get();
        if (instance_ids.size() === 0) {
          alert('Please select items in the inventory that you would like to add these charges to.');
          return false;
        }
        data.push({
          name: 'instance_ids',
          value: instance_ids
        });
      }
      advanced_settings_form = $j(this).parents('[id^=available_services_for_field_]').find('.services_search_advanced_settings');
      if (advanced_settings_form.css('display') !== "none") {
        data.push({
          name: 'billing_status',
          value: advanced_settings_form.find('[name=billing_status]').val()
        });
        data.push({
          name: 'status',
          value: advanced_settings_form.find('[name=status]').val()
        });
        data.push({
          name: 'purchased_on[date]',
          value: advanced_settings_form.find('[name=addon_purchased_on_date]').val()
        });
        data.push({
          name: 'purchased_on[time]',
          value: advanced_settings_form.find('[name=addon_purchased_on_time]').val()
        });
        data.push({
          name: 'completed_at[date]',
          value: advanced_settings_form.find('[name=addon_completed_at_date]').val()
        });
        data.push({
          name: 'completed_at[time]',
          value: advanced_settings_form.find('[name=addon_completed_at_time]').val()
        });
      }
      $j.ajax(form.attr('action'), {
        type: "POST",
        data: data,
        beforeSend: (function(_this) {
          return function() {
            $j(_this).hide();
            return Spinners.create($j(_this).parents(".buttons").get(0)).play();
          };
        })(this),
        complete: (function(_this) {
          return function() {
            $j(_this).show();
            Spinners.get($j(_this).parents(".buttons").get(0)).remove();
            if (!$j.isEmptyObject(data.instance_ids)) {
              if ($j.isArray(data.instance_ids)) {
                return Tipped.hide("#service_item_service_rows_" + data.service_item_id + " .instance_action#add_charges_button");
              } else {
                return Tipped.hide("#view_charges_" + data.instance_ids + "_button");
              }
            }
          };
        })(this)
      });
      return false;
    });
    $j(" .add_recurring_btn").live("click", function() {
      var blockID, form, serviceID, url, wrapper;
      url = $j(this).attr('action');
      form = $j(this).parents('.form');
      serviceID = $j(this).attr('service_id');
      blockID = "recurrence_components_" + serviceID;
      wrapper = form.closest('.services_list_wrapper');
      form.find('.add_line_item_button').addClass('disabled').prop('disabled', true).attr('href', 'javascript:;');
      $j.ajax(url, {
        complete: (function(_this) {
          return function(response) {
            $j(form).next('.recurrence_components').remove();
            $j(form).after("<div id='" + blockID + "' class='recurrence_components'>");
            $j('#' + blockID).html(response.responseText).effect("highlight", 3000).find('.buttons').append('<a href="javascript:;" class="button remove_recurrence_components">Cancel</div>');
            Tipped.refresh('*');
            wrapper.animate({
              scrollTop: wrapper.scrollTop() - wrapper.offset().top + $j('#' + blockID).offset().top
            }, 200);
            return $j("#" + blockID + " .remove_recurrence_components").click(function() {
              $j('#' + blockID).remove();
              wrapper.animate({
                scrollTop: wrapper.scrollTop() - wrapper.offset().top + form.offset().top
              }, 200);
              return form.find('.add_line_item_button').removeClass('disabled').prop('disabled', false);
            });
          };
        })(this)
      });
      return false;
    });
    $j(' .remove_assignee').live('click', function() {
      var form;
      form = $j(this).children().first();
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function() {
            return $j(_this).parent().remove();
          };
        })(this)
      });
      return false;
    });
    $j(' .add_assignee').live('click', function() {
      var form;
      form = $j(this).parent();
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function() {
            $j(_this).next().hide();
            return $j(_this).show();
          };
        })(this)
      });
      return false;
    });
    $j(' .update_service_item_schedule').live('click', function() {
      var form;
      form = $j(this).parent();
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            return showSpinner($j(_this));
          };
        })(this),
        complete: (function(_this) {
          return function() {
            $j(".update_service_item_schedule a").removeAttr("style");
            return hideSpinner($j(_this));
          };
        })(this)
      });
      return false;
    });
    $j('#add_lab_button').live('click', function() {
      var form;
      form = $j(this).parents('form');
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        error: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            $j(_this).show();
            return form.parent().prev().html(response.responseText);
          };
        })(this),
        success: (function(_this) {
          return function(response) {
            Tipped.hideAll();
            return $j('#institution_group_list_tbody').prepend(response);
          };
        })(this)
      });
      return false;
    });
    $j('#change_lab_for_request_button').live('click', function() {
      var form;
      form = $j(this).parents('form');
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            return showSpinner($j(_this));
          };
        })(this),
        error: (function(_this) {
          return function(response) {
            hideSpinner($j(_this));
            return form.parent().prev().html(response.responseText);
          };
        })(this),
        success: (function(_this) {
          return function(response) {
            Tipped.remove('*');
            return $j('#group_access_requests_div').html(response);
          };
        })(this)
      });
      return false;
    });
    $j(' .update_requests_section').live('click', function() {
      $j.ajax($j(this).attr('href'), {
        type: 'GET',
        complete: (function(_this) {
          return function(response) {
            return $j('#group_access_requests_div').html(response.responseText);
          };
        })(this)
      });
      return false;
    });
    $j(' .process_all_chargeable_runs').live('click', function() {
      var form;
      form = $j(this).parents('form');
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            return $j(_this).show();
          };
        })(this)
      });
      return false;
    });
    $j(' .add_recurring_charges_button').live('click', function() {
      var asset_id, data, form, i, id, instance_ids, len, quantity, service_item_id;
      form = $j(this).parents('form').first();
      data = form.serialize();
      service_item_id = form.find('#service_item_id').val();
      asset_id = form.find('#service_id').val();
      quantity = $j(' .service_item_' + service_item_id + '_asset_' + asset_id + '_quantity').filter(':visible').val();
      data += '&quantity=' + quantity;
      if (true) {
        instance_ids = ($j("#service_item_service_rows_" + service_item_id + " input[type=checkbox].instance_checkboxes:checked").map(function() {
          return $j(this).val();
        })).get();
        for (i = 0, len = instance_ids.length; i < len; i++) {
          id = instance_ids[i];
          data += '&instance_ids[]=' + id;
        }
      }
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            return $j(_this).show();
          };
        })(this)
      });
      return false;
    });
    $j(' .add_new_charge_button').live('click', function() {
      var form;
      form = $j(this).parents('form');
      if (form.find('#charge_cart_price').val() === '') {
        alert('Please specify the unit cost.');
        return false;
      }
      if (form.find('#charge_justification').val() === '') {
        alert('Please specify the justification.');
        return false;
      }
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            return $j(_this).show();
          };
        })(this)
      });
      return false;
    });
    $j(' .add_custom_form_to_service_item_link, .add_new_milestone_to_service_item_link').live('click', function() {
      var form;
      form = $j(this).parents('form');
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            $j(_this).next().show();
            return $j(_this).hide();
          };
        })(this),
        complete: (function(_this) {
          return function(response) {
            $j(_this).next().hide();
            return $j(_this).show();
          };
        })(this)
      });
      return false;
    });
    $j(' .book_all_equipments_link').live('click', function() {
      var form;
      form = $j(this).parents('form');
      $j.ajax(form.attr('action'), {
        type: 'POST',
        data: form.serialize(),
        beforeSend: (function(_this) {
          return function() {
            return loadmask('#service_request_event_form');
          };
        })(this),
        complete: (function(_this) {
          return function(response) {};
        })(this)
      });
      return false;
    });
    $j(' .override_asset_line_availabilities').livequery(function() {
      $j(this).live('change', function() {
        var table;
        table = $j(this).parents().find('table[event_id]');
        window.selected_add_event_availabilities = {};
        $j.map($j('.asset_line_availability_line select'), function(el) {
          return window.selected_add_event_availabilities[$j(el).attr('id')] = $j(el).val();
        });
        events_around(table.attr('event_id'), table.attr('id'), this);
        return true;
      });
      return false;
    });
    $j(' .book_single_event').live('click', function() {
      var data, equipment_id;
      equipment_id = $j(this).attr('equipment_id');
      data = {};
      $j.each($j('#service_request_event_form').serializeArray(), function(_, kv) {
        if (data[kv.name]) {
          if (!(data[kv.name] instanceof Array)) {
            data[kv.name] = [data[kv.name]];
          }
          return data[kv.name].push(kv.value);
        } else {
          return data[kv.name] = kv.value;
        }
      });
      data.equipment_id = equipment_id;
      data.start_date = {
        date: $j("#equipment_" + equipment_id + "_start_date_date").val(),
        time: $j("#equipment_" + equipment_id + "_start_date_time").val()
      };
      data.end_date = {
        date: $j("#equipment_" + equipment_id + "_end_date_date").val(),
        time: $j("#equipment_" + equipment_id + "_end_date_time").val()
      };
      data.price_id = $j("#equipment_" + equipment_id + "_price_id").val();
      $j.ajax("/service/add_single_event/" + ($j(this).attr('service_item_id')), {
        type: 'POST',
        data: data,
        beforeSend: (function(_this) {
          return function() {
            return loadmask('#service_request_event_form');
          };
        })(this),
        complete: (function(_this) {
          return function(response) {};
        })(this)
      });
      return false;
    });
    $j(' .toggle_updates_list').live('click', function() {
      $j(this).parent().next().toggle();
      if ($j(this).prev().length > 0) {
        $j(this).prev().find('span').show();
      } else {
        $j(this).next().find('span').show();
      }
      $j(this).find('span').hide();
      Tipped.refresh('*');
      return false;
    });
    $j(' .load_sample_expansion').live('click', function() {
      $j(this).find('.closed').toggle();
      $j(this).find('.expanded').toggle();
      if ($j(this).hasClass('loaded')) {
        $j(this).parent().next().toggle();
      } else {
        $j.ajax($j(this).attr('action'), {
          type: 'GET',
          beforeSend: (function(_this) {
            return function() {
              return $j(_this).find('.spinner_wrapper span').show();
            };
          })(this),
          complete: (function(_this) {
            return function(response) {
              $j(_this).find('.spinner_wrapper span').hide();
              $j(_this).addClass('loaded');
              return $j(_this).parent().after(response.responseText);
            };
          })(this)
        });
      }
      return false;
    });
    $j('a.show_prices_for_favorite_product').on('click', function() {
      var pid;
      pid = $j(this).data('product_id');
      $j('#product_' + pid + '_prices_row').toggle();
      return false;
    });
    $j('#send_to_emails_to_be_checked').live('blur', function() {
      var si_id;
      si_id = $j('#service_item_id').val();
      $j.ajax({
        url: '/service_item/check_additional_emails_access/' + si_id,
        data: $j(this).serialize()
      });
      return false;
    });
    false;
    $j('#new_service_item, #service_items, #product_cores_kiosk.picking_kiosk').livequery(function() {
      var container;
      container = $j(this);
      container.on('click', '#service_item_delivery_type_delivery', function() {
        return $j('#selected_delivery_location_label').show();
      });
      return container.on('click', '#service_item_delivery_type_pickup', function() {
        return $j('#selected_delivery_location_label').hide();
      });
    });
    $j('.change_cart_price').live('click', function(e) {
      var action, id, price;
      e.preventDefault();
      showSpinner(this);
      action = e.currentTarget.href;
      id = $j(this).data('id');
      price = $j('#price_override_' + id).val();
      return $j.post(action, {
        price_override: price
      }).done(function() {
        return $j('#price_override_' + id).remove();
      });
    });
    $j('.add_animal_order_to_service').live('click', function(e) {
      var url;
      e.preventDefault();
      url = e.currentTarget.getAttribute('href');
      return $j.magnificPopup.open({
        showCloseBtn: true,
        closeBtnInside: false,
        closeOnBgClick: false,
        closeOnContentClick: false,
        preloader: true,
        items: {
          src: '<div class="animal_popup_wrapper"><iframe id="form_iframe" frameBorder="0" src="' + url + '"></iframe></div>'
        },
        type: 'inline',
        closeMarkup: '<button class="animal_popup_mfp_close mfp-close"></button>',
        callbacks: {
          open: function() {
            $j.magnificPopup.instance.updateStatus('loading', 'Loading...');
            return $j.magnificPopup.instance.close = function() {
              if (!confirm('Are you sure you want to close the popup?')) {
                return;
              }
              return $j.magnificPopup.proto.close.call(this);
            };
          }
        }
      });
    });
    $j('.breeding_details_modal').live('click', function(e) {
      var url;
      e.preventDefault();
      url = e.currentTarget.getAttribute('href');
      return $j.magnificPopup.open({
        showCloseBtn: true,
        closeBtnInside: false,
        closeOnBgClick: false,
        closeOnContentClick: false,
        preloader: true,
        items: {
          src: '<div class="animal_breeding_popup_wrapper"><iframe id="form_iframe" frameBorder="0" src="' + url + '"></iframe></div>'
        },
        type: 'inline',
        closeMarkup: '<button class="animal_popup_mfp_close mfp-close"></button>',
        callbacks: {
          open: function() {
            return $j.magnificPopup.instance.updateStatus('loading', 'Loading...');
          }
        }
      });
    });
    $j('.edit_request_source').live('click', function(e) {
      var url;
      e.preventDefault();
      url = e.currentTarget.getAttribute('href');
      return $j.magnificPopup.open({
        showCloseBtn: true,
        closeBtnInside: false,
        closeOnBgClick: false,
        closeOnContentClick: false,
        preloader: true,
        items: {
          src: '<div class="animal_popup_wrapper"><iframe id="form_iframe" frameBorder="0" src="' + url + '"></iframe></div>'
        },
        type: 'inline',
        closeMarkup: '<button class="animal_popup_mfp_close mfp-close"></button>',
        callbacks: {
          open: function() {
            $j.magnificPopup.instance.updateStatus('loading', 'Loading...');
            return $j.magnificPopup.instance.close = function() {
              if (!confirm('Are you sure you want to close the popup?')) {
                return;
              }
              return $j.magnificPopup.proto.close.call(this);
            };
          }
        }
      });
    });
    $j('input#edit_animal_source').livequery(function() {
      return $j(this).select2({
        placeholder: 'Start searching',
        minimumInputLength: 2,
        ajax: {
          url: $j(this).data('url'),
          dataType: 'json',
          data: (function(_this) {
            return function(term, page) {
              return {
                animal_source: term
              };
            };
          })(this),
          results: function(data, page) {
            return {
              results: data
            };
          }
        },
        createSearchChoice: function(term, data) {
          return {
            id: term,
            text: term + ' (add new)'
          };
        },
        initSelection: function(element, callback) {
          return callback({
            id: element.data('id'),
            text: element.data('label')
          });
        }
      });
    });
    $j('.delivery_date').livequery('click', function() {
      var field, spinner, text;
      text = $j(this).find('.delivery_date_text');
      field = $j(this).find('.delivery_date_datepicker');
      spinner = $j(this).find('.spinner');
      text.val(field.val());
      text.hide();
      field.show();
      field.datepicker({
        dateFormat: "M d, yy",
        onClose: function(selected) {
          text.show();
          return field.hide();
        },
        onSelect: (function(_this) {
          return function(date, inst) {
            if (confirm('Are you sure you want to change the date?')) {
              return $j.ajax({
                url: field.data('url'),
                dataType: 'json',
                method: 'put',
                data: {
                  date_needed: date
                },
                beforeSend: function() {
                  showSpinner(spinner);
                  return field.datepicker('hide');
                },
                success: function(response) {
                  field.datepicker('hide');
                  field.val(response.date_needed);
                  return text.text(response.date_needed);
                }
              }).done(function() {
                hideSpinner(spinner);
                text.show();
                return field.hide();
              });
            } else {
              text.show();
              return field.hide();
            }
          };
        })(this)
      });
      return field.datepicker('show');
    });
    return $j('.delivery_date_ilabs').livequery('click', function() {
      var field, spinner, text;
      text = $j(this).find('.delivery_date_text');
      field = $j(this).find('.delivery_date_datepicker');
      spinner = $j(this).find('.spinner');
      text.val(field.val());
      text.hide();
      field.show();
      $j(field).datetimepicker({
        format: 'M d, Y',
        timepicker: false,
        maxDate: $j(this).data('maxdate'),
        scrollInput: false,
        onClose: function(selected) {
          text.show();
          return field.hide();
        },
        onSelectDate: (function(_this) {
          return function(date, inst) {
            if (confirm('Are you sure you want to change date needed?')) {
              return $j.ajax({
                url: field.data('url'),
                dataType: 'json',
                method: 'put',
                data: {
                  date_needed: date
                },
                beforeSend: function() {
                  showSpinner(spinner);
                  field.datetimepicker('hide');
                  $j('.xdsoft_datetimepicker').hide();
                  return field.datetimepicker('destroy');
                },
                success: function(response) {
                  return text.text(response.date_needed);
                }
              }).done(function() {
                $j('.xdsoft_datetimepicker').hide();
                hideSpinner(spinner);
                text.show();
                return field.hide();
              });
            } else {
              text.show();
              return field.hide();
            }
          };
        })(this)
      });
      return field.datetimepicker('show');
    });
  });

  $j(' .attach_pdf_form_form').live('submit', function(event) {
    var form, submit;
    event.preventDefault();
    form = $j(this);
    submit = $j(this).find('.generate_pdf_quote_submit');
    $j.ajax(form.attr('action'), {
      type: 'POST',
      dataType: "script",
      data: form.serializeArray(),
      complete: (function(_this) {
        return function(response) {
          Tipped.hideAll();
          return $j(' .wait_for_quote_banner_div').show();
        };
      })(this)
    });
    return false;
  });

  $j('a.render_sharing_form').live('click', function() {
    var si_id;
    si_id = $j(this).data('si_id');
    showSpinner($j(this));
    $j('#sharing_panel_' + si_id).load('/service_item/render_sharing_form/' + si_id);
    return false;
  });

  window.checkAttachmentReady = function(si_id, job_id, delay) {
    $j.ajax('/service_item/attachment_ready/' + si_id + '?job_id=' + job_id + '&delay=' + delay, {
      dataType: "script",
      type: 'GET'
    });
    return false;
  };

  window.reloadPrototipFileupload = function(el, field_number, custom_form_id, tf_attachment_type) {
    Tipped.hideAll();
    window.setTimeout((function() {
      var $container;
      $container = $j(Tipped.get(el)['items']()[0]['container']);
      $container.find('.t_ContentContainer').append($j('#add_attachment_to_cf'));
      $container.find('#attachment_tf_id').val(field_number);
      $container.find('#attachment_custom_form_id').val(custom_form_id);
      return $container.find('#attachment_category').val(tf_attachment_type);
    }), 150);
    return false;
  };

  window.workflowStep = function(el, url) {
    $j.ajax(url, {
      asynchronous: true,
      evalScripts: true,
      onLoaded: (function(_this) {
        return function() {
          $j(el).parent().next().hide();
          return $j(el).show();
        };
      })(this),
      onLoading: (function(_this) {
        return function() {
          $j(el).parent().next().show();
          return $j(el).hide();
        };
      })(this),
      parameters: $j(el).parent().parent().parent().parent().serialize()
    });
    return false;
  };

  window.populateAliquotsGrid = function(asset_id, id) {
    var url;
    url = "/service_item/load_generated_aliquots/" + id;
    return $j.ajax(url, {
      asynchronous: true,
      evalScripts: true,
      complete: (function(_this) {
        return function(response) {
          var data;
          data = eval(response.responseText);
          return $j("#generate_aliquots_grid_" + asset_id + "_" + id).data('handsontable').loadData(data);
        };
      })(this)
    });
  };

  window.tmhs_ecs_update = function(obj) {
    var show;
    show = !!$j(':selected', obj).data('dept');
    $j('+ .extra', obj).toggle(show);
    $j('+ .extra input', obj).prop('disabled', !show);
    return Tipped.refresh('*');
  };

}).call(this);
I18n.translations || (I18n.translations = {});
I18n.translations["en"] = I18n.extend((I18n.translations["en"] || {}), {"js":{"frontend":{"schedules":{"additional_assets_btn":{"hide_tooltip":"Hide other relevant schedules","label":"Linked Calendar","show_tooltip":"Show other relevant schedules"},"alert_box":{"close":"Close"},"asset_select_dropdown":{"search_tooltip":"Search calendar"},"background":{"recurring_events":{"create":{"employee":"Checking the availability and attempting to update the requested times. You will be notified if the times you selected are not available.","regular":"We are checking the availbility and attempting to update your requested times. You will be notified if your reservation is successfully created."},"destroy":{"employee":"Removing recurrent events.","regular":"We are removing the recurrent events."}}},"breadcrumb":{"back_to_core":"Back to service center","label":"View Schedule"},"calendar_component":{"linked_error_content":"This is a linked reservation that cannot be edited directly. Please edit the parent reservation instead.","linked_error_title":"Linked Reservation"},"calendar_details_modal":{"color_code_legend":{"employee_others":"Other's Event","no_show":"Cancelled or No Show","owner":"My Event","owner_approved":"Approved Event","owner_past":"Past Event","pending":"Pending Approval","regular_others":"Other's Event","title":{"employee":"Employee Event Color Codes","regular":"Event Color Codes"},"unavailable":"Unavailable","unavailable_except_trained":"Available for Specific Permissions"},"label":"Calendar Details","title":"%{name} Calendar"},"cancellation_notification_toggle":{"label":"Receive cancellation notifications","tooltip":"Turn on to get an email if a reservation is cancelled within the next "},"cancelled":"Cancelled","confirm_usage_btn":{"label":"Confirm Usage"},"datepicker":{"closeText":"Close","currentText":"Today","dateFormat":"mm/dd/yy","dayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"dayNamesMin":["Su","Mo","Tu","We","Th","Fr","Sa"],"dayNamesShort":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"firstDay":1,"isRTL":false,"monthNames":["January","February","March","April","May","June","July","August","September","October","November","December"],"monthNamesShort":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"nextText":"Next","prevText":"Prev","showMonthAfterYear":false,"weekHeader":"Wk","yearSuffix":""},"description_modal":{"label":"Resource Description","title":"%{name} Description"},"event_text":{"approved":"(Approved)","availability_info":{"empty_name":"--","empty_price":"--","more_name":"...","more_price":"...","price":"Price","time_tracked_in":{"hours":"hr","minutes":"min"},"type":"Type"},"buffer_info":{"and":"and","header":"Required buffer","no24h":"h:mm A","with24h":"H:mm"},"cancelled":"(Cancelled)","capping_caused_approval":"because of capping rules","confirmed":"(Confirmed)","has_linked_reservations":"Has linked reservations","lab":"Lab Name","last_urgent_comment":"Last urgent comment","maintenance":"Unavailable","missing_equipment":"Missing equipment, contact support","no_show":"(No show)","not_approved":"(Not Approved)","note":"Note","pending_approval":"Pending approval by core","pi":"PI","pi_phone":"PI Number","poor_match":{"link_text":"Review Usage","text":"Owner/Group Unknown. Please adjust in "},"temporary_reservation":"Unsaved reservation, click \u003cstrong\u003eSave Reservation\u003c/strong\u003e. Will expire in 15 minutes.","time_lines":{"duration":"Duration","end":"End","hours":{"plural":"hours","singular":"hour"},"minutes":{"plural":"mins","singular":"min"},"no24h":{"multiline_format":"dddd, MMMM D [at] h:mm A","oneline_end_format":"h:mm A","oneline_start_format":"dddd, MMMM D [at] h:mm A [through] "},"start":"Start","with24h":{"multiline_format":"dddd, MMMM D [at] H:mm","oneline_end_format":"H:mm","oneline_start_format":"dddd, MMMM D [at] H:mm [through] "}}},"favorite_btn":{"tooltip_bookmarked":"Remove from Favorites","tooltip_unbookmarked":"Add to Favorites"},"lab_select":{"modal":{"cancel":"Cancel","lab_dropdown":{"label":"Lab","placeholder":"select which group the request will be for"},"next":"Next","title":"%{from} - %{to} Create Reservation"},"save_reservation_error":"An error occured while saving the reservation"},"linked_reservation_modal":{"accept":"OK","cancel":"Cancel","content":"This is a linked reservation that cannot be edited directly. Would you like to edit the parent reservation?","title":"Linked reservation"},"no_show":"No show","offline_message":"Resource is offline. No reservations are being accepted.","pdf_button":{"tooltip":"Export to PDF"},"restricted_schedule":{"contact_assistance":"Please contact the core for assistance.","readonly_accesss":{"content":"You are not authorized to create or edit reservations. Please contact your core manager if you need to do so.","header":"Note"},"text":"This schedule is only available to select users."},"settings_btn":{"tooltip":"Edit Equipment Settings"},"timeframe_select":{"day":"Day","month":"Month","multi":"Multi View","week5":"Week (5 Days)","week7":"Week (7 Days)"},"update_reservation":{"cancel":"Cancel","header":"Update Reservation","proceed":"Proceed","proceed_message":"%{message}\u003cbr /\u003eDo you want to proceed anyway?","you_have_no_labs":"You don't belong to any lab"},"user_select":{"create_reservation":"Create reservation","modal":{"cancel":"Cancel","event_type":"Event Type","lab_dropdown":{"label":"Lab","placeholder":"select which group the request will be for"},"next":"Next","reservation_text":"Reservation","save":"Save","title":"%{from} - %{to} Create Reservation","unavailable_text":"Unavailable (maintenance, holiday etc...)","usage_cappings":{"booked_amount":"Booked Amount","booked_usage_amount":"%{amount} hours","cap_amount":"%{amount} hours","capped_amount":"Capped Amount","other_is_affected":"This user is affected by the following capping rules:","scope":"Scope","you_are_affected":"You are affected by the following capping rules:"},"user_dropdown":{"label":"Customer","placeholder":"type in the person’s first name then last name for whom you’d like to create a reservation"},"user_scope":{"all":"All","customers":"Current Customers","institution":"This institution","search_within":"Search within:"}},"save_reservation_error":"An error occured while saving the reservation","user_without_groups":{"content":"Cannot create a request for a user with no labs.","header":"Please select another user."}},"validations":{"maximum_time":"Maximum time allowed is %{time} minutes.","minimum_time":"Minimum time allowed is %{time} minutes."}}}}});
!function(f){"object"==typeof exports&&"undefined"!=typeof module?module.exports=f():"function"==typeof define&&define.amd?define([],f):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).App=f()}(function(){var define,module,exports;return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);throw(f=new Error("Cannot find module '"+i+"'")).code="MODULE_NOT_FOUND",f}c=n[i]={exports:{}},e[i][0].call(c.exports,function(r){return o(e[i][1][r]||r)},c,c.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){module.exports=function(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2},module.exports.__esModule=!0,module.exports.default=module.exports},{}],2:[function(require,module,exports){module.exports=function(arr){if(Array.isArray(arr))return arr},module.exports.__esModule=!0,module.exports.default=module.exports},{}],3:[function(require,module,exports){var arrayLikeToArray=require("./arrayLikeToArray.js");module.exports=function(arr){if(Array.isArray(arr))return arrayLikeToArray(arr)},module.exports.__esModule=!0,module.exports.default=module.exports},{"./arrayLikeToArray.js":1}],4:[function(require,module,exports){module.exports=function(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self},module.exports.__esModule=!0,module.exports.default=module.exports},{}],5:[function(require,module,exports){module.exports=function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")},module.exports.__esModule=!0,module.exports.default=module.exports},{}],6:[function(require,module,exports){var toPropertyKey=require("./toPropertyKey.js");function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,toPropertyKey(descriptor.key),descriptor)}}module.exports=function(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor},module.exports.__esModule=!0,module.exports.default=module.exports},{"./toPropertyKey.js":29}],7:[function(require,module,exports){var toPropertyKey=require("./toPropertyKey.js");module.exports=function(obj,key,value){return(key=toPropertyKey(key))in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj},module.exports.__esModule=!0,module.exports.default=module.exports},{"./toPropertyKey.js":29}],8:[function(require,module,exports){function _extends(){return module.exports=_extends=Object.assign?Object.assign.bind():function(target){for(var i=1;i<arguments.length;i++){var key,source=arguments[i];for(key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},module.exports.__esModule=!0,module.exports.default=module.exports,_extends.apply(this,arguments)}module.exports=_extends,module.exports.__esModule=!0,module.exports.default=module.exports},{}],9:[function(require,module,exports){var superPropBase=require("./superPropBase.js");function _get(){return"undefined"!=typeof Reflect&&Reflect.get?module.exports=_get=Reflect.get.bind():module.exports=_get=function(target,property,receiver){var base=superPropBase(target,property);if(base)return(base=Object.getOwnPropertyDescriptor(base,property)).get?base.get.call(arguments.length<3?target:receiver):base.value},module.exports.__esModule=!0,module.exports.default=module.exports,_get.apply(this,arguments)}module.exports=_get,module.exports.__esModule=!0,module.exports.default=module.exports},{"./superPropBase.js":26}],10:[function(require,module,exports){function _getPrototypeOf(o){return module.exports=_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o){return o.__proto__||Object.getPrototypeOf(o)},module.exports.__esModule=!0,module.exports.default=module.exports,_getPrototypeOf(o)}module.exports=_getPrototypeOf,module.exports.__esModule=!0,module.exports.default=module.exports},{}],11:[function(require,module,exports){var setPrototypeOf=require("./setPrototypeOf.js");module.exports=function(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),Object.defineProperty(subClass,"prototype",{writable:!1}),superClass&&setPrototypeOf(subClass,superClass)},module.exports.__esModule=!0,module.exports.default=module.exports},{"./setPrototypeOf.js":24}],12:[function(require,module,exports){var setPrototypeOf=require("./setPrototypeOf.js");module.exports=function(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,setPrototypeOf(subClass,superClass)},module.exports.__esModule=!0,module.exports.default=module.exports},{"./setPrototypeOf.js":24}],13:[function(require,module,exports){module.exports=function(obj){return obj&&obj.__esModule?obj:{default:obj}},module.exports.__esModule=!0,module.exports.default=module.exports},{}],14:[function(require,module,exports){var _typeof=require("./typeof.js").default;function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}module.exports=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};if((nodeInterop=_getRequireWildcardCache(nodeInterop))&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,desc,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj)"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]);return newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj),newObj},module.exports.__esModule=!0,module.exports.default=module.exports},{"./typeof.js":30}],15:[function(require,module,exports){module.exports=function(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)},module.exports.__esModule=!0,module.exports.default=module.exports},{}],16:[function(require,module,exports){module.exports=function(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null!=_i){var _s,_e,_x,_r,_arr=[],_n=!0,_d=!1;try{if(_x=(_i=_i.call(arr)).next,0===i){if(Object(_i)!==_i)return;_n=!1}else for(;!(_n=(_s=_x.call(_i)).done)&&(_arr.push(_s.value),_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{if(!_n&&null!=_i.return&&(_r=_i.return(),Object(_r)!==_r))return}finally{if(_d)throw _e}}return _arr}},module.exports.__esModule=!0,module.exports.default=module.exports},{}],17:[function(require,module,exports){module.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},module.exports.__esModule=!0,module.exports.default=module.exports},{}],18:[function(require,module,exports){module.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},module.exports.__esModule=!0,module.exports.default=module.exports},{}],19:[function(require,module,exports){var defineProperty=require("./defineProperty.js");module.exports=function(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?Object(arguments[i]):{},ownKeys=Object.keys(source);"function"==typeof Object.getOwnPropertySymbols&&ownKeys.push.apply(ownKeys,Object.getOwnPropertySymbols(source).filter(function(sym){return Object.getOwnPropertyDescriptor(source,sym).enumerable})),ownKeys.forEach(function(key){defineProperty(target,key,source[key])})}return target},module.exports.__esModule=!0,module.exports.default=module.exports},{"./defineProperty.js":7}],20:[function(require,module,exports){var defineProperty=require("./defineProperty.js");function ownKeys(object,enumerableOnly){var symbols,keys=Object.keys(object);return Object.getOwnPropertySymbols&&(symbols=Object.getOwnPropertySymbols(object),enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys.push.apply(keys,symbols)),keys}module.exports=function(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(Object(source),!0).forEach(function(key){defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target},module.exports.__esModule=!0,module.exports.default=module.exports},{"./defineProperty.js":7}],21:[function(require,module,exports){var objectWithoutPropertiesLoose=require("./objectWithoutPropertiesLoose.js");module.exports=function(source,excluded){if(null==source)return{};var key,target=objectWithoutPropertiesLoose(source,excluded);if(Object.getOwnPropertySymbols)for(var sourceSymbolKeys=Object.getOwnPropertySymbols(source),i=0;i<sourceSymbolKeys.length;i++)key=sourceSymbolKeys[i],0<=excluded.indexOf(key)||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key]);return target},module.exports.__esModule=!0,module.exports.default=module.exports},{"./objectWithoutPropertiesLoose.js":22}],22:[function(require,module,exports){module.exports=function(source,excluded){if(null==source)return{};for(var key,target={},sourceKeys=Object.keys(source),i=0;i<sourceKeys.length;i++)key=sourceKeys[i],0<=excluded.indexOf(key)||(target[key]=source[key]);return target},module.exports.__esModule=!0,module.exports.default=module.exports},{}],23:[function(require,module,exports){var _typeof=require("./typeof.js").default,assertThisInitialized=require("./assertThisInitialized.js");module.exports=function(self,call){if(call&&("object"===_typeof(call)||"function"==typeof call))return call;if(void 0!==call)throw new TypeError("Derived constructors may only return object or undefined");return assertThisInitialized(self)},module.exports.__esModule=!0,module.exports.default=module.exports},{"./assertThisInitialized.js":4,"./typeof.js":30}],24:[function(require,module,exports){function _setPrototypeOf(o,p){return module.exports=_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(o,p){return o.__proto__=p,o},module.exports.__esModule=!0,module.exports.default=module.exports,_setPrototypeOf(o,p)}module.exports=_setPrototypeOf,module.exports.__esModule=!0,module.exports.default=module.exports},{}],25:[function(require,module,exports){var arrayWithHoles=require("./arrayWithHoles.js"),iterableToArrayLimit=require("./iterableToArrayLimit.js"),unsupportedIterableToArray=require("./unsupportedIterableToArray.js"),nonIterableRest=require("./nonIterableRest.js");module.exports=function(arr,i){return arrayWithHoles(arr)||iterableToArrayLimit(arr,i)||unsupportedIterableToArray(arr,i)||nonIterableRest()},module.exports.__esModule=!0,module.exports.default=module.exports},{"./arrayWithHoles.js":2,"./iterableToArrayLimit.js":16,"./nonIterableRest.js":17,"./unsupportedIterableToArray.js":31}],26:[function(require,module,exports){var getPrototypeOf=require("./getPrototypeOf.js");module.exports=function(object,property){for(;!Object.prototype.hasOwnProperty.call(object,property)&&null!==(object=getPrototypeOf(object)););return object},module.exports.__esModule=!0,module.exports.default=module.exports},{"./getPrototypeOf.js":10}],27:[function(require,module,exports){var arrayWithoutHoles=require("./arrayWithoutHoles.js"),iterableToArray=require("./iterableToArray.js"),unsupportedIterableToArray=require("./unsupportedIterableToArray.js"),nonIterableSpread=require("./nonIterableSpread.js");module.exports=function(arr){return arrayWithoutHoles(arr)||iterableToArray(arr)||unsupportedIterableToArray(arr)||nonIterableSpread()},module.exports.__esModule=!0,module.exports.default=module.exports},{"./arrayWithoutHoles.js":3,"./iterableToArray.js":15,"./nonIterableSpread.js":18,"./unsupportedIterableToArray.js":31}],28:[function(require,module,exports){var _typeof=require("./typeof.js").default;module.exports=function(input,hint){if("object"!==_typeof(input)||null===input)return input;var prim=input[Symbol.toPrimitive];if(void 0===prim)return("string"===hint?String:Number)(input);if(prim=prim.call(input,hint||"default"),"object"!==_typeof(prim))return prim;throw new TypeError("@@toPrimitive must return a primitive value.")},module.exports.__esModule=!0,module.exports.default=module.exports},{"./typeof.js":30}],29:[function(require,module,exports){var _typeof=require("./typeof.js").default,toPrimitive=require("./toPrimitive.js");module.exports=function(arg){return arg=toPrimitive(arg,"string"),"symbol"===_typeof(arg)?arg:String(arg)},module.exports.__esModule=!0,module.exports.default=module.exports},{"./toPrimitive.js":28,"./typeof.js":30}],30:[function(require,module,exports){function _typeof(obj){return module.exports=_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},module.exports.__esModule=!0,module.exports.default=module.exports,_typeof(obj)}module.exports=_typeof,module.exports.__esModule=!0,module.exports.default=module.exports},{}],31:[function(require,module,exports){var arrayLikeToArray=require("./arrayLikeToArray.js");module.exports=function(o,minLen){var n;if(o)return"string"==typeof o?arrayLikeToArray(o,minLen):"Map"===(n="Object"===(n=Object.prototype.toString.call(o).slice(8,-1))&&o.constructor?o.constructor.name:n)||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?arrayLikeToArray(o,minLen):void 0},module.exports.__esModule=!0,module.exports.default=module.exports},{"./arrayLikeToArray.js":1}],32:[function(require,module,exports){!function(process){!function(){"use strict";exports.__esModule=!0;var _react=require("react"),_propTypes2=(_interopRequireDefault(_react),_interopRequireDefault(require("prop-types"))),_gud2=_interopRequireDefault(require("gud")),_warning2=_interopRequireDefault(require("warning"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(self)return!call||"object"!=typeof call&&"function"!=typeof call?self:call;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}exports.default=function(defaultValue,calculateChangedBits){var _Consumer$contextType,contextProp="__create-react-context-"+(0,_gud2.default)()+"__",Provider=function(_Component){function Provider(){var _temp,_this;_classCallCheck(this,Provider);for(var value,handlers,_len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_temp=_this=_possibleConstructorReturn(this,_Component.call.apply(_Component,[this].concat(args)))).emitter=(value=_this.props.value,handlers=[],{on:function(handler){handlers.push(handler)},off:function(handler){handlers=handlers.filter(function(h){return h!==handler})},get:function(){return value},set:function(newValue,changedBits){value=newValue,handlers.forEach(function(handler){return handler(value,changedBits)})}}),_possibleConstructorReturn(_this,_temp)}return _inherits(Provider,_Component),Provider.prototype.getChildContext=function(){var _ref={};return _ref[contextProp]=this.emitter,_ref},Provider.prototype.componentWillReceiveProps=function(nextProps){var oldValue,newValue,changedBits,x,y;this.props.value!==nextProps.value&&(oldValue=this.props.value,newValue=nextProps.value,changedBits=void 0,(x=oldValue)===(y=newValue)?0===x&&1/x!=1/y:x==x||y==y)&&(changedBits="function"==typeof calculateChangedBits?calculateChangedBits(oldValue,newValue):1073741823,"production"!==process.env.NODE_ENV&&(0,_warning2.default)((1073741823&changedBits)===changedBits,"calculateChangedBits: Expected the return value to be a 31-bit integer. Instead received: %s",changedBits),0!==(changedBits|=0))&&this.emitter.set(nextProps.value,changedBits)},Provider.prototype.render=function(){return this.props.children},Provider}(_react.Component),_Provider$childContex=(Provider.childContextTypes=((_Provider$childContex={})[contextProp]=_propTypes2.default.object.isRequired,_Provider$childContex),function(_Component2){function Consumer(){var _temp2,_this2;_classCallCheck(this,Consumer);for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];return(_temp2=_this2=_possibleConstructorReturn(this,_Component2.call.apply(_Component2,[this].concat(args)))).state={value:_this2.getValue()},_this2.onUpdate=function(newValue,changedBits){0!=((0|_this2.observedBits)&changedBits)&&_this2.setState({value:_this2.getValue()})},_possibleConstructorReturn(_this2,_temp2)}return _inherits(Consumer,_Component2),Consumer.prototype.componentWillReceiveProps=function(nextProps){nextProps=nextProps.observedBits;this.observedBits=null==nextProps?1073741823:nextProps},Consumer.prototype.componentDidMount=function(){this.context[contextProp]&&this.context[contextProp].on(this.onUpdate);var observedBits=this.props.observedBits;this.observedBits=null==observedBits?1073741823:observedBits},Consumer.prototype.componentWillUnmount=function(){this.context[contextProp]&&this.context[contextProp].off(this.onUpdate)},Consumer.prototype.getValue=function(){return this.context[contextProp]?this.context[contextProp].get():defaultValue},Consumer.prototype.render=function(){return children=this.props.children,(Array.isArray(children)?children[0]:children)(this.state.value);var children},Consumer}(_react.Component));return _Provider$childContex.contextTypes=((_Consumer$contextType={})[contextProp]=_propTypes2.default.object,_Consumer$contextType),{Provider:Provider,Consumer:_Provider$childContex}},module.exports=exports.default}.call(this)}.call(this,require("_process"))},{_process:1042,gud:645,"prop-types":1046,react:1427,warning:1702}],33:[function(require,module,exports){"use strict";exports.__esModule=!0;var _react2=_interopRequireDefault(require("react")),require=_interopRequireDefault(require("./implementation"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=_react2.default.createContext||require.default,module.exports=exports.default},{"./implementation":32,react:1427}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var env=require("exenv"),PropTypes=require("prop-types"),require=require("react");function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps)}function _defineProperty(obj,key,value){key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value}function _getPrototypeOf(o){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(o){return o.__proto__||Object.getPrototypeOf(o)})(o)}function _setPrototypeOf(o,p){return(_setPrototypeOf=Object.setPrototypeOf||function(o,p){return o.__proto__=p,o})(o,p)}function _possibleConstructorReturn(self,call){return!call||"object"!=typeof call&&"function"!=typeof call?function(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}(self):call}var EventSet=function(){function EventSet(eventHandlers){_classCallCheck(this,EventSet),_defineProperty(this,"handlers",void 0),this.handlers=eventHandlers.slice(0)}return _createClass(EventSet,[{key:"addHandlers",value:function(additionalHandlers){for(var newHandlers=this.handlers.slice(0),length=additionalHandlers.length,i=0;i<length;i+=1)newHandlers.push(additionalHandlers[i]);return new EventSet(newHandlers)}},{key:"dispatchEvent",value:function(event,dispatchAll){var count=this.handlers.length-1;if(dispatchAll){for(var i=count;0<=i;--i)this.handlers[i].called||(this.handlers[i].called=!0,this.handlers[i](event));for(var _i=count;0<=_i;--_i)this.handlers[_i].called=!1}else(0,this.handlers[count])(event)}},{key:"hasHandlers",value:function(){return 0<this.handlers.length}},{key:"removeHandlers",value:function(removalHandlers){for(var newHandlers=[],length=this.handlers.length,i=0;i<length;i+=1){var handler=this.handlers[i];-1===removalHandlers.indexOf(handler)&&newHandlers.push(handler)}return new EventSet(newHandlers)}}]),EventSet}();function cloneMap(map){var newMap=new Map;return map.forEach(function(value,key){newMap.set(key,value)}),newMap}function normalizeHandlers(handlers){return Array.isArray(handlers)?handlers:[handlers]}var isRefObject=function(ref){return null!==ref&&"object"===_typeof(ref)&&ref.hasOwnProperty("current")};function normalizeTarget(target){return"document"===target?document:"window"===target?window:isRefObject(target)?target.current||document:target||document}var EventPool=function(){function EventPool(poolName,handlerSets){_classCallCheck(this,EventPool),_defineProperty(this,"handlerSets",void 0),_defineProperty(this,"poolName",void 0),this.handlerSets=handlerSets,this.poolName=poolName}return _createClass(EventPool,[{key:"addHandlers",value:function(eventType,eventHandlers){var eventSet,handlerSets=cloneMap(this.handlerSets);return handlerSets.has(eventType)?(eventSet=handlerSets.get(eventType),handlerSets.set(eventType,eventSet.addHandlers(eventHandlers))):handlerSets.set(eventType,new EventSet(eventHandlers)),new EventPool(this.poolName,handlerSets)}},{key:"dispatchEvent",value:function(eventType,event){var eventType=this.handlerSets.get(eventType),shouldDispatchAll="default"===this.poolName;eventType&&eventType.dispatchEvent(event,shouldDispatchAll)}},{key:"hasHandlers",value:function(eventType){return eventType?!!(eventType=this.handlerSets.get(eventType))&&eventType.hasHandlers():0<this.handlerSets.size}},{key:"removeHandlers",value:function(eventType,eventHandlers){var handlerSets=cloneMap(this.handlerSets);return handlerSets.has(eventType)&&((eventHandlers=handlerSets.get(eventType).removeHandlers(eventHandlers)).hasHandlers()?handlerSets.set(eventType,eventHandlers):handlerSets.delete(eventType)),new EventPool(this.poolName,handlerSets)}}]),EventPool}(),EventTarget=(_defineProperty(EventPool,"createByType",function(poolName,eventType,eventHandlers){var handlerSets=new Map;return handlerSets.set(eventType,new EventSet(eventHandlers)),new EventPool(poolName,handlerSets)}),function(){function EventTarget(target){var _this=this;_classCallCheck(this,EventTarget),_defineProperty(this,"handlers",new Map),_defineProperty(this,"pools",new Map),_defineProperty(this,"target",void 0),_defineProperty(this,"createEmitter",function(eventType){return function(event){_this.pools.forEach(function(pool){pool.dispatchEvent(eventType,event)})}}),this.target=target}return _createClass(EventTarget,[{key:"addHandlers",value:function(poolName,eventType,eventHandlers){var eventPool;this.pools.has(poolName)?(eventPool=this.pools.get(poolName),this.pools.set(poolName,eventPool.addHandlers(eventType,eventHandlers))):this.pools.set(poolName,EventPool.createByType(poolName,eventType,eventHandlers)),this.handlers.has(eventType)||this.addTargetHandler(eventType)}},{key:"hasHandlers",value:function(){return 0<this.handlers.size}},{key:"removeHandlers",value:function(poolName,eventType,eventHandlers){var hasHandlers;this.pools.has(poolName)&&((eventHandlers=this.pools.get(poolName).removeHandlers(eventType,eventHandlers)).hasHandlers()?this.pools.set(poolName,eventHandlers):this.pools.delete(poolName),hasHandlers=!1,this.pools.forEach(function(pool){return hasHandlers=hasHandlers||pool.hasHandlers(eventType)}),hasHandlers||this.removeTargetHandler(eventType))}},{key:"addTargetHandler",value:function(eventType){var handler=this.createEmitter(eventType);this.handlers.set(eventType,handler),this.target.addEventListener(eventType,handler,!0)}},{key:"removeTargetHandler",value:function(eventType){this.handlers.has(eventType)&&(this.target.removeEventListener(eventType,this.handlers.get(eventType),!0),this.handlers.delete(eventType))}}]),EventTarget}()),instance=new(function(){function EventStack(){var _this=this;_classCallCheck(this,EventStack),_defineProperty(this,"targets",new Map),_defineProperty(this,"getTarget",function(target){var autoCreate=!(1<arguments.length&&void 0!==arguments[1])||arguments[1],target=normalizeTarget(target);return _this.targets.has(target)?_this.targets.get(target):autoCreate?(autoCreate=new EventTarget(target),_this.targets.set(target,autoCreate),autoCreate):null}),_defineProperty(this,"removeTarget",function(target){_this.targets.delete(normalizeTarget(target))})}return _createClass(EventStack,[{key:"sub",value:function(eventName,eventHandlers){var _options$target,options=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};env.canUseDOM&&(_options$target=void 0===(_options$target=options.target)?document:_options$target,options=void 0===(options=options.pool)?"default":options,this.getTarget(_options$target).addHandlers(options,eventName,normalizeHandlers(eventHandlers)))}},{key:"unsub",value:function(eventName,eventHandlers){var _options$target2,eventTarget,options=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};env.canUseDOM&&(_options$target2=void 0===(_options$target2=options.target)?document:_options$target2,options=void 0===(options=options.pool)?"default":options,eventTarget=this.getTarget(_options$target2,!1))&&(eventTarget.removeHandlers(options,eventName,normalizeHandlers(eventHandlers)),eventTarget.hasHandlers()||this.removeTarget(_options$target2))}}]),EventStack}()),require=function(_React$PureComponent){var subClass=EventStack;if("function"!=typeof _React$PureComponent&&null!==_React$PureComponent)throw new TypeError("Super expression must either be null or a function");function EventStack(){return _classCallCheck(this,EventStack),_possibleConstructorReturn(this,_getPrototypeOf(EventStack).apply(this,arguments))}return subClass.prototype=Object.create(_React$PureComponent&&_React$PureComponent.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),_React$PureComponent&&_setPrototypeOf(subClass,_React$PureComponent),_createClass(EventStack,[{key:"componentDidMount",value:function(){this.subscribe(this.props)}},{key:"componentDidUpdate",value:function(prevProps){this.unsubscribe(prevProps),this.subscribe(this.props)}},{key:"componentWillUnmount",value:function(){this.unsubscribe(this.props)}},{key:"subscribe",value:function(props){var name=props.name,on=props.on,pool=props.pool,props=props.target;instance.sub(name,on,{pool:pool,target:props})}},{key:"unsubscribe",value:function(props){var name=props.name,on=props.on,pool=props.pool,props=props.target;instance.unsub(name,on,{pool:pool,target:props})}},{key:"render",value:function(){return null}}]),EventStack}(require.PureComponent);_defineProperty(require,"defaultProps",{pool:"default",target:"document"}),require.propTypes={name:PropTypes.string.isRequired,on:PropTypes.oneOfType([PropTypes.func,PropTypes.arrayOf(PropTypes.func)]).isRequired,pool:PropTypes.string,target:PropTypes.oneOfType([PropTypes.oneOf(["document","window"]),PropTypes.instanceOf(env.canUseDOM?HTMLElement:Object),PropTypes.shape({current:PropTypes.object})])},exports.instance=instance,exports.default=require},{exenv:640,"prop-types":1046,react:1427}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var env=require("exenv"),require=(require("prop-types"),require("react"));function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n)}function _defineProperty(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function _possibleConstructorReturn(e,t){return!t||"object"!=typeof t&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}_createClass(e,[{key:"addHandlers",value:function(t){for(var n=this.handlers.slice(0),r=t.length,o=0;o<r;o+=1)n.push(t[o]);return new e(n)}},{key:"dispatchEvent",value:function(e,t){var n=this.handlers.length-1;if(t){for(var r=n;0<=r;--r)this.handlers[r].called||(this.handlers[r].called=!0,this.handlers[r](e));for(var o=n;0<=o;--o)this.handlers[o].called=!1}else(0,this.handlers[n])(e)}},{key:"hasHandlers",value:function(){return 0<this.handlers.length}},{key:"removeHandlers",value:function(t){for(var n=[],r=this.handlers.length,o=0;o<r;o+=1){var a=this.handlers[o];-1===t.indexOf(a)&&n.push(a)}return new e(n)}}]);var EventSet=e;function e(t){_classCallCheck(this,e),_defineProperty(this,"handlers",void 0),this.handlers=t.slice(0)}function cloneMap(e){var t=new Map;return e.forEach(function(e,n){t.set(n,e)}),t}function normalizeHandlers(e){return Array.isArray(e)?e:[e]}var isRefObject=function(e){return null!==e&&"object"===_typeof(e)&&e.hasOwnProperty("current")};function normalizeTarget(e){return"document"===e?document:"window"===e?window:isRefObject(e)?e.current||document:e||document}var EventPool=function(){function e(t,n){_classCallCheck(this,e),_defineProperty(this,"handlerSets",void 0),_defineProperty(this,"poolName",void 0),this.handlerSets=n,this.poolName=t}return _createClass(e,[{key:"addHandlers",value:function(t,n){var o,r=cloneMap(this.handlerSets);return r.has(t)?(o=r.get(t),r.set(t,o.addHandlers(n))):r.set(t,new EventSet(n)),new e(this.poolName,r)}},{key:"dispatchEvent",value:function(e,t){var e=this.handlerSets.get(e),r="default"===this.poolName;e&&e.dispatchEvent(t,r)}},{key:"hasHandlers",value:function(e){return e?!!(e=this.handlerSets.get(e))&&e.hasHandlers():0<this.handlerSets.size}},{key:"removeHandlers",value:function(t,n){var r=cloneMap(this.handlerSets);return r.has(t)&&((n=r.get(t).removeHandlers(n)).hasHandlers()?r.set(t,n):r.delete(t)),new e(this.poolName,r)}}]),e}(),EventTarget=(_defineProperty(EventPool,"createByType",function(e,t,n){var r=new Map;return r.set(t,new EventSet(n)),new EventPool(e,r)}),function(){function e(t){var n=this;_classCallCheck(this,e),_defineProperty(this,"handlers",new Map),_defineProperty(this,"pools",new Map),_defineProperty(this,"target",void 0),_defineProperty(this,"createEmitter",function(e){return function(t){n.pools.forEach(function(n){n.dispatchEvent(e,t)})}}),this.target=t}return _createClass(e,[{key:"addHandlers",value:function(e,t,n){var r;this.pools.has(e)?(r=this.pools.get(e),this.pools.set(e,r.addHandlers(t,n))):this.pools.set(e,EventPool.createByType(e,t,n)),this.handlers.has(t)||this.addTargetHandler(t)}},{key:"hasHandlers",value:function(){return 0<this.handlers.size}},{key:"removeHandlers",value:function(e,t,n){var o;this.pools.has(e)&&((n=this.pools.get(e).removeHandlers(t,n)).hasHandlers()?this.pools.set(e,n):this.pools.delete(e),o=!1,this.pools.forEach(function(e){return o=o||e.hasHandlers(t)}),o||this.removeTargetHandler(t))}},{key:"addTargetHandler",value:function(e){var t=this.createEmitter(e);this.handlers.set(e,t),this.target.addEventListener(e,t,!0)}},{key:"removeTargetHandler",value:function(e){this.handlers.has(e)&&(this.target.removeEventListener(e,this.handlers.get(e),!0),this.handlers.delete(e))}}]),e}()),instance=new(function(){function e(){var t=this;_classCallCheck(this,e),_defineProperty(this,"targets",new Map),_defineProperty(this,"getTarget",function(e){var n=!(1<arguments.length&&void 0!==arguments[1])||arguments[1],e=normalizeTarget(e);return t.targets.has(e)?t.targets.get(e):n?(n=new EventTarget(e),t.targets.set(e,n),n):null}),_defineProperty(this,"removeTarget",function(e){t.targets.delete(normalizeTarget(e))})}return _createClass(e,[{key:"sub",value:function(e,t){var r,n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};env.canUseDOM&&(r=void 0===(r=n.target)?document:r,n=void 0===(n=n.pool)?"default":n,this.getTarget(r).addHandlers(n,e,normalizeHandlers(t)))}},{key:"unsub",value:function(e,t){var r,i,n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};env.canUseDOM&&(r=void 0===(r=n.target)?document:r,n=void 0===(n=n.pool)?"default":n,i=this.getTarget(r,!1))&&(i.removeHandlers(n,e,normalizeHandlers(t)),i.hasHandlers()||this.removeTarget(r))}}]),e}()),require=(function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_setPrototypeOf(e,t)}(t,require.PureComponent),_createClass(t,[{key:"componentDidMount",value:function(){this.subscribe(this.props)}},{key:"componentDidUpdate",value:function(e){this.unsubscribe(e),this.subscribe(this.props)}},{key:"componentWillUnmount",value:function(){this.unsubscribe(this.props)}},{key:"subscribe",value:function(e){var t=e.name,n=e.on,r=e.pool,e=e.target;instance.sub(t,n,{pool:r,target:e})}},{key:"unsubscribe",value:function(e){var t=e.name,n=e.on,r=e.pool,e=e.target;instance.unsub(t,n,{pool:r,target:e})}},{key:"render",value:function(){return null}}]),t);function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,_getPrototypeOf(t).apply(this,arguments))}_defineProperty(require,"defaultProps",{pool:"default",target:"document"}),require.propTypes={},exports.instance=instance,exports.default=require},{exenv:640,"prop-types":1046,react:1427}],36:[function(require,module,exports){!function(process){!function(){"use strict";var stack="production"===process.env.NODE_ENV?require("./cjs/event-stack.production.js"):require("./cjs/event-stack.development.js");module.exports=stack.default,module.exports.instance=stack.instance}.call(this)}.call(this,require("_process"))},{"./cjs/event-stack.development.js":34,"./cjs/event-stack.production.js":35,_process:1042}],37:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),types_1=require("@sentry/types"),utils_1=require("@sentry/utils"),eventbuilder_1=require("./eventbuilder"),transports_1=require("./transports"),require=function(_super){function BrowserBackend(){return null!==_super&&_super.apply(this,arguments)||this}return tslib_1.__extends(BrowserBackend,_super),BrowserBackend.prototype.eventFromException=function(exception,hint){return eventbuilder_1.eventFromException(this._options,exception,hint)},BrowserBackend.prototype.eventFromMessage=function(message,level,hint){return void 0===level&&(level=types_1.Severity.Info),eventbuilder_1.eventFromMessage(this._options,message,level,hint)},BrowserBackend.prototype._setupTransport=function(){var transportOptions;return this._options.dsn?(transportOptions=tslib_1.__assign(tslib_1.__assign({},this._options.transportOptions),{dsn:this._options.dsn}),new(this._options.transport||(utils_1.supportsFetch()?transports_1.FetchTransport:transports_1.XHRTransport))(transportOptions)):_super.prototype._setupTransport.call(this)},BrowserBackend}(core_1.BaseBackend);exports.BrowserBackend=require},{"./eventbuilder":39,"./transports":54,"@sentry/core":60,"@sentry/types":73,"@sentry/utils":83,tslib:1698}],38:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),utils_1=require("@sentry/utils"),backend_1=require("./backend"),helpers_1=require("./helpers"),integrations_1=require("./integrations"),version_1=require("./version"),require=function(_super){function BrowserClient(options){return _super.call(this,backend_1.BrowserBackend,options=void 0===options?{}:options)||this}return tslib_1.__extends(BrowserClient,_super),BrowserClient.prototype.showReportDialog=function(options){void 0===options&&(options={}),utils_1.getGlobalObject().document&&(this._isEnabled()?helpers_1.injectReportDialog(tslib_1.__assign(tslib_1.__assign({},options),{dsn:options.dsn||this.getDsn()})):utils_1.logger.error("Trying to call showReportDialog with Sentry Client disabled"))},BrowserClient.prototype._prepareEvent=function(event,scope,hint){return event.platform=event.platform||"javascript",event.sdk=tslib_1.__assign(tslib_1.__assign({},event.sdk),{name:version_1.SDK_NAME,packages:tslib_1.__spread(event.sdk&&event.sdk.packages||[],[{name:"npm:@sentry/browser",version:version_1.SDK_VERSION}]),version:version_1.SDK_VERSION}),_super.prototype._prepareEvent.call(this,event,scope,hint)},BrowserClient.prototype._sendEvent=function(event){var integration=this.getIntegration(integrations_1.Breadcrumbs);integration&&integration.addSentryBreadcrumb(event),_super.prototype._sendEvent.call(this,event)},BrowserClient}(core_1.BaseClient);exports.BrowserClient=require},{"./backend":37,"./helpers":41,"./integrations":45,"./version":56,"@sentry/core":60,"@sentry/utils":83,tslib:1698}],39:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),types_1=require("@sentry/types"),utils_1=require("@sentry/utils"),parsers_1=require("./parsers"),tracekit_1=require("./tracekit");function eventFromUnknownInput(exception,syntheticException,options){var domException,event,name_1;if(void 0===options&&(options={}),utils_1.isErrorEvent(exception)&&exception.error)return exception=exception.error,event=parsers_1.eventFromStacktrace(tracekit_1.computeStackTrace(exception));if(utils_1.isDOMError(exception)||utils_1.isDOMException(exception))name_1=(domException=exception).name||(utils_1.isDOMError(domException)?"DOMError":"DOMException"),event=eventFromString(name_1=domException.message?name_1+": "+domException.message:name_1,syntheticException,options),utils_1.addExceptionTypeValue(event,name_1),"code"in domException&&(event.tags=tslib_1.__assign(tslib_1.__assign({},event.tags),{"DOMException.code":""+domException.code}));else{if(utils_1.isError(exception))return event=parsers_1.eventFromStacktrace(tracekit_1.computeStackTrace(exception));utils_1.isPlainObject(exception)||utils_1.isEvent(exception)?(name_1=exception,event=parsers_1.eventFromPlainObject(name_1,syntheticException,options.rejection)):(event=eventFromString(exception,syntheticException,options),utils_1.addExceptionTypeValue(event,""+exception,void 0)),utils_1.addExceptionMechanism(event,{synthetic:!0})}return event}function eventFromString(input,syntheticException,options){input={message:input};return(options=void 0===options?{}:options).attachStacktrace&&syntheticException&&(options=tracekit_1.computeStackTrace(syntheticException),syntheticException=parsers_1.prepareFramesForEvent(options.stack),input.stacktrace={frames:syntheticException}),input}exports.eventFromException=function(options,exception,hint){return exception=eventFromUnknownInput(exception,hint&&hint.syntheticException||void 0,{attachStacktrace:options.attachStacktrace}),utils_1.addExceptionMechanism(exception,{handled:!0,type:"generic"}),exception.level=types_1.Severity.Error,hint&&hint.event_id&&(exception.event_id=hint.event_id),utils_1.SyncPromise.resolve(exception)},exports.eventFromMessage=function(options,message,level,hint){return void 0===level&&(level=types_1.Severity.Info),(message=eventFromString(message,hint&&hint.syntheticException||void 0,{attachStacktrace:options.attachStacktrace})).level=level,hint&&hint.event_id&&(message.event_id=hint.event_id),utils_1.SyncPromise.resolve(message)},exports.eventFromUnknownInput=eventFromUnknownInput,exports.eventFromString=eventFromString},{"./parsers":49,"./tracekit":51,"@sentry/types":73,"@sentry/utils":83,tslib:1698}],40:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var types_1=require("@sentry/types"),types_1=(exports.Severity=types_1.Severity,exports.Status=types_1.Status,require("@sentry/core")),types_1=(exports.addGlobalEventProcessor=types_1.addGlobalEventProcessor,exports.addBreadcrumb=types_1.addBreadcrumb,exports.captureException=types_1.captureException,exports.captureEvent=types_1.captureEvent,exports.captureMessage=types_1.captureMessage,exports.configureScope=types_1.configureScope,exports.getHubFromCarrier=types_1.getHubFromCarrier,exports.getCurrentHub=types_1.getCurrentHub,exports.Hub=types_1.Hub,exports.makeMain=types_1.makeMain,exports.Scope=types_1.Scope,exports.startTransaction=types_1.startTransaction,exports.setContext=types_1.setContext,exports.setExtra=types_1.setExtra,exports.setExtras=types_1.setExtras,exports.setTag=types_1.setTag,exports.setTags=types_1.setTags,exports.setUser=types_1.setUser,exports.withScope=types_1.withScope,require("./client")),types_1=(exports.BrowserClient=types_1.BrowserClient,require("./helpers")),types_1=(exports.injectReportDialog=types_1.injectReportDialog,require("./eventbuilder")),types_1=(exports.eventFromException=types_1.eventFromException,exports.eventFromMessage=types_1.eventFromMessage,require("./sdk")),types_1=(exports.defaultIntegrations=types_1.defaultIntegrations,exports.forceLoad=types_1.forceLoad,exports.init=types_1.init,exports.lastEventId=types_1.lastEventId,exports.onLoad=types_1.onLoad,exports.showReportDialog=types_1.showReportDialog,exports.flush=types_1.flush,exports.close=types_1.close,exports.wrap=types_1.wrap,require("./version"));exports.SDK_NAME=types_1.SDK_NAME,exports.SDK_VERSION=types_1.SDK_VERSION},{"./client":38,"./eventbuilder":39,"./helpers":41,"./sdk":50,"./version":56,"@sentry/core":60,"@sentry/types":73}],41:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),utils_1=require("@sentry/utils"),ignoreOnError=0;function ignoreNextOnError(){ignoreOnError+=1,setTimeout(function(){--ignoreOnError})}exports.shouldIgnoreOnError=function(){return 0<ignoreOnError},exports.ignoreNextOnError=ignoreNextOnError,exports.wrap=function wrap(fn,options,before){if(void 0===options&&(options={}),"function"!=typeof fn)return fn;try{if(fn.__sentry__)return fn;if(fn.__sentry_wrapped__)return fn.__sentry_wrapped__}catch(e){return fn}function sentryWrapped(){var args=Array.prototype.slice.call(arguments);try{before&&"function"==typeof before&&before.apply(this,arguments);var wrappedArguments=args.map(function(arg){return wrap(arg,options)});return(fn.handleEvent||fn).apply(this,wrappedArguments)}catch(ex){throw ignoreNextOnError(),core_1.withScope(function(scope){scope.addEventProcessor(function(event){return event=tslib_1.__assign({},event),options.mechanism&&(utils_1.addExceptionTypeValue(event,void 0,void 0),utils_1.addExceptionMechanism(event,options.mechanism)),event.extra=tslib_1.__assign(tslib_1.__assign({},event.extra),{arguments:args}),event}),core_1.captureException(ex)}),ex}}try{for(var property in fn)Object.prototype.hasOwnProperty.call(fn,property)&&(sentryWrapped[property]=fn[property])}catch(_oO){}fn.prototype=fn.prototype||{},sentryWrapped.prototype=fn.prototype,Object.defineProperty(fn,"__sentry_wrapped__",{enumerable:!1,value:sentryWrapped}),Object.defineProperties(sentryWrapped,{__sentry__:{enumerable:!1,value:!0},__sentry_original__:{enumerable:!1,value:fn}});try{Object.getOwnPropertyDescriptor(sentryWrapped,"name").configurable&&Object.defineProperty(sentryWrapped,"name",{get:function(){return fn.name}})}catch(_oO){}return sentryWrapped},exports.injectReportDialog=function(options){var script;(options=void 0===options?{}:options).eventId?options.dsn?((script=document.createElement("script")).async=!0,script.src=new core_1.API(options.dsn).getReportDialogEndpoint(options),options.onLoad&&(script.onload=options.onLoad),(document.head||document.body).appendChild(script)):utils_1.logger.error("Missing dsn option in showReportDialog call"):utils_1.logger.error("Missing eventId option in showReportDialog call")}},{"@sentry/core":60,"@sentry/utils":83,tslib:1698}],42:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=(tslib_1.__exportStar(require("./exports"),exports),require("@sentry/core")),utils_1=require("@sentry/utils"),BrowserIntegrations=require("./integrations"),require=require("./transports"),require=(exports.Transports=require,{}),utils_1=utils_1.getGlobalObject(),utils_1=(utils_1.Sentry&&utils_1.Sentry.Integrations&&(require=utils_1.Sentry.Integrations),tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({},require),core_1.Integrations),BrowserIntegrations));exports.Integrations=utils_1},{"./exports":40,"./integrations":45,"./transports":54,"@sentry/core":60,"@sentry/utils":83,tslib:1698}],43:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),types_1=require("@sentry/types"),utils_1=require("@sentry/utils"),require=function(){function Breadcrumbs(options){this.name=Breadcrumbs.id,this._options=tslib_1.__assign({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},options)}return Breadcrumbs.prototype.addSentryBreadcrumb=function(event){this._options.sentry&&core_1.getCurrentHub().addBreadcrumb({category:"sentry."+("transaction"===event.type?"transaction":"event"),event_id:event.event_id,level:event.level,message:utils_1.getEventDescription(event)},{event:event})},Breadcrumbs.prototype.setupOnce=function(){var _this=this;this._options.console&&utils_1.addInstrumentationHandler({callback:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];_this._consoleBreadcrumb.apply(_this,tslib_1.__spread(args))},type:"console"}),this._options.dom&&utils_1.addInstrumentationHandler({callback:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];_this._domBreadcrumb.apply(_this,tslib_1.__spread(args))},type:"dom"}),this._options.xhr&&utils_1.addInstrumentationHandler({callback:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];_this._xhrBreadcrumb.apply(_this,tslib_1.__spread(args))},type:"xhr"}),this._options.fetch&&utils_1.addInstrumentationHandler({callback:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];_this._fetchBreadcrumb.apply(_this,tslib_1.__spread(args))},type:"fetch"}),this._options.history&&utils_1.addInstrumentationHandler({callback:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];_this._historyBreadcrumb.apply(_this,tslib_1.__spread(args))},type:"history"})},Breadcrumbs.prototype._consoleBreadcrumb=function(handlerData){var breadcrumb={category:"console",data:{arguments:handlerData.args,logger:"console"},level:types_1.Severity.fromString(handlerData.level),message:utils_1.safeJoin(handlerData.args," ")};if("assert"===handlerData.level){if(!1!==handlerData.args[0])return;breadcrumb.message="Assertion failed: "+(utils_1.safeJoin(handlerData.args.slice(1)," ")||"console.assert"),breadcrumb.data.arguments=handlerData.args.slice(1)}core_1.getCurrentHub().addBreadcrumb(breadcrumb,{input:handlerData.args,level:handlerData.level})},Breadcrumbs.prototype._domBreadcrumb=function(handlerData){var target;try{target=handlerData.event.target?utils_1.htmlTreeAsString(handlerData.event.target):utils_1.htmlTreeAsString(handlerData.event)}catch(e){target="<unknown>"}0!==target.length&&core_1.getCurrentHub().addBreadcrumb({category:"ui."+handlerData.name,message:target},{event:handlerData.event,name:handlerData.name})},Breadcrumbs.prototype._xhrBreadcrumb=function(handlerData){var method,url,status_code,_a;handlerData.endTimestamp&&!handlerData.xhr.__sentry_own_request__&&(method=(_a=handlerData.xhr.__sentry_xhr__||{}).method,url=_a.url,status_code=_a.status_code,_a=_a.body,core_1.getCurrentHub().addBreadcrumb({category:"xhr",data:{method:method,url:url,status_code:status_code},type:"http"},{xhr:handlerData.xhr,input:_a}))},Breadcrumbs.prototype._fetchBreadcrumb=function(handlerData){!handlerData.endTimestamp||handlerData.fetchData.url.match(/sentry_key/)&&"POST"===handlerData.fetchData.method||(handlerData.error?core_1.getCurrentHub().addBreadcrumb({category:"fetch",data:handlerData.fetchData,level:types_1.Severity.Error,type:"http"},{data:handlerData.error,input:handlerData.args}):core_1.getCurrentHub().addBreadcrumb({category:"fetch",data:tslib_1.__assign(tslib_1.__assign({},handlerData.fetchData),{status_code:handlerData.response.status}),type:"http"},{input:handlerData.args,response:handlerData.response}))},Breadcrumbs.prototype._historyBreadcrumb=function(handlerData){var global=utils_1.getGlobalObject(),from=handlerData.from,handlerData=handlerData.to,global=utils_1.parseUrl(global.location.href),parsedFrom=utils_1.parseUrl(from),parsedTo=utils_1.parseUrl(handlerData);parsedFrom.path||(parsedFrom=global),global.protocol===parsedTo.protocol&&global.host===parsedTo.host&&(handlerData=parsedTo.relative),global.protocol===parsedFrom.protocol&&global.host===parsedFrom.host&&(from=parsedFrom.relative),core_1.getCurrentHub().addBreadcrumb({category:"navigation",data:{from:from,to:handlerData}})},Breadcrumbs.id="Breadcrumbs",Breadcrumbs}();exports.Breadcrumbs=require},{"@sentry/core":60,"@sentry/types":73,"@sentry/utils":83,tslib:1698}],44:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),types_1=require("@sentry/types"),utils_1=require("@sentry/utils"),eventbuilder_1=require("../eventbuilder"),helpers_1=require("../helpers"),require=function(){function GlobalHandlers(options){this.name=GlobalHandlers.id,this._onErrorHandlerInstalled=!1,this._onUnhandledRejectionHandlerInstalled=!1,this._options=tslib_1.__assign({onerror:!0,onunhandledrejection:!0},options)}return GlobalHandlers.prototype.setupOnce=function(){Error.stackTraceLimit=50,this._options.onerror&&(utils_1.logger.log("Global Handler attached: onerror"),this._installGlobalOnErrorHandler()),this._options.onunhandledrejection&&(utils_1.logger.log("Global Handler attached: onunhandledrejection"),this._installGlobalOnUnhandledRejectionHandler())},GlobalHandlers.prototype._installGlobalOnErrorHandler=function(){var _this=this;this._onErrorHandlerInstalled||(utils_1.addInstrumentationHandler({callback:function(data){var error=data.error,currentHub=core_1.getCurrentHub(),hasIntegration=currentHub.getIntegration(GlobalHandlers),isFailedOwnDelivery=error&&!0===error.__sentry_own_request__;!hasIntegration||helpers_1.shouldIgnoreOnError()||isFailedOwnDelivery||(hasIntegration=currentHub.getClient(),isFailedOwnDelivery=utils_1.isPrimitive(error)?_this._eventFromIncompleteOnError(data.msg,data.url,data.line,data.column):_this._enhanceEventWithInitialFrame(eventbuilder_1.eventFromUnknownInput(error,void 0,{attachStacktrace:hasIntegration&&hasIntegration.getOptions().attachStacktrace,rejection:!1}),data.url,data.line,data.column),utils_1.addExceptionMechanism(isFailedOwnDelivery,{handled:!1,type:"onerror"}),currentHub.captureEvent(isFailedOwnDelivery,{originalException:error}))},type:"error"}),this._onErrorHandlerInstalled=!0)},GlobalHandlers.prototype._installGlobalOnUnhandledRejectionHandler=function(){var _this=this;this._onUnhandledRejectionHandlerInstalled||(utils_1.addInstrumentationHandler({callback:function(e){var error=e;try{"reason"in e?error=e.reason:"detail"in e&&"reason"in e.detail&&(error=e.detail.reason)}catch(_oO){}var e=core_1.getCurrentHub(),hasIntegration=e.getIntegration(GlobalHandlers),isFailedOwnDelivery=error&&!0===error.__sentry_own_request__;if(!hasIntegration||helpers_1.shouldIgnoreOnError()||isFailedOwnDelivery)return!0;hasIntegration=e.getClient(),isFailedOwnDelivery=utils_1.isPrimitive(error)?_this._eventFromRejectionWithPrimitive(error):eventbuilder_1.eventFromUnknownInput(error,void 0,{attachStacktrace:hasIntegration&&hasIntegration.getOptions().attachStacktrace,rejection:!0});isFailedOwnDelivery.level=types_1.Severity.Error,utils_1.addExceptionMechanism(isFailedOwnDelivery,{handled:!1,type:"onunhandledrejection"}),e.captureEvent(isFailedOwnDelivery,{originalException:error})},type:"unhandledrejection"}),this._onUnhandledRejectionHandlerInstalled=!0)},GlobalHandlers.prototype._eventFromIncompleteOnError=function(msg,url,line,column){var name,msg=utils_1.isErrorEvent(msg)?msg.message:msg,groups=(utils_1.isString(msg)&&(groups=msg.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i))&&(name=groups[1],msg=groups[2]),{exception:{values:[{type:name||"Error",value:msg}]}});return this._enhanceEventWithInitialFrame(groups,url,line,column)},GlobalHandlers.prototype._eventFromRejectionWithPrimitive=function(reason){return{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(reason)}]}}},GlobalHandlers.prototype._enhanceEventWithInitialFrame=function(event,url,line,column){event.exception=event.exception||{},event.exception.values=event.exception.values||[],event.exception.values[0]=event.exception.values[0]||{},event.exception.values[0].stacktrace=event.exception.values[0].stacktrace||{},event.exception.values[0].stacktrace.frames=event.exception.values[0].stacktrace.frames||[];column=isNaN(parseInt(column,10))?void 0:column,line=isNaN(parseInt(line,10))?void 0:line,url=utils_1.isString(url)&&0<url.length?url:utils_1.getLocationHref();return 0===event.exception.values[0].stacktrace.frames.length&&event.exception.values[0].stacktrace.frames.push({colno:column,filename:url,function:"?",in_app:!0,lineno:line}),event},GlobalHandlers.id="GlobalHandlers",GlobalHandlers}();exports.GlobalHandlers=require},{"../eventbuilder":39,"../helpers":41,"@sentry/core":60,"@sentry/types":73,"@sentry/utils":83,tslib:1698}],45:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var globalhandlers_1=require("./globalhandlers"),globalhandlers_1=(exports.GlobalHandlers=globalhandlers_1.GlobalHandlers,require("./trycatch")),globalhandlers_1=(exports.TryCatch=globalhandlers_1.TryCatch,require("./breadcrumbs")),globalhandlers_1=(exports.Breadcrumbs=globalhandlers_1.Breadcrumbs,require("./linkederrors")),globalhandlers_1=(exports.LinkedErrors=globalhandlers_1.LinkedErrors,require("./useragent"));exports.UserAgent=globalhandlers_1.UserAgent},{"./breadcrumbs":43,"./globalhandlers":44,"./linkederrors":46,"./trycatch":47,"./useragent":48}],46:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),utils_1=require("@sentry/utils"),parsers_1=require("../parsers"),tracekit_1=require("../tracekit"),require=function(){function LinkedErrors(options){void 0===options&&(options={}),this.name=LinkedErrors.id,this._key=options.key||"cause",this._limit=options.limit||5}return LinkedErrors.prototype.setupOnce=function(){core_1.addGlobalEventProcessor(function(event,hint){var self=core_1.getCurrentHub().getIntegration(LinkedErrors);return self?self._handler(event,hint):event})},LinkedErrors.prototype._handler=function(event,hint){return event.exception&&event.exception.values&&hint&&utils_1.isInstanceOf(hint.originalException,Error)&&(hint=this._walkErrorTree(hint.originalException,this._key),event.exception.values=tslib_1.__spread(hint,event.exception.values)),event},LinkedErrors.prototype._walkErrorTree=function(error,key,stack){var stacktrace;return void 0===stack&&(stack=[]),!utils_1.isInstanceOf(error[key],Error)||stack.length+1>=this._limit?stack:(stacktrace=tracekit_1.computeStackTrace(error[key]),stacktrace=parsers_1.exceptionFromStacktrace(stacktrace),this._walkErrorTree(error[key],key,tslib_1.__spread([stacktrace],stack)))},LinkedErrors.id="LinkedErrors",LinkedErrors}();exports.LinkedErrors=require},{"../parsers":49,"../tracekit":51,"@sentry/core":60,"@sentry/utils":83,tslib:1698}],47:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),utils_1=require("@sentry/utils"),helpers_1=require("../helpers"),DEFAULT_EVENT_TARGET=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],require=function(){function TryCatch(options){this.name=TryCatch.id,this._options=tslib_1.__assign({XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0},options)}return TryCatch.prototype.setupOnce=function(){var global=utils_1.getGlobalObject();this._options.setTimeout&&utils_1.fill(global,"setTimeout",this._wrapTimeFunction.bind(this)),this._options.setInterval&&utils_1.fill(global,"setInterval",this._wrapTimeFunction.bind(this)),this._options.requestAnimationFrame&&utils_1.fill(global,"requestAnimationFrame",this._wrapRAF.bind(this)),this._options.XMLHttpRequest&&"XMLHttpRequest"in global&&utils_1.fill(XMLHttpRequest.prototype,"send",this._wrapXHR.bind(this)),this._options.eventTarget&&(Array.isArray(this._options.eventTarget)?this._options.eventTarget:DEFAULT_EVENT_TARGET).forEach(this._wrapEventTarget.bind(this))},TryCatch.prototype._wrapTimeFunction=function(original){return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return args[0]=helpers_1.wrap(args[0],{mechanism:{data:{function:utils_1.getFunctionName(original)},handled:!0,type:"instrument"}}),original.apply(this,args)}},TryCatch.prototype._wrapRAF=function(original){return function(callback){return original.call(this,helpers_1.wrap(callback,{mechanism:{data:{function:"requestAnimationFrame",handler:utils_1.getFunctionName(original)},handled:!0,type:"instrument"}}))}},TryCatch.prototype._wrapEventTarget=function(target){var global=utils_1.getGlobalObject(),global=global[target]&&global[target].prototype;global&&global.hasOwnProperty&&global.hasOwnProperty("addEventListener")&&(utils_1.fill(global,"addEventListener",function(original){return function(eventName,fn,options){try{"function"==typeof fn.handleEvent&&(fn.handleEvent=helpers_1.wrap(fn.handleEvent.bind(fn),{mechanism:{data:{function:"handleEvent",handler:utils_1.getFunctionName(fn),target:target},handled:!0,type:"instrument"}}))}catch(err){}return original.call(this,eventName,helpers_1.wrap(fn,{mechanism:{data:{function:"addEventListener",handler:utils_1.getFunctionName(fn),target:target},handled:!0,type:"instrument"}}),options)}}),utils_1.fill(global,"removeEventListener",function(originalRemoveEventListener){return function(eventName,fn,options){var _a;try{var originalEventHandler=null==(_a=fn)?void 0:_a.__sentry_wrapped__;originalEventHandler&&originalRemoveEventListener.call(this,eventName,originalEventHandler,options)}catch(e){}return originalRemoveEventListener.call(this,eventName,fn,options)}}))},TryCatch.prototype._wrapXHR=function(originalSend){return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];var xhr=this;return["onload","onerror","onprogress","onreadystatechange"].forEach(function(prop){prop in xhr&&"function"==typeof xhr[prop]&&utils_1.fill(xhr,prop,function(original){var wrapOptions={mechanism:{data:{function:prop,handler:utils_1.getFunctionName(original)},handled:!0,type:"instrument"}};return original.__sentry_original__&&(wrapOptions.mechanism.data.handler=utils_1.getFunctionName(original.__sentry_original__)),helpers_1.wrap(original,wrapOptions)})}),originalSend.apply(this,args)}},TryCatch.id="TryCatch",TryCatch}();exports.TryCatch=require},{"../helpers":41,"@sentry/utils":83,tslib:1698}],48:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),global=require("@sentry/utils").getGlobalObject(),require=function(){function UserAgent(){this.name=UserAgent.id}return UserAgent.prototype.setupOnce=function(){core_1.addGlobalEventProcessor(function(event){var _a,userAgent,_c,referrer;return core_1.getCurrentHub().getIntegration(UserAgent)&&(global.navigator||global.location||global.document)?(_a=(null==(_a=event.request)?void 0:_a.url)||(null==(_a=global.location)?void 0:_a.href),referrer=(global.document||{}).referrer,userAgent=(global.navigator||{}).userAgent,_c=tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({},null==(_c=event.request)?void 0:_c.headers),referrer&&{Referer:referrer}),userAgent&&{"User-Agent":userAgent}),referrer=tslib_1.__assign(tslib_1.__assign({},_a&&{url:_a}),{headers:_c}),tslib_1.__assign(tslib_1.__assign({},event),{request:referrer})):event})},UserAgent.id="UserAgent",UserAgent}();exports.UserAgent=require},{"@sentry/core":60,"@sentry/utils":83,tslib:1698}],49:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var utils_1=require("@sentry/utils"),tracekit_1=require("./tracekit"),STACKTRACE_LIMIT=50;function exceptionFromStacktrace(stacktrace){var frames=prepareFramesForEvent(stacktrace.stack),stacktrace={type:stacktrace.name,value:stacktrace.message};return frames&&frames.length&&(stacktrace.stacktrace={frames:frames}),void 0===stacktrace.type&&""===stacktrace.value&&(stacktrace.value="Unrecoverable error caught"),stacktrace}function prepareFramesForEvent(stack){var localStack,lastFrameFunction;return stack&&stack.length?(stack=(localStack=stack)[0].func||"",lastFrameFunction=localStack[localStack.length-1].func||"",-1===stack.indexOf("captureMessage")&&-1===stack.indexOf("captureException")||(localStack=localStack.slice(1)),(localStack=-1!==lastFrameFunction.indexOf("sentryWrapped")?localStack.slice(0,-1):localStack).slice(0,STACKTRACE_LIMIT).map(function(frame){return{colno:null===frame.column?void 0:frame.column,filename:frame.url||localStack[0].url,function:frame.func||"?",in_app:!0,lineno:null===frame.line?void 0:frame.line}}).reverse()):[]}exports.exceptionFromStacktrace=exceptionFromStacktrace,exports.eventFromPlainObject=function(exception,syntheticException,rejection){return rejection={exception:{values:[{type:utils_1.isEvent(exception)?exception.constructor.name:rejection?"UnhandledRejection":"Error",value:"Non-Error "+(rejection?"promise rejection":"exception")+" captured with keys: "+utils_1.extractExceptionKeysForMessage(exception)}]},extra:{__serialized__:utils_1.normalizeToSize(exception)}},syntheticException&&(exception=prepareFramesForEvent(tracekit_1.computeStackTrace(syntheticException).stack),rejection.stacktrace={frames:exception}),rejection},exports.eventFromStacktrace=function(stacktrace){return{exception:{values:[exceptionFromStacktrace(stacktrace)]}}},exports.prepareFramesForEvent=prepareFramesForEvent},{"./tracekit":51,"@sentry/utils":83}],50:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var core_1=require("@sentry/core"),utils_1=require("@sentry/utils"),client_1=require("./client"),helpers_1=require("./helpers"),require=require("./integrations");exports.defaultIntegrations=[new core_1.Integrations.InboundFilters,new core_1.Integrations.FunctionToString,new require.TryCatch,new require.Breadcrumbs,new require.GlobalHandlers,new require.LinkedErrors,new require.UserAgent],exports.init=function(options){var window_1;if(void 0===(options=void 0===options?{}:options).defaultIntegrations&&(options.defaultIntegrations=exports.defaultIntegrations),void 0===options.release&&(window_1=utils_1.getGlobalObject()).SENTRY_RELEASE&&window_1.SENTRY_RELEASE.id&&(options.release=window_1.SENTRY_RELEASE.id),void 0===options.autoSessionTracking&&(options.autoSessionTracking=!1),core_1.initAndBind(client_1.BrowserClient,options),options.autoSessionTracking){function possiblyEndSession(){fcpResolved&&loadResolved&&hub.endSession()}function resolveWindowLoaded(){loadResolved=!0,possiblyEndSession(),window.removeEventListener("load",resolveWindowLoaded)}var window=utils_1.getGlobalObject(),hub=core_1.getCurrentHub(),loadResolved="complete"===document.readyState,fcpResolved=!1;hub.startSession(),loadResolved||window.addEventListener("load",resolveWindowLoaded);try{var po=new PerformanceObserver(function(entryList,po){entryList.getEntries().forEach(function(entry){"first-contentful-paint"===entry.name&&entry.startTime<firstHiddenTime_1&&(po.disconnect(),fcpResolved=!0,possiblyEndSession())})}),firstHiddenTime_1="hidden"===document.visibilityState?0:1/0;document.addEventListener("visibilitychange",function(event){firstHiddenTime_1=Math.min(firstHiddenTime_1,event.timeStamp)},{once:!0}),po.observe({type:"paint",buffered:!0})}catch(e){fcpResolved=!0,possiblyEndSession()}}},exports.showReportDialog=function(options){(options=void 0===options?{}:options).eventId||(options.eventId=core_1.getCurrentHub().lastEventId());var client=core_1.getCurrentHub().getClient();client&&client.showReportDialog(options)},exports.lastEventId=function(){return core_1.getCurrentHub().lastEventId()},exports.forceLoad=function(){},exports.onLoad=function(callback){callback()},exports.flush=function(timeout){var client=core_1.getCurrentHub().getClient();return client?client.flush(timeout):utils_1.SyncPromise.reject(!1)},exports.close=function(timeout){var client=core_1.getCurrentHub().getClient();return client?client.close(timeout):utils_1.SyncPromise.reject(!1)},exports.wrap=function(fn){return helpers_1.wrap(fn)()}},{"./client":38,"./helpers":41,"./integrations":45,"@sentry/core":60,"@sentry/utils":83}],51:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),UNKNOWN_FUNCTION="?",chrome=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,gecko=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,winjs=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,geckoEval=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,chromeEval=/\((\S*)(?::(\d+))(?::(\d+))\)/,reactMinifiedRegexp=/Minified React error #\d+;/i;function popFrames(stacktrace,popSize){try{return tslib_1.__assign(tslib_1.__assign({},stacktrace),{stack:stacktrace.stack.slice(popSize)})}catch(e){return stacktrace}}function extractMessage(ex){ex=ex&&ex.message;return ex?ex.error&&"string"==typeof ex.error.message?ex.error.message:ex:"No error message"}exports.computeStackTrace=function(ex){var stack=null,popSize=0;ex&&("number"==typeof ex.framesToPop?popSize=ex.framesToPop:reactMinifiedRegexp.test(ex.message)&&(popSize=1));try{if(stack=function(ex){if(!ex||!ex.stacktrace)return null;for(var parts,stacktrace=ex.stacktrace,opera10Regex=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,opera11Regex=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\((.*)\))? in (.*):\s*$/i,lines=stacktrace.split("\n"),stack=[],line=0;line<lines.length;line+=2){var element=null;(parts=opera10Regex.exec(lines[line]))?element={url:parts[2],func:parts[3],args:[],line:+parts[1],column:null}:(parts=opera11Regex.exec(lines[line]))&&(element={url:parts[6],func:parts[3]||parts[4],args:parts[5]?parts[5].split(","):[],line:+parts[1],column:+parts[2]}),element&&(!element.func&&element.line&&(element.func=UNKNOWN_FUNCTION),stack.push(element))}return stack.length?{message:extractMessage(ex),name:ex.name,stack:stack}:null}(ex))return popFrames(stack,popSize)}catch(e){}try{if(stack=function(ex){if(!ex||!ex.stack)return null;for(var submatch,parts,stack=[],lines=ex.stack.split("\n"),i=0;i<lines.length;++i){if(parts=chrome.exec(lines[i])){var isNative=parts[2]&&0===parts[2].indexOf("native");parts[2]&&0===parts[2].indexOf("eval")&&(submatch=chromeEval.exec(parts[2]))&&(parts[2]=submatch[1],parts[3]=submatch[2],parts[4]=submatch[3]),isNative={url:parts[2]&&0===parts[2].indexOf("address at ")?parts[2].substr("address at ".length):parts[2],func:parts[1]||UNKNOWN_FUNCTION,args:isNative?[parts[2]]:[],line:parts[3]?+parts[3]:null,column:parts[4]?+parts[4]:null}}else if(parts=winjs.exec(lines[i]))isNative={url:parts[2],func:parts[1]||UNKNOWN_FUNCTION,args:[],line:+parts[3],column:parts[4]?+parts[4]:null};else{if(!(parts=gecko.exec(lines[i])))continue;parts[3]&&-1<parts[3].indexOf(" > eval")&&(submatch=geckoEval.exec(parts[3]))?(parts[1]=parts[1]||"eval",parts[3]=submatch[1],parts[4]=submatch[2],parts[5]=""):0!==i||parts[5]||void 0===ex.columnNumber||(stack[0].column=ex.columnNumber+1),isNative={url:parts[3],func:parts[1]||UNKNOWN_FUNCTION,args:parts[2]?parts[2].split(","):[],line:parts[4]?+parts[4]:null,column:parts[5]?+parts[5]:null}}!isNative.func&&isNative.line&&(isNative.func=UNKNOWN_FUNCTION),stack.push(isNative)}return stack.length?{message:extractMessage(ex),name:ex.name,stack:stack}:null}(ex))return popFrames(stack,popSize)}catch(e){}return{message:extractMessage(ex),name:ex&&ex.name,stack:[],failed:!0}}},{tslib:1698}],52:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),types_1=require("@sentry/types"),utils_1=require("@sentry/utils"),require=function(){function BaseTransport(options){this.options=options,this._buffer=new utils_1.PromiseBuffer(30),this._rateLimits={},this._api=new core_1.API(this.options.dsn),this.url=this._api.getStoreEndpointWithUrlEncodedAuth()}return BaseTransport.prototype.sendEvent=function(_){throw new utils_1.SentryError("Transport Class has to implement `sendEvent` method")},BaseTransport.prototype.close=function(timeout){return this._buffer.drain(timeout)},BaseTransport.prototype._handleResponse=function(_a){var requestType=_a.requestType,response=_a.response,headers=_a.headers,resolve=_a.resolve,_a=_a.reject,status=types_1.Status.fromHttpCode(response.status);this._handleRateLimit(headers)&&utils_1.logger.warn("Too many requests, backing off until: "+this._disabledUntil(requestType)),status===types_1.Status.Success?resolve({status:status}):_a(response)},BaseTransport.prototype._disabledUntil=function(category){return this._rateLimits[category]||this._rateLimits.all},BaseTransport.prototype._isRateLimited=function(category){return this._disabledUntil(category)>new Date(Date.now())},BaseTransport.prototype._handleRateLimit=function(headers){var e_1,_a,e_2,_b,now=Date.now(),rlHeader=headers["x-sentry-rate-limits"],headers=headers["retry-after"];if(rlHeader){try{for(var _c=tslib_1.__values(rlHeader.trim().split(",")),_d=_c.next();!_d.done;_d=_c.next()){var parameters=_d.value.split(":",2),headerDelay=parseInt(parameters[0],10),delay=1e3*(isNaN(headerDelay)?60:headerDelay);try{e_2=void 0;for(var _e=tslib_1.__values(parameters[1].split(";")),_f=_e.next();!_f.done;_f=_e.next()){var category=_f.value;this._rateLimits[category||"all"]=new Date(now+delay)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{_f&&!_f.done&&(_b=_e.return)&&_b.call(_e)}finally{if(e_2)throw e_2.error}}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_d&&!_d.done&&(_a=_c.return)&&_a.call(_c)}finally{if(e_1)throw e_1.error}}return!0}return!!headers&&(this._rateLimits.all=new Date(now+utils_1.parseRetryAfterHeader(now,headers)),!0)},BaseTransport}();exports.BaseTransport=require},{"@sentry/core":60,"@sentry/types":73,"@sentry/utils":83,tslib:1698}],53:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),utils_1=require("@sentry/utils"),require=require("./base"),global=utils_1.getGlobalObject(),require=function(_super){function FetchTransport(){return null!==_super&&_super.apply(this,arguments)||this}return tslib_1.__extends(FetchTransport,_super),FetchTransport.prototype.sendEvent=function(event){return this._sendRequest(core_1.eventToSentryRequest(event,this._api),event)},FetchTransport.prototype.sendSession=function(session){return this._sendRequest(core_1.sessionToSentryRequest(session,this._api),session)},FetchTransport.prototype._sendRequest=function(sentryRequest,originalPayload){var options,_this=this;return this._isRateLimited(sentryRequest.type)?Promise.reject({event:originalPayload,type:sentryRequest.type,reason:"Transport locked till "+this._disabledUntil(sentryRequest.type)+" due to too many requests.",status:429}):(options={body:sentryRequest.body,method:"POST",referrerPolicy:utils_1.supportsReferrerPolicy()?"origin":""},void 0!==this.options.fetchParameters&&Object.assign(options,this.options.fetchParameters),void 0!==this.options.headers&&(options.headers=this.options.headers),this._buffer.add(new utils_1.SyncPromise(function(resolve,reject){global.fetch(sentryRequest.url,options).then(function(response){var headers={"x-sentry-rate-limits":response.headers.get("X-Sentry-Rate-Limits"),"retry-after":response.headers.get("Retry-After")};_this._handleResponse({requestType:sentryRequest.type,response:response,headers:headers,resolve:resolve,reject:reject})}).catch(reject)})))},FetchTransport}(require.BaseTransport);exports.FetchTransport=require},{"./base":52,"@sentry/core":60,"@sentry/utils":83,tslib:1698}],54:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var base_1=require("./base"),base_1=(exports.BaseTransport=base_1.BaseTransport,require("./fetch")),base_1=(exports.FetchTransport=base_1.FetchTransport,require("./xhr"));exports.XHRTransport=base_1.XHRTransport},{"./base":52,"./fetch":53,"./xhr":55}],55:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),core_1=require("@sentry/core"),utils_1=require("@sentry/utils"),require=function(_super){function XHRTransport(){return null!==_super&&_super.apply(this,arguments)||this}return tslib_1.__extends(XHRTransport,_super),XHRTransport.prototype.sendEvent=function(event){return this._sendRequest(core_1.eventToSentryRequest(event,this._api),event)},XHRTransport.prototype.sendSession=function(session){return this._sendRequest(core_1.sessionToSentryRequest(session,this._api),session)},XHRTransport.prototype._sendRequest=function(sentryRequest,originalPayload){var _this=this;return this._isRateLimited(sentryRequest.type)?Promise.reject({event:originalPayload,type:sentryRequest.type,reason:"Transport locked till "+this._disabledUntil(sentryRequest.type)+" due to too many requests.",status:429}):this._buffer.add(new utils_1.SyncPromise(function(resolve,reject){var header,request=new XMLHttpRequest;for(header in request.onreadystatechange=function(){var headers;4===request.readyState&&(headers={"x-sentry-rate-limits":request.getResponseHeader("X-Sentry-Rate-Limits"),"retry-after":request.getResponseHeader("Retry-After")},_this._handleResponse({requestType:sentryRequest.type,response:request,headers:headers,resolve:resolve,reject:reject}))},request.open("POST",sentryRequest.url),_this.options.headers)_this.options.headers.hasOwnProperty(header)&&request.setRequestHeader(header,_this.options.headers[header]);request.send(sentryRequest.body)}))},XHRTransport}(require("./base").BaseTransport);exports.XHRTransport=require},{"./base":52,"@sentry/core":60,"@sentry/utils":83,tslib:1698}],56:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.SDK_NAME="sentry.javascript.browser",exports.SDK_VERSION="5.30.0"},{}],57:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var utils_1=require("@sentry/utils"),require=function(){function API(dsn){this.dsn=dsn,this._dsnObject=new utils_1.Dsn(dsn)}return API.prototype.getDsn=function(){return this._dsnObject},API.prototype.getBaseApiEndpoint=function(){var dsn=this._dsnObject,protocol=dsn.protocol?dsn.protocol+":":"",port=dsn.port?":"+dsn.port:"";return protocol+"//"+dsn.host+port+(dsn.path?"/"+dsn.path:"")+"/api/"},API.prototype.getStoreEndpoint=function(){return this._getIngestEndpoint("store")},API.prototype.getStoreEndpointWithUrlEncodedAuth=function(){return this.getStoreEndpoint()+"?"+this._encodedAuth()},API.prototype.getEnvelopeEndpointWithUrlEncodedAuth=function(){return this._getEnvelopeEndpoint()+"?"+this._encodedAuth()},API.prototype.getStoreEndpointPath=function(){var dsn=this._dsnObject;return(dsn.path?"/"+dsn.path:"")+"/api/"+dsn.projectId+"/store/"},API.prototype.getRequestHeaders=function(clientName,clientVersion){var dsn=this._dsnObject,header=["Sentry sentry_version=7"];return header.push("sentry_client="+clientName+"/"+clientVersion),header.push("sentry_key="+dsn.user),dsn.pass&&header.push("sentry_secret="+dsn.pass),{"Content-Type":"application/json","X-Sentry-Auth":header.join(", ")}},API.prototype.getReportDialogEndpoint=function(dialogOptions){void 0===dialogOptions&&(dialogOptions={});var key,dsn=this._dsnObject,endpoint=this.getBaseApiEndpoint()+"embed/error-page/",encodedOptions=[];for(key in encodedOptions.push("dsn="+dsn.toString()),dialogOptions)"dsn"!==key&&("user"===key?dialogOptions.user&&(dialogOptions.user.name&&encodedOptions.push("name="+encodeURIComponent(dialogOptions.user.name)),dialogOptions.user.email)&&encodedOptions.push("email="+encodeURIComponent(dialogOptions.user.email)):encodedOptions.push(encodeURIComponent(key)+"="+encodeURIComponent(dialogOptions[key])));return encodedOptions.length?endpoint+"?"+encodedOptions.join("&"):endpoint},API.prototype._getEnvelopeEndpoint=function(){return this._getIngestEndpoint("envelope")},API.prototype._getIngestEndpoint=function(target){return""+this.getBaseApiEndpoint()+this._dsnObject.projectId+"/"+target+"/"},API.prototype._encodedAuth=function(){var auth={sentry_key:this._dsnObject.user,sentry_version:"7"};return utils_1.urlEncode(auth)},API}();exports.API=require},{"@sentry/utils":83}],58:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var utils_1=require("@sentry/utils"),noop_1=require("./transports/noop"),require=function(){function BaseBackend(options){this._options=options,this._options.dsn||utils_1.logger.warn("No DSN provided, backend will not do anything."),this._transport=this._setupTransport()}return BaseBackend.prototype.eventFromException=function(_exception,_hint){throw new utils_1.SentryError("Backend has to implement `eventFromException` method")},BaseBackend.prototype.eventFromMessage=function(_message,_level,_hint){throw new utils_1.SentryError("Backend has to implement `eventFromMessage` method")},BaseBackend.prototype.sendEvent=function(event){this._transport.sendEvent(event).then(null,function(reason){utils_1.logger.error("Error while sending event: "+reason)})},BaseBackend.prototype.sendSession=function(session){this._transport.sendSession?this._transport.sendSession(session).then(null,function(reason){utils_1.logger.error("Error while sending session: "+reason)}):utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession")},BaseBackend.prototype.getTransport=function(){return this._transport},BaseBackend.prototype._setupTransport=function(){return new noop_1.NoopTransport},BaseBackend}();exports.BaseBackend=require},{"./transports/noop":67,"@sentry/utils":83}],59:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),hub_1=require("@sentry/hub"),types_1=require("@sentry/types"),utils_1=require("@sentry/utils"),integration_1=require("./integration"),require=function(){function BaseClient(backendClass,options){this._integrations={},this._processing=0,this._backend=new backendClass(options),(this._options=options).dsn&&(this._dsn=new utils_1.Dsn(options.dsn))}return BaseClient.prototype.captureException=function(exception,hint,scope){var _this=this,eventId=hint&&hint.event_id;return this._process(this._getBackend().eventFromException(exception,hint).then(function(event){return _this._captureEvent(event,hint,scope)}).then(function(result){eventId=result})),eventId},BaseClient.prototype.captureMessage=function(message,level,hint,scope){var _this=this,eventId=hint&&hint.event_id,level=utils_1.isPrimitive(message)?this._getBackend().eventFromMessage(String(message),level,hint):this._getBackend().eventFromException(message,hint);return this._process(level.then(function(event){return _this._captureEvent(event,hint,scope)}).then(function(result){eventId=result})),eventId},BaseClient.prototype.captureEvent=function(event,hint,scope){var eventId=hint&&hint.event_id;return this._process(this._captureEvent(event,hint,scope).then(function(result){eventId=result})),eventId},BaseClient.prototype.captureSession=function(session){session.release?this._sendSession(session):utils_1.logger.warn("Discarded session because of missing release")},BaseClient.prototype.getDsn=function(){return this._dsn},BaseClient.prototype.getOptions=function(){return this._options},BaseClient.prototype.flush=function(timeout){var _this=this;return this._isClientProcessing(timeout).then(function(ready){return _this._getBackend().getTransport().close(timeout).then(function(transportFlushed){return ready&&transportFlushed})})},BaseClient.prototype.close=function(timeout){var _this=this;return this.flush(timeout).then(function(result){return _this.getOptions().enabled=!1,result})},BaseClient.prototype.setupIntegrations=function(){this._isEnabled()&&(this._integrations=integration_1.setupIntegrations(this._options))},BaseClient.prototype.getIntegration=function(integration){try{return this._integrations[integration.id]||null}catch(_oO){return utils_1.logger.warn("Cannot retrieve integration "+integration.id+" from the current Client"),null}},BaseClient.prototype._updateSessionFromEvent=function(session,event){var e_1,_a,userAgent,crashed=!1,errored=!1,exceptions=event.exception&&event.exception.values;if(exceptions){errored=!0;try{for(var exceptions_1=tslib_1.__values(exceptions),exceptions_1_1=exceptions_1.next();!exceptions_1_1.done;exceptions_1_1=exceptions_1.next()){var mechanism=exceptions_1_1.value.mechanism;if(mechanism&&!1===mechanism.handled){crashed=!0;break}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{exceptions_1_1&&!exceptions_1_1.done&&(_a=exceptions_1.return)&&_a.call(exceptions_1)}finally{if(e_1)throw e_1.error}}}exceptions=event.user;if(!session.userAgent){var key,headers=event.request?event.request.headers:{};for(key in headers)if("user-agent"===key.toLowerCase()){userAgent=headers[key];break}}session.update(tslib_1.__assign(tslib_1.__assign({},crashed&&{status:types_1.SessionStatus.Crashed}),{user:exceptions,userAgent:userAgent,errors:session.errors+Number(errored||crashed)}))},BaseClient.prototype._sendSession=function(session){this._getBackend().sendSession(session)},BaseClient.prototype._isClientProcessing=function(timeout){var _this=this;return new utils_1.SyncPromise(function(resolve){var ticked=0,interval=setInterval(function(){0==_this._processing?(clearInterval(interval),resolve(!0)):(ticked+=1,timeout&&timeout<=ticked&&(clearInterval(interval),resolve(!1)))},1)})},BaseClient.prototype._getBackend=function(){return this._backend},BaseClient.prototype._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._dsn},BaseClient.prototype._prepareEvent=function(event,scope,hint){var _this=this,_a=this.getOptions().normalizeDepth,normalizeDepth=void 0===_a?3:_a,_a=tslib_1.__assign(tslib_1.__assign({},event),{event_id:event.event_id||(hint&&hint.event_id?hint.event_id:utils_1.uuid4()),timestamp:event.timestamp||utils_1.dateTimestampInSeconds()}),event=(this._applyClientOptions(_a),this._applyIntegrationsMetadata(_a),scope),scope=(hint&&hint.captureContext&&(event=hub_1.Scope.clone(event).update(hint.captureContext)),utils_1.SyncPromise.resolve(_a));return(scope=event?event.applyToEvent(_a,hint):scope).then(function(evt){return"number"==typeof normalizeDepth&&0<normalizeDepth?_this._normalizeEvent(evt,normalizeDepth):evt})},BaseClient.prototype._normalizeEvent=function(event,depth){var normalized;return event?(normalized=tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({},event),event.breadcrumbs&&{breadcrumbs:event.breadcrumbs.map(function(b){return tslib_1.__assign(tslib_1.__assign({},b),b.data&&{data:utils_1.normalize(b.data,depth)})})}),event.user&&{user:utils_1.normalize(event.user,depth)}),event.contexts&&{contexts:utils_1.normalize(event.contexts,depth)}),event.extra&&{extra:utils_1.normalize(event.extra,depth)}),event.contexts&&event.contexts.trace&&(normalized.contexts.trace=event.contexts.trace),normalized):null},BaseClient.prototype._applyClientOptions=function(event){var options=this.getOptions(),environment=options.environment,release=options.release,dist=options.dist,_a=options.maxValueLength,_a=void 0===_a?250:_a,options=("environment"in event||(event.environment="environment"in options?environment:"production"),void 0===event.release&&void 0!==release&&(event.release=release),void 0===event.dist&&void 0!==dist&&(event.dist=dist),event.message&&(event.message=utils_1.truncate(event.message,_a)),event.exception&&event.exception.values&&event.exception.values[0]),environment=(options&&options.value&&(options.value=utils_1.truncate(options.value,_a)),event.request);environment&&environment.url&&(environment.url=utils_1.truncate(environment.url,_a))},BaseClient.prototype._applyIntegrationsMetadata=function(event){var event=event.sdk,integrationsArray=Object.keys(this._integrations);event&&0<integrationsArray.length&&(event.integrations=integrationsArray)},BaseClient.prototype._sendEvent=function(event){this._getBackend().sendEvent(event)},BaseClient.prototype._captureEvent=function(event,hint,scope){return this._processEvent(event,hint,scope).then(function(finalEvent){return finalEvent.event_id},function(reason){utils_1.logger.error(reason)})},BaseClient.prototype._processEvent=function(event,hint,scope){var isTransaction,_this=this,_a=this.getOptions(),beforeSend=_a.beforeSend,_a=_a.sampleRate;return this._isEnabled()?!(isTransaction="transaction"===event.type)&&"number"==typeof _a&&Math.random()>_a?utils_1.SyncPromise.reject(new utils_1.SentryError("Discarding event because it's not included in the random sample (sampling rate = "+_a+")")):this._prepareEvent(event,scope,hint).then(function(prepared){if(null===prepared)throw new utils_1.SentryError("An event processor returned null, will not send event.");if(hint&&hint.data&&!0===hint.data.__sentry__||isTransaction||!beforeSend)return prepared;prepared=beforeSend(prepared,hint);if(void 0===prepared)throw new utils_1.SentryError("`beforeSend` method has to return `null` or a valid event.");return utils_1.isThenable(prepared)?prepared.then(function(event){return event},function(e){throw new utils_1.SentryError("beforeSend rejected with "+e)}):prepared}).then(function(processedEvent){if(null===processedEvent)throw new utils_1.SentryError("`beforeSend` returned `null`, will not send event.");var session=scope&&scope.getSession&&scope.getSession();return!isTransaction&&session&&_this._updateSessionFromEvent(session,processedEvent),_this._sendEvent(processedEvent),processedEvent}).then(null,function(reason){if(reason instanceof utils_1.SentryError)throw reason;throw _this.captureException(reason,{data:{__sentry__:!0},originalException:reason}),new utils_1.SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+reason)}):utils_1.SyncPromise.reject(new utils_1.SentryError("SDK not enabled, will not send event."))},BaseClient.prototype._process=function(promise){var _this=this;this._processing+=1,promise.then(function(value){return--_this._processing,value},function(reason){return--_this._processing,reason})},BaseClient}();exports.BaseClient=require},{"./integration":61,"@sentry/hub":69,"@sentry/types":73,"@sentry/utils":83,tslib:1698}],60:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var minimal_1=require("@sentry/minimal"),minimal_1=(exports.addBreadcrumb=minimal_1.addBreadcrumb,exports.captureException=minimal_1.captureException,exports.captureEvent=minimal_1.captureEvent,exports.captureMessage=minimal_1.captureMessage,exports.configureScope=minimal_1.configureScope,exports.startTransaction=minimal_1.startTransaction,exports.setContext=minimal_1.setContext,exports.setExtra=minimal_1.setExtra,exports.setExtras=minimal_1.setExtras,exports.setTag=minimal_1.setTag,exports.setTags=minimal_1.setTags,exports.setUser=minimal_1.setUser,exports.withScope=minimal_1.withScope,require("@sentry/hub")),minimal_1=(exports.addGlobalEventProcessor=minimal_1.addGlobalEventProcessor,exports.getCurrentHub=minimal_1.getCurrentHub,exports.getHubFromCarrier=minimal_1.getHubFromCarrier,exports.Hub=minimal_1.Hub,exports.makeMain=minimal_1.makeMain,exports.Scope=minimal_1.Scope,require("./api")),minimal_1=(exports.API=minimal_1.API,require("./baseclient")),minimal_1=(exports.BaseClient=minimal_1.BaseClient,require("./basebackend")),minimal_1=(exports.BaseBackend=minimal_1.BaseBackend,require("./request")),minimal_1=(exports.eventToSentryRequest=minimal_1.eventToSentryRequest,exports.sessionToSentryRequest=minimal_1.sessionToSentryRequest,require("./sdk")),minimal_1=(exports.initAndBind=minimal_1.initAndBind,require("./transports/noop")),minimal_1=(exports.NoopTransport=minimal_1.NoopTransport,require("./integrations"));exports.Integrations=minimal_1},{"./api":57,"./basebackend":58,"./baseclient":59,"./integrations":64,"./request":65,"./sdk":66,"./transports/noop":67,"@sentry/hub":69,"@sentry/minimal":72}],61:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),hub_1=require("@sentry/hub"),utils_1=require("@sentry/utils");function getIntegrationsToSetup(options){var userIntegrationsNames_1,pickedIntegrationsNames_1,defaultIntegrations=options.defaultIntegrations&&tslib_1.__spread(options.defaultIntegrations)||[],options=options.integrations,integrations=[],options=(Array.isArray(options)?(userIntegrationsNames_1=options.map(function(i){return i.name}),pickedIntegrationsNames_1=[],defaultIntegrations.forEach(function(defaultIntegration){-1===userIntegrationsNames_1.indexOf(defaultIntegration.name)&&-1===pickedIntegrationsNames_1.indexOf(defaultIntegration.name)&&(integrations.push(defaultIntegration),pickedIntegrationsNames_1.push(defaultIntegration.name))}),options.forEach(function(userIntegration){-1===pickedIntegrationsNames_1.indexOf(userIntegration.name)&&(integrations.push(userIntegration),pickedIntegrationsNames_1.push(userIntegration.name))})):integrations="function"==typeof options?(integrations=options(defaultIntegrations),Array.isArray(integrations)?integrations:[integrations]):tslib_1.__spread(defaultIntegrations),integrations.map(function(i){return i.name}));return-1!==options.indexOf("Debug")&&integrations.push.apply(integrations,tslib_1.__spread(integrations.splice(options.indexOf("Debug"),1))),integrations}function setupIntegration(integration){-1===exports.installedIntegrations.indexOf(integration.name)&&(integration.setupOnce(hub_1.addGlobalEventProcessor,hub_1.getCurrentHub),exports.installedIntegrations.push(integration.name),utils_1.logger.log("Integration installed: "+integration.name))}exports.installedIntegrations=[],exports.getIntegrationsToSetup=getIntegrationsToSetup,exports.setupIntegration=setupIntegration,exports.setupIntegrations=function(options){var integrations={};return getIntegrationsToSetup(options).forEach(function(integration){setupIntegration(integrations[integration.name]=integration)}),integrations}},{"@sentry/hub":69,"@sentry/utils":83,tslib:1698}],62:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var originalFunctionToString,FunctionToString=function(){function FunctionToString(){this.name=FunctionToString.id}return FunctionToString.prototype.setupOnce=function(){originalFunctionToString=Function.prototype.toString,Function.prototype.toString=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];var context=this.__sentry_original__||this;return originalFunctionToString.apply(context,args)}},FunctionToString.id="FunctionToString",FunctionToString}();exports.FunctionToString=FunctionToString},{}],63:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),hub_1=require("@sentry/hub"),utils_1=require("@sentry/utils"),DEFAULT_IGNORE_ERRORS=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/],require=function(){function InboundFilters(_options){this._options=_options=void 0===_options?{}:_options,this.name=InboundFilters.id}return InboundFilters.prototype.setupOnce=function(){hub_1.addGlobalEventProcessor(function(event){var hub=hub_1.getCurrentHub();if(hub){var self=hub.getIntegration(InboundFilters);if(self){hub=hub.getClient(),hub=hub?hub.getOptions():{},hub=self._mergeOptions(hub);if(self._shouldDropEvent(event,hub))return null}}return event})},InboundFilters.prototype._shouldDropEvent=function(event,options){return this._isSentryError(event,options)?(utils_1.logger.warn("Event dropped due to being internal Sentry Error.\nEvent: "+utils_1.getEventDescription(event)),!0):this._isIgnoredError(event,options)?(utils_1.logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: "+utils_1.getEventDescription(event)),!0):this._isDeniedUrl(event,options)?(utils_1.logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: "+utils_1.getEventDescription(event)+".\nUrl: "+this._getEventFilterUrl(event)),!0):!this._isAllowedUrl(event,options)&&(utils_1.logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: "+utils_1.getEventDescription(event)+".\nUrl: "+this._getEventFilterUrl(event)),!0)},InboundFilters.prototype._isSentryError=function(event,options){if(!options.ignoreInternal)return!1;try{return event&&event.exception&&event.exception.values&&event.exception.values[0]&&"SentryError"===event.exception.values[0].type||!1}catch(_oO){return!1}},InboundFilters.prototype._isIgnoredError=function(event,options){return!(!options.ignoreErrors||!options.ignoreErrors.length)&&this._getPossibleEventMessages(event).some(function(message){return options.ignoreErrors.some(function(pattern){return utils_1.isMatchingPattern(message,pattern)})})},InboundFilters.prototype._isDeniedUrl=function(event,options){var url;return!(!options.denyUrls||!options.denyUrls.length||!(url=this._getEventFilterUrl(event)))&&options.denyUrls.some(function(pattern){return utils_1.isMatchingPattern(url,pattern)})},InboundFilters.prototype._isAllowedUrl=function(event,options){var url;return!options.allowUrls||!options.allowUrls.length||!(url=this._getEventFilterUrl(event))||options.allowUrls.some(function(pattern){return utils_1.isMatchingPattern(url,pattern)})},InboundFilters.prototype._mergeOptions=function(clientOptions){return{allowUrls:tslib_1.__spread(this._options.whitelistUrls||[],this._options.allowUrls||[],(clientOptions=void 0===clientOptions?{}:clientOptions).whitelistUrls||[],clientOptions.allowUrls||[]),denyUrls:tslib_1.__spread(this._options.blacklistUrls||[],this._options.denyUrls||[],clientOptions.blacklistUrls||[],clientOptions.denyUrls||[]),ignoreErrors:tslib_1.__spread(this._options.ignoreErrors||[],clientOptions.ignoreErrors||[],DEFAULT_IGNORE_ERRORS),ignoreInternal:void 0===this._options.ignoreInternal||this._options.ignoreInternal}},InboundFilters.prototype._getPossibleEventMessages=function(event){if(event.message)return[event.message];if(event.exception)try{var _a=event.exception.values&&event.exception.values[0]||{},_b=_a.type,type=void 0===_b?"":_b,_c=_a.value,value=void 0===_c?"":_c;return[""+value,type+": "+value]}catch(oO){utils_1.logger.error("Cannot extract message for event "+utils_1.getEventDescription(event))}return[]},InboundFilters.prototype._getEventFilterUrl=function(event){try{var frames_1,frames_2;return event.stacktrace?(frames_1=event.stacktrace.frames)&&frames_1[frames_1.length-1].filename||null:event.exception&&(frames_2=event.exception.values&&event.exception.values[0].stacktrace&&event.exception.values[0].stacktrace.frames)&&frames_2[frames_2.length-1].filename||null}catch(oO){return utils_1.logger.error("Cannot extract url for event "+utils_1.getEventDescription(event)),null}},InboundFilters.id="InboundFilters",InboundFilters}();exports.InboundFilters=require},{"@sentry/hub":69,"@sentry/utils":83,tslib:1698}],64:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var functiontostring_1=require("./functiontostring"),functiontostring_1=(exports.FunctionToString=functiontostring_1.FunctionToString,require("./inboundfilters"));exports.InboundFilters=functiontostring_1.InboundFilters},{"./functiontostring":62,"./inboundfilters":63}],65:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib");exports.sessionToSentryRequest=function(session,api){return{body:JSON.stringify({sent_at:(new Date).toISOString()})+"\n"+JSON.stringify({type:"session"})+"\n"+JSON.stringify(session),type:"session",url:api.getEnvelopeEndpointWithUrlEncodedAuth()}},exports.eventToSentryRequest=function(event,api){var samplingMethod=(_a=event.tags||{}).__sentry_samplingMethod,sampleRate=_a.__sentry_sampleRate,_a=tslib_1.__rest(_a,["__sentry_samplingMethod","__sentry_sampleRate"]),_a=(event.tags=_a,"transaction"===event.type),api={body:JSON.stringify(event),type:event.type||"event",url:_a?api.getEnvelopeEndpointWithUrlEncodedAuth():api.getStoreEndpointWithUrlEncodedAuth()};return _a&&(_a=JSON.stringify({event_id:event.event_id,sent_at:(new Date).toISOString()}),event=JSON.stringify({type:event.type,sample_rates:[{id:samplingMethod,rate:sampleRate}]}),api.body=_a+"\n"+event+"\n"+api.body),api}},{tslib:1698}],66:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var hub_1=require("@sentry/hub"),utils_1=require("@sentry/utils");exports.initAndBind=function(clientClass,options){!0===options.debug&&utils_1.logger.enable();var hub=hub_1.getCurrentHub(),clientClass=new clientClass(options);hub.bindClient(clientClass)}},{"@sentry/hub":69,"@sentry/utils":83}],67:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var types_1=require("@sentry/types"),utils_1=require("@sentry/utils"),require=function(){function NoopTransport(){}return NoopTransport.prototype.sendEvent=function(_){return utils_1.SyncPromise.resolve({reason:"NoopTransport: Event has been skipped because no Dsn is configured.",status:types_1.Status.Skipped})},NoopTransport.prototype.close=function(_){return utils_1.SyncPromise.resolve(!0)},NoopTransport}();exports.NoopTransport=require},{"@sentry/types":73,"@sentry/utils":83}],68:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),utils_1=require("@sentry/utils"),scope_1=require("./scope"),session_1=require("./session"),Hub=(exports.API_VERSION=3,function(){function Hub(client,scope,_version){void 0===scope&&(scope=new scope_1.Scope),void 0===_version&&(_version=exports.API_VERSION),this._version=_version,this._stack=[{}],this.getStackTop().scope=scope,this.bindClient(client)}return Hub.prototype.isOlderThan=function(version){return this._version<version},Hub.prototype.bindClient=function(client){(this.getStackTop().client=client)&&client.setupIntegrations&&client.setupIntegrations()},Hub.prototype.pushScope=function(){var scope=scope_1.Scope.clone(this.getScope());return this.getStack().push({client:this.getClient(),scope:scope}),scope},Hub.prototype.popScope=function(){return!(this.getStack().length<=1||!this.getStack().pop())},Hub.prototype.withScope=function(callback){var scope=this.pushScope();try{callback(scope)}finally{this.popScope()}},Hub.prototype.getClient=function(){return this.getStackTop().client},Hub.prototype.getScope=function(){return this.getStackTop().scope},Hub.prototype.getStack=function(){return this._stack},Hub.prototype.getStackTop=function(){return this._stack[this._stack.length-1]},Hub.prototype.captureException=function(exception,hint){var eventId=this._lastEventId=utils_1.uuid4(),finalHint=hint;if(!hint){hint=void 0;try{throw new Error("Sentry syntheticException")}catch(exception){hint=exception}finalHint={originalException:exception,syntheticException:hint}}return this._invokeClient("captureException",exception,tslib_1.__assign(tslib_1.__assign({},finalHint),{event_id:eventId})),eventId},Hub.prototype.captureMessage=function(message,level,hint){var eventId=this._lastEventId=utils_1.uuid4(),finalHint=hint;if(!hint){hint=void 0;try{throw new Error(message)}catch(exception){hint=exception}finalHint={originalException:message,syntheticException:hint}}return this._invokeClient("captureMessage",message,level,tslib_1.__assign(tslib_1.__assign({},finalHint),{event_id:eventId})),eventId},Hub.prototype.captureEvent=function(event,hint){var eventId=this._lastEventId=utils_1.uuid4();return this._invokeClient("captureEvent",event,tslib_1.__assign(tslib_1.__assign({},hint),{event_id:eventId})),eventId},Hub.prototype.lastEventId=function(){return this._lastEventId},Hub.prototype.addBreadcrumb=function(breadcrumb,hint){var beforeBreadcrumb,mergedBreadcrumb,_c,_a=this.getStackTop(),scope=_a.scope,_a=_a.client;scope&&_a&&(_c=(_a=_a.getOptions&&_a.getOptions()||{}).beforeBreadcrumb,beforeBreadcrumb=void 0===_c?null:_c,(_a=void 0===(_c=_a.maxBreadcrumbs)?100:_c)<=0||(_c=utils_1.dateTimestampInSeconds(),mergedBreadcrumb=tslib_1.__assign({timestamp:_c},breadcrumb),null!==(_c=beforeBreadcrumb?utils_1.consoleSandbox(function(){return beforeBreadcrumb(mergedBreadcrumb,hint)}):mergedBreadcrumb)&&scope.addBreadcrumb(_c,Math.min(_a,100))))},Hub.prototype.setUser=function(user){var scope=this.getScope();scope&&scope.setUser(user)},Hub.prototype.setTags=function(tags){var scope=this.getScope();scope&&scope.setTags(tags)},Hub.prototype.setExtras=function(extras){var scope=this.getScope();scope&&scope.setExtras(extras)},Hub.prototype.setTag=function(key,value){var scope=this.getScope();scope&&scope.setTag(key,value)},Hub.prototype.setExtra=function(key,extra){var scope=this.getScope();scope&&scope.setExtra(key,extra)},Hub.prototype.setContext=function(name,context){var scope=this.getScope();scope&&scope.setContext(name,context)},Hub.prototype.configureScope=function(callback){var _a=this.getStackTop(),scope=_a.scope,_a=_a.client;scope&&_a&&callback(scope)},Hub.prototype.run=function(callback){var oldHub=makeMain(this);try{callback(this)}finally{makeMain(oldHub)}},Hub.prototype.getIntegration=function(integration){var client=this.getClient();if(!client)return null;try{return client.getIntegration(integration)}catch(_oO){return utils_1.logger.warn("Cannot retrieve integration "+integration.id+" from the current Hub"),null}},Hub.prototype.startSpan=function(context){return this._callExtensionMethod("startSpan",context)},Hub.prototype.startTransaction=function(context,customSamplingContext){return this._callExtensionMethod("startTransaction",context,customSamplingContext)},Hub.prototype.traceHeaders=function(){return this._callExtensionMethod("traceHeaders")},Hub.prototype.startSession=function(context){this.endSession();var _a=this.getStackTop(),scope=_a.scope,_a=_a.client,_a=_a&&_a.getOptions()||{},release=_a.release,_a=_a.environment,release=new session_1.Session(tslib_1.__assign(tslib_1.__assign({release:release,environment:_a},scope&&{user:scope.getUser()}),context));return scope&&scope.setSession(release),release},Hub.prototype.endSession=function(){var session,_a=this.getStackTop(),scope=_a.scope,_a=_a.client;scope&&(session=scope.getSession&&scope.getSession())&&(session.close(),_a&&_a.captureSession&&_a.captureSession(session),scope.setSession())},Hub.prototype._invokeClient=function(method){for(var args=[],_i=1;_i<arguments.length;_i++)args[_i-1]=arguments[_i];var _b=this.getStackTop(),scope=_b.scope,_b=_b.client;_b&&_b[method]&&_b[method].apply(_b,tslib_1.__spread(args,[scope]))},Hub.prototype._callExtensionMethod=function(method){for(var args=[],_i=1;_i<arguments.length;_i++)args[_i-1]=arguments[_i];var sentry=getMainCarrier().__SENTRY__;if(sentry&&sentry.extensions&&"function"==typeof sentry.extensions[method])return sentry.extensions[method].apply(this,args);utils_1.logger.warn("Extension method "+method+" couldn't be found, doing nothing.")},Hub}());function getMainCarrier(){var carrier=utils_1.getGlobalObject();return carrier.__SENTRY__=carrier.__SENTRY__||{extensions:{},hub:void 0},carrier}function makeMain(hub){var registry=getMainCarrier(),oldHub=getHubFromCarrier(registry);return setHubOnCarrier(registry,hub),oldHub}function getActiveDomain(){var sentry=getMainCarrier().__SENTRY__;return sentry&&sentry.extensions&&sentry.extensions.domain&&sentry.extensions.domain.active}function hasHubOnCarrier(carrier){return carrier&&carrier.__SENTRY__&&carrier.__SENTRY__.hub}function getHubFromCarrier(carrier){return carrier&&carrier.__SENTRY__&&carrier.__SENTRY__.hub||(carrier.__SENTRY__=carrier.__SENTRY__||{},carrier.__SENTRY__.hub=new Hub),carrier.__SENTRY__.hub}function setHubOnCarrier(carrier,hub){return!!carrier&&(carrier.__SENTRY__=carrier.__SENTRY__||{},carrier.__SENTRY__.hub=hub,!0)}exports.Hub=Hub,exports.getMainCarrier=getMainCarrier,exports.makeMain=makeMain,exports.getCurrentHub=function(){var registry=getMainCarrier();return hasHubOnCarrier(registry)&&!getHubFromCarrier(registry).isOlderThan(exports.API_VERSION)||setHubOnCarrier(registry,new Hub),(utils_1.isNodeEnv()?function(registry){try{var registryHubTopStack,activeDomain=getActiveDomain();return activeDomain?(hasHubOnCarrier(activeDomain)&&!getHubFromCarrier(activeDomain).isOlderThan(exports.API_VERSION)||(registryHubTopStack=getHubFromCarrier(registry).getStackTop(),setHubOnCarrier(activeDomain,new Hub(registryHubTopStack.client,scope_1.Scope.clone(registryHubTopStack.scope)))),getHubFromCarrier(activeDomain)):getHubFromCarrier(registry)}catch(_Oo){return getHubFromCarrier(registry)}}:getHubFromCarrier)(registry)},exports.getActiveDomain=getActiveDomain,exports.getHubFromCarrier=getHubFromCarrier,exports.setHubOnCarrier=setHubOnCarrier},{"./scope":70,"./session":71,"@sentry/utils":83,tslib:1698}],69:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var scope_1=require("./scope"),scope_1=(exports.addGlobalEventProcessor=scope_1.addGlobalEventProcessor,exports.Scope=scope_1.Scope,require("./session")),scope_1=(exports.Session=scope_1.Session,require("./hub"));exports.getActiveDomain=scope_1.getActiveDomain,exports.getCurrentHub=scope_1.getCurrentHub,exports.getHubFromCarrier=scope_1.getHubFromCarrier,exports.getMainCarrier=scope_1.getMainCarrier,exports.Hub=scope_1.Hub,exports.makeMain=scope_1.makeMain,exports.setHubOnCarrier=scope_1.setHubOnCarrier},{"./hub":68,"./scope":70,"./session":71}],70:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),utils_1=require("@sentry/utils"),require=function(){function Scope(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._user={},this._tags={},this._extra={},this._contexts={}}return Scope.clone=function(scope){var newScope=new Scope;return scope&&(newScope._breadcrumbs=tslib_1.__spread(scope._breadcrumbs),newScope._tags=tslib_1.__assign({},scope._tags),newScope._extra=tslib_1.__assign({},scope._extra),newScope._contexts=tslib_1.__assign({},scope._contexts),newScope._user=scope._user,newScope._level=scope._level,newScope._span=scope._span,newScope._session=scope._session,newScope._transactionName=scope._transactionName,newScope._fingerprint=scope._fingerprint,newScope._eventProcessors=tslib_1.__spread(scope._eventProcessors)),newScope},Scope.prototype.addScopeListener=function(callback){this._scopeListeners.push(callback)},Scope.prototype.addEventProcessor=function(callback){return this._eventProcessors.push(callback),this},Scope.prototype.setUser=function(user){return this._user=user||{},this._session&&this._session.update({user:user}),this._notifyScopeListeners(),this},Scope.prototype.getUser=function(){return this._user},Scope.prototype.setTags=function(tags){return this._tags=tslib_1.__assign(tslib_1.__assign({},this._tags),tags),this._notifyScopeListeners(),this},Scope.prototype.setTag=function(key,value){var _a;return this._tags=tslib_1.__assign(tslib_1.__assign({},this._tags),((_a={})[key]=value,_a)),this._notifyScopeListeners(),this},Scope.prototype.setExtras=function(extras){return this._extra=tslib_1.__assign(tslib_1.__assign({},this._extra),extras),this._notifyScopeListeners(),this},Scope.prototype.setExtra=function(key,extra){var _a;return this._extra=tslib_1.__assign(tslib_1.__assign({},this._extra),((_a={})[key]=extra,_a)),this._notifyScopeListeners(),this},Scope.prototype.setFingerprint=function(fingerprint){return this._fingerprint=fingerprint,this._notifyScopeListeners(),this},Scope.prototype.setLevel=function(level){return this._level=level,this._notifyScopeListeners(),this},Scope.prototype.setTransactionName=function(name){return this._transactionName=name,this._notifyScopeListeners(),this},Scope.prototype.setTransaction=function(name){return this.setTransactionName(name)},Scope.prototype.setContext=function(key,context){var _a;return null===context?delete this._contexts[key]:this._contexts=tslib_1.__assign(tslib_1.__assign({},this._contexts),((_a={})[key]=context,_a)),this._notifyScopeListeners(),this},Scope.prototype.setSpan=function(span){return this._span=span,this._notifyScopeListeners(),this},Scope.prototype.getSpan=function(){return this._span},Scope.prototype.getTransaction=function(){var _a,span=this.getSpan();return null!=(_a=span)&&_a.transaction?null==(_a=span)?void 0:_a.transaction:null!=(_a=null==(_a=span)?void 0:_a.spanRecorder)&&_a.spans[0]?span.spanRecorder.spans[0]:void 0},Scope.prototype.setSession=function(session){return session?this._session=session:delete this._session,this._notifyScopeListeners(),this},Scope.prototype.getSession=function(){return this._session},Scope.prototype.update=function(captureContext){if(captureContext){var updatedScope;if("function"==typeof captureContext)return(updatedScope=captureContext(this))instanceof Scope?updatedScope:this;captureContext instanceof Scope?(this._tags=tslib_1.__assign(tslib_1.__assign({},this._tags),captureContext._tags),this._extra=tslib_1.__assign(tslib_1.__assign({},this._extra),captureContext._extra),this._contexts=tslib_1.__assign(tslib_1.__assign({},this._contexts),captureContext._contexts),captureContext._user&&Object.keys(captureContext._user).length&&(this._user=captureContext._user),captureContext._level&&(this._level=captureContext._level),captureContext._fingerprint&&(this._fingerprint=captureContext._fingerprint)):utils_1.isPlainObject(captureContext)&&(this._tags=tslib_1.__assign(tslib_1.__assign({},this._tags),captureContext.tags),this._extra=tslib_1.__assign(tslib_1.__assign({},this._extra),captureContext.extra),this._contexts=tslib_1.__assign(tslib_1.__assign({},this._contexts),captureContext.contexts),captureContext.user&&(this._user=captureContext.user),captureContext.level&&(this._level=captureContext.level),captureContext.fingerprint)&&(this._fingerprint=captureContext.fingerprint)}return this},Scope.prototype.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this},Scope.prototype.addBreadcrumb=function(breadcrumb,maxBreadcrumbs){breadcrumb=tslib_1.__assign({timestamp:utils_1.dateTimestampInSeconds()},breadcrumb);return this._breadcrumbs=void 0!==maxBreadcrumbs&&0<=maxBreadcrumbs?tslib_1.__spread(this._breadcrumbs,[breadcrumb]).slice(-maxBreadcrumbs):tslib_1.__spread(this._breadcrumbs,[breadcrumb]),this._notifyScopeListeners(),this},Scope.prototype.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},Scope.prototype.applyToEvent=function(event,hint){var _a;return this._extra&&Object.keys(this._extra).length&&(event.extra=tslib_1.__assign(tslib_1.__assign({},this._extra),event.extra)),this._tags&&Object.keys(this._tags).length&&(event.tags=tslib_1.__assign(tslib_1.__assign({},this._tags),event.tags)),this._user&&Object.keys(this._user).length&&(event.user=tslib_1.__assign(tslib_1.__assign({},this._user),event.user)),this._contexts&&Object.keys(this._contexts).length&&(event.contexts=tslib_1.__assign(tslib_1.__assign({},this._contexts),event.contexts)),this._level&&(event.level=this._level),this._transactionName&&(event.transaction=this._transactionName),this._span&&(event.contexts=tslib_1.__assign({trace:this._span.getTraceContext()},event.contexts),_a=null==(_a=this._span.transaction)?void 0:_a.name)&&(event.tags=tslib_1.__assign({transaction:_a},event.tags)),this._applyFingerprint(event),event.breadcrumbs=tslib_1.__spread(event.breadcrumbs||[],this._breadcrumbs),event.breadcrumbs=0<event.breadcrumbs.length?event.breadcrumbs:void 0,this._notifyEventProcessors(tslib_1.__spread(getGlobalEventProcessors(),this._eventProcessors),event,hint)},Scope.prototype._notifyEventProcessors=function(processors,event,hint,index){var _this=this;return void 0===index&&(index=0),new utils_1.SyncPromise(function(resolve,reject){var processor=processors[index];null===event||"function"!=typeof processor?resolve(event):(processor=processor(tslib_1.__assign({},event),hint),(utils_1.isThenable(processor)?processor.then(function(final){return _this._notifyEventProcessors(processors,final,hint,index+1).then(resolve)}):_this._notifyEventProcessors(processors,processor,hint,index+1).then(resolve)).then(null,reject))})},Scope.prototype._notifyScopeListeners=function(){var _this=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(function(callback){callback(_this)}),this._notifyingListeners=!1)},Scope.prototype._applyFingerprint=function(event){event.fingerprint=event.fingerprint?Array.isArray(event.fingerprint)?event.fingerprint:[event.fingerprint]:[],this._fingerprint&&(event.fingerprint=event.fingerprint.concat(this._fingerprint)),event.fingerprint&&!event.fingerprint.length&&delete event.fingerprint},Scope}();function getGlobalEventProcessors(){var global=utils_1.getGlobalObject();return global.__SENTRY__=global.__SENTRY__||{},global.__SENTRY__.globalEventProcessors=global.__SENTRY__.globalEventProcessors||[],global.__SENTRY__.globalEventProcessors}exports.Scope=require,exports.addGlobalEventProcessor=function(callback){getGlobalEventProcessors().push(callback)}},{"@sentry/utils":83,tslib:1698}],71:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var types_1=require("@sentry/types"),utils_1=require("@sentry/utils"),require=function(){function Session(context){this.errors=0,this.sid=utils_1.uuid4(),this.timestamp=Date.now(),this.started=Date.now(),this.duration=0,this.status=types_1.SessionStatus.Ok,context&&this.update(context)}return Session.prototype.update=function(context){(context=void 0===context?{}:context).user&&(context.user.ip_address&&(this.ipAddress=context.user.ip_address),context.did||(this.did=context.user.id||context.user.email||context.user.username)),this.timestamp=context.timestamp||Date.now(),context.sid&&(this.sid=32===context.sid.length?context.sid:utils_1.uuid4()),context.did&&(this.did=""+context.did),"number"==typeof context.started&&(this.started=context.started),"number"==typeof context.duration?this.duration=context.duration:this.duration=this.timestamp-this.started,context.release&&(this.release=context.release),context.environment&&(this.environment=context.environment),context.ipAddress&&(this.ipAddress=context.ipAddress),context.userAgent&&(this.userAgent=context.userAgent),"number"==typeof context.errors&&(this.errors=context.errors),context.status&&(this.status=context.status)},Session.prototype.close=function(status){status?this.update({status:status}):this.status===types_1.SessionStatus.Ok?this.update({status:types_1.SessionStatus.Exited}):this.update()},Session.prototype.toJSON=function(){return utils_1.dropUndefinedKeys({sid:""+this.sid,init:!0,started:new Date(this.started).toISOString(),timestamp:new Date(this.timestamp).toISOString(),status:this.status,errors:this.errors,did:"number"==typeof this.did||"string"==typeof this.did?""+this.did:void 0,duration:this.duration,attrs:utils_1.dropUndefinedKeys({release:this.release,environment:this.environment,ip_address:this.ipAddress,user_agent:this.userAgent})})},Session}();exports.Session=require},{"@sentry/types":73,"@sentry/utils":83}],72:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),hub_1=require("@sentry/hub");function callOnHub(method){for(var args=[],_i=1;_i<arguments.length;_i++)args[_i-1]=arguments[_i];var hub=hub_1.getCurrentHub();if(hub&&hub[method])return hub[method].apply(hub,tslib_1.__spread(args));throw new Error("No hub defined or "+method+" was not found on the hub, please open a bug report.")}exports.captureException=function(exception,captureContext){var syntheticException;try{throw new Error("Sentry syntheticException")}catch(exception){syntheticException=exception}return callOnHub("captureException",exception,{captureContext:captureContext,originalException:exception,syntheticException:syntheticException})},exports.captureMessage=function(message,captureContext){var syntheticException;try{throw new Error(message)}catch(exception){syntheticException=exception}return callOnHub("captureMessage",message,"string"==typeof captureContext?captureContext:void 0,tslib_1.__assign({originalException:message,syntheticException:syntheticException},"string"!=typeof captureContext?{captureContext:captureContext}:void 0))},exports.captureEvent=function(event){return callOnHub("captureEvent",event)},exports.configureScope=function(callback){callOnHub("configureScope",callback)},exports.addBreadcrumb=function(breadcrumb){callOnHub("addBreadcrumb",breadcrumb)},exports.setContext=function(name,context){callOnHub("setContext",name,context)},exports.setExtras=function(extras){callOnHub("setExtras",extras)},exports.setTags=function(tags){callOnHub("setTags",tags)},exports.setExtra=function(key,extra){callOnHub("setExtra",key,extra)},exports.setTag=function(key,value){callOnHub("setTag",key,value)},exports.setUser=function(user){callOnHub("setUser",user)},exports.withScope=function(callback){callOnHub("withScope",callback)},exports._callOnClient=function(method){for(var args=[],_i=1;_i<arguments.length;_i++)args[_i-1]=arguments[_i];callOnHub.apply(void 0,tslib_1.__spread(["_invokeClient",method],args))},exports.startTransaction=function(context,customSamplingContext){return callOnHub("startTransaction",tslib_1.__assign({},context),customSamplingContext)}},{"@sentry/hub":69,tslib:1698}],73:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var loglevel_1=require("./loglevel"),loglevel_1=(exports.LogLevel=loglevel_1.LogLevel,require("./session")),loglevel_1=(exports.SessionStatus=loglevel_1.SessionStatus,require("./severity")),loglevel_1=(exports.Severity=loglevel_1.Severity,require("./status")),loglevel_1=(exports.Status=loglevel_1.Status,require("./transaction"));exports.TransactionSamplingMethod=loglevel_1.TransactionSamplingMethod},{"./loglevel":74,"./session":75,"./severity":76,"./status":77,"./transaction":78}],74:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),function(LogLevel){LogLevel[LogLevel.None=0]="None",LogLevel[LogLevel.Error=1]="Error",LogLevel[LogLevel.Debug=2]="Debug",LogLevel[LogLevel.Verbose=3]="Verbose"}(exports.LogLevel||(exports.LogLevel={}))},{}],75:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),function(SessionStatus){SessionStatus.Ok="ok",SessionStatus.Exited="exited",SessionStatus.Crashed="crashed",SessionStatus.Abnormal="abnormal"}(exports.SessionStatus||(exports.SessionStatus={}))},{}],76:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),function(Severity){Severity.Fatal="fatal",Severity.Error="error",Severity.Warning="warning",Severity.Log="log",Severity.Info="info",Severity.Debug="debug",Severity.Critical="critical"}(exports.Severity||(exports.Severity={})),function(Severity){Severity.fromString=function(level){switch(level){case"debug":return Severity.Debug;case"info":return Severity.Info;case"warn":case"warning":return Severity.Warning;case"error":return Severity.Error;case"fatal":return Severity.Fatal;case"critical":return Severity.Critical;default:return Severity.Log}}}(exports.Severity||(exports.Severity={}))},{}],77:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),function(Status){Status.Unknown="unknown",Status.Skipped="skipped",Status.Success="success",Status.RateLimit="rate_limit",Status.Invalid="invalid",Status.Failed="failed"}(exports.Status||(exports.Status={})),function(Status){Status.fromHttpCode=function(code){return 200<=code&&code<300?Status.Success:429===code?Status.RateLimit:400<=code&&code<500?Status.Invalid:500<=code?Status.Failed:Status.Unknown}}(exports.Status||(exports.Status={}))},{}],78:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),function(TransactionSamplingMethod){TransactionSamplingMethod.Explicit="explicitly_set",TransactionSamplingMethod.Sampler="client_sampler",TransactionSamplingMethod.Rate="client_rate",TransactionSamplingMethod.Inheritance="inheritance"}(exports.TransactionSamplingMethod||(exports.TransactionSamplingMethod={}))},{}],79:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.forget=function(promise){promise.then(null,function(e){console.error(e)})}},{}],80:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var is_1=require("./is");exports.htmlTreeAsString=function(elem){try{for(var nextStr,currentElem=elem,out=[],height=0,len=0,sepLength=" > ".length;currentElem&&height++<5&&!("html"===(nextStr=function(el){var classes,key,attr,i,elem=el,out=[];if(!elem||!elem.tagName)return"";out.push(elem.tagName.toLowerCase()),elem.id&&out.push("#"+elem.id);if((el=elem.className)&&is_1.isString(el))for(classes=el.split(/\s+/),i=0;i<classes.length;i++)out.push("."+classes[i]);var allowedAttrs=["type","name","title","alt"];for(i=0;i<allowedAttrs.length;i++)key=allowedAttrs[i],(attr=elem.getAttribute(key))&&out.push("["+key+'="'+attr+'"]');return out.join("")}(currentElem))||1<height&&80<=len+out.length*sepLength+nextStr.length);)out.push(nextStr),len+=nextStr.length,currentElem=currentElem.parentNode;return out.reverse().join(" > ")}catch(_oO){return"<unknown>"}}},{"./is":85}],81:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),error_1=require("./error"),DSN_REGEX=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/,require=function(){function Dsn(from){"string"==typeof from?this._fromString(from):this._fromComponents(from),this._validate()}return Dsn.prototype.toString=function(withPassword){var _a=this,host=_a.host,path=_a.path,pass=_a.pass,port=_a.port,projectId=_a.projectId;return _a.protocol+"://"+_a.user+((withPassword=void 0===withPassword?!1:withPassword)&&pass?":"+pass:"")+"@"+host+(port?":"+port:"")+"/"+(path&&path+"/")+projectId},Dsn.prototype._fromString=function(str){str=DSN_REGEX.exec(str);if(!str)throw new error_1.SentryError("Invalid Dsn");var str=tslib_1.__read(str.slice(1),6),protocol=str[0],user=str[1],_b=str[2],_b=void 0===_b?"":_b,host=str[3],_c=str[4],_c=void 0===_c?"":_c,path="",str=str[5],split=str.split("/");1<split.length&&(path=split.slice(0,-1).join("/"),str=split.pop()),str&&(split=str.match(/^\d+/))&&(str=split[0]),this._fromComponents({host:host,pass:_b,path:path,projectId:str,port:_c,protocol:protocol,user:user})},Dsn.prototype._fromComponents=function(components){this.protocol=components.protocol,this.user=components.user,this.pass=components.pass||"",this.host=components.host,this.port=components.port||"",this.path=components.path||"",this.projectId=components.projectId},Dsn.prototype._validate=function(){var _this=this;if(["protocol","user","host","projectId"].forEach(function(component){if(!_this[component])throw new error_1.SentryError("Invalid Dsn: "+component+" missing")}),!this.projectId.match(/^\d+$/))throw new error_1.SentryError("Invalid Dsn: Invalid projectId "+this.projectId);if("http"!==this.protocol&&"https"!==this.protocol)throw new error_1.SentryError("Invalid Dsn: Invalid protocol "+this.protocol);if(this.port&&isNaN(parseInt(this.port,10)))throw new error_1.SentryError("Invalid Dsn: Invalid port "+this.port)},Dsn}();exports.Dsn=require},{"./error":82,tslib:1698}],82:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),polyfill_1=require("./polyfill"),require=function(_super){function SentryError(message){var _newTarget=this.constructor,_this=_super.call(this,message)||this;return _this.message=message,_this.name=_newTarget.prototype.constructor.name,polyfill_1.setPrototypeOf(_this,_newTarget.prototype),_this}return tslib_1.__extends(SentryError,_super),SentryError}(Error);exports.SentryError=require},{"./polyfill":92,tslib:1698}],83:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib");tslib_1.__exportStar(require("./async"),exports),tslib_1.__exportStar(require("./browser"),exports),tslib_1.__exportStar(require("./dsn"),exports),tslib_1.__exportStar(require("./error"),exports),tslib_1.__exportStar(require("./instrument"),exports),tslib_1.__exportStar(require("./is"),exports),tslib_1.__exportStar(require("./logger"),exports),tslib_1.__exportStar(require("./memo"),exports),tslib_1.__exportStar(require("./misc"),exports),tslib_1.__exportStar(require("./node"),exports),tslib_1.__exportStar(require("./object"),exports),tslib_1.__exportStar(require("./path"),exports),tslib_1.__exportStar(require("./promisebuffer"),exports),tslib_1.__exportStar(require("./stacktrace"),exports),tslib_1.__exportStar(require("./string"),exports),tslib_1.__exportStar(require("./supports"),exports),tslib_1.__exportStar(require("./syncpromise"),exports),tslib_1.__exportStar(require("./time"),exports)},{"./async":79,"./browser":80,"./dsn":81,"./error":82,"./instrument":84,"./is":85,"./logger":86,"./memo":87,"./misc":88,"./node":89,"./object":90,"./path":91,"./promisebuffer":93,"./stacktrace":94,"./string":95,"./supports":96,"./syncpromise":97,"./time":98,tslib:1698}],84:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var lastHref,tslib_1=require("tslib"),is_1=require("./is"),logger_1=require("./logger"),misc_1=require("./misc"),object_1=require("./object"),stacktrace_1=require("./stacktrace"),supports_1=require("./supports"),global=misc_1.getGlobalObject(),handlers={},instrumented={};function instrument(type){var oldOnPopState,requestKeys,requestValues,xhrproto;if(!instrumented[type])switch(instrumented[type]=!0,type){case"console":"console"in global&&["debug","info","warn","error","log","assert"].forEach(function(level){level in global.console&&object_1.fill(global.console,level,function(originalConsoleLevel){return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];triggerHandlers("console",{args:args,level:level}),originalConsoleLevel&&Function.prototype.apply.call(originalConsoleLevel,global.console,args)}})});break;case"dom":"document"in global&&(global.document.addEventListener("click",domEventHandler("click",triggerHandlers.bind(null,"dom")),!1),global.document.addEventListener("keypress",keypressEventHandler(triggerHandlers.bind(null,"dom")),!1),["EventTarget","Node"].forEach(function(target){target=global[target]&&global[target].prototype;target&&target.hasOwnProperty&&target.hasOwnProperty("addEventListener")&&(object_1.fill(target,"addEventListener",function(original){return function(eventName,fn,options){return fn&&fn.handleEvent?("click"===eventName&&object_1.fill(fn,"handleEvent",function(innerOriginal){return function(event){return domEventHandler("click",triggerHandlers.bind(null,"dom"))(event),innerOriginal.call(this,event)}}),"keypress"===eventName&&object_1.fill(fn,"handleEvent",function(innerOriginal){return function(event){return keypressEventHandler(triggerHandlers.bind(null,"dom"))(event),innerOriginal.call(this,event)}})):("click"===eventName&&domEventHandler("click",triggerHandlers.bind(null,"dom"),!0)(this),"keypress"===eventName&&keypressEventHandler(triggerHandlers.bind(null,"dom"))(this)),original.call(this,eventName,fn,options)}}),object_1.fill(target,"removeEventListener",function(original){return function(eventName,fn,options){try{original.call(this,eventName,fn.__sentry_wrapped__,options)}catch(e){}return original.call(this,eventName,fn,options)}}))}));break;case"xhr":"XMLHttpRequest"in global&&(requestKeys=[],requestValues=[],xhrproto=XMLHttpRequest.prototype,object_1.fill(xhrproto,"open",function(originalOpen){return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];function onreadystatechangeHandler(){if(4===xhr.readyState){try{xhr.__sentry_xhr__&&(xhr.__sentry_xhr__.status_code=xhr.status)}catch(e){}try{var args_1,requestPos=requestKeys.indexOf(xhr);-1!==requestPos&&(requestKeys.splice(requestPos),args_1=requestValues.splice(requestPos)[0],xhr.__sentry_xhr__)&&void 0!==args_1[0]&&(xhr.__sentry_xhr__.body=args_1[0])}catch(e){}triggerHandlers("xhr",{args:args,endTimestamp:Date.now(),startTimestamp:Date.now(),xhr:xhr})}}var xhr=this,url=args[1];xhr.__sentry_xhr__={method:is_1.isString(args[0])?args[0].toUpperCase():args[0],url:args[1]},is_1.isString(url)&&"POST"===xhr.__sentry_xhr__.method&&url.match(/sentry_key/)&&(xhr.__sentry_own_request__=!0);return"onreadystatechange"in xhr&&"function"==typeof xhr.onreadystatechange?object_1.fill(xhr,"onreadystatechange",function(original){return function(){for(var readyStateArgs=[],_i=0;_i<arguments.length;_i++)readyStateArgs[_i]=arguments[_i];return onreadystatechangeHandler(),original.apply(xhr,readyStateArgs)}}):xhr.addEventListener("readystatechange",onreadystatechangeHandler),originalOpen.apply(xhr,args)}}),object_1.fill(xhrproto,"send",function(originalSend){return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return requestKeys.push(this),requestValues.push(args),triggerHandlers("xhr",{args:args,startTimestamp:Date.now(),xhr:this}),originalSend.apply(this,args)}}));break;case"fetch":supports_1.supportsNativeFetch()&&object_1.fill(global,"fetch",function(originalFetch){return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];var handlerData={args:args,fetchData:{method:function(fetchArgs){void 0===fetchArgs&&(fetchArgs=[]);if("Request"in global&&is_1.isInstanceOf(fetchArgs[0],Request)&&fetchArgs[0].method)return String(fetchArgs[0].method).toUpperCase();if(fetchArgs[1]&&fetchArgs[1].method)return String(fetchArgs[1].method).toUpperCase();return"GET"}(args),url:function(fetchArgs){void 0===fetchArgs&&(fetchArgs=[]);if("string"==typeof fetchArgs[0])return fetchArgs[0];if("Request"in global&&is_1.isInstanceOf(fetchArgs[0],Request))return fetchArgs[0].url;return String(fetchArgs[0])}(args)},startTimestamp:Date.now()};return triggerHandlers("fetch",tslib_1.__assign({},handlerData)),originalFetch.apply(global,args).then(function(response){return triggerHandlers("fetch",tslib_1.__assign(tslib_1.__assign({},handlerData),{endTimestamp:Date.now(),response:response})),response},function(error){throw triggerHandlers("fetch",tslib_1.__assign(tslib_1.__assign({},handlerData),{endTimestamp:Date.now(),error:error})),error})}});break;case"history":supports_1.supportsHistory()&&(oldOnPopState=global.onpopstate,global.onpopstate=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];var to=global.location.href;if(triggerHandlers("history",{from:lastHref,to:lastHref=to}),oldOnPopState)return oldOnPopState.apply(this,args)},object_1.fill(global.history,"pushState",historyReplacementFunction),object_1.fill(global.history,"replaceState",historyReplacementFunction));break;case"error":_oldOnErrorHandler=global.onerror,global.onerror=function(msg,url,line,column,error){return triggerHandlers("error",{column:column,error:error,line:line,msg:msg,url:url}),!!_oldOnErrorHandler&&_oldOnErrorHandler.apply(this,arguments)};break;case"unhandledrejection":_oldOnUnhandledRejectionHandler=global.onunhandledrejection,global.onunhandledrejection=function(e){return triggerHandlers("unhandledrejection",e),!_oldOnUnhandledRejectionHandler||_oldOnUnhandledRejectionHandler.apply(this,arguments)};break;default:logger_1.logger.warn("unknown instrumentation type:",type)}function historyReplacementFunction(originalHistoryFunction){return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];var from,url=2<args.length?args[2]:void 0;return url&&(from=lastHref,url=String(url),triggerHandlers("history",{from:from,to:lastHref=url})),originalHistoryFunction.apply(this,args)}}}function triggerHandlers(type,data){var e_1,_a;if(type&&handlers[type])try{for(var _b=tslib_1.__values(handlers[type]||[]),_c=_b.next();!_c.done;_c=_b.next()){var handler=_c.value;try{handler(data)}catch(e){logger_1.logger.error("Error while triggering instrumentation handler.\nType: "+type+"\nName: "+stacktrace_1.getFunctionName(handler)+"\nError: "+e)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_c&&!_c.done&&(_a=_b.return)&&_a.call(_b)}finally{if(e_1)throw e_1.error}}}exports.addInstrumentationHandler=function(handler){handler&&"string"==typeof handler.type&&"function"==typeof handler.callback&&(handlers[handler.type]=handlers[handler.type]||[],handlers[handler.type].push(handler.callback),instrument(handler.type))};var keypressTimeout,lastCapturedEvent,debounceDuration=1e3,debounceTimer=0;function domEventHandler(name,handler,debounce){return void 0===debounce&&(debounce=!1),function(event){keypressTimeout=void 0,event&&lastCapturedEvent!==event&&(lastCapturedEvent=event,debounceTimer&&clearTimeout(debounceTimer),debounce?debounceTimer=setTimeout(function(){handler({event:event,name:name})}):handler({event:event,name:name}))}}function keypressEventHandler(handler){return function(event){var target;try{target=event.target}catch(e){return}var tagName=target&&target.tagName;tagName&&("INPUT"===tagName||"TEXTAREA"===tagName||target.isContentEditable)&&(keypressTimeout||domEventHandler("input",handler)(event),clearTimeout(keypressTimeout),keypressTimeout=setTimeout(function(){keypressTimeout=void 0},debounceDuration))}}var _oldOnErrorHandler=null;var _oldOnUnhandledRejectionHandler=null},{"./is":85,"./logger":86,"./misc":88,"./object":90,"./stacktrace":94,"./supports":96,tslib:1698}],85:[function(require,module,exports){function isPlainObject(wat){return"[object Object]"===Object.prototype.toString.call(wat)}function isInstanceOf(wat,base){try{return wat instanceof base}catch(_e){return!1}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.isError=function(wat){switch(Object.prototype.toString.call(wat)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return isInstanceOf(wat,Error)}},exports.isErrorEvent=function(wat){return"[object ErrorEvent]"===Object.prototype.toString.call(wat)},exports.isDOMError=function(wat){return"[object DOMError]"===Object.prototype.toString.call(wat)},exports.isDOMException=function(wat){return"[object DOMException]"===Object.prototype.toString.call(wat)},exports.isString=function(wat){return"[object String]"===Object.prototype.toString.call(wat)},exports.isPrimitive=function(wat){return null===wat||"object"!=typeof wat&&"function"!=typeof wat},exports.isPlainObject=isPlainObject,exports.isEvent=function(wat){return"undefined"!=typeof Event&&isInstanceOf(wat,Event)},exports.isElement=function(wat){return"undefined"!=typeof Element&&isInstanceOf(wat,Element)},exports.isRegExp=function(wat){return"[object RegExp]"===Object.prototype.toString.call(wat)},exports.isThenable=function(wat){return Boolean(wat&&wat.then&&"function"==typeof wat.then)},exports.isSyntheticEvent=function(wat){return isPlainObject(wat)&&"nativeEvent"in wat&&"preventDefault"in wat&&"stopPropagation"in wat},exports.isInstanceOf=isInstanceOf},{}],86:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var misc_1=require("./misc"),global=misc_1.getGlobalObject(),PREFIX="Sentry Logger ",require=function(){function Logger(){this._enabled=!1}return Logger.prototype.disable=function(){this._enabled=!1},Logger.prototype.enable=function(){this._enabled=!0},Logger.prototype.log=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];this._enabled&&misc_1.consoleSandbox(function(){global.console.log(PREFIX+"[Log]: "+args.join(" "))})},Logger.prototype.warn=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];this._enabled&&misc_1.consoleSandbox(function(){global.console.warn(PREFIX+"[Warn]: "+args.join(" "))})},Logger.prototype.error=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];this._enabled&&misc_1.consoleSandbox(function(){global.console.error(PREFIX+"[Error]: "+args.join(" "))})},Logger}(),require=(global.__SENTRY__=global.__SENTRY__||{},global.__SENTRY__.logger||(global.__SENTRY__.logger=new require));exports.logger=require},{"./misc":88}],87:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var Memo=function(){function Memo(){this._hasWeakSet="function"==typeof WeakSet,this._inner=this._hasWeakSet?new WeakSet:[]}return Memo.prototype.memoize=function(obj){if(this._hasWeakSet)return!!this._inner.has(obj)||(this._inner.add(obj),!1);for(var i=0;i<this._inner.length;i++)if(this._inner[i]===obj)return!0;return this._inner.push(obj),!1},Memo.prototype.unmemoize=function(obj){if(this._hasWeakSet)this._inner.delete(obj);else for(var i=0;i<this._inner.length;i++)if(this._inner[i]===obj){this._inner.splice(i,1);break}},Memo}();exports.Memo=Memo},{}],88:[function(require,module,exports){!function(global){!function(){Object.defineProperty(exports,"__esModule",{value:!0});var node_1=require("./node"),string_1=require("./string"),fallbackGlobalObject={};function getGlobalObject(){return node_1.isNodeEnv()?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:fallbackGlobalObject}exports.getGlobalObject=getGlobalObject,exports.uuid4=function(){var arr,global=getGlobalObject();return void 0!==(global=global.crypto||global.msCrypto)&&global.getRandomValues?(arr=new Uint16Array(8),global.getRandomValues(arr),arr[3]=4095&arr[3]|16384,arr[4]=16383&arr[4]|32768,(global=function(num){for(var v=num.toString(16);v.length<4;)v="0"+v;return v})(arr[0])+global(arr[1])+global(arr[2])+global(arr[3])+global(arr[4])+global(arr[5])+global(arr[6])+global(arr[7])):"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0;return("x"===c?r:3&r|8).toString(16)})},exports.parseUrl=function(url){var query,fragment;return(url=url&&url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/))?(query=url[6]||"",fragment=url[8]||"",{host:url[4],path:url[5],protocol:url[2],relative:url[5]+query+fragment}):{}},exports.getEventDescription=function(event){var exception;return event.message||(event.exception&&event.exception.values&&event.exception.values[0]?(exception=event.exception.values[0]).type&&exception.value?exception.type+": "+exception.value:exception.type||exception.value||event.event_id||"<unknown>":event.event_id||"<unknown>")},exports.consoleSandbox=function(callback){var originalConsole,wrappedLevels,result,global=getGlobalObject();return"console"in global?(originalConsole=global.console,wrappedLevels={},["debug","info","warn","error","log","assert"].forEach(function(level){level in global.console&&originalConsole[level].__sentry_original__&&(wrappedLevels[level]=originalConsole[level],originalConsole[level]=originalConsole[level].__sentry_original__)}),result=callback(),Object.keys(wrappedLevels).forEach(function(level){originalConsole[level]=wrappedLevels[level]}),result):callback()},exports.addExceptionTypeValue=function(event,value,type){event.exception=event.exception||{},event.exception.values=event.exception.values||[],event.exception.values[0]=event.exception.values[0]||{},event.exception.values[0].value=event.exception.values[0].value||value||"",event.exception.values[0].type=event.exception.values[0].type||type||"Error"},exports.addExceptionMechanism=function(event,mechanism){void 0===mechanism&&(mechanism={});try{event.exception.values[0].mechanism=event.exception.values[0].mechanism||{},Object.keys(mechanism).forEach(function(key){event.exception.values[0].mechanism[key]=mechanism[key]})}catch(_oO){}},exports.getLocationHref=function(){try{return document.location.href}catch(oO){return""}};var SEMVER_REGEXP=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;exports.parseSemver=function(input){var input=input.match(SEMVER_REGEXP)||[],major=parseInt(input[1],10),minor=parseInt(input[2],10),patch=parseInt(input[3],10);return{buildmetadata:input[5],major:isNaN(major)?void 0:major,minor:isNaN(minor)?void 0:minor,patch:isNaN(patch)?void 0:patch,prerelease:input[4]}};exports.parseRetryAfterHeader=function(now,header){var headerDelay;return header?(headerDelay=parseInt(""+header,10),isNaN(headerDelay)?(header=Date.parse(""+header),isNaN(header)?6e4:header-now):1e3*headerDelay):6e4},exports.addContextToFrame=function(lines,frame,linesOfContext){void 0===linesOfContext&&(linesOfContext=5);var lineno=frame.lineno||0,maxLines=lines.length,lineno=Math.max(Math.min(maxLines,lineno-1),0);frame.pre_context=lines.slice(Math.max(0,lineno-linesOfContext),lineno).map(function(line){return string_1.snipLine(line,0)}),frame.context_line=string_1.snipLine(lines[Math.min(maxLines-1,lineno)],frame.colno||0),frame.post_context=lines.slice(Math.min(lineno+1,maxLines),lineno+1+linesOfContext).map(function(line){return string_1.snipLine(line,0)})},exports.stripUrlQueryAndFragment=function(urlPath){return urlPath.split(/[\?#]/,1)[0]}}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./node":89,"./string":95}],89:[function(require,module,exports){!function(process){!function(){Object.defineProperty(exports,"__esModule",{value:!0});var is_1=require("./is"),object_1=require("./object");function isNodeEnv(){return"[object process]"===Object.prototype.toString.call(void 0!==process?process:0)}function dynamicRequire(mod,request){return mod.require(request)}exports.isNodeEnv=isNodeEnv,exports.dynamicRequire=dynamicRequire;var DEFAULT_REQUEST_KEYS=["cookies","data","headers","method","query_string","url"];exports.extractNodeRequestData=function(req,keys){var requestData,headers,method,host,protocol,originalUrl,absoluteUrl;if(void 0===keys&&(keys=DEFAULT_REQUEST_KEYS),isNodeEnv())return requestData={},headers=req.headers||req.header||{},method=req.method,host=req.hostname||req.host||headers.host||"<no host>",protocol="https"===req.protocol||req.secure||(req.socket||{}).encrypted?"https":"http",originalUrl=req.originalUrl||req.url||"",absoluteUrl=protocol+"://"+host+originalUrl,keys.forEach(function(key){switch(key){case"headers":requestData.headers=headers;break;case"method":requestData.method=method;break;case"url":requestData.url=absoluteUrl;break;case"cookies":requestData.cookies=req.cookies||dynamicRequire(module,"cookie").parse(headers.cookie||"");break;case"query_string":requestData.query_string=dynamicRequire(module,"url").parse(originalUrl||"",!1).query;break;case"data":"GET"!==method&&"HEAD"!==method&&void 0!==req.body&&(requestData.data=is_1.isString(req.body)?req.body:JSON.stringify(object_1.normalize(req.body)));break;default:!{}.hasOwnProperty.call(req,key)||(requestData[key]=req[key])}}),requestData;throw new Error("Can't get node request data outside of a node environment")}}.call(this)}.call(this,require("_process"))},{"./is":85,"./object":90,_process:1042}],90:[function(require,module,exports){!function(global){!function(){Object.defineProperty(exports,"__esModule",{value:!0});var tslib_1=require("tslib"),browser_1=require("./browser"),is_1=require("./is"),memo_1=require("./memo"),stacktrace_1=require("./stacktrace"),string_1=require("./string");function getWalkSource(value){if(is_1.isError(value)){var error=value,err={message:error.message,name:error.name,stack:error.stack};for(i in error)Object.prototype.hasOwnProperty.call(error,i)&&(err[i]=error[i]);return err}if(is_1.isEvent(value)){var i,event_1=value,source={};source.type=event_1.type;try{source.target=is_1.isElement(event_1.target)?browser_1.htmlTreeAsString(event_1.target):Object.prototype.toString.call(event_1.target)}catch(_oO){source.target="<unknown>"}try{source.currentTarget=is_1.isElement(event_1.currentTarget)?browser_1.htmlTreeAsString(event_1.currentTarget):Object.prototype.toString.call(event_1.currentTarget)}catch(_oO){source.currentTarget="<unknown>"}for(i in"undefined"!=typeof CustomEvent&&is_1.isInstanceOf(value,CustomEvent)&&(source.detail=event_1.detail),event_1)Object.prototype.hasOwnProperty.call(event_1,i)&&(source[i]=event_1);return source}return value}function jsonSize(value){return function(value){return~-encodeURI(value).split(/%..|./).length}(JSON.stringify(value))}function normalizeValue(value,key){return"domain"===key&&value&&"object"==typeof value&&value._events?"[Domain]":"domainEmitter"===key?"[DomainEmitter]":void 0!==global&&value===global?"[Global]":"undefined"!=typeof window&&value===window?"[Window]":"undefined"!=typeof document&&value===document?"[Document]":is_1.isSyntheticEvent(value)?"[SyntheticEvent]":"number"==typeof value&&value!=value?"[NaN]":void 0===value?"[undefined]":"function"==typeof value?"[Function: "+stacktrace_1.getFunctionName(value)+"]":"symbol"==typeof value?"["+String(value)+"]":"bigint"==typeof value?"[BigInt: "+String(value)+"]":value}function walk(key,value,depth,memo){if(void 0===depth&&(depth=1/0),void 0===memo&&(memo=new memo_1.Memo),0===depth)return function(value){var type=Object.prototype.toString.call(value);return"string"==typeof value?value:"[object Object]"===type?"[Object]":"[object Array]"===type?"[Array]":(value=normalizeValue(value),is_1.isPrimitive(value)?value:type)}(value);if(null!=value&&"function"==typeof value.toJSON)return value.toJSON();key=normalizeValue(value,key);if(is_1.isPrimitive(key))return key;var innerKey,source=getWalkSource(value),acc=Array.isArray(value)?[]:{};if(memo.memoize(value))return"[Circular ~]";for(innerKey in source)Object.prototype.hasOwnProperty.call(source,innerKey)&&(acc[innerKey]=walk(innerKey,source[innerKey],depth-1,memo));return memo.unmemoize(value),acc}function normalize(input,depth){try{return JSON.parse(JSON.stringify(input,function(key,value){return walk(key,value,depth)}))}catch(_oO){return"**non-serializable**"}}exports.fill=function(source,name,replacementFactory){if(name in source){var original=source[name],replacementFactory=replacementFactory(original);if("function"==typeof replacementFactory)try{replacementFactory.prototype=replacementFactory.prototype||{},Object.defineProperties(replacementFactory,{__sentry_original__:{enumerable:!1,value:original}})}catch(_Oo){}source[name]=replacementFactory}},exports.urlEncode=function(object){return Object.keys(object).map(function(key){return encodeURIComponent(key)+"="+encodeURIComponent(object[key])}).join("&")},exports.normalizeToSize=function normalizeToSize(object,depth,maxSize){void 0===maxSize&&(maxSize=102400);var serialized=normalize(object,depth=void 0===depth?3:depth);return jsonSize(serialized)>maxSize?normalizeToSize(object,depth-1,maxSize):serialized},exports.walk=walk,exports.normalize=normalize,exports.extractExceptionKeysForMessage=function(exception,maxLength){void 0===maxLength&&(maxLength=40);var keys=Object.keys(getWalkSource(exception));if(keys.sort(),!keys.length)return"[object has no keys]";if(keys[0].length>=maxLength)return string_1.truncate(keys[0],maxLength);for(var includedKeys=keys.length;0<includedKeys;includedKeys--){var serialized=keys.slice(0,includedKeys).join(", ");if(!(serialized.length>maxLength))return includedKeys===keys.length?serialized:string_1.truncate(serialized,maxLength)}return""},exports.dropUndefinedKeys=function dropUndefinedKeys(val){var e_1,_a;if(is_1.isPlainObject(val)){var obj=val,rv={};try{for(var _b=tslib_1.__values(Object.keys(obj)),_c=_b.next();!_c.done;_c=_b.next()){var key=_c.value;void 0!==obj[key]&&(rv[key]=dropUndefinedKeys(obj[key]))}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_c&&!_c.done&&(_a=_b.return)&&_a.call(_b)}finally{if(e_1)throw e_1.error}}return rv}return Array.isArray(val)?val.map(dropUndefinedKeys):val}}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./browser":80,"./is":85,"./memo":87,"./stacktrace":94,"./string":95,tslib:1698}],91:[function(require,module,exports){function normalizeArray(parts,allowAboveRoot){for(var up=0,i=parts.length-1;0<=i;i--){var last=parts[i];"."===last?parts.splice(i,1):".."===last?(parts.splice(i,1),up++):up&&(parts.splice(i,1),up--)}if(allowAboveRoot)for(;up--;)parts.unshift("..");return parts}Object.defineProperty(exports,"__esModule",{value:!0});var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/;function splitPath(filename){filename=splitPathRe.exec(filename);return filename?filename.slice(1):[]}function resolve(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];for(var resolvedPath="",resolvedAbsolute=!1,i=args.length-1;-1<=i&&!resolvedAbsolute;i--){var path=0<=i?args[i]:"/";path&&(resolvedPath=path+"/"+resolvedPath,resolvedAbsolute="/"===path.charAt(0))}return(resolvedAbsolute?"/":"")+(resolvedPath=normalizeArray(resolvedPath.split("/").filter(function(p){return!!p}),!resolvedAbsolute).join("/"))||"."}function trim(arr){for(var start=0;start<arr.length&&""===arr[start];start++);for(var end=arr.length-1;0<=end&&""===arr[end];end--);return end<start?[]:arr.slice(start,end-start+1)}function normalizePath(path){var isPathAbsolute=isAbsolute(path),trailingSlash="/"===path.substr(-1),path=normalizeArray(path.split("/").filter(function(p){return!!p}),!isPathAbsolute).join("/");return(path=path||isPathAbsolute?path:".")&&trailingSlash&&(path+="/"),(isPathAbsolute?"/":"")+path}function isAbsolute(path){return"/"===path.charAt(0)}exports.resolve=resolve,exports.relative=function(from,to){from=resolve(from).substr(1),to=resolve(to).substr(1);for(var fromParts=trim(from.split("/")),toParts=trim(to.split("/")),length=Math.min(fromParts.length,toParts.length),samePartsLength=length,i=0;i<length;i++)if(fromParts[i]!==toParts[i]){samePartsLength=i;break}for(var outputParts=[],i=samePartsLength;i<fromParts.length;i++)outputParts.push("..");return(outputParts=outputParts.concat(toParts.slice(samePartsLength))).join("/")},exports.normalizePath=normalizePath,exports.isAbsolute=isAbsolute,exports.join=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return normalizePath(args.join("/"))},exports.dirname=function(path){var root=(path=splitPath(path))[0],path=path[1];return root||path?root+(path=path&&path.substr(0,path.length-1)):"."},exports.basename=function(path,ext){return path=splitPath(path)[2],path=ext&&path.substr(-1*ext.length)===ext?path.substr(0,path.length-ext.length):path}},{}],92:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPrototypeOf=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(obj,proto){return obj.__proto__=proto,obj}:function(obj,proto){for(var prop in proto)obj.hasOwnProperty(prop)||(obj[prop]=proto[prop]);return obj})},{}],93:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var error_1=require("./error"),syncpromise_1=require("./syncpromise"),require=function(){function PromiseBuffer(_limit){this._limit=_limit,this._buffer=[]}return PromiseBuffer.prototype.isReady=function(){return void 0===this._limit||this.length()<this._limit},PromiseBuffer.prototype.add=function(task){var _this=this;return this.isReady()?(-1===this._buffer.indexOf(task)&&this._buffer.push(task),task.then(function(){return _this.remove(task)}).then(null,function(){return _this.remove(task).then(null,function(){})}),task):syncpromise_1.SyncPromise.reject(new error_1.SentryError("Not adding Promise due to buffer limit reached."))},PromiseBuffer.prototype.remove=function(task){return this._buffer.splice(this._buffer.indexOf(task),1)[0]},PromiseBuffer.prototype.length=function(){return this._buffer.length},PromiseBuffer.prototype.drain=function(timeout){var _this=this;return new syncpromise_1.SyncPromise(function(resolve){var capturedSetTimeout=setTimeout(function(){timeout&&0<timeout&&resolve(!1)},timeout);syncpromise_1.SyncPromise.all(_this._buffer).then(function(){clearTimeout(capturedSetTimeout),resolve(!0)}).then(null,function(){resolve(!0)})})},PromiseBuffer}();exports.PromiseBuffer=require},{"./error":82,"./syncpromise":97}],94:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});exports.getFunctionName=function(fn){try{return fn&&"function"==typeof fn?fn.name||"<anonymous>":"<anonymous>"}catch(e){return"<anonymous>"}}},{}],95:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var is_1=require("./is");exports.truncate=function(str,max){return void 0===max&&(max=0),"string"!=typeof str||0===max||str.length<=max?str:str.substr(0,max)+"..."},exports.snipLine=function(line,colno){var end,ll=line.length;return ll<=150||(ll<colno&&(colno=ll),(colno=Math.max(colno-60,0))<5&&(colno=0),(end=ll-5<(end=Math.min(colno+140,ll))?ll:end)===ll&&(colno=Math.max(end-140,0)),line=line.slice(colno,end),0<colno&&(line="'{snip} "+line),end<ll&&(line+=" {snip}")),line},exports.safeJoin=function(input,delimiter){if(!Array.isArray(input))return"";for(var output=[],i=0;i<input.length;i++){var value=input[i];try{output.push(String(value))}catch(e){output.push("[value cannot be serialized]")}}return output.join(delimiter)},exports.isMatchingPattern=function(value,pattern){return!!is_1.isString(value)&&(is_1.isRegExp(pattern)?pattern.test(value):"string"==typeof pattern&&-1!==value.indexOf(pattern))}},{"./is":85}],96:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var logger_1=require("./logger"),misc_1=require("./misc");function supportsFetch(){if(!("fetch"in misc_1.getGlobalObject()))return!1;try{return new Headers,new Request(""),new Response,!0}catch(e){return!1}}function isNativeFetch(func){return func&&/^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString())}exports.supportsErrorEvent=function(){try{return new ErrorEvent(""),!0}catch(e){return!1}},exports.supportsDOMError=function(){try{return new DOMError(""),!0}catch(e){return!1}},exports.supportsDOMException=function(){try{return new DOMException(""),!0}catch(e){return!1}},exports.supportsFetch=supportsFetch,exports.supportsNativeFetch=function(){if(!supportsFetch())return!1;var global=misc_1.getGlobalObject();if(isNativeFetch(global.fetch))return!0;var result=!1;if((global=global.document)&&"function"==typeof global.createElement)try{var sandbox=global.createElement("iframe");sandbox.hidden=!0,global.head.appendChild(sandbox),sandbox.contentWindow&&sandbox.contentWindow.fetch&&(result=isNativeFetch(sandbox.contentWindow.fetch)),global.head.removeChild(sandbox)}catch(err){logger_1.logger.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",err)}return result},exports.supportsReportingObserver=function(){return"ReportingObserver"in misc_1.getGlobalObject()},exports.supportsReferrerPolicy=function(){if(!supportsFetch())return!1;try{return new Request("_",{referrerPolicy:"origin"}),!0}catch(e){return!1}},exports.supportsHistory=function(){var global=misc_1.getGlobalObject(),chrome=(chrome=global.chrome)&&chrome.app&&chrome.app.runtime,global="history"in global&&!!global.history.pushState&&!!global.history.replaceState;return!chrome&&global}},{"./logger":86,"./misc":88}],97:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var States,is_1=require("./is"),require=(!function(States){States.PENDING="PENDING",States.RESOLVED="RESOLVED",States.REJECTED="REJECTED"}(States=States||{}),function(){function SyncPromise(executor){var _this=this;this._state=States.PENDING,this._handlers=[],this._resolve=function(value){_this._setResult(States.RESOLVED,value)},this._reject=function(reason){_this._setResult(States.REJECTED,reason)},this._setResult=function(state,value){_this._state===States.PENDING&&(is_1.isThenable(value)?value.then(_this._resolve,_this._reject):(_this._state=state,_this._value=value,_this._executeHandlers()))},this._attachHandler=function(handler){_this._handlers=_this._handlers.concat(handler),_this._executeHandlers()},this._executeHandlers=function(){var cachedHandlers;_this._state!==States.PENDING&&(cachedHandlers=_this._handlers.slice(),_this._handlers=[],cachedHandlers.forEach(function(handler){handler.done||(_this._state===States.RESOLVED&&handler.onfulfilled&&handler.onfulfilled(_this._value),_this._state===States.REJECTED&&handler.onrejected&&handler.onrejected(_this._value),handler.done=!0)}))};try{executor(this._resolve,this._reject)}catch(e){this._reject(e)}}return SyncPromise.resolve=function(value){return new SyncPromise(function(resolve){resolve(value)})},SyncPromise.reject=function(reason){return new SyncPromise(function(_,reject){reject(reason)})},SyncPromise.all=function(collection){return new SyncPromise(function(resolve,reject){var counter,resolvedCollection;Array.isArray(collection)?0===collection.length?resolve([]):(counter=collection.length,resolvedCollection=[],collection.forEach(function(item,index){SyncPromise.resolve(item).then(function(value){resolvedCollection[index]=value,0==--counter&&resolve(resolvedCollection)}).then(null,reject)})):reject(new TypeError("Promise.all requires an array as input."))})},SyncPromise.prototype.then=function(onfulfilled,onrejected){var _this=this;return new SyncPromise(function(resolve,reject){_this._attachHandler({done:!1,onfulfilled:function(result){if(onfulfilled)try{resolve(onfulfilled(result))}catch(e){reject(e)}else resolve(result)},onrejected:function(reason){if(onrejected)try{resolve(onrejected(reason))}catch(e){reject(e)}else reject(reason)}})})},SyncPromise.prototype.catch=function(onrejected){return this.then(function(val){return val},onrejected)},SyncPromise.prototype.finally=function(onfinally){var _this=this;return new SyncPromise(function(resolve,reject){var val,isRejected;_this.then(function(value){isRejected=!1,val=value,onfinally&&onfinally()},function(reason){isRejected=!0,val=reason,onfinally&&onfinally()}).then(function(){(isRejected?reject:resolve)(val)})})},SyncPromise.prototype.toString=function(){return"[object SyncPromise]"},SyncPromise}());exports.SyncPromise=require},{"./is":85}],98:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0});var misc_1=require("./misc"),node_1=require("./node"),require={nowSeconds:function(){return Date.now()/1e3}};var platformPerformance=(node_1.isNodeEnv()?function(){try{return node_1.dynamicRequire(module,"perf_hooks").performance}catch(_){}}:function(){var performance=misc_1.getGlobalObject().performance;if(performance&&performance.now)return{now:function(){return performance.now()},timeOrigin:Date.now()-performance.now()}})(),timestampSource=void 0===platformPerformance?require:{nowSeconds:function(){return(platformPerformance.timeOrigin+platformPerformance.now())/1e3}};exports.dateTimestampInSeconds=require.nowSeconds.bind(require),exports.timestampInSeconds=timestampSource.nowSeconds.bind(timestampSource),exports.timestampWithMs=exports.timestampInSeconds,exports.usingPerformanceAPI=void 0!==platformPerformance,exports.browserPerformanceTimeOrigin=function(){var performance=misc_1.getGlobalObject().performance;if(performance)return performance.timeOrigin||performance.timing&&performance.timing.navigationStart||Date.now()}()},{"./misc":88,"./node":89}],99:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireWildcard=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireWildcard(require("prop-types"))),_useEventListener=_interopRequireDefault(require("./useEventListener"));function EventListener(props){return(0,_useEventListener.default)(props),null}EventListener.displayName="EventListener",EventListener.propTypes="production"!==process.env.NODE_ENV?{capture:_interopRequireWildcard.bool,listener:_interopRequireWildcard.func.isRequired,targetRef:_interopRequireWildcard.shape({current:_interopRequireWildcard.object}).isRequired,type:_interopRequireWildcard.string.isRequired}:{},EventListener.defaultProps={capture:!1},exports.default=EventListener}.call(this)}.call(this,require("_process"))},{"./useEventListener":102,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,_process:1042,"prop-types":1046}],100:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_exportNames=(Object.defineProperty(exports,"__esModule",{value:!0}),{documentRef:!0,windowRef:!0,EventListener:!0,useEventListener:!0}),_EventListener=(Object.defineProperty(exports,"EventListener",{enumerable:!0,get:function(){return _EventListener.default}}),Object.defineProperty(exports,"useEventListener",{enumerable:!0,get:function(){return _useEventListener.default}}),exports.windowRef=exports.documentRef=void 0,_interopRequireDefault(require("./EventListener"))),_types=require("./types"),_useEventListener=(Object.keys(_types).forEach(function(key){"default"===key||"__esModule"===key||Object.prototype.hasOwnProperty.call(_exportNames,key)||Object.defineProperty(exports,key,{enumerable:!0,get:function(){return _types[key]}})}),_interopRequireDefault(require("./useEventListener"))),_interopRequireDefault={current:"undefined"==typeof document?null:document},require=(exports.documentRef=_interopRequireDefault,{current:"undefined"==typeof window?null:window});exports.windowRef=require},{"./EventListener":99,"./types":101,"./useEventListener":102,"@babel/runtime/helpers/interopRequireDefault":13}],101:[function(require,module,exports){},{}],102:[function(require,module,exports){!function(process){!function(){"use strict";function isActionSupported(targetRef,method){return targetRef&&!!targetRef.current&&!!targetRef.current[method]}var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),React=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireWildcard(require("react")));exports.default=function(options){var capture=options.capture,listener=options.listener,type=options.type,targetRef=options.targetRef,latestListener=React.useRef(listener),eventHandler=(latestListener.current=listener,React.useCallback(function(event){return latestListener.current(event)},[]));React.useEffect(function(){if(isActionSupported(targetRef,"addEventListener"))targetRef.current.addEventListener(type,eventHandler,capture);else if("production"!==process.env.NODE_ENV)throw new Error("@stardust-ui/react-component-event-listener: Passed `targetRef` is not valid or does not support `addEventListener()` method.");return function(){if(isActionSupported(targetRef,"removeEventListener"))targetRef.current.removeEventListener(type,eventHandler,capture);else if("production"!==process.env.NODE_ENV)throw new Error("@stardust-ui/react-component-event-listener: Passed `targetRef` is not valid or does not support `removeEventListener()` method.")}},[capture,targetRef,type])}}.call(this)}.call(this,require("_process"))},{"@babel/runtime/helpers/interopRequireWildcard":14,_process:1042,react:1427}],103:[function(require,module,exports){!function(process){!function(){"use strict";function Ref(props){var children=props.children,props=props.innerRef,children=React.Children.only(children),ElementType=(ReactIs.isForwardRef(children)?_RefForward:_RefFindNode).default;return React.createElement(ElementType,{innerRef:props},children)}var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),PropTypes=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireWildcard(require("prop-types"))),React=_interopRequireWildcard(require("react")),ReactIs=_interopRequireWildcard(require("react-is")),_RefFindNode=_interopRequireDefault(require("./RefFindNode")),_RefForward=_interopRequireDefault(require("./RefForward")),_interopRequireWildcard=require("./types");Ref.displayName="Ref","production"!==process.env.NODE_ENV&&(Ref.propTypes={children:PropTypes.element.isRequired,innerRef:_interopRequireWildcard.refPropType.isRequired}),exports.default=Ref}.call(this)}.call(this,require("_process"))},{"./RefFindNode":104,"./RefForward":105,"./types":110,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,_process:1042,"prop-types":1046,react:1427,"react-is":1385}],104:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_classCallCheck2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"))),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),PropTypes=_interopRequireWildcard(require("prop-types")),React=_interopRequireWildcard(require("react")),ReactDOM=_interopRequireWildcard(require("react-dom")),_handleRef=_interopRequireDefault(require("./handleRef")),_interopRequireWildcard=require("./types"),_interopRequireDefault=function(_React$Component){function RefFindNode(){var _getPrototypeOf2;(0,_classCallCheck2.default)(this,RefFindNode);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _getPrototypeOf2=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(RefFindNode)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_getPrototypeOf2),"prevNode",null),_getPrototypeOf2}return(0,_inherits2.default)(RefFindNode,_React$Component),(0,_createClass2.default)(RefFindNode,[{key:"componentDidMount",value:function(){this.prevNode=ReactDOM.findDOMNode(this),(0,_handleRef.default)(this.props.innerRef,this.prevNode)}},{key:"componentDidUpdate",value:function(prevProps){var currentNode=ReactDOM.findDOMNode(this);this.prevNode!==currentNode&&(this.prevNode=currentNode,(0,_handleRef.default)(this.props.innerRef,currentNode)),prevProps.innerRef!==this.props.innerRef&&(0,_handleRef.default)(this.props.innerRef,currentNode)}},{key:"componentWillUnmount",value:function(){(0,_handleRef.default)(this.props.innerRef,null)}},{key:"render",value:function(){return this.props.children}}]),RefFindNode}(React.Component);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"displayName","RefFindNode"),(0,_defineProperty2.default)(_interopRequireDefault,"propTypes","production"!==process.env.NODE_ENV?{children:PropTypes.element.isRequired,innerRef:_interopRequireWildcard.refPropType.isRequired}:{})}.call(this)}.call(this,require("_process"))},{"./handleRef":106,"./types":110,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"prop-types":1046,react:1427,"react-dom":1382}],105:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_classCallCheck2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"))),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),PropTypes=_interopRequireWildcard(require("prop-types")),React=_interopRequireWildcard(require("react")),_handleRef=_interopRequireDefault(require("./handleRef")),_interopRequireWildcard=require("./types"),_interopRequireDefault=function(_React$Component){function RefForward(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,RefForward);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(RefForward)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleRefOverride",function(node){var _this$props=_this.props,children=_this$props.children,_this$props=_this$props.innerRef;(0,_handleRef.default)(children.ref,node),(0,_handleRef.default)(_this$props,node)}),_this}return(0,_inherits2.default)(RefForward,_React$Component),(0,_createClass2.default)(RefForward,[{key:"render",value:function(){var children=this.props.children;return React.cloneElement(children,{ref:this.handleRefOverride})}}]),RefForward}(React.Component);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"displayName","RefForward"),(0,_defineProperty2.default)(_interopRequireDefault,"propTypes","production"!==process.env.NODE_ENV?{children:PropTypes.element.isRequired,innerRef:_interopRequireWildcard.refPropType.isRequired}:{})}.call(this)}.call(this,require("_process"))},{"./handleRef":106,"./types":110,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"prop-types":1046,react:1427}],106:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_typeof2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/typeof")));exports.default=function(ref,node){if("production"!==process.env.NODE_ENV&&"string"==typeof ref)throw new Error("We do not support refs as string, this is a legacy API and will be likely to be removed in one of the future releases of React.");"function"==typeof ref?ref(node):null!==ref&&"object"===(0,_typeof2.default)(ref)&&(ref.current=node)}}.call(this)}.call(this,require("_process"))},{"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":30,_process:1042}],107:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_exportNames=(Object.defineProperty(exports,"__esModule",{value:!0}),{handleRef:!0,isRefObject:!0,toRefObject:!0,Ref:!0,RefFindNode:!0,RefForward:!0}),_handleRef=(Object.defineProperty(exports,"handleRef",{enumerable:!0,get:function(){return _handleRef.default}}),Object.defineProperty(exports,"isRefObject",{enumerable:!0,get:function(){return _isRefObject.default}}),Object.defineProperty(exports,"toRefObject",{enumerable:!0,get:function(){return _toRefObject.default}}),Object.defineProperty(exports,"Ref",{enumerable:!0,get:function(){return _Ref.default}}),Object.defineProperty(exports,"RefFindNode",{enumerable:!0,get:function(){return _RefFindNode.default}}),Object.defineProperty(exports,"RefForward",{enumerable:!0,get:function(){return _RefForward.default}}),_interopRequireDefault(require("./handleRef"))),_isRefObject=_interopRequireDefault(require("./isRefObject")),_toRefObject=_interopRequireDefault(require("./toRefObject")),_Ref=_interopRequireDefault(require("./Ref")),_RefFindNode=_interopRequireDefault(require("./RefFindNode")),_RefForward=_interopRequireDefault(require("./RefForward")),_types=require("./types");Object.keys(_types).forEach(function(key){"default"===key||"__esModule"===key||Object.prototype.hasOwnProperty.call(_exportNames,key)||Object.defineProperty(exports,key,{enumerable:!0,get:function(){return _types[key]}})})},{"./Ref":103,"./RefFindNode":104,"./RefForward":105,"./handleRef":106,"./isRefObject":108,"./toRefObject":109,"./types":110,"@babel/runtime/helpers/interopRequireDefault":13}],108:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_typeof2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/typeof")));exports.default=function(ref){return null!==ref&&"object"===(0,_typeof2.default)(ref)&&ref.hasOwnProperty("current")}},{"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":30}],109:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var nullRefObject={current:null},refObjects=new WeakMap;exports.default=function(node){return null===node?nullRefObject:refObjects.has(node)?refObjects.get(node):(refObjects.set(node,node={current:node}),node)}},{}],110:[function(require,module,exports){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireWildcard=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.refPropType=void 0,_interopRequireWildcard(require("prop-types"))),require=_interopRequireWildcard.oneOfType([_interopRequireWildcard.func,_interopRequireWildcard.object]);exports.refPropType=require},{"@babel/runtime/helpers/interopRequireWildcard":14,"prop-types":1046}],111:[function(require,module,exports){"use strict";exports.byteLength=function(b64){var b64=getLens(b64),validLen=b64[0],b64=b64[1];return 3*(validLen+b64)/4-b64},exports.toByteArray=function(b64){var tmp,i,lens=getLens(b64),validLen=lens[0],lens=lens[1],arr=new Arr(function(validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}(validLen,lens)),curByte=0,len=0<lens?validLen-4:validLen;for(i=0;i<len;i+=4)tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)],arr[curByte++]=tmp>>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp;2===lens&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp);1===lens&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp);return arr},exports.fromByteArray=function(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,parts=[],i=0,len2=len-extraBytes;i<len2;i+=16383)parts.push(function(uint8,start,end){for(var tmp,output=[],i=start;i<end;i+=3)tmp=(uint8[i]<<16&16711680)+(uint8[i+1]<<8&65280)+(255&uint8[i+2]),output.push(function(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}(tmp));return output.join("")}(uint8,i,len2<i+16383?len2:i+16383));1==extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):2==extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"="));return parts.join("")};for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;function getLens(b64){var len=b64.length;if(0<len%4)throw new Error("Invalid string. Length must be a multiple of 4");b64=b64.indexOf("="),len=(b64=-1===b64?len:b64)===len?0:4-b64%4;return[b64,len]}revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},{}],112:[function(require,module,exports){!function(process,global,setImmediate){!function(){!function(e){var f;"object"==typeof exports&&void 0!==module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?f=window:void 0!==global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e())}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof _dereq_&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}a=n[o]={exports:{}};t[o][0].call(a.exports,function(e){var n=t[o][1][e];return s(n||e)},a,a.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof _dereq_&&_dereq_,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var SomePromiseArray=Promise._SomePromiseArray;function any(promises){var promises=new SomePromiseArray(promises),promise=promises.promise();return promises.setHowMany(1),promises.setUnwrap(),promises.init(),promise}Promise.any=any,Promise.prototype.any=function(){return any(this)}}},{}],2:[function(_dereq_,module,exports){"use strict";var firstLineError;try{throw new Error}catch(e){firstLineError=e}var schedule=_dereq_("./schedule"),Queue=_dereq_("./queue");function Async(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new Queue(16),this._normalQueue=new Queue(16),this._haveDrainedQueues=!1;var self=this;this.drainQueues=function(){self._drainQueues()},this._schedule=schedule}function _drainQueue(queue){for(;0<queue.length();)!function(queue){var fn=queue.shift();{var receiver;"function"!=typeof fn?fn._settlePromises():(receiver=queue.shift(),queue=queue.shift(),fn.call(receiver,queue))}}(queue)}Async.prototype.setScheduler=function(fn){var prev=this._schedule;return this._schedule=fn,this._customScheduler=!0,prev},Async.prototype.hasCustomScheduler=function(){return this._customScheduler},Async.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},Async.prototype.fatalError=function(e,isNode){isNode?(process.stderr.write("Fatal "+(e instanceof Error?e.stack:e)+"\n"),process.exit(2)):this.throwLater(e)},Async.prototype.throwLater=function(fn,arg){if(1===arguments.length&&(arg=fn,fn=function(){throw arg}),"undefined"!=typeof setTimeout)setTimeout(function(){fn(arg)},0);else try{this._schedule(function(){fn(arg)})}catch(e){throw new Error("No async scheduler available\n\n    See http://goo.gl/MqrFmX\n")}},Async.prototype.invokeLater=function(fn,receiver,arg){this._lateQueue.push(fn,receiver,arg),this._queueTick()},Async.prototype.invoke=function(fn,receiver,arg){this._normalQueue.push(fn,receiver,arg),this._queueTick()},Async.prototype.settlePromises=function(promise){this._normalQueue._pushOne(promise),this._queueTick()},Async.prototype._drainQueues=function(){_drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,_drainQueue(this._lateQueue)},Async.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},Async.prototype._reset=function(){this._isTickUsed=!1},module.exports=Async,module.exports.firstLineError=firstLineError},{"./queue":26,"./schedule":29}],3:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,debug){function rejectThis(_,e){this._reject(e)}function targetRejected(e,context){context.promiseRejectionQueued=!0,context.bindingPromise._then(rejectThis,rejectThis,null,this,e)}function bindingResolved(thisArg,context){0==(50397184&this._bitField)&&this._resolveCallback(context.target)}function bindingRejected(e,context){context.promiseRejectionQueued||this._reject(e)}var calledBind=!1;Promise.prototype.bind=function(thisArg){calledBind||(calledBind=!0,Promise.prototype._propagateFrom=debug.propagateFromFunction(),Promise.prototype._boundValue=debug.boundValueFunction());var context,thisArg=tryConvertToPromise(thisArg),ret=new Promise(INTERNAL),target=(ret._propagateFrom(this,1),this._target());return ret._setBoundTo(thisArg),thisArg instanceof Promise?(target._then(INTERNAL,targetRejected,void 0,ret,context={promiseRejectionQueued:!1,promise:ret,target:target,bindingPromise:thisArg}),thisArg._then(bindingResolved,bindingRejected,void 0,ret,context),ret._setOnCancel(thisArg)):ret._resolveCallback(target),ret},Promise.prototype._setBoundTo=function(obj){void 0!==obj?(this._bitField=2097152|this._bitField,this._boundTo=obj):this._bitField=-2097153&this._bitField},Promise.prototype._isBound=function(){return 2097152==(2097152&this._bitField)},Promise.bind=function(thisArg,value){return Promise.resolve(value).bind(thisArg)}}},{}],4:[function(_dereq_,module,exports){"use strict";var old;"undefined"!=typeof Promise&&(old=Promise);var bluebird=_dereq_("./promise")();bluebird.noConflict=function(){try{Promise===bluebird&&(Promise=old)}catch(e){}return bluebird},module.exports=bluebird},{"./promise":22}],5:[function(_dereq_,module,exports){"use strict";var callerCache,cr=Object.create;cr&&(callerCache=cr(null),cr=cr(null),callerCache[" size"]=cr[" size"]=0),module.exports=function(Promise){var getGetter,util=_dereq_("./util"),canEvaluate=util.canEvaluate;util.isIdentifier;function ensureMethod(obj,methodName){var fn;if("function"!=typeof(fn=null!=obj?obj[methodName]:fn))throw obj="Object "+util.classString(obj)+" has no method '"+util.toString(methodName)+"'",new Promise.TypeError(obj);return fn}function caller(obj){return ensureMethod(obj,this.pop()).apply(obj,this)}function namedGetter(obj){return obj[this]}function indexedGetter(obj){var index=+this;return obj[index=index<0?Math.max(0,index+obj.length):index]}Promise.prototype.call=function(methodName){var args=[].slice.call(arguments,1);return args.push(methodName),this._then(caller,void 0,void 0,args,void 0)},Promise.prototype.get=function(propertyName){var maybeGetter;return maybeGetter="number"==typeof propertyName?indexedGetter:canEvaluate&&null!==(maybeGetter=getGetter(propertyName))?maybeGetter:namedGetter,this._then(maybeGetter,void 0,void 0,propertyName,void 0)}}},{"./util":36}],6:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,debug){var util=_dereq_("./util"),tryCatch=util.tryCatch,errorObj=util.errorObj,async=Promise._async;Promise.prototype.break=Promise.prototype.cancel=function(){if(!debug.cancellation())return this._warn("cancellation is disabled");for(var promise=this,child=promise;promise._isCancellable();){if(!promise._cancelBy(child)){child._isFollowing()?child._followee().cancel():child._cancelBranched();break}var parent=promise._cancellationParent;if(null==parent||!parent._isCancellable()){promise._isFollowing()?promise._followee().cancel():promise._cancelBranched();break}promise._isFollowing()&&promise._followee().cancel(),promise._setWillBeCancelled(),child=promise,promise=parent}},Promise.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},Promise.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},Promise.prototype._cancelBy=function(canceller){return canceller===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},Promise.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},Promise.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),async.invoke(this._cancelPromises,this,void 0))},Promise.prototype._cancelPromises=function(){0<this._length()&&this._settlePromises()},Promise.prototype._unsetOnCancel=function(){this._onCancelField=void 0},Promise.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},Promise.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},Promise.prototype._doInvokeOnCancel=function(onCancelCallback,internalOnly){var e;if(util.isArray(onCancelCallback))for(var i=0;i<onCancelCallback.length;++i)this._doInvokeOnCancel(onCancelCallback[i],internalOnly);else void 0!==onCancelCallback&&("function"==typeof onCancelCallback?internalOnly||(e=tryCatch(onCancelCallback).call(this._boundValue()))===errorObj&&(this._attachExtraTrace(e.e),async.throwLater(e.e)):onCancelCallback._resultCancelled(this))},Promise.prototype._invokeOnCancel=function(){var onCancelCallback=this._onCancel();this._unsetOnCancel(),async.invoke(this._doInvokeOnCancel,this,onCancelCallback)},Promise.prototype._invokeInternalOnCancel=function(){this._isCancellable()&&(this._doInvokeOnCancel(this._onCancel(),!0),this._unsetOnCancel())},Promise.prototype._resultCancelled=function(){this.cancel()}}},{"./util":36}],7:[function(_dereq_,module,exports){"use strict";module.exports=function(NEXT_FILTER){var util=_dereq_("./util"),getKeys=_dereq_("./es5").keys,tryCatch=util.tryCatch,errorObj=util.errorObj;return function(instances,cb,promise){return function(e){var boundTo=promise._boundValue();predicateLoop:for(var i=0;i<instances.length;++i){var item=instances[i];if(item===Error||null!=item&&item.prototype instanceof Error){if(e instanceof item)return tryCatch(cb).call(boundTo,e)}else if("function"==typeof item){var matchesPredicate=tryCatch(item).call(boundTo,e);if(matchesPredicate===errorObj)return matchesPredicate;if(matchesPredicate)return tryCatch(cb).call(boundTo,e)}else if(util.isObject(e)){for(var keys=getKeys(item),j=0;j<keys.length;++j){var key=keys[j];if(item[key]!=e[key])continue predicateLoop}return tryCatch(cb).call(boundTo,e)}}return NEXT_FILTER}}}},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var longStackTraces=!1,contextStack=[];function Context(){this._trace=new Context.CapturedTrace(peekContext())}function peekContext(){var lastIndex=contextStack.length-1;if(0<=lastIndex)return contextStack[lastIndex]}return Promise.prototype._promiseCreated=function(){},Promise.prototype._pushContext=function(){},Promise.prototype._popContext=function(){return null},Promise._peekContext=Promise.prototype._peekContext=function(){},Context.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,contextStack.push(this._trace))},Context.prototype._popContext=function(){var trace,ret;return void 0!==this._trace?(ret=(trace=contextStack.pop())._promiseCreated,trace._promiseCreated=null,ret):null},Context.CapturedTrace=null,Context.create=function(){if(longStackTraces)return new Context},Context.deactivateLongStackTraces=function(){},Context.activateLongStackTraces=function(){var Promise_pushContext=Promise.prototype._pushContext,Promise_popContext=Promise.prototype._popContext,Promise_PeekContext=Promise._peekContext,Promise_peekContext=Promise.prototype._peekContext,Promise_promiseCreated=Promise.prototype._promiseCreated;Context.deactivateLongStackTraces=function(){Promise.prototype._pushContext=Promise_pushContext,Promise.prototype._popContext=Promise_popContext,Promise._peekContext=Promise_PeekContext,Promise.prototype._peekContext=Promise_peekContext,Promise.prototype._promiseCreated=Promise_promiseCreated,longStackTraces=!1},longStackTraces=!0,Promise.prototype._pushContext=Context.prototype._pushContext,Promise.prototype._popContext=Context.prototype._popContext,Promise._peekContext=Promise.prototype._peekContext=peekContext,Promise.prototype._promiseCreated=function(){var ctx=this._peekContext();ctx&&null==ctx._promiseCreated&&(ctx._promiseCreated=this)}},Context}},{}],9:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,Context,enableAsyncHooks,disableAsyncHooks){var unhandledRejectionHandled,possiblyUnhandledRejection,printWarning,deferUnhandledRejectionCheck,promises,async=Promise._async,Warning=_dereq_("./errors").Warning,util=_dereq_("./util"),es5=_dereq_("./es5"),canAttachTrace=util.canAttachTrace,bluebirdFramePattern=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,nodeFramePattern=/\((?:timers\.js):\d+:\d+\)/,parseLinePattern=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,stackFramePattern=null,formatStack=null,indentStackFrames=!1,debugging=!(0==util.env("BLUEBIRD_DEBUG")),warnings=!(0==util.env("BLUEBIRD_WARNINGS")||!debugging&&!util.env("BLUEBIRD_WARNINGS")),debugging=!(0==util.env("BLUEBIRD_LONG_STACK_TRACES")||!debugging&&!util.env("BLUEBIRD_LONG_STACK_TRACES")),wForgottenReturn=0!=util.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(warnings||!!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));function unhandledRejectionCheck(){for(var i=0;i<promises.length;++i)promises[i]._notifyUnhandledRejection();promises.length=0}function unhandledRejectionClear(){promises.length=0}promises=[],deferUnhandledRejectionCheck=function(promise){promises.push(promise),setTimeout(unhandledRejectionCheck,1)},es5.defineProperty(Promise,"_unhandledRejectionCheck",{value:unhandledRejectionCheck}),es5.defineProperty(Promise,"_unhandledRejectionClear",{value:unhandledRejectionClear}),Promise.prototype.suppressUnhandledRejections=function(){var target=this._target();target._bitField=-1048577&target._bitField|524288},Promise.prototype._ensurePossibleRejectionHandled=function(){0==(524288&this._bitField)&&(this._setRejectionIsUnhandled(),deferUnhandledRejectionCheck(this))},Promise.prototype._notifyUnhandledRejectionIsHandled=function(){fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,void 0,this)},Promise.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},Promise.prototype._returnedNonUndefined=function(){return 0!=(268435456&this._bitField)},Promise.prototype._notifyUnhandledRejection=function(){var reason;this._isRejectionUnhandled()&&(reason=this._settledValue(),this._setUnhandledRejectionIsNotified(),fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this))},Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},Promise.prototype._isUnhandledRejectionNotified=function(){return 0<(262144&this._bitField)},Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},Promise.prototype._isRejectionUnhandled=function(){return 0<(1048576&this._bitField)},Promise.prototype._warn=function(message,shouldUseOwnTrace,promise){return warn(message,shouldUseOwnTrace,promise||this)},Promise.onPossiblyUnhandledRejection=function(fn){var context=Promise._getContext();possiblyUnhandledRejection=util.contextBind(context,fn)},Promise.onUnhandledRejectionHandled=function(fn){var context=Promise._getContext();unhandledRejectionHandled=util.contextBind(context,fn)};var disableLongStackTraces=function(){},legacyHandlers=(Promise.longStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n    See http://goo.gl/MqrFmX\n");var Promise_captureStackTrace,Promise_attachExtraTrace,Promise_dereferenceTrace;!config.longStackTraces&&longStackTracesIsSupported()&&(Promise_captureStackTrace=Promise.prototype._captureStackTrace,Promise_attachExtraTrace=Promise.prototype._attachExtraTrace,Promise_dereferenceTrace=Promise.prototype._dereferenceTrace,config.longStackTraces=!0,disableLongStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n    See http://goo.gl/MqrFmX\n");Promise.prototype._captureStackTrace=Promise_captureStackTrace,Promise.prototype._attachExtraTrace=Promise_attachExtraTrace,Promise.prototype._dereferenceTrace=Promise_dereferenceTrace,Context.deactivateLongStackTraces(),config.longStackTraces=!1},Promise.prototype._captureStackTrace=longStackTracesCaptureStackTrace,Promise.prototype._attachExtraTrace=longStackTracesAttachExtraTrace,Promise.prototype._dereferenceTrace=longStackTracesDereferenceTrace,Context.activateLongStackTraces())},Promise.hasLongStackTraces=function(){return config.longStackTraces&&longStackTracesIsSupported()},{unhandledrejection:{before:function(){var ret=util.global.onunhandledrejection;return util.global.onunhandledrejection=null,ret},after:function(fn){util.global.onunhandledrejection=fn}},rejectionhandled:{before:function(){var ret=util.global.onrejectionhandled;return util.global.onrejectionhandled=null,ret},after:function(fn){util.global.onrejectionhandled=fn}}}),fireDomEvent=function(){function dispatch(legacy,e){if(!legacy)return!util.global.dispatchEvent(e);var fn;try{return fn=legacy.before(),!util.global.dispatchEvent(e)}finally{legacy.after(fn)}}var event;try{return"function"==typeof CustomEvent?(event=new CustomEvent("CustomEvent"),util.global.dispatchEvent(event),function(name,event){name=name.toLowerCase();var domEvent=new CustomEvent(name,{detail:event,cancelable:!0});return es5.defineProperty(domEvent,"promise",{value:event.promise}),es5.defineProperty(domEvent,"reason",{value:event.reason}),dispatch(legacyHandlers[name],domEvent)}):"function"==typeof Event?(event=new Event("CustomEvent"),util.global.dispatchEvent(event),function(name,event){name=name.toLowerCase();var domEvent=new Event(name,{cancelable:!0});return domEvent.detail=event,es5.defineProperty(domEvent,"promise",{value:event.promise}),es5.defineProperty(domEvent,"reason",{value:event.reason}),dispatch(legacyHandlers[name],domEvent)}):((event=document.createEvent("CustomEvent")).initCustomEvent("testingtheevent",!1,!0,{}),util.global.dispatchEvent(event),function(name,event){name=name.toLowerCase();var domEvent=document.createEvent("CustomEvent");return domEvent.initCustomEvent(name,!1,!0,event),dispatch(legacyHandlers[name],domEvent)})}catch(e){}return function(){return!1}}(),fireGlobalEvent=util.isNode?function(){return process.emit.apply(process,arguments)}:util.global?function(name){name="on"+name.toLowerCase(),name=util.global[name];return!!name&&(name.apply(util.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function generatePromiseLifecycleEventObject(name,promise){return{promise:promise}}var eventToObjectGenerator={promiseCreated:generatePromiseLifecycleEventObject,promiseFulfilled:generatePromiseLifecycleEventObject,promiseRejected:generatePromiseLifecycleEventObject,promiseResolved:generatePromiseLifecycleEventObject,promiseCancelled:generatePromiseLifecycleEventObject,promiseChained:function(name,promise,child){return{promise:promise,child:child}},warning:function(name,warning){return{warning:warning}},unhandledRejection:function(name,reason,promise){return{reason:reason,promise:promise}},rejectionHandled:generatePromiseLifecycleEventObject},activeFireEvent=function(name){var globalEventFired=!1;try{globalEventFired=fireGlobalEvent.apply(null,arguments)}catch(e){async.throwLater(e),globalEventFired=!0}var domEventFired=!1;try{domEventFired=fireDomEvent(name,eventToObjectGenerator[name].apply(null,arguments))}catch(e){async.throwLater(e),domEventFired=!0}return domEventFired||globalEventFired};function defaultFireEvent(){return!1}function cancellationExecute(executor,resolve,reject){var promise=this;try{executor(resolve,reject,function(onCancel){if("function"!=typeof onCancel)throw new TypeError("onCancel must be a function, got: "+util.toString(onCancel));promise._attachCancellationCallback(onCancel)})}catch(e){return e}}function cancellationAttachCancellationCallback(onCancel){if(!this._isCancellable())return this;var previousOnCancel=this._onCancel();void 0!==previousOnCancel?util.isArray(previousOnCancel)?previousOnCancel.push(onCancel):this._setOnCancel([previousOnCancel,onCancel]):this._setOnCancel(onCancel)}function cancellationOnCancel(){return this._onCancelField}function cancellationSetOnCancel(onCancel){this._onCancelField=onCancel}function cancellationClearCancellationData(){this._cancellationParent=void 0,this._onCancelField=void 0}function cancellationPropagateFrom(parent,flags){var branchesRemainingToCancel;0!=(1&flags)&&(branchesRemainingToCancel=(this._cancellationParent=parent)._branchesRemainingToCancel,parent._branchesRemainingToCancel=(branchesRemainingToCancel=void 0===branchesRemainingToCancel?0:branchesRemainingToCancel)+1),0!=(2&flags)&&parent._isBound()&&this._setBoundTo(parent._boundTo)}Promise.config=function(opts){var warningsOption;if("longStackTraces"in(opts=Object(opts))&&(opts.longStackTraces?Promise.longStackTraces():!opts.longStackTraces&&Promise.hasLongStackTraces()&&disableLongStackTraces()),"warnings"in opts&&(warningsOption=opts.warnings,config.warnings=!!warningsOption,wForgottenReturn=config.warnings,util.isObject(warningsOption))&&"wForgottenReturn"in warningsOption&&(wForgottenReturn=!!warningsOption.wForgottenReturn),"cancellation"in opts&&opts.cancellation&&!config.cancellation){if(async.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");Promise.prototype._clearCancellationData=cancellationClearCancellationData,Promise.prototype._propagateFrom=cancellationPropagateFrom,Promise.prototype._onCancel=cancellationOnCancel,Promise.prototype._setOnCancel=cancellationSetOnCancel,Promise.prototype._attachCancellationCallback=cancellationAttachCancellationCallback,Promise.prototype._execute=cancellationExecute,propagateFromFunction=cancellationPropagateFrom,config.cancellation=!0}return"monitoring"in opts&&(opts.monitoring&&!config.monitoring?(config.monitoring=!0,Promise.prototype._fireEvent=activeFireEvent):!opts.monitoring&&config.monitoring&&(config.monitoring=!1,Promise.prototype._fireEvent=defaultFireEvent)),"asyncHooks"in opts&&util.nodeSupportsAsyncResource&&config.asyncHooks!==(warningsOption=!!opts.asyncHooks)&&((config.asyncHooks=warningsOption)?enableAsyncHooks:disableAsyncHooks)(),Promise},Promise.prototype._fireEvent=defaultFireEvent,Promise.prototype._execute=function(executor,resolve,reject){try{executor(resolve,reject)}catch(e){return e}},Promise.prototype._onCancel=function(){},Promise.prototype._setOnCancel=function(handler){},Promise.prototype._attachCancellationCallback=function(onCancel){},Promise.prototype._captureStackTrace=function(){},Promise.prototype._attachExtraTrace=function(){},Promise.prototype._dereferenceTrace=function(){},Promise.prototype._clearCancellationData=function(){},Promise.prototype._propagateFrom=function(parent,flags){};var propagateFromFunction=function(parent,flags){0!=(2&flags)&&parent._isBound()&&this._setBoundTo(parent._boundTo)};function boundValueFunction(){var ret=this._boundTo;return void 0!==ret&&ret instanceof Promise?ret.isFulfilled()?ret.value():void 0:ret}function longStackTracesCaptureStackTrace(){this._trace=new CapturedTrace(this._peekContext())}function longStackTracesAttachExtraTrace(error,ignoreSelf){var trace;canAttachTrace(error)&&(void 0!==(trace=void 0!==(trace=this._trace)&&ignoreSelf?trace._parent:trace)?trace.attachExtraTrace(error):error.__stackCleaned__||(ignoreSelf=parseStackAndMessage(error),util.notEnumerableProp(error,"stack",ignoreSelf.message+"\n"+ignoreSelf.stack.join("\n")),util.notEnumerableProp(error,"__stackCleaned__",!0)))}function longStackTracesDereferenceTrace(){this._trace=void 0}function warn(message,shouldUseOwnTrace,promise){config.warnings&&(message=new Warning(message),shouldUseOwnTrace?promise._attachExtraTrace(message):config.longStackTraces&&(shouldUseOwnTrace=Promise._peekContext())?shouldUseOwnTrace.attachExtraTrace(message):(promise=parseStackAndMessage(message),message.stack=promise.message+"\n"+promise.stack.join("\n")),activeFireEvent("warning",message)||formatAndLogError(message,"",!0))}function cleanStack(stack){for(var ret=[],i=0;i<stack.length;++i){var line=stack[i],isTraceLine="    (No stack trace)"===line||stackFramePattern.test(line),isInternalFrame=isTraceLine&&shouldIgnore(line);isTraceLine&&!isInternalFrame&&(indentStackFrames&&" "!==line.charAt(0)&&(line="    "+line),ret.push(line))}return ret}function parseStackAndMessage(error){var stack=error.stack,message=error.toString(),stack="string"==typeof stack&&0<stack.length?function(error){for(var stack=error.stack.replace(/\s+$/g,"").split("\n"),i=0;i<stack.length;++i){var line=stack[i];if("    (No stack trace)"===line||stackFramePattern.test(line))break}return stack=0<i&&"SyntaxError"!=error.name?stack.slice(i):stack}(error):["    (No stack trace)"];return{message:message,stack:"SyntaxError"==error.name?stack:cleanStack(stack)}}function formatAndLogError(error,title,isSoft){var stack;"undefined"!=typeof console&&(stack=util.isObject(error)?(stack=error.stack,title+formatStack(stack,error)):title+String(error),"function"==typeof printWarning?printWarning(stack,isSoft):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(stack))}function fireRejectionEvent(name,localHandler,reason,promise){var localEventFired=!1;try{"function"==typeof localHandler&&(localEventFired=!0,"rejectionHandled"===name?localHandler(promise):localHandler(reason,promise))}catch(e){async.throwLater(e)}"unhandledRejection"===name?activeFireEvent(name,reason,promise)||localEventFired||formatAndLogError(reason,"Unhandled rejection "):activeFireEvent(name,promise)}function formatNonError(obj){if("function"==typeof obj)str="[function "+(obj.name||"anonymous")+"]";else{str=obj&&"function"==typeof obj.toString?obj.toString():util.toString(obj);if(/\[object [a-zA-Z0-9$_]+\]/.test(str))try{var str=JSON.stringify(obj)}catch(e){}0===str.length&&(str="(empty array)")}return"(<"+function(str){if(str.length<41)return str;return str.substr(0,38)+"..."}(str)+">, no stack trace)"}function longStackTracesIsSupported(){return"function"==typeof captureStackTrace}var shouldIgnore=function(){return!1},parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function parseLineInfo(line){line=line.match(parseLineInfoRegex);if(line)return{fileName:line[1],line:parseInt(line[2],10)}}function CapturedTrace(parent){this._parent=parent,this._promisesCreated=0;parent=this._length=1+(void 0===parent?0:parent._length);captureStackTrace(this,CapturedTrace),32<parent&&this.uncycle()}util.inherits(CapturedTrace,Error),(Context.CapturedTrace=CapturedTrace).prototype.uncycle=function(){var length=this._length;if(!(length<2)){for(var nodes=[],stackToIndex={},i=0,node=this;void 0!==node;++i)nodes.push(node),node=node._parent;for(i=(length=this._length=i)-1;0<=i;--i){var stack=nodes[i].stack;void 0===stackToIndex[stack]&&(stackToIndex[stack]=i)}for(i=0;i<length;++i){var index=stackToIndex[nodes[i].stack];if(void 0!==index&&index!==i){0<index&&(nodes[index-1]._parent=void 0,nodes[index-1]._length=1),nodes[i]._parent=void 0,nodes[i]._length=1;for(var cycleEdgeNode=0<i?nodes[i-1]:this,currentChildLength=(index<length-1?(cycleEdgeNode._parent=nodes[index+1],cycleEdgeNode._parent.uncycle(),cycleEdgeNode._length=cycleEdgeNode._parent._length+1):(cycleEdgeNode._parent=void 0,cycleEdgeNode._length=1),cycleEdgeNode._length+1),j=i-2;0<=j;--j)nodes[j]._length=currentChildLength,currentChildLength++;return}}}},CapturedTrace.prototype.attachExtraTrace=function(error){if(!error.__stackCleaned__){this.uncycle();for(var parsed=parseStackAndMessage(error),message=parsed.message,stacks=[parsed.stack],trace=this;void 0!==trace;)stacks.push(cleanStack(trace.stack.split("\n"))),trace=trace._parent;!function(stacks){for(var current=stacks[0],i=1;i<stacks.length;++i){for(var prev=stacks[i],currentLastIndex=current.length-1,currentLastLine=current[currentLastIndex],commonRootMeetPoint=-1,j=prev.length-1;0<=j;--j)if(prev[j]===currentLastLine){commonRootMeetPoint=j;break}for(j=commonRootMeetPoint;0<=j;--j){var line=prev[j];if(current[currentLastIndex]!==line)break;current.pop(),currentLastIndex--}current=prev}}(stacks),!function(stacks){for(var i=0;i<stacks.length;++i)(0===stacks[i].length||i+1<stacks.length&&stacks[i][0]===stacks[i+1][0])&&(stacks.splice(i,1),i--)}(stacks),util.notEnumerableProp(error,"stack",function(message,stacks){for(var i=0;i<stacks.length-1;++i)stacks[i].push("From previous event:"),stacks[i]=stacks[i].join("\n");return i<stacks.length&&(stacks[i]=stacks[i].join("\n")),message+"\n"+stacks.join("\n")}(message,stacks)),util.notEnumerableProp(error,"__stackCleaned__",!0)}};var captureStackTrace=function(){function v8stackFormatter(stack,error){return"string"==typeof stack?stack:void 0!==error.name&&void 0!==error.message?error.toString():formatNonError(error)}var captureStackTrace,v8stackFramePattern=/^\s*at\s*/;if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace)return Error.stackTraceLimit+=6,stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter,captureStackTrace=Error.captureStackTrace,shouldIgnore=function(line){return bluebirdFramePattern.test(line)},function(receiver,ignoreUntil){Error.stackTraceLimit+=6,captureStackTrace(receiver,ignoreUntil),Error.stackTraceLimit-=6};var hasStackAfterThrow,err=new Error;if("string"==typeof err.stack&&0<=err.stack.split("\n")[0].indexOf("stackDetection@"))return stackFramePattern=/@/,formatStack=v8stackFormatter,indentStackFrames=!0,function(o){o.stack=(new Error).stack};try{throw new Error}catch(e){hasStackAfterThrow="stack"in e}return"stack"in err||!hasStackAfterThrow||"number"!=typeof Error.stackTraceLimit?(formatStack=function(stack,error){return"string"==typeof stack?stack:"object"!=typeof error&&"function"!=typeof error||void 0===error.name||void 0===error.message?formatNonError(error):error.toString()},null):(stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter,function(o){Error.stackTraceLimit+=6;try{throw new Error}catch(e){o.stack=e.stack}Error.stackTraceLimit-=6})}(),config=("undefined"!=typeof console&&void 0!==console.warn&&(printWarning=function(message){console.warn(message)},util.isNode&&process.stderr.isTTY?printWarning=function(message,isSoft){console.warn((isSoft?"[33m":"[31m")+message+"[0m\n")}:util.isNode||"string"!=typeof(new Error).stack||(printWarning=function(message,isSoft){console.warn("%c"+message,isSoft?"color: darkorange":"color: red")})),{warnings:warnings,longStackTraces:!1,cancellation:!1,monitoring:!1,asyncHooks:!1});return debugging&&Promise.longStackTraces(),{asyncHooks:function(){return config.asyncHooks},longStackTraces:function(){return config.longStackTraces},warnings:function(){return config.warnings},cancellation:function(){return config.cancellation},monitoring:function(){return config.monitoring},propagateFromFunction:function(){return propagateFromFunction},boundValueFunction:function(){return boundValueFunction},checkForgottenReturns:function(returnValue,promiseCreated,name,promise,parent){if(void 0===returnValue&&null!==promiseCreated&&wForgottenReturn&&(void 0===parent||!parent._returnedNonUndefined())&&0!=(65535&promise._bitField)){name&&(name+=" ");var handlerLine="",creatorLine="";if(promiseCreated._trace){for(var traceLines=promiseCreated._trace.stack.split("\n"),stack=cleanStack(traceLines),i=stack.length-1;0<=i;--i){var line=stack[i];if(!nodeFramePattern.test(line)){line=line.match(parseLinePattern);line&&(handlerLine="at "+line[1]+":"+line[2]+":"+line[3]+" ");break}}if(0<stack.length)for(var firstUserLine=stack[0],i=0;i<traceLines.length;++i)if(traceLines[i]===firstUserLine){0<i&&(creatorLine="\n"+traceLines[i-1]);break}}promise._warn("a promise was created in a "+name+"handler "+handlerLine+"but was not returned from it, see http://goo.gl/rRqMUw"+creatorLine,!0,promiseCreated)}},setBounds:function(firstLineError,lastLineError){if(longStackTracesIsSupported()){for(var firstFileName,lastFileName,firstStackLines=(firstLineError.stack||"").split("\n"),lastStackLines=(lastLineError.stack||"").split("\n"),firstIndex=-1,lastIndex=-1,i=0;i<firstStackLines.length;++i)if(result=parseLineInfo(firstStackLines[i])){firstFileName=result.fileName,firstIndex=result.line;break}for(var result,i=0;i<lastStackLines.length;++i)if(result=parseLineInfo(lastStackLines[i])){lastFileName=result.fileName,lastIndex=result.line;break}firstIndex<0||lastIndex<0||!firstFileName||!lastFileName||firstFileName!==lastFileName||lastIndex<=firstIndex||(shouldIgnore=function(line){return!!bluebirdFramePattern.test(line)||!!((line=parseLineInfo(line))&&line.fileName===firstFileName&&firstIndex<=line.line&&line.line<=lastIndex)})}},warn:warn,deprecated:function(name,replacement){return name+=" is deprecated and will be removed in a future version.",replacement&&(name+=" Use "+replacement+" instead."),warn(name)},CapturedTrace:CapturedTrace,fireDomEvent:fireDomEvent,fireGlobalEvent:fireGlobalEvent}}},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function returner(){return this.value}function thrower(){throw this.reason}Promise.prototype.return=Promise.prototype.thenReturn=function(value){return value instanceof Promise&&value.suppressUnhandledRejections(),this._then(returner,void 0,void 0,{value:value},void 0)},Promise.prototype.throw=Promise.prototype.thenThrow=function(reason){return this._then(thrower,void 0,void 0,{reason:reason},void 0)},Promise.prototype.catchThrow=function(reason){var _reason;return arguments.length<=1?this._then(void 0,thrower,void 0,{reason:reason},void 0):(_reason=arguments[1],this.caught(reason,function(){throw _reason}))},Promise.prototype.catchReturn=function(value){var _value;return arguments.length<=1?(value instanceof Promise&&value.suppressUnhandledRejections(),this._then(void 0,returner,void 0,{value:value},void 0)):((_value=arguments[1])instanceof Promise&&_value.suppressUnhandledRejections(),this.caught(value,function(){return _value}))}}},{}],11:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseReduce=Promise.reduce,PromiseAll=Promise.all;function promiseAllThis(){return PromiseAll(this)}Promise.prototype.each=function(fn){return PromiseReduce(this,fn,INTERNAL,0)._then(promiseAllThis,void 0,void 0,this,void 0)},Promise.prototype.mapSeries=function(fn){return PromiseReduce(this,fn,INTERNAL,INTERNAL)},Promise.each=function(promises,fn){return PromiseReduce(promises,fn,INTERNAL,0)._then(promiseAllThis,void 0,void 0,promises,void 0)},Promise.mapSeries=function(promises,fn){return PromiseReduce(promises,fn,INTERNAL,INTERNAL)}}},{}],12:[function(_dereq_,module,exports){"use strict";var _TypeError,_RangeError,es5=_dereq_("./es5"),Objectfreeze=es5.freeze,_dereq_=_dereq_("./util"),inherits=_dereq_.inherits,notEnumerableProp=_dereq_.notEnumerableProp;function subError(nameProperty,defaultMessage){function SubError(message){if(!(this instanceof SubError))return new SubError(message);notEnumerableProp(this,"message","string"==typeof message?message:defaultMessage),notEnumerableProp(this,"name",nameProperty),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return inherits(SubError,Error),SubError}var _dereq_=subError("Warning","warning"),CancellationError=subError("CancellationError","cancellation error"),TimeoutError=subError("TimeoutError","timeout error"),AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError,_RangeError=RangeError}catch(e){_TypeError=subError("TypeError","type error"),_RangeError=subError("RangeError","range error")}for(var methods="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),i=0;i<methods.length;++i)"function"==typeof Array.prototype[methods[i]]&&(AggregateError.prototype[methods[i]]=Array.prototype[methods[i]]);es5.defineProperty(AggregateError.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),AggregateError.prototype.isOperational=!0;var level=0;function OperationalError(message){if(!(this instanceof OperationalError))return new OperationalError(message);notEnumerableProp(this,"name","OperationalError"),notEnumerableProp(this,"message",message),this.cause=message,this.isOperational=!0,message instanceof Error?(notEnumerableProp(this,"message",message.message),notEnumerableProp(this,"stack",message.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}AggregateError.prototype.toString=function(){var ret="\n"+Array(4*level+1).join(" ")+"AggregateError of:\n";level++;for(var indent=Array(4*level+1).join(" "),i=0;i<this.length;++i){for(var str=this[i]===this?"[Circular AggregateError]":this[i]+"",lines=str.split("\n"),j=0;j<lines.length;++j)lines[j]=indent+lines[j];ret+=(str=lines.join("\n"))+"\n"}return level--,ret},inherits(OperationalError,Error);var errorTypes=Error.__BluebirdErrorTypes__;errorTypes||(errorTypes=Objectfreeze({CancellationError:CancellationError,TimeoutError:TimeoutError,OperationalError:OperationalError,RejectionError:OperationalError,AggregateError:AggregateError}),es5.defineProperty(Error,"__BluebirdErrorTypes__",{value:errorTypes,writable:!1,enumerable:!1,configurable:!1})),module.exports={Error:Error,TypeError:_TypeError,RangeError:_RangeError,CancellationError:errorTypes.CancellationError,OperationalError:errorTypes.OperationalError,TimeoutError:errorTypes.TimeoutError,AggregateError:errorTypes.AggregateError,Warning:_dereq_}},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){var has,str,proto,isES5=function(){"use strict";return void 0===this}();isES5?module.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:isES5,propertyIsWritable:function(obj,prop){obj=Object.getOwnPropertyDescriptor(obj,prop);return!(obj&&!obj.writable&&!obj.set)}}:(has={}.hasOwnProperty,str={}.toString,proto={}.constructor.prototype,module.exports={isArray:function(obj){try{return"[object Array]"===str.call(obj)}catch(e){return!1}},keys:module=function(o){var key,ret=[];for(key in o)has.call(o,key)&&ret.push(key);return ret},names:module,defineProperty:function(o,key,desc){return o[key]=desc.value,o},getDescriptor:function(o,key){return{value:o[key]}},freeze:function(obj){return obj},getPrototypeOf:function(obj){try{return Object(obj).constructor.prototype}catch(e){return proto}},isES5:isES5,propertyIsWritable:function(){return!0}})},{}],14:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseMap=Promise.map;Promise.prototype.filter=function(fn,options){return PromiseMap(this,fn,options,INTERNAL)},Promise.filter=function(promises,fn,options){return PromiseMap(promises,fn,options,INTERNAL)}}},{}],15:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,tryConvertToPromise,NEXT_FILTER){var util=_dereq_("./util"),CancellationError=Promise.CancellationError,errorObj=util.errorObj,catchFilter=_dereq_("./catch_filter")(NEXT_FILTER);function PassThroughHandlerContext(promise,type,handler){this.promise=promise,this.type=type,this.handler=handler,this.called=!1,this.cancelPromise=null}function FinallyHandlerCancelReaction(finallyHandler){this.finallyHandler=finallyHandler}function checkCancel(ctx,reason){return null!=ctx.cancelPromise&&(1<arguments.length?ctx.cancelPromise._reject(reason):ctx.cancelPromise._cancel(),ctx.cancelPromise=null,1)}function succeed(){return finallyHandler.call(this,this.promise._target()._settledValue())}function fail(reason){if(!checkCancel(this,reason))return errorObj.e=reason,errorObj}function finallyHandler(reasonOrValue){var promise=this.promise,handler=this.handler;if(!this.called){this.called=!0;handler=this.isFinallyHandler()?handler.call(promise._boundValue()):handler.call(promise._boundValue(),reasonOrValue);if(handler===NEXT_FILTER)return handler;if(void 0!==handler){promise._setReturnedNonUndefined();var reason,handler=tryConvertToPromise(handler,promise);if(handler instanceof Promise){if(null!=this.cancelPromise){if(handler._isCancelled())return reason=new CancellationError("late cancellation observer"),promise._attachExtraTrace(reason),errorObj.e=reason,errorObj;handler.isPending()&&handler._attachCancellationCallback(new FinallyHandlerCancelReaction(this))}return handler._then(succeed,fail,void 0,this,void 0)}}}return promise.isRejected()?(checkCancel(this),errorObj.e=reasonOrValue,errorObj):(checkCancel(this),reasonOrValue)}return PassThroughHandlerContext.prototype.isFinallyHandler=function(){return 0===this.type},FinallyHandlerCancelReaction.prototype._resultCancelled=function(){checkCancel(this.finallyHandler)},Promise.prototype._passThrough=function(handler,type,success,fail){return"function"!=typeof handler?this.then():this._then(success,fail,void 0,new PassThroughHandlerContext(this,type,handler),void 0)},Promise.prototype.lastly=Promise.prototype.finally=function(handler){return this._passThrough(handler,0,finallyHandler,finallyHandler)},Promise.prototype.tap=function(handler){return this._passThrough(handler,1,finallyHandler)},Promise.prototype.tapCatch=function(handlerOrPredicate){var len=arguments.length;if(1===len)return this._passThrough(handlerOrPredicate,1,void 0,finallyHandler);for(var catchInstances=new Array(len-1),j=0,i=0;i<len-1;++i){var item=arguments[i];if(!util.isObject(item))return Promise.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+util.classString(item)));catchInstances[j++]=item}return catchInstances.length=j,this._passThrough(catchFilter(catchInstances,arguments[i],this),1,void 0,finallyHandler)},PassThroughHandlerContext}},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug){var TypeError=_dereq_("./errors").TypeError,util=_dereq_("./util"),errorObj=util.errorObj,tryCatch=util.tryCatch,yieldHandlers=[];function PromiseSpawn(generatorFunction,receiver,yieldHandler,stack){var internal,_finallyPromise;debug.cancellation()?(internal=new Promise(INTERNAL),_finallyPromise=this._finallyPromise=new Promise(INTERNAL),this._promise=internal.lastly(function(){return _finallyPromise}),internal._captureStackTrace(),internal._setOnCancel(this)):(this._promise=new Promise(INTERNAL))._captureStackTrace(),this._stack=stack,this._generatorFunction=generatorFunction,this._receiver=receiver,this._generator=void 0,this._yieldHandlers="function"==typeof yieldHandler?[yieldHandler].concat(yieldHandlers):yieldHandlers,this._yieldedPromise=null,this._cancellationPhase=!1}util.inherits(PromiseSpawn,Proxyable),PromiseSpawn.prototype._isResolved=function(){return null===this._promise},PromiseSpawn.prototype._cleanup=function(){this._promise=this._generator=null,debug.cancellation()&&null!==this._finallyPromise&&(this._finallyPromise._fulfill(),this._finallyPromise=null)},PromiseSpawn.prototype._promiseCancelled=function(){var reason;this._isResolved()||(reason=void 0!==this._generator.return?(this._promise._pushContext(),tryCatch(this._generator.return).call(this._generator,void 0)):(reason=new Promise.CancellationError("generator .return() sentinel"),Promise.coroutine.returnSentinel=reason,this._promise._attachExtraTrace(reason),this._promise._pushContext(),tryCatch(this._generator.throw).call(this._generator,reason)),this._promise._popContext(),this._cancellationPhase=!0,this._yieldedPromise=null,this._continue(reason))},PromiseSpawn.prototype._promiseFulfilled=function(value){this._yieldedPromise=null,this._promise._pushContext();value=tryCatch(this._generator.next).call(this._generator,value);this._promise._popContext(),this._continue(value)},PromiseSpawn.prototype._promiseRejected=function(reason){this._yieldedPromise=null,this._promise._attachExtraTrace(reason),this._promise._pushContext();reason=tryCatch(this._generator.throw).call(this._generator,reason);this._promise._popContext(),this._continue(reason)},PromiseSpawn.prototype._resultCancelled=function(){var promise;this._yieldedPromise instanceof Promise&&(promise=this._yieldedPromise,this._yieldedPromise=null,promise.cancel())},PromiseSpawn.prototype.promise=function(){return this._promise},PromiseSpawn.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver),this._receiver=this._generatorFunction=void 0,this._promiseFulfilled(void 0)},PromiseSpawn.prototype._continue=function(result){var value,promise=this._promise;return result===errorObj?(this._cleanup(),this._cancellationPhase?promise.cancel():promise._rejectCallback(result.e,!1)):(value=result.value,!0===result.done?(this._cleanup(),this._cancellationPhase?promise.cancel():promise._resolveCallback(value)):void((result=tryConvertToPromise(value,this._promise))instanceof Promise||null!==(result=function(value,yieldHandlers,traceParent){for(var i=0;i<yieldHandlers.length;++i){traceParent._pushContext();var result=tryCatch(yieldHandlers[i])(value);if(traceParent._popContext(),result===errorObj)return traceParent._pushContext(),ret=Promise.reject(errorObj.e),traceParent._popContext(),ret;var ret=tryConvertToPromise(result,traceParent);if(ret instanceof Promise)return ret}return null}(result,this._yieldHandlers,this._promise))?0==(50397184&(promise=(result=result._target())._bitField))?(this._yieldedPromise=result)._proxy(this,null):0!=(33554432&promise)?Promise._async.invoke(this._promiseFulfilled,this,result._value()):0!=(16777216&promise)?Promise._async.invoke(this._promiseRejected,this,result._reason()):this._promiseCancelled():this._promiseRejected(new TypeError("A value %s was yielded that could not be treated as a promise\n\n    See http://goo.gl/MqrFmX\n\n".replace("%s",String(value))+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")))))},Promise.coroutine=function(generatorFunction,options){if("function"!=typeof generatorFunction)throw new TypeError("generatorFunction must be a function\n\n    See http://goo.gl/MqrFmX\n");var yieldHandler=Object(options).yieldHandler,PromiseSpawn$=PromiseSpawn,stack=(new Error).stack;return function(){var generator=generatorFunction.apply(this,arguments),spawn=new PromiseSpawn$(void 0,void 0,yieldHandler,stack),ret=spawn.promise();return spawn._generator=generator,spawn._promiseFulfilled(void 0),ret}},Promise.coroutine.addYieldHandler=function(fn){if("function"!=typeof fn)throw new TypeError("expecting a function but got "+util.classString(fn));yieldHandlers.push(fn)},Promise.spawn=function(generatorFunction){var ret;return debug.deprecated("Promise.spawn()","Promise.coroutine()"),"function"!=typeof generatorFunction?apiRejection("generatorFunction must be a function\n\n    See http://goo.gl/MqrFmX\n"):(ret=(generatorFunction=new PromiseSpawn(generatorFunction,this)).promise(),generatorFunction._run(Promise.spawn),ret)}}},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,INTERNAL,async){var util=_dereq_("./util");util.canEvaluate,util.tryCatch,util.errorObj;Promise.join=function(){var fn,last=arguments.length-1,last=(0<last&&"function"==typeof arguments[last]&&(fn=arguments[last]),[].slice.call(arguments)),last=(fn&&last.pop(),new PromiseArray(last).promise());return void 0!==fn?last.spread(fn):last}}},{"./util":36}],18:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){var util=_dereq_("./util"),tryCatch=util.tryCatch,errorObj=util.errorObj,async=Promise._async;function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises),this._promise._captureStackTrace();var context=Promise._getContext();if(this._callback=util.contextBind(context,fn),this._preservedValues=_filter===INTERNAL?new Array(this.length()):null,this._limit=limit,this._inFlight=0,this._queue=[],async.invoke(this._asyncInit,this,void 0),util.isArray(promises))for(var i=0;i<promises.length;++i){var maybePromise=promises[i];maybePromise instanceof Promise&&maybePromise.suppressUnhandledRejections()}}function map(promises,fn,options,_filter){if("function"!=typeof fn)return apiRejection("expecting a function but got "+util.classString(fn));var limit=0;if(void 0!==options){if("object"!=typeof options||null===options)return Promise.reject(new TypeError("options argument must be an object but it is "+util.classString(options)));if("number"!=typeof options.concurrency)return Promise.reject(new TypeError("'concurrency' must be a number but it is "+util.classString(options.concurrency)));limit=options.concurrency}return new MappingPromiseArray(promises,fn,limit="number"==typeof limit&&isFinite(limit)&&1<=limit?limit:0,_filter).promise()}util.inherits(MappingPromiseArray,PromiseArray),MappingPromiseArray.prototype._asyncInit=function(){this._init$(void 0,-2)},MappingPromiseArray.prototype._init=function(){},MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values,length=this.length(),preservedValues=this._preservedValues,limit=this._limit;if(index<0){if(values[index=-1*index-1]=value,1<=limit&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(1<=limit&&this._inFlight>=limit)return values[index]=value,this._queue.push(index),!1;null!==preservedValues&&(preservedValues[index]=value);var promise=this._promise,callback=this._callback,receiver=promise._boundValue(),callback=(promise._pushContext(),tryCatch(callback).call(receiver,value,index,length)),receiver=promise._popContext();if(debug.checkForgottenReturns(callback,receiver,null!==preservedValues?"Promise.filter":"Promise.map",promise),callback===errorObj)return this._reject(callback.e),!0;if((value=tryConvertToPromise(callback,this._promise))instanceof Promise){receiver=(value=value._target())._bitField;if(0==(50397184&receiver))return 1<=limit&&this._inFlight++,(values[index]=value)._proxy(this,-1*(index+1)),!1;if(0==(33554432&receiver))return 0!=(16777216&receiver)?this._reject(value._reason()):this._cancel(),!0;callback=value._value()}values[index]=callback}return length<=++this._totalResolved&&(null!==preservedValues?this._filter(values,preservedValues):this._resolve(values),!0)},MappingPromiseArray.prototype._drainQueue=function(){for(var queue=this._queue,limit=this._limit,values=this._values;0<queue.length&&this._inFlight<limit;){if(this._isResolved())return;var index=queue.pop();this._promiseFulfilled(values[index],index)}},MappingPromiseArray.prototype._filter=function(booleans,values){for(var len=values.length,ret=new Array(len),j=0,i=0;i<len;++i)booleans[i]&&(ret[j++]=values[i]);ret.length=j,this._resolve(ret)},MappingPromiseArray.prototype.preservedValues=function(){return this._preservedValues},Promise.prototype.map=function(fn,options){return map(this,fn,options,null)},Promise.map=map}},{"./util":36}],19:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug){var util=_dereq_("./util"),tryCatch=util.tryCatch;Promise.method=function(fn){if("function"!=typeof fn)throw new Promise.TypeError("expecting a function but got "+util.classString(fn));return function(){var ret=new Promise(INTERNAL),value=(ret._captureStackTrace(),ret._pushContext(),tryCatch(fn).apply(this,arguments)),promiseCreated=ret._popContext();return debug.checkForgottenReturns(value,promiseCreated,"Promise.method",ret),ret._resolveFromSyncValue(value),ret}},Promise.attempt=Promise.try=function(fn){var ret,ctx,arg;return"function"!=typeof fn?apiRejection("expecting a function but got "+util.classString(fn)):((ret=new Promise(INTERNAL))._captureStackTrace(),ret._pushContext(),ctx=1<arguments.length?(debug.deprecated("calling Promise.try with more than 1 argument"),arg=arguments[1],ctx=arguments[2],util.isArray(arg)?tryCatch(fn).apply(ctx,arg):tryCatch(fn).call(ctx,arg)):tryCatch(fn)(),arg=ret._popContext(),debug.checkForgottenReturns(ctx,arg,"Promise.try",ret),ret._resolveFromSyncValue(ctx),ret)},Promise.prototype._resolveFromSyncValue=function(value){value===util.errorObj?this._rejectCallback(value.e,!1):this._resolveCallback(value,!0)}}},{"./util":36}],20:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util"),maybeWrapAsError=util.maybeWrapAsError,OperationalError=_dereq_("./errors").OperationalError,es5=_dereq_("./es5");var rErrorKey=/^(?:name|message|stack|cause)$/;function wrapAsOperationalError(obj){var ret;if(function(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}(obj)){(ret=new OperationalError(obj)).name=obj.name,ret.message=obj.message,ret.stack=obj.stack;for(var keys=es5.keys(obj),i=0;i<keys.length;++i){var key=keys[i];rErrorKey.test(key)||(ret[key]=obj[key])}return ret}return util.markAsOriginatingFromRejection(obj),obj}module.exports=function(promise,multiArgs){return function(err,value){null!==promise&&(err?(err=wrapAsOperationalError(maybeWrapAsError(err)),promise._attachExtraTrace(err),promise._reject(err)):multiArgs?(err=[].slice.call(arguments,1),promise._fulfill(err)):promise._fulfill(value),promise=null)}}},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var util=_dereq_("./util"),async=Promise._async,tryCatch=util.tryCatch,errorObj=util.errorObj;function spreadAdapter(val,nodeback){if(!util.isArray(val))return successAdapter.call(this,val,nodeback);nodeback=tryCatch(nodeback).apply(this._boundValue(),[null].concat(val));nodeback===errorObj&&async.throwLater(nodeback.e)}function successAdapter(val,nodeback){var receiver=this._boundValue(),nodeback=void 0===val?tryCatch(nodeback).call(receiver,null):tryCatch(nodeback).call(receiver,null,val);nodeback===errorObj&&async.throwLater(nodeback.e)}function errorAdapter(reason,nodeback){reason||((newReason=new Error(reason+"")).cause=reason,reason=newReason);var newReason=tryCatch(nodeback).call(this._boundValue(),reason);newReason===errorObj&&async.throwLater(newReason.e)}Promise.prototype.asCallback=Promise.prototype.nodeify=function(nodeback,options){var adapter;return"function"==typeof nodeback&&(adapter=successAdapter,void 0!==options&&Object(options).spread&&(adapter=spreadAdapter),this._then(adapter,errorAdapter,void 0,this,nodeback)),this}}},{"./util":36}],22:[function(_dereq_,module,exports){"use strict";module.exports=function(){function makeSelfResolutionError(){return new TypeError("circular promise resolution chain\n\n    See http://goo.gl/MqrFmX\n")}function reflectHandler(){return new Promise.PromiseInspection(this._target())}function apiRejection(msg){return Promise.reject(new TypeError(msg))}function Proxyable(){}function getContextDomain(){return{domain:getDomain(),async:null}}function getContextAsyncHooks(){return{domain:getDomain(),async:new AsyncResource("Bluebird::Promise")}}var UNDEFINED_BINDING={},util=_dereq_("./util"),getDomain=(util.setReflectHandler(reflectHandler),function(){var domain=process.domain;return void 0===domain?null:domain}),AsyncResource=util.isNode&&util.nodeSupportsAsyncResource?_dereq_("async_hooks").AsyncResource:null,getContext=util.isNode?getContextDomain:function(){return null},es5=(util.notEnumerableProp(Promise,"_getContext",getContext),_dereq_("./es5")),Async=_dereq_("./async"),async=new Async,errors=(es5.defineProperty(Promise,"_async",{value:async}),_dereq_("./errors")),TypeError=Promise.TypeError=errors.TypeError,CancellationError=(Promise.RangeError=errors.RangeError,Promise.CancellationError=errors.CancellationError),INTERNAL=(Promise.TimeoutError=errors.TimeoutError,Promise.OperationalError=errors.OperationalError,Promise.RejectionError=errors.OperationalError,Promise.AggregateError=errors.AggregateError,function(){}),APPLY={},NEXT_FILTER={},tryConvertToPromise=_dereq_("./thenables")(Promise,INTERNAL),PromiseArray=_dereq_("./promise_array")(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable),errors=_dereq_("./context")(Promise),createContext=errors.create,debug=_dereq_("./debuggability")(Promise,errors,function(){getContext=getContextAsyncHooks,util.notEnumerableProp(Promise,"_getContext",getContextAsyncHooks)},function(){getContext=getContextDomain,util.notEnumerableProp(Promise,"_getContext",getContextDomain)}),PassThroughHandlerContext=(debug.CapturedTrace,_dereq_("./finally")(Promise,tryConvertToPromise,NEXT_FILTER)),catchFilter=_dereq_("./catch_filter")(NEXT_FILTER),nodebackForPromise=_dereq_("./nodeback"),errorObj=util.errorObj,tryCatch=util.tryCatch;function Promise(executor){executor!==INTERNAL&&!function(self,executor){if(null==self||self.constructor!==Promise)throw new TypeError("the promise constructor cannot be invoked directly\n\n    See http://goo.gl/MqrFmX\n");if("function"!=typeof executor)throw new TypeError("expecting a function but got "+util.classString(executor))}(this,executor),this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._resolveFromExecutor(executor),this._promiseCreated(),this._fireEvent("promiseCreated",this)}function deferResolve(v){this.promise._resolveCallback(v)}function deferReject(v){this.promise._rejectCallback(v,!1)}function fillTypes(value){var p=new Promise(INTERNAL);p._fulfillmentHandler0=value,p._rejectionHandler0=value,p._promise0=value,p._receiver0=value}return Promise.prototype.toString=function(){return"[object Promise]"},Promise.prototype.caught=Promise.prototype.catch=function(fn){var len=arguments.length;if(1<len){for(var catchInstances=new Array(len-1),j=0,i=0;i<len-1;++i){var item=arguments[i];if(!util.isObject(item))return apiRejection("Catch statement predicate: expecting an object but got "+util.classString(item));catchInstances[j++]=item}if(catchInstances.length=j,"function"!=typeof(fn=arguments[i]))throw new TypeError("The last argument to .catch() must be a function, got "+util.toString(fn));return this.then(void 0,catchFilter(catchInstances,fn,this))}return this.then(void 0,fn)},Promise.prototype.reflect=function(){return this._then(reflectHandler,reflectHandler,void 0,this,void 0)},Promise.prototype.then=function(didFulfill,didReject){var msg;return debug.warnings()&&0<arguments.length&&"function"!=typeof didFulfill&&"function"!=typeof didReject&&(msg=".then() only accepts functions but was passed: "+util.classString(didFulfill),1<arguments.length&&(msg+=", "+util.classString(didReject)),this._warn(msg)),this._then(didFulfill,didReject,void 0,void 0,void 0)},Promise.prototype.done=function(didFulfill,didReject){this._then(didFulfill,didReject,void 0,void 0,void 0)._setIsFinal()},Promise.prototype.spread=function(fn){return"function"!=typeof fn?apiRejection("expecting a function but got "+util.classString(fn)):this.all()._then(fn,void 0,void 0,APPLY,void 0)},Promise.prototype.toJSON=function(){var ret={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(ret.fulfillmentValue=this.value(),ret.isFulfilled=!0):this.isRejected()&&(ret.rejectionReason=this.reason(),ret.isRejected=!0),ret},Promise.prototype.all=function(){return 0<arguments.length&&this._warn(".all() was passed arguments but it does not take any"),new PromiseArray(this).promise()},Promise.prototype.error=function(fn){return this.caught(util.originatesFromRejection,fn)},Promise.getNewLibraryCopy=module.exports,Promise.is=function(val){return val instanceof Promise},Promise.fromNode=Promise.fromCallback=function(fn){var ret=new Promise(INTERNAL),multiArgs=(ret._captureStackTrace(),1<arguments.length&&!!Object(arguments[1]).multiArgs),fn=tryCatch(fn)(nodebackForPromise(ret,multiArgs));return fn===errorObj&&ret._rejectCallback(fn.e,!0),ret._isFateSealed()||ret._setAsyncGuaranteed(),ret},Promise.all=function(promises){return new PromiseArray(promises).promise()},Promise.resolve=Promise.fulfilled=Promise.cast=function(obj){var ret=tryConvertToPromise(obj);return ret instanceof Promise||((ret=new Promise(INTERNAL))._captureStackTrace(),ret._setFulfilled(),ret._rejectionHandler0=obj),ret},Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);return ret._captureStackTrace(),ret._rejectCallback(reason,!0),ret},Promise.setScheduler=function(fn){if("function"!=typeof fn)throw new TypeError("expecting a function but got "+util.classString(fn));return async.setScheduler(fn)},Promise.prototype._then=function(didFulfill,didReject,_,receiver,internalData){var handler,value,settler,haveInternalData=void 0!==internalData,internalData=haveInternalData?internalData:new Promise(INTERNAL),target=this._target(),bitField=target._bitField,haveInternalData=(haveInternalData||(internalData._propagateFrom(this,3),internalData._captureStackTrace(),void 0===receiver&&0!=(2097152&this._bitField)&&(receiver=0!=(50397184&bitField)?this._boundValue():target===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,internalData)),getContext());return 0!=(50397184&bitField)?(settler=target._settlePromiseCtx,0!=(33554432&bitField)?(value=target._rejectionHandler0,handler=didFulfill):0!=(16777216&bitField)?(value=target._fulfillmentHandler0,handler=didReject,target._unsetRejectionIsUnhandled()):(settler=target._settlePromiseLateCancellationObserver,value=new CancellationError("late cancellation observer"),target._attachExtraTrace(value),handler=didReject),async.invoke(settler,target,{handler:util.contextBind(haveInternalData,handler),promise:internalData,receiver:receiver,value:value})):target._addCallbacks(didFulfill,didReject,internalData,receiver,haveInternalData),internalData},Promise.prototype._length=function(){return 65535&this._bitField},Promise.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},Promise.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},Promise.prototype._setLength=function(len){this._bitField=-65536&this._bitField|65535&len},Promise.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},Promise.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},Promise.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},Promise.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},Promise.prototype._isFinal=function(){return 0<(4194304&this._bitField)},Promise.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},Promise.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},Promise.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},Promise.prototype._setAsyncGuaranteed=function(){var bitField;async.hasCustomScheduler()||(bitField=this._bitField,this._bitField=bitField|(536870912&bitField)>>2^134217728)},Promise.prototype._setNoAsyncGuarantee=function(){this._bitField=-134217729&(536870912|this._bitField)},Promise.prototype._receiverAt=function(index){index=0===index?this._receiver0:this[4*index-4+3];if(index!==UNDEFINED_BINDING)return void 0===index&&this._isBound()?this._boundValue():index},Promise.prototype._promiseAt=function(index){return this[4*index-4+2]},Promise.prototype._fulfillmentHandlerAt=function(index){return this[4*index-4]},Promise.prototype._rejectionHandlerAt=function(index){return this[4*index-4+1]},Promise.prototype._boundValue=function(){},Promise.prototype._migrateCallback0=function(follower){follower._bitField;var fulfill=follower._fulfillmentHandler0,reject=follower._rejectionHandler0,promise=follower._promise0,follower=follower._receiverAt(0);this._addCallbacks(fulfill,reject,promise,follower=void 0===follower?UNDEFINED_BINDING:follower,null)},Promise.prototype._migrateCallbackAt=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index),reject=follower._rejectionHandlerAt(index),promise=follower._promiseAt(index),follower=follower._receiverAt(index);this._addCallbacks(fulfill,reject,promise,follower=void 0===follower?UNDEFINED_BINDING:follower,null)},Promise.prototype._addCallbacks=function(fulfill,reject,promise,receiver,context){var base,index=this._length();return 65531<=index&&this._setLength(index=0),0===index?(this._promise0=promise,this._receiver0=receiver,"function"==typeof fulfill&&(this._fulfillmentHandler0=util.contextBind(context,fulfill)),"function"==typeof reject&&(this._rejectionHandler0=util.contextBind(context,reject))):(this[2+(base=4*index-4)]=promise,this[3+base]=receiver,"function"==typeof fulfill&&(this[base]=util.contextBind(context,fulfill)),"function"==typeof reject&&(this[1+base]=util.contextBind(context,reject))),this._setLength(index+1),index},Promise.prototype._proxy=function(proxyable,arg){this._addCallbacks(void 0,void 0,arg,proxyable,null)},Promise.prototype._resolveCallback=function(value,shouldBind){if(0==(117506048&this._bitField)){if(value===this)return this._rejectCallback(makeSelfResolutionError(),!1);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);shouldBind&&this._propagateFrom(maybePromise,2);var promise=maybePromise._target();if(promise===this)this._reject(makeSelfResolutionError());else{value=promise._bitField;if(0==(50397184&value)){var len=this._length();0<len&&promise._migrateCallback0(this);for(var i=1;i<len;++i)promise._migrateCallbackAt(this,i);this._setFollowing(),this._setLength(0),this._setFollowee(maybePromise)}else 0!=(33554432&value)?this._fulfill(promise._value()):0!=(16777216&value)?this._reject(promise._reason()):(shouldBind=new CancellationError("late cancellation observer"),promise._attachExtraTrace(shouldBind),this._reject(shouldBind))}}},Promise.prototype._rejectCallback=function(reason,synchronous,ignoreNonErrorWarnings){var trace=util.ensureErrorObject(reason),hasStack=trace===reason;hasStack||ignoreNonErrorWarnings||!debug.warnings()||(ignoreNonErrorWarnings="a promise was rejected with a non-error: "+util.classString(reason),this._warn(ignoreNonErrorWarnings,!0)),this._attachExtraTrace(trace,!!synchronous&&hasStack),this._reject(reason)},Promise.prototype._resolveFromExecutor=function(executor){var promise,synchronous;executor!==INTERNAL&&((promise=this)._captureStackTrace(),this._pushContext(),synchronous=!0,executor=this._execute(executor,function(value){promise._resolveCallback(value)},function(reason){promise._rejectCallback(reason,synchronous)}),synchronous=!1,this._popContext(),void 0!==executor)&&promise._rejectCallback(executor,!0)},Promise.prototype._settlePromiseFromHandler=function(handler,receiver,value,promise){var x;0==(65536&promise._bitField)&&(promise._pushContext(),receiver===APPLY?value&&"number"==typeof value.length?x=tryCatch(handler).apply(this._boundValue(),value):(x=errorObj).e=new TypeError("cannot .spread() a non-array: "+util.classString(value)):x=tryCatch(handler).call(receiver,value),handler=promise._popContext(),0==(65536&promise._bitField))&&(x===NEXT_FILTER?promise._reject(value):x===errorObj?promise._rejectCallback(x.e,!1):(debug.checkForgottenReturns(x,handler,"",promise,this),promise._resolveCallback(x)))},Promise.prototype._target=function(){for(var ret=this;ret._isFollowing();)ret=ret._followee();return ret},Promise.prototype._followee=function(){return this._rejectionHandler0},Promise.prototype._setFollowee=function(promise){this._rejectionHandler0=promise},Promise.prototype._settlePromise=function(promise,handler,receiver,value){var isPromise=promise instanceof Promise,bitField=this._bitField,asyncGuaranteed=0!=(134217728&bitField);0!=(65536&bitField)?(isPromise&&promise._invokeInternalOnCancel(),receiver instanceof PassThroughHandlerContext&&receiver.isFinallyHandler()?(receiver.cancelPromise=promise,tryCatch(handler).call(receiver,value)===errorObj&&promise._reject(errorObj.e)):handler===reflectHandler?promise._fulfill(reflectHandler.call(receiver)):receiver instanceof Proxyable?receiver._promiseCancelled(promise):isPromise||promise instanceof PromiseArray?promise._cancel():receiver.cancel()):"function"==typeof handler?isPromise?(asyncGuaranteed&&promise._setAsyncGuaranteed(),this._settlePromiseFromHandler(handler,receiver,value,promise)):handler.call(receiver,value,promise):receiver instanceof Proxyable?receiver._isResolved()||(0!=(33554432&bitField)?receiver._promiseFulfilled(value,promise):receiver._promiseRejected(value,promise)):isPromise&&(asyncGuaranteed&&promise._setAsyncGuaranteed(),0!=(33554432&bitField)?promise._fulfill(value):promise._reject(value))},Promise.prototype._settlePromiseLateCancellationObserver=function(ctx){var handler=ctx.handler,promise=ctx.promise,receiver=ctx.receiver,ctx=ctx.value;"function"==typeof handler?promise instanceof Promise?this._settlePromiseFromHandler(handler,receiver,ctx,promise):handler.call(receiver,ctx,promise):promise instanceof Promise&&promise._reject(ctx)},Promise.prototype._settlePromiseCtx=function(ctx){this._settlePromise(ctx.promise,ctx.handler,ctx.receiver,ctx.value)},Promise.prototype._settlePromise0=function(handler,value,bitField){var promise=this._promise0,receiver=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(promise,handler,receiver,value)},Promise.prototype._clearCallbackDataAtIndex=function(index){index=4*index-4;this[2+index]=this[3+index]=this[index]=this[1+index]=void 0},Promise.prototype._fulfill=function(value){var err,bitField=this._bitField;if(!((117506048&bitField)>>>16)){if(value===this)return err=makeSelfResolutionError(),this._attachExtraTrace(err),this._reject(err);this._setFulfilled(),this._rejectionHandler0=value,0<(65535&bitField)&&(0!=(134217728&bitField)?this._settlePromises():async.settlePromises(this),this._dereferenceTrace())}},Promise.prototype._reject=function(reason){var bitField=this._bitField;if(!((117506048&bitField)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=reason,this._isFinal())return async.fatalError(reason,util.isNode);0<(65535&bitField)?async.settlePromises(this):this._ensurePossibleRejectionHandled()}},Promise.prototype._fulfillPromises=function(len,value){for(var i=1;i<len;i++){var handler=this._fulfillmentHandlerAt(i),promise=this._promiseAt(i),receiver=this._receiverAt(i);this._clearCallbackDataAtIndex(i),this._settlePromise(promise,handler,receiver,value)}},Promise.prototype._rejectPromises=function(len,reason){for(var i=1;i<len;i++){var handler=this._rejectionHandlerAt(i),promise=this._promiseAt(i),receiver=this._receiverAt(i);this._clearCallbackDataAtIndex(i),this._settlePromise(promise,handler,receiver,reason)}},Promise.prototype._settlePromises=function(){var reason,bitField=this._bitField,len=65535&bitField;0<len&&(0!=(16842752&bitField)?(reason=this._fulfillmentHandler0,this._settlePromise0(this._rejectionHandler0,reason,bitField),this._rejectPromises(len,reason)):(reason=this._rejectionHandler0,this._settlePromise0(this._fulfillmentHandler0,reason,bitField),this._fulfillPromises(len,reason)),this._setLength(0)),this._clearCancellationData()},Promise.prototype._settledValue=function(){var bitField=this._bitField;return 0!=(33554432&bitField)?this._rejectionHandler0:0!=(16777216&bitField)?this._fulfillmentHandler0:void 0},"undefined"!=typeof Symbol&&Symbol.toStringTag&&es5.defineProperty(Promise.prototype,Symbol.toStringTag,{get:function(){return"Object"}}),Promise.defer=Promise.pending=function(){return debug.deprecated("Promise.defer","new Promise"),{promise:new Promise(INTERNAL),resolve:deferResolve,reject:deferReject}},util.notEnumerableProp(Promise,"_makeSelfResolutionError",makeSelfResolutionError),_dereq_("./method")(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug),_dereq_("./bind")(Promise,INTERNAL,tryConvertToPromise,debug),_dereq_("./cancel")(Promise,PromiseArray,apiRejection,debug),_dereq_("./direct_resolve")(Promise),_dereq_("./synchronous_inspection")(Promise),_dereq_("./join")(Promise,PromiseArray,tryConvertToPromise,INTERNAL,async),(Promise.Promise=Promise).version="3.7.2",_dereq_("./call_get.js")(Promise),_dereq_("./generators.js")(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug),_dereq_("./map.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug),_dereq_("./nodeify.js")(Promise),_dereq_("./promisify.js")(Promise,INTERNAL),_dereq_("./props.js")(Promise,PromiseArray,tryConvertToPromise,apiRejection),_dereq_("./race.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection),_dereq_("./reduce.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug),_dereq_("./settle.js")(Promise,PromiseArray,debug),_dereq_("./some.js")(Promise,PromiseArray,apiRejection),_dereq_("./timers.js")(Promise,INTERNAL,debug),_dereq_("./using.js")(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug),_dereq_("./any.js")(Promise),_dereq_("./each.js")(Promise,INTERNAL),_dereq_("./filter.js")(Promise,INTERNAL),util.toFastProperties(Promise),util.toFastProperties(Promise.prototype),fillTypes({a:1}),fillTypes({b:2}),fillTypes({c:3}),fillTypes(1),fillTypes(function(){}),fillTypes(void 0),fillTypes(!1),fillTypes(new Promise(INTERNAL)),debug.setBounds(Async.firstLineError,util.lastLineError),Promise}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,async_hooks:void 0}],23:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable){var util=_dereq_("./util");util.isArray;function PromiseArray(values){var promise=this._promise=new Promise(INTERNAL);values instanceof Promise&&(promise._propagateFrom(values,3),values.suppressUnhandledRejections()),promise._setOnCancel(this),this._values=values,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return util.inherits(PromiseArray,Proxyable),PromiseArray.prototype.length=function(){return this._length},PromiseArray.prototype.promise=function(){return this._promise},PromiseArray.prototype._init=function init(_,resolveValueIfEmpty){if((values=tryConvertToPromise(this._values,this._promise))instanceof Promise){var values,bitField=(values=values._target())._bitField;if(this._values=values,0==(50397184&bitField))return this._promise._setAsyncGuaranteed(),values._then(init,this._reject,void 0,this,resolveValueIfEmpty);if(0==(33554432&bitField))return 0!=(16777216&bitField)?this._reject(values._reason()):this._cancel();values=values._value()}null===(values=util.asArray(values))?(bitField=apiRejection("expecting an array or an iterable object but got "+util.classString(values)).reason(),this._promise._rejectCallback(bitField,!1)):0===values.length?-5===resolveValueIfEmpty?this._resolveEmptyArray():this._resolve(function(val){switch(val){case-2:return[];case-3:return{};case-6:return new Map}}(resolveValueIfEmpty)):this._iterate(values)},PromiseArray.prototype._iterate=function(values){for(var len=this.getActualLength(values.length),result=(this._length=len,this._values=this.shouldCopyValues()?new Array(len):this._values,this._promise),isResolved=!1,bitField=null,i=0;i<len;++i){var maybePromise=tryConvertToPromise(values[i],result),bitField=maybePromise instanceof Promise?(maybePromise=maybePromise._target())._bitField:null;isResolved?null!==bitField&&maybePromise.suppressUnhandledRejections():null!==bitField?0==(50397184&bitField)?(maybePromise._proxy(this,i),this._values[i]=maybePromise):isResolved=0!=(33554432&bitField)?this._promiseFulfilled(maybePromise._value(),i):0!=(16777216&bitField)?this._promiseRejected(maybePromise._reason(),i):this._promiseCancelled(i):isResolved=this._promiseFulfilled(maybePromise,i)}isResolved||result._setAsyncGuaranteed()},PromiseArray.prototype._isResolved=function(){return null===this._values},PromiseArray.prototype._resolve=function(value){this._values=null,this._promise._fulfill(value)},PromiseArray.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},PromiseArray.prototype._reject=function(reason){this._values=null,this._promise._rejectCallback(reason,!1)},PromiseArray.prototype._promiseFulfilled=function(value,index){return this._values[index]=value,++this._totalResolved>=this._length&&(this._resolve(this._values),!0)},PromiseArray.prototype._promiseCancelled=function(){return this._cancel(),!0},PromiseArray.prototype._promiseRejected=function(reason){return this._totalResolved++,this._reject(reason),!0},PromiseArray.prototype._resultCancelled=function(){if(!this._isResolved()){var values=this._values;if(this._cancel(),values instanceof Promise)values.cancel();else for(var i=0;i<values.length;++i)values[i]instanceof Promise&&values[i].cancel()}},PromiseArray.prototype.shouldCopyValues=function(){return!0},PromiseArray.prototype.getActualLength=function(len){return len},PromiseArray}},{"./util":36}],24:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var THIS={},util=_dereq_("./util"),nodebackForPromise=_dereq_("./nodeback"),withAppended=util.withAppended,maybeWrapAsError=util.maybeWrapAsError,canEvaluate=util.canEvaluate,TypeError=_dereq_("./errors").TypeError,defaultPromisified={__isPromisified__:!0},noCopyPropsPattern=new RegExp("^(?:"+["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"].join("|")+")$"),defaultFilter=function(name){return util.isIdentifier(name)&&"_"!==name.charAt(0)&&"constructor"!==name};function propsFilter(key){return!noCopyPropsPattern.test(key)}function isPromisified(fn){try{return!0===fn.__isPromisified__}catch(e){return!1}}function promisifiableMethods(obj,suffix,suffixRegexp,filter){for(var keys=util.inheritedDataKeys(obj),ret=[],i=0;i<keys.length;++i){var key=keys[i],value=obj[key],passesDefaultFilter=filter===defaultFilter||defaultFilter(key,value,obj);"function"!=typeof value||isPromisified(value)||function(obj,key,suffix){return(obj=util.getDataPropertyOrDefault(obj,key+suffix,defaultPromisified))&&isPromisified(obj)}(obj,key,suffix)||!filter(key,value,obj,passesDefaultFilter)||ret.push(key,value)}return function(ret,suffix,suffixRegexp){for(var i=0;i<ret.length;i+=2){var key=ret[i];if(suffixRegexp.test(key))for(var keyWithoutAsyncSuffix=key.replace(suffixRegexp,""),j=0;j<ret.length;j+=2)if(ret[j]===keyWithoutAsyncSuffix)throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\n\n    See http://goo.gl/MqrFmX\n".replace("%s",suffix))}}(ret,suffix,suffixRegexp),ret}var makeNodePromisifiedEval;var makeNodePromisified=canEvaluate?makeNodePromisifiedEval:function(callback,receiver,_,fn,__,multiArgs){var defaultThis=function(){return this}(),method=callback;function promisified(){var _receiver=receiver,promise=(receiver===THIS&&(_receiver=this),new Promise(INTERNAL)),cb=(promise._captureStackTrace(),"string"==typeof method&&this!==defaultThis?this[method]:callback),fn=nodebackForPromise(promise,multiArgs);try{cb.apply(_receiver,withAppended(arguments,fn))}catch(e){promise._rejectCallback(maybeWrapAsError(e),!0,!0)}return promise._isFateSealed()||promise._setAsyncGuaranteed(),promise}return"string"==typeof method&&(callback=fn),util.notEnumerableProp(promisified,"__isPromisified__",!0),promisified};function promisifyAll(obj,suffix,filter,promisifier,multiArgs){for(var suffixRegexp=new RegExp(suffix.replace(/([$])/,"\\$")+"$"),methods=promisifiableMethods(obj,suffix,suffixRegexp,filter),i=0,len=methods.length;i<len;i+=2){var promisified,key=methods[i],fn=methods[i+1],promisifiedKey=key+suffix;promisifier===makeNodePromisified?obj[promisifiedKey]=makeNodePromisified(key,THIS,key,fn,suffix,multiArgs):(promisified=promisifier(fn,function(){return makeNodePromisified(key,THIS,key,fn,suffix,multiArgs)}),util.notEnumerableProp(promisified,"__isPromisified__",!0),obj[promisifiedKey]=promisified)}return util.toFastProperties(obj),obj}Promise.promisify=function(fn,options){if("function"!=typeof fn)throw new TypeError("expecting a function but got "+util.classString(fn));return isPromisified(fn)?fn:(options=function(callback,receiver,multiArgs){return makeNodePromisified(callback,receiver,void 0,callback,null,multiArgs)}(fn,void 0===(options=Object(options)).context?THIS:options.context,!!options.multiArgs),util.copyDescriptors(fn,options,propsFilter),options)},Promise.promisifyAll=function(target,options){if("function"!=typeof target&&"object"!=typeof target)throw new TypeError("the target of promisifyAll must be an object or a function\n\n    See http://goo.gl/MqrFmX\n");var multiArgs=!!(options=Object(options)).multiArgs,suffix=options.suffix,filter=options.filter,promisifier=("function"!=typeof filter&&(filter=defaultFilter),options.promisifier);if("function"!=typeof promisifier&&(promisifier=makeNodePromisified),!util.isIdentifier(suffix="string"!=typeof suffix?"Async":suffix))throw new RangeError("suffix must be a valid identifier\n\n    See http://goo.gl/MqrFmX\n");for(var keys=util.inheritedDataKeys(target),i=0;i<keys.length;++i){var value=target[keys[i]];"constructor"!==keys[i]&&util.isClass(value)&&(promisifyAll(value.prototype,suffix,filter,promisifier,multiArgs),promisifyAll(value,suffix,filter,promisifier,multiArgs))}return promisifyAll(target,suffix,filter,promisifier,multiArgs)}}},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,apiRejection){var Es6Map,size,index,util=_dereq_("./util"),isObject=util.isObject,es5=_dereq_("./es5"),mapToEntries=("function"==typeof Map&&(Es6Map=Map),index=0,function(map){size=map.size,index=0;var ret=new Array(2*map.size);return map.forEach(extractEntry,ret),ret});function extractEntry(value,key){this[index]=value,this[index+size]=key,index++}function PropertiesPromiseArray(obj){var isMap=!1;if(void 0!==Es6Map&&obj instanceof Es6Map)entries=mapToEntries(obj),isMap=!0;else for(var keys=es5.keys(obj),len=keys.length,entries=new Array(2*len),i=0;i<len;++i){var key=keys[i];entries[i]=obj[key],entries[i+len]=key}this.constructor$(entries),this._isMap=isMap,this._init$(void 0,isMap?-6:-3)}function props(promises){var ret,promises=tryConvertToPromise(promises);return isObject(promises)?(ret=promises instanceof Promise?promises._then(Promise.props,void 0,void 0,void 0,void 0):new PropertiesPromiseArray(promises).promise(),promises instanceof Promise&&ret._propagateFrom(promises,2),ret):apiRejection("cannot await properties of a non-object\n\n    See http://goo.gl/MqrFmX\n")}util.inherits(PropertiesPromiseArray,PromiseArray),PropertiesPromiseArray.prototype._init=function(){},PropertiesPromiseArray.prototype._promiseFulfilled=function(value,index){if(this._values[index]=value,++this._totalResolved>=this._length){if(this._isMap)val=function(entries){for(var ret=new Es6Map,length=entries.length/2|0,i=0;i<length;++i){var key=entries[length+i],value=entries[i];ret.set(key,value)}return ret}(this._values);else for(var val={},keyOffset=this.length(),i=0,len=this.length();i<len;++i)val[this._values[i+keyOffset]]=this._values[i];return this._resolve(val),!0}return!1},PropertiesPromiseArray.prototype.shouldCopyValues=function(){return!1},PropertiesPromiseArray.prototype.getActualLength=function(len){return len>>1},Promise.prototype.props=function(){return props(this)},Promise.props=props}},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){"use strict";function Queue(capacity){this._capacity=capacity,this._length=0,this._front=0}Queue.prototype._willBeOverCapacity=function(size){return this._capacity<size},Queue.prototype._pushOne=function(arg){var length=this.length(),i=(this._checkCapacity(length+1),this._front+length&this._capacity-1);this[i]=arg,this._length=length+1},Queue.prototype.push=function(fn,receiver,arg){var j,wrapMask,length=this.length()+3;this._willBeOverCapacity(length)?(this._pushOne(fn),this._pushOne(receiver),this._pushOne(arg)):(j=this._front+length-3,this._checkCapacity(length),wrapMask=this._capacity-1,this[j&wrapMask]=fn,this[1+j&wrapMask]=receiver,this[2+j&wrapMask]=arg,this._length=length)},Queue.prototype.shift=function(){var front=this._front,ret=this[front];return this[front]=void 0,this._front=front+1&this._capacity-1,this._length--,ret},Queue.prototype.length=function(){return this._length},Queue.prototype._checkCapacity=function(size){this._capacity<size&&this._resizeTo(this._capacity<<1)},Queue.prototype._resizeTo=function(capacity){var oldCapacity=this._capacity;this._capacity=capacity;for(var capacity=this._front+this._length&oldCapacity-1,src=this,srcIndex=0,dst=this,dstIndex=oldCapacity,len=capacity,j=0;j<len;++j)dst[j+dstIndex]=src[j+srcIndex],src[j+srcIndex]=void 0},module.exports=Queue},{}],27:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){function raceLater(promise){return promise.then(function(array){return race(array,promise)})}var util=_dereq_("./util");function race(promises,parent){var maybePromise=tryConvertToPromise(promises);if(maybePromise instanceof Promise)return raceLater(maybePromise);if(null===(promises=util.asArray(promises)))return apiRejection("expecting an array or an iterable object but got "+util.classString(promises));for(var ret=new Promise(INTERNAL),fulfill=(void 0!==parent&&ret._propagateFrom(parent,3),ret._fulfill),reject=ret._reject,i=0,len=promises.length;i<len;++i){var val=promises[i];(void 0!==val||i in promises)&&Promise.cast(val)._then(fulfill,reject,void 0,ret,null)}return ret}Promise.race=function(promises){return race(promises,void 0)},Promise.prototype.race=function(){return race(this,void 0)}}},{"./util":36}],28:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){var util=_dereq_("./util"),tryCatch=util.tryCatch;function ReductionPromiseArray(promises,fn,initialValue,_each){this.constructor$(promises);promises=Promise._getContext();this._fn=util.contextBind(promises,fn),void 0!==initialValue&&(initialValue=Promise.resolve(initialValue))._attachCancellationCallback(this),this._initialValue=initialValue,this._currentCancellable=null,this._eachValues=_each===INTERNAL?Array(this._length):0===_each?null:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function completed(valueOrReason,array){this.isFulfilled()?array._resolve(valueOrReason):array._reject(valueOrReason)}function reduce(promises,fn,initialValue,_each){return"function"!=typeof fn?apiRejection("expecting a function but got "+util.classString(fn)):new ReductionPromiseArray(promises,fn,initialValue,_each).promise()}function gotAccum(accum){this.accum=accum,this.array._gotAccum(accum);accum=tryConvertToPromise(this.value,this.array._promise);return accum instanceof Promise?(this.array._currentCancellable=accum)._then(gotValue,void 0,void 0,this,void 0):gotValue.call(this,accum)}function gotValue(value){var array=this.array,promise=array._promise,fn=tryCatch(array._fn),value=(promise._pushContext(),(fn=void 0!==array._eachValues?fn.call(promise._boundValue(),value,this.index,this.length):fn.call(promise._boundValue(),this.accum,value,this.index,this.length))instanceof Promise&&(array._currentCancellable=fn),promise._popContext());return debug.checkForgottenReturns(fn,value,void 0!==array._eachValues?"Promise.each":"Promise.reduce",promise),fn}util.inherits(ReductionPromiseArray,PromiseArray),ReductionPromiseArray.prototype._gotAccum=function(accum){void 0!==this._eachValues&&null!==this._eachValues&&accum!==INTERNAL&&this._eachValues.push(accum)},ReductionPromiseArray.prototype._eachComplete=function(value){return null!==this._eachValues&&this._eachValues.push(value),this._eachValues},ReductionPromiseArray.prototype._init=function(){},ReductionPromiseArray.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},ReductionPromiseArray.prototype.shouldCopyValues=function(){return!1},ReductionPromiseArray.prototype._resolve=function(value){this._promise._resolveCallback(value),this._values=null},ReductionPromiseArray.prototype._resultCancelled=function(sender){if(sender===this._initialValue)return this._cancel();this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof Promise&&this._currentCancellable.cancel(),this._initialValue instanceof Promise&&this._initialValue.cancel())},ReductionPromiseArray.prototype._iterate=function(values){var length=(this._values=values).length,i=void 0!==this._initialValue?(value=this._initialValue,0):(value=Promise.resolve(values[0]),1);this._currentCancellable=value;for(var j=i;j<length;++j){var maybePromise=values[j];maybePromise instanceof Promise&&maybePromise.suppressUnhandledRejections()}if(!value.isRejected())for(;i<length;++i){var ctx={accum:null,value:values[i],index:i,length:length,array:this},value=value._then(gotAccum,void 0,void 0,ctx,void 0);0==(127&i)&&value._setNoAsyncGuarantee()}(value=void 0!==this._eachValues?value._then(this._eachComplete,void 0,void 0,this,void 0):value)._then(completed,completed,void 0,value,this)},Promise.prototype.reduce=function(fn,initialValue){return reduce(this,fn,initialValue,null)},Promise.reduce=reduce}},{"./util":36}],29:[function(_dereq_,module,exports){"use strict";var GlobalSetImmediate,ProcessNextTick,nativePromise,_dereq_=_dereq_("./util"),NativePromise=_dereq_.getNativePromise();_dereq_=_dereq_.isNode&&"undefined"==typeof MutationObserver?(GlobalSetImmediate=global.setImmediate,ProcessNextTick=process.nextTick,_dereq_.isRecentNode?function(fn){GlobalSetImmediate.call(global,fn)}:function(fn){ProcessNextTick.call(process,fn)}):"function"==typeof NativePromise&&"function"==typeof NativePromise.resolve?(nativePromise=NativePromise.resolve(),function(fn){nativePromise.then(fn)}):"undefined"!=typeof MutationObserver&&("undefined"==typeof window||!window.navigator||!window.navigator.standalone&&!window.cordova)&&"classList"in document.documentElement?function(){var div=document.createElement("div"),opts={attributes:!0},toggleScheduled=!1,div2=document.createElement("div");new MutationObserver(function(){div.classList.toggle("foo"),toggleScheduled=!1}).observe(div2,opts);return function(fn){var o=new MutationObserver(function(){o.disconnect(),fn()});o.observe(div,opts),toggleScheduled||(toggleScheduled=!0,div2.classList.toggle("foo"))}}():void 0!==setImmediate?function(fn){setImmediate(fn)}:"undefined"!=typeof setTimeout?function(fn){setTimeout(fn,0)}:function(){throw new Error("No async scheduler available\n\n    See http://goo.gl/MqrFmX\n")},module.exports=_dereq_},{"./util":36}],30:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,debug){var PromiseInspection=Promise.PromiseInspection;function SettledPromiseArray(values){this.constructor$(values)}_dereq_("./util").inherits(SettledPromiseArray,PromiseArray),SettledPromiseArray.prototype._promiseResolved=function(index,inspection){return this._values[index]=inspection,++this._totalResolved>=this._length&&(this._resolve(this._values),!0)},SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection;return ret._bitField=33554432,ret._settledValueField=value,this._promiseResolved(index,ret)},SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection;return ret._bitField=16777216,ret._settledValueField=reason,this._promiseResolved(index,ret)},Promise.settle=function(promises){return debug.deprecated(".settle()",".reflect()"),new SettledPromiseArray(promises).promise()},Promise.allSettled=function(promises){return new SettledPromiseArray(promises).promise()},Promise.prototype.settle=function(){return Promise.settle(this)}}},{"./util":36}],31:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection){var util=_dereq_("./util"),RangeError=_dereq_("./errors").RangeError,AggregateError=_dereq_("./errors").AggregateError,isArray=util.isArray,CANCELLATION={};function SomePromiseArray(values){this.constructor$(values),this._howMany=0,this._unwrap=!1,this._initialized=!1}function some(promises,howMany){var promise;return(0|howMany)!==howMany||howMany<0?apiRejection("expecting a positive integer\n\n    See http://goo.gl/MqrFmX\n"):(promise=(promises=new SomePromiseArray(promises)).promise(),promises.setHowMany(howMany),promises.init(),promise)}util.inherits(SomePromiseArray,PromiseArray),SomePromiseArray.prototype._init=function(){var isArrayResolved;this._initialized&&(0===this._howMany?this._resolve([]):(this._init$(void 0,-5),isArrayResolved=isArray(this._values),!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))))},SomePromiseArray.prototype.init=function(){this._initialized=!0,this._init()},SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=!0},SomePromiseArray.prototype.howMany=function(){return this._howMany},SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count},SomePromiseArray.prototype._promiseFulfilled=function(value){return this._addFulfilled(value),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},SomePromiseArray.prototype._promiseRejected=function(reason){return this._addRejected(reason),this._checkOutcome()},SomePromiseArray.prototype._promiseCancelled=function(){return this._values instanceof Promise||null==this._values?this._cancel():(this._addRejected(CANCELLATION),this._checkOutcome())},SomePromiseArray.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var e=new AggregateError,i=this.length();i<this._values.length;++i)this._values[i]!==CANCELLATION&&e.push(this._values[i]);return 0<e.length?this._reject(e):this._cancel(),!0}return!1},SomePromiseArray.prototype._fulfilled=function(){return this._totalResolved},SomePromiseArray.prototype._rejected=function(){return this._values.length-this.length()},SomePromiseArray.prototype._addRejected=function(reason){this._values.push(reason)},SomePromiseArray.prototype._addFulfilled=function(value){this._values[this._totalResolved++]=value},SomePromiseArray.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},SomePromiseArray.prototype._getRangeError=function(count){count="Input array must contain at least "+this._howMany+" items but contains only "+count+" items";return new RangeError(count)},SomePromiseArray.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},Promise.some=some,Promise.prototype.some=function(howMany){return some(this,howMany)},Promise._SomePromiseArray=SomePromiseArray}},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function PromiseInspection(promise){void 0!==promise?(promise=promise._target(),this._bitField=promise._bitField,this._settledValueField=promise._isFateSealed()?promise._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}PromiseInspection.prototype._settledValue=function(){return this._settledValueField};var value=PromiseInspection.prototype.value=function(){if(this.isFulfilled())return this._settledValue();throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n    See http://goo.gl/MqrFmX\n")},reason=PromiseInspection.prototype.error=PromiseInspection.prototype.reason=function(){if(this.isRejected())return this._settledValue();throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n    See http://goo.gl/MqrFmX\n")},isFulfilled=PromiseInspection.prototype.isFulfilled=function(){return 0!=(33554432&this._bitField)},isRejected=PromiseInspection.prototype.isRejected=function(){return 0!=(16777216&this._bitField)},isPending=PromiseInspection.prototype.isPending=function(){return 0==(50397184&this._bitField)},isResolved=PromiseInspection.prototype.isResolved=function(){return 0!=(50331648&this._bitField)};PromiseInspection.prototype.isCancelled=function(){return 0!=(8454144&this._bitField)},Promise.prototype.__isCancelled=function(){return 65536==(65536&this._bitField)},Promise.prototype._isCancelled=function(){return this._target().__isCancelled()},Promise.prototype.isCancelled=function(){return 0!=(8454144&this._target()._bitField)},Promise.prototype.isPending=function(){return isPending.call(this._target())},Promise.prototype.isRejected=function(){return isRejected.call(this._target())},Promise.prototype.isFulfilled=function(){return isFulfilled.call(this._target())},Promise.prototype.isResolved=function(){return isResolved.call(this._target())},Promise.prototype.value=function(){return value.call(this._target())},Promise.prototype.reason=function(){var target=this._target();return target._unsetRejectionIsUnhandled(),reason.call(target)},Promise.prototype._value=function(){return this._settledValue()},Promise.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},Promise.PromiseInspection=PromiseInspection}},{}],33:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var util=_dereq_("./util"),errorObj=util.errorObj,isObject=util.isObject;var hasProp={}.hasOwnProperty;return function(obj,context){if(isObject(obj)){if(obj instanceof Promise)return obj;var ret,then=function(obj){try{return obj.then}catch(e){return errorObj.e=e,errorObj}}(obj);if(then===errorObj)return context&&context._pushContext(),ret=Promise.reject(then.e),context&&context._popContext(),ret;if("function"==typeof then)return function(obj){try{return hasProp.call(obj,"_promise0")}catch(e){}}(obj)?(ret=new Promise(INTERNAL),obj._then(ret._fulfill,ret._reject,void 0,ret,null),ret):function(x,then,context){var promise=new Promise(INTERNAL),ret=promise;context&&context._pushContext();promise._captureStackTrace(),context&&context._popContext();var synchronous=!0,context=util.tryCatch(then).call(x,function(value){promise&&(promise._resolveCallback(value),promise=null)},function(reason){promise&&(promise._rejectCallback(reason,synchronous,!0),promise=null)});synchronous=!1,promise&&context===errorObj&&(promise._rejectCallback(context.e,!0,!0),promise=null);return ret}(obj,then,context)}return obj}}},{"./util":36}],34:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,debug){var util=_dereq_("./util"),TimeoutError=Promise.TimeoutError;function HandleWrapper(handle){this.handle=handle}HandleWrapper.prototype._resultCancelled=function(){clearTimeout(this.handle)};function afterValue(value){return delay(+this).thenReturn(value)}var delay=Promise.delay=function(ms,value){var ret;return void 0!==value?(ret=Promise.resolve(value)._then(afterValue,null,null,ms,void 0),debug.cancellation()&&value instanceof Promise&&ret._setOnCancel(value)):(ret=new Promise(INTERNAL),value=setTimeout(function(){ret._fulfill()},+ms),debug.cancellation()&&ret._setOnCancel(new HandleWrapper(value)),ret._captureStackTrace()),ret._setAsyncGuaranteed(),ret};Promise.prototype.delay=function(ms){return delay(ms,this)};function successClear(value){return clearTimeout(this.handle),value}function failureClear(reason){throw clearTimeout(this.handle),reason}Promise.prototype.timeout=function(ms,message){ms=+ms;var ret,parent,ms=new HandleWrapper(setTimeout(function(){ret.isPending()&&!function(promise,message,parent){message="string"!=typeof message?message instanceof Error?message:new TimeoutError("operation timed out"):new TimeoutError(message);util.markAsOriginatingFromRejection(message),promise._attachExtraTrace(message),promise._reject(message),null!=parent&&parent.cancel()}(ret,message,parent)},ms));return debug.cancellation()?(parent=this.then(),(ret=parent._then(successClear,failureClear,void 0,ms,void 0))._setOnCancel(ms)):ret=this._then(successClear,failureClear,void 0,ms,void 0),ret}}},{"./util":36}],35:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug){var util=_dereq_("./util"),TypeError=_dereq_("./errors").TypeError,inherits=_dereq_("./util").inherits,errorObj=util.errorObj,tryCatch=util.tryCatch,NULL={};function thrower(e){setTimeout(function(){throw e},0)}function dispose(resources,inspection){var i=0,len=resources.length,ret=new Promise(INTERNAL);return function iterator(){if(len<=i)return ret._fulfill();var maybePromise=function(thenable){var maybePromise=tryConvertToPromise(thenable);return maybePromise!==thenable&&"function"==typeof thenable._isDisposable&&"function"==typeof thenable._getDisposer&&thenable._isDisposable()&&maybePromise._setDisposable(thenable._getDisposer()),maybePromise}(resources[i++]);if(maybePromise instanceof Promise&&maybePromise._isDisposable()){try{maybePromise=tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection),resources.promise)}catch(e){return thrower(e)}if(maybePromise instanceof Promise)return maybePromise._then(iterator,thrower,null,null,null)}iterator()}(),ret}function Disposer(data,promise,context){this._data=data,this._promise=promise,this._context=context}function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context)}function maybeUnwrapDisposer(value){return Disposer.isDisposer(value)?(this.resources[this.index]._setDisposable(value),value.promise()):value}function ResourceList(length){this.length=length,this.promise=null,this[length-1]=null}Disposer.prototype.data=function(){return this._data},Disposer.prototype.promise=function(){return this._promise},Disposer.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():NULL},Disposer.prototype.tryDispose=function(inspection){var resource=this.resource(),context=this._context,resource=(void 0!==context&&context._pushContext(),resource!==NULL?this.doDispose(resource,inspection):null);return void 0!==context&&context._popContext(),this._promise._unsetDisposable(),this._data=null,resource},Disposer.isDisposer=function(d){return null!=d&&"function"==typeof d.resource&&"function"==typeof d.tryDispose},inherits(FunctionDisposer,Disposer),FunctionDisposer.prototype.doDispose=function(resource,inspection){return this.data().call(resource,resource,inspection)},ResourceList.prototype._resultCancelled=function(){for(var len=this.length,i=0;i<len;++i){var item=this[i];item instanceof Promise&&item.cancel()}},Promise.using=function(){var len=arguments.length;if(len<2)return apiRejection("you must pass at least 2 arguments to Promise.using");var input,fn=arguments[len-1];if("function"!=typeof fn)return apiRejection("expecting a function but got "+util.classString(fn));for(var spreadArgs=!0,resources=(2===len&&Array.isArray(arguments[0])?(len=(input=arguments[0]).length,spreadArgs=!1):(input=arguments,len--),new ResourceList(len)),i=0;i<len;++i){var disposer,resource=input[i];Disposer.isDisposer(resource)?(resource=(disposer=resource).promise())._setDisposable(disposer):(disposer=tryConvertToPromise(resource))instanceof Promise&&(resource=disposer._then(maybeUnwrapDisposer,null,null,{resources:resources,index:i},void 0)),resources[i]=resource}for(var reflectedResources=new Array(resources.length),i=0;i<reflectedResources.length;++i)reflectedResources[i]=Promise.resolve(resources[i]).reflect();var resultPromise=Promise.all(reflectedResources).then(function(inspections){for(var i=0;i<inspections.length;++i){var inspection=inspections[i];if(inspection.isRejected())return errorObj.e=inspection.error(),errorObj;if(!inspection.isFulfilled())return void resultPromise.cancel();inspections[i]=inspection.value()}promise._pushContext(),fn=tryCatch(fn);var ret=spreadArgs?fn.apply(void 0,inspections):fn(inspections),promiseCreated=promise._popContext();return debug.checkForgottenReturns(ret,promiseCreated,"Promise.using",promise),ret}),promise=resultPromise.lastly(function(){var inspection=new Promise.PromiseInspection(resultPromise);return dispose(resources,inspection)});return(resources.promise=promise)._setOnCancel(resources),promise},Promise.prototype._setDisposable=function(disposer){this._bitField=131072|this._bitField,this._disposer=disposer},Promise.prototype._isDisposable=function(){return 0<(131072&this._bitField)},Promise.prototype._getDisposer=function(){return this._disposer},Promise.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},Promise.prototype.disposer=function(fn){if("function"==typeof fn)return new FunctionDisposer(fn,this,createContext());throw new TypeError}}},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5"),canEvaluate="undefined"==typeof navigator,errorObj={e:{}},tryCatchTarget,globalObject="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==global?global:void 0!==this?this:null;function tryCatcher(){try{var target=tryCatchTarget;return tryCatchTarget=null,target.apply(this,arguments)}catch(e){return errorObj.e=e,errorObj}}function tryCatch(fn){return tryCatchTarget=fn,tryCatcher}var inherits=function(Child,Parent){var hasProp={}.hasOwnProperty;function T(){for(var propertyName in this.constructor=Child,(this.constructor$=Parent).prototype)hasProp.call(Parent.prototype,propertyName)&&"$"!==propertyName.charAt(propertyName.length-1)&&(this[propertyName+"$"]=Parent.prototype[propertyName])}return T.prototype=Parent.prototype,Child.prototype=new T,Child.prototype};function isPrimitive(val){return null==val||!0===val||!1===val||"string"==typeof val||"number"==typeof val}function isObject(value){return"function"==typeof value||"object"==typeof value&&null!==value}function maybeWrapAsError(maybeError){return isPrimitive(maybeError)?new Error(safeToString(maybeError)):maybeError}function withAppended(target,appendee){for(var len=target.length,ret=new Array(len+1),i=0;i<len;++i)ret[i]=target[i];return ret[i]=appendee,ret}function getDataPropertyOrDefault(obj,key,defaultValue){var desc;return es5.isES5?null!=(desc=Object.getOwnPropertyDescriptor(obj,key))?null==desc.get&&null==desc.set?desc.value:defaultValue:void 0:{}.hasOwnProperty.call(obj,key)?obj[key]:void 0}function notEnumerableProp(obj,name,value){return isPrimitive(obj)||es5.defineProperty(obj,name,{value:value,configurable:!0,enumerable:!1,writable:!0}),obj}function thrower(r){throw r}var inheritedDataKeys=function(){function isExcludedProto(val){for(var i=0;i<excludedPrototypes.length;++i)if(excludedPrototypes[i]===val)return 1}var getKeys,hasProp,excludedPrototypes=[Array.prototype,Object.prototype,Function.prototype];return es5.isES5?(getKeys=Object.getOwnPropertyNames,function(obj){for(var keys,ret=[],visitedKeys=Object.create(null);null!=obj&&!isExcludedProto(obj);){try{keys=getKeys(obj)}catch(e){return ret}for(var i=0;i<keys.length;++i){var desc,key=keys[i];visitedKeys[key]||(visitedKeys[key]=!0,null!=(desc=Object.getOwnPropertyDescriptor(obj,key))&&null==desc.get&&null==desc.set&&ret.push(key))}obj=es5.getPrototypeOf(obj)}return ret}):(hasProp={}.hasOwnProperty,function(obj){if(isExcludedProto(obj))return[];var ret=[];enumeration:for(var key in obj){if(!hasProp.call(obj,key))for(var i=0;i<excludedPrototypes.length;++i)if(hasProp.call(excludedPrototypes[i],key))continue enumeration;ret.push(key)}return ret})}(),thisAssignmentPattern=/this\s*\.\s*\S+\s*=/;function isClass(fn){try{if("function"==typeof fn){var keys=es5.names(fn.prototype),hasMethods=es5.isES5&&1<keys.length,hasMethodsOtherThanConstructor=0<keys.length&&!(1===keys.length&&"constructor"===keys[0]),hasThisAssignmentAndStaticMethods=thisAssignmentPattern.test(fn+"")&&0<es5.names(fn).length;if(hasMethods||hasMethodsOtherThanConstructor||hasThisAssignmentAndStaticMethods)return!0}return!1}catch(e){return!1}}function toFastProperties(obj){function FakeConstructor(){}FakeConstructor.prototype=obj;var receiver=new FakeConstructor;function ic(){receiver.foo}return ic(),ic(),obj}var rident=/^[a-z$_][a-z$_0-9]*$/i;function isIdentifier(str){return rident.test(str)}function filledRange(count,prefix,suffix){for(var ret=new Array(count),i=0;i<count;++i)ret[i]=prefix+i+suffix;return ret}function safeToString(obj){try{return obj+""}catch(e){return"[no string representation]"}}function isError(obj){return obj instanceof Error||null!==obj&&"object"==typeof obj&&"string"==typeof obj.message&&"string"==typeof obj.name}function markAsOriginatingFromRejection(e){try{notEnumerableProp(e,"isOperational",!0)}catch(ignore){}}function originatesFromRejection(e){return null!=e&&(e instanceof Error.__BluebirdErrorTypes__.OperationalError||!0===e.isOperational)}function canAttachTrace(obj){return isError(obj)&&es5.propertyIsWritable(obj,"stack")}var ensureErrorObject="stack"in new Error?function(value){return canAttachTrace(value)?value:new Error(safeToString(value))}:function(value){if(canAttachTrace(value))return value;try{throw new Error(safeToString(value))}catch(err){return err}};function classString(obj){return{}.toString.call(obj)}function copyDescriptors(from,to,filter){for(var keys=es5.names(from),i=0;i<keys.length;++i){var key=keys[i];if(filter(key))try{es5.defineProperty(to,key,es5.getDescriptor(from,key))}catch(ignore){}}}var asArray=function(v){return es5.isArray(v)?v:null},ArrayFrom,asArray,isNode=("undefined"!=typeof Symbol&&Symbol.iterator&&(ArrayFrom="function"==typeof Array.from?function(v){return Array.from(v)}:function(v){for(var itResult,ret=[],it=v[Symbol.iterator]();!(itResult=it.next()).done;)ret.push(itResult.value);return ret},asArray=function(v){return es5.isArray(v)?v:null!=v&&"function"==typeof v[Symbol.iterator]?ArrayFrom(v):null}),void 0!==process&&"[object process]"===classString(process).toLowerCase()),hasEnvVariables=void 0!==process&&void 0!==process.env,reflectHandler;function env(key){return hasEnvVariables?process.env[key]:void 0}function getNativePromise(){if("function"==typeof Promise)try{if("[object Promise]"===classString(new Promise(function(){})))return Promise}catch(e){}}function contextBind(ctx,cb){var async,old;return null!==ctx&&"function"==typeof cb&&cb!==reflectHandler&&(null!==ctx.domain&&(cb=ctx.domain.bind(cb)),null!==(async=ctx.async))&&(old=cb,cb=function(){var args=new Array(2).concat([].slice.call(arguments));return args[0]=old,args[1]=this,async.runInAsyncScope.apply(async,args)}),cb}var ret={setReflectHandler:function(fn){reflectHandler=fn},isClass:isClass,isIdentifier:isIdentifier,inheritedDataKeys:inheritedDataKeys,getDataPropertyOrDefault:getDataPropertyOrDefault,thrower:thrower,isArray:es5.isArray,asArray:asArray,notEnumerableProp:notEnumerableProp,isPrimitive:isPrimitive,isObject:isObject,isError:isError,canEvaluate:canEvaluate,errorObj:errorObj,tryCatch:tryCatch,inherits:inherits,withAppended:withAppended,maybeWrapAsError:maybeWrapAsError,toFastProperties:toFastProperties,filledRange:filledRange,toString:safeToString,canAttachTrace:canAttachTrace,ensureErrorObject:ensureErrorObject,originatesFromRejection:originatesFromRejection,markAsOriginatingFromRejection:markAsOriginatingFromRejection,classString:classString,copyDescriptors:copyDescriptors,isNode:isNode,hasEnvVariables:hasEnvVariables,env:env,global:globalObject,getNativePromise:getNativePromise,contextBind:contextBind};ret.isRecentNode=ret.isNode&&function(){var version;return process.versions&&process.versions.node?version=process.versions.node.split(".").map(Number):process.version&&(version=process.version.split(".").map(Number)),0===version[0]&&10<version[1]||0<version[0]}(),ret.nodeSupportsAsyncResource=ret.isNode&&function(){var supportsAsync=!1;try{supportsAsync="function"==typeof _dereq_("async_hooks").AsyncResource.prototype.runInAsyncScope}catch(e){supportsAsync=!1}return supportsAsync}(),ret.isNode&&ret.toFastProperties(process);try{throw new Error}catch(e){ret.lastLineError=e}module.exports=ret},{"./es5":13,async_hooks:void 0}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}.call(this)}.call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require("timers").setImmediate)},{_process:1042,timers:1695}],113:[function(require,module,exports){!function(Buffer){!function(){"use strict";var base64=require("base64-js"),ieee754=require("ieee754"),K_MAX_LENGTH=(exports.Buffer=Buffer,exports.SlowBuffer=function(length){+length!=length&&(length=0);return Buffer.alloc(+length)},exports.INSPECT_MAX_BYTES=50,2147483647);function createBuffer(length){if(K_MAX_LENGTH<length)throw new RangeError('The value "'+length+'" is invalid for option "size"');length=new Uint8Array(length);return length.__proto__=Buffer.prototype,length}function Buffer(arg,encodingOrOffset,length){if("number"!=typeof arg)return from(arg,encodingOrOffset,length);if("string"==typeof encodingOrOffset)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(arg)}function from(value,encodingOrOffset,length){if("string"==typeof value)return function(string,encoding){"string"==typeof encoding&&""!==encoding||(encoding="utf8");if(!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),string=buf.write(string,encoding);string!==length&&(buf=buf.slice(0,string));return buf}(value,encodingOrOffset);if(ArrayBuffer.isView(value))return fromArrayLike(value);if(null==value)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return function(array,byteOffset,length){if(byteOffset<0||array.byteLength<byteOffset)throw new RangeError('"offset" is outside of buffer bounds');if(array.byteLength<byteOffset+(length||0))throw new RangeError('"length" is outside of buffer bounds');array=void 0===byteOffset&&void 0===length?new Uint8Array(array):void 0===length?new Uint8Array(array,byteOffset):new Uint8Array(array,byteOffset,length);return array.__proto__=Buffer.prototype,array}(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('The "value" argument must not be of type number. Received type number');var valueOf=value.valueOf&&value.valueOf();if(null!=valueOf&&valueOf!==value)return Buffer.from(valueOf,encodingOrOffset,length);valueOf=function(obj){{var len,buf;if(Buffer.isBuffer(obj))return len=0|checked(obj.length),0!==(buf=createBuffer(len)).length&&obj.copy(buf,0,0,len),buf}if(void 0!==obj.length)return"number"!=typeof obj.length||numberIsNaN(obj.length)?createBuffer(0):fromArrayLike(obj);if("Buffer"===obj.type&&Array.isArray(obj.data))return fromArrayLike(obj.data)}(value);if(valueOf)return valueOf;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof value[Symbol.toPrimitive])return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value)}function assertSize(size){if("number"!=typeof size)throw new TypeError('"size" argument must be of type number');if(size<0)throw new RangeError('The value "'+size+'" is invalid for option "size"')}function allocUnsafe(size){return assertSize(size),createBuffer(size<0?0:0|checked(size))}function fromArrayLike(array){for(var length=array.length<0?0:0|checked(array.length),buf=createBuffer(length),i=0;i<length;i+=1)buf[i]=255&array[i];return buf}function checked(length){if(K_MAX_LENGTH<=length)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes");return 0|length}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof string);var len=string.length,mustMatch=2<arguments.length&&!0===arguments[2];if(!mustMatch&&0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((start=void 0===start||start<0?0:start)>this.length)return"";if((end=void 0===end||end>this.length?this.length:end)<=0)return"";if((end>>>=0)<=(start>>>=0))return"";for(encoding=encoding||"utf8";;)switch(encoding){case"hex":return function(buf,start,end){var len=buf.length;(!start||start<0)&&(start=0);(!end||end<0||len<end)&&(end=len);for(var out="",i=start;i<end;++i)out+=function(n){return n<16?"0"+n.toString(16):n.toString(16)}(buf[i]);return out}(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return function(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i)ret+=String.fromCharCode(127&buf[i]);return ret}(this,start,end);case"latin1":case"binary":return function(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i)ret+=String.fromCharCode(buf[i]);return ret}(this,start,end);case"base64":return function(buf,start,end){return 0===start&&end===buf.length?base64.fromByteArray(buf):base64.fromByteArray(buf.slice(start,end))}(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(buf,start,end){for(var bytes=buf.slice(start,end),res="",i=0;i<bytes.length;i+=2)res+=String.fromCharCode(bytes[i]+256*bytes[i+1]);return res}(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):2147483647<byteOffset?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),(byteOffset=(byteOffset=numberIsNaN(byteOffset=+byteOffset)?dir?0:buffer.length-1:byteOffset)<0?buffer.length+byteOffset:byteOffset)>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?(dir?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;arrLength/=indexSize=2,valLength/=2,byteOffset/=2}function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}if(dir)for(var foundIndex=-1,i=byteOffset;i<arrLength;i++)if(read(arr,i)===read(val,-1===foundIndex?0:i-foundIndex)){if(i-(foundIndex=-1===foundIndex?i:foundIndex)+1===valLength)return foundIndex*indexSize}else-1!==foundIndex&&(i-=i-foundIndex),foundIndex=-1;else for(i=byteOffset=arrLength<byteOffset+valLength?arrLength-valLength:byteOffset;0<=i;i--){for(var found=!0,j=0;j<valLength;j++)if(read(arr,i+j)!==read(val,j)){found=!1;break}if(found)return i}return-1}function asciiWrite(buf,string,offset,length){return blitBuffer(function(str){for(var byteArray=[],i=0;i<str.length;++i)byteArray.push(255&str.charCodeAt(i));return byteArray}(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(function(str,units){for(var c,hi,byteArray=[],i=0;i<str.length&&!((units-=2)<0);++i)c=str.charCodeAt(i),hi=c>>8,byteArray.push(c%256),byteArray.push(hi);return byteArray}(string,buf.length-offset),buf,offset,length)}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);for(var res=[],i=start;i<end;){var secondByte,thirdByte,fourthByte,tempCodePoint,firstByte=buf[i],codePoint=null,bytesPerSequence=239<firstByte?4:223<firstByte?3:191<firstByte?2:1;if(i+bytesPerSequence<=end)switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:128==(192&(secondByte=buf[i+1]))&&127<(tempCodePoint=(31&firstByte)<<6|63&secondByte)&&(codePoint=tempCodePoint);break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&2047<(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte)&&(tempCodePoint<55296||57343<tempCodePoint)&&(codePoint=tempCodePoint);break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&65535<(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte)&&tempCodePoint<1114112&&(codePoint=tempCodePoint)}null===codePoint?(codePoint=65533,bytesPerSequence=1):65535<codePoint&&(res.push((codePoint-=65536)>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return function(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);var res="",i=0;for(;i<len;)res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH));return res}(res)}exports.kMaxLength=K_MAX_LENGTH,(Buffer.TYPED_ARRAY_SUPPORT=function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()}catch(e){return!1}}())||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.buffer}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),Buffer.poolSize=8192,Buffer.from=from,Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,Buffer.alloc=function(size,fill,encoding){return assertSize(size),!(size<=0)&&void 0!==fill?"string"==typeof encoding?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill):createBuffer(size)},Buffer.allocUnsafe=allocUnsafe,Buffer.allocUnsafeSlow=allocUnsafe,Buffer.isBuffer=function(b){return null!=b&&!0===b._isBuffer&&b!==Buffer.prototype},Buffer.compare=function(a,b){if(isInstance(a,Uint8Array)&&(a=Buffer.from(a,a.offset,a.byteLength)),isInstance(b,Uint8Array)&&(b=Buffer.from(b,b.offset,b.byteLength)),!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i<len;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return x<y?-1:y<x?1:0},Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Buffer.concat=function(list,length){if(!Array.isArray(list))throw new TypeError('"list" argument must be an Array of Buffers');if(0===list.length)return Buffer.alloc(0);if(void 0===length)for(i=length=0;i<list.length;++i)length+=list[i].length;for(var buffer=Buffer.allocUnsafe(length),pos=0,i=0;i<list.length;++i){var buf=list[i];if(isInstance(buf,Uint8Array)&&(buf=Buffer.from(buf)),!Buffer.isBuffer(buf))throw new TypeError('"list" argument must be an Array of Buffers');buf.copy(buffer,pos),pos+=buf.length}return buffer},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function(){var len=this.length;if(len%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var i=0;i<len;i+=2)swap(this,i,i+1);return this},Buffer.prototype.swap32=function(){var len=this.length;if(len%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var i=0;i<len;i+=4)swap(this,i,i+3),swap(this,i+1,i+2);return this},Buffer.prototype.swap64=function(){var len=this.length;if(len%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;i<len;i+=8)swap(this,i,i+7),swap(this,i+1,i+6),swap(this,i+2,i+5),swap(this,i+3,i+4);return this},Buffer.prototype.toLocaleString=Buffer.prototype.toString=function(){var length=this.length;return 0===length?"":0===arguments.length?utf8Slice(this,0,length):slowToString.apply(this,arguments)},Buffer.prototype.equals=function(b){if(Buffer.isBuffer(b))return this===b||0===Buffer.compare(this,b);throw new TypeError("Argument must be a Buffer")},Buffer.prototype.inspect=function(){var str="",max=exports.INSPECT_MAX_BYTES,str=this.toString("hex",0,max).replace(/(.{2})/g,"$1 ").trim();return this.length>max&&(str+=" ... "),"<Buffer "+str+">"},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof target);if(void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),(start=void 0===start?0:start)<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisEnd<=thisStart&&end<=start)return 0;if(thisEnd<=thisStart)return-1;if(end<=start)return 1;if(this===target)return 0;for(var x=(thisEnd>>>=0)-(thisStart>>>=0),y=(end>>>=0)-(start>>>=0),len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i<len;++i)if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i],y=targetCopy[i];break}return x<y?-1:y<x?1:0},Buffer.prototype.includes=function(val,byteOffset,encoding){return-1!==this.indexOf(val,byteOffset,encoding)},Buffer.prototype.indexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!0)},Buffer.prototype.lastIndexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!1)},Buffer.prototype.write=function(string,offset,length,encoding){if(void 0===offset)encoding="utf8",length=this.length,offset=0;else if(void 0===length&&"string"==typeof offset)encoding=offset,length=this.length,offset=0;else{if(!isFinite(offset))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");offset>>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}var remaining=this.length-offset;if((void 0===length||remaining<length)&&(length=remaining),0<string.length&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding=encoding||"utf8";for(var loweredCase=!1;;)switch(encoding){case"hex":return function(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;(!length||remaining<(length=Number(length)))&&(length=remaining),(remaining=string.length)/2<length&&(length=remaining/2);for(var i=0;i<length;++i){var parsed=parseInt(string.substr(2*i,2),16);if(numberIsNaN(parsed))return i;buf[offset+i]=parsed}return i}(this,string,offset,length);case"utf8":case"utf-8":return function(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return asciiWrite(this,string,offset,length);case"base64":return function(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function checkOffset(offset,ext,length){if(offset%1!=0||offset<0)throw new RangeError("offset is not uint");if(length<offset+ext)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(max<value||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}function checkIEEE754(buf,value,offset,ext){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,0,offset,4),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,0,offset,8),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}Buffer.prototype.slice=function(start,end){var len=this.length,len=((start=~~start)<0?(start+=len)<0&&(start=0):len<start&&(start=len),(end=void 0===end?len:~~end)<0?(end+=len)<0&&(end=0):len<end&&(end=len),end<start&&(end=start),this.subarray(start,end));return len.__proto__=Buffer.prototype,len},Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i<byteLength&&(mul*=256);)val+=this[offset+i]*mul;return val},Buffer.prototype.readUIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;0<byteLength&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i<byteLength&&(mul*=256);)val+=this[offset+i]*mul;return(mul*=128)<=val&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];0<i&&(mul*=256);)val+=this[offset+--i]*mul;return(mul*=128)<=val&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);noAssert=this[offset]|this[offset+1]<<8;return 32768&noAssert?4294901760|noAssert:noAssert},Buffer.prototype.readInt16BE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);noAssert=this[offset+1]|this[offset]<<8;return 32768&noAssert?4294901760|noAssert:noAssert},Buffer.prototype.readInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){value=+value,offset>>>=0,byteLength>>>=0,noAssert||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0);var mul=1,i=0;for(this[offset]=255&value;++i<byteLength&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUIntBE=function(value,offset,byteLength,noAssert){value=+value,offset>>>=0,byteLength>>>=0,noAssert||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0);var i=byteLength-1,mul=1;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,byteLength,(noAssert=Math.pow(2,8*byteLength-1))-1,-noAssert);var i=0,mul=1,sub=0;for(this[offset]=255&value;++i<byteLength&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,byteLength,(noAssert=Math.pow(2,8*byteLength-1))-1,-noAssert);var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),this[offset]=255&(value=value<0?255+value+1:value),offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=(value=value<0?4294967295+value+1:value)>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start=start||0,end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),(end=0<end&&end<start?start:end)===start)return 0;if(0===target.length||0===this.length)return 0;if((targetStart=targetStart||0)<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length);var len=(end=target.length-targetStart<end-start?target.length-targetStart+start:end)-start;if(this===target&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(targetStart,start,end);else if(this===target&&start<targetStart&&targetStart<end)for(var i=len-1;0<=i;--i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart);return len},Buffer.prototype.fill=function(val,start,end,encoding){if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=this.length):"string"==typeof end&&(encoding=end,end=this.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var code;1===val.length&&(code=val.charCodeAt(0),"utf8"===encoding&&code<128||"latin1"===encoding)&&(val=code)}else"number"==typeof val&&(val&=255);if(start<0||this.length<start||this.length<end)throw new RangeError("Out of range index");var i;if(!(end<=start))if(start>>>=0,end=void 0===end?this.length:end>>>0,"number"==typeof(val=val||0))for(i=start;i<end;++i)this[i]=val;else{var bytes=Buffer.isBuffer(val)?val:Buffer.from(val,encoding),len=bytes.length;if(0===len)throw new TypeError('The value "'+val+'" is invalid for argument "value"');for(i=0;i<end-start;++i)this[i+start]=bytes[i%len]}return this};var INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i<length;++i){if(55295<(codePoint=string.charCodeAt(i))&&codePoint<57344){if(!leadSurrogate){if(56319<codePoint){-1<(units-=3)&&bytes.push(239,191,189);continue}if(i+1===length){-1<(units-=3)&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){-1<(units-=3)&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&-1<(units-=3)&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if(--units<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function base64ToBytes(str){return base64.toByteArray(function(str){if((str=(str=str.split("=")[0]).trim().replace(INVALID_BASE64_RE,"")).length<2)return"";for(;str.length%4!=0;)str+="=";return str}(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length&&!(i+offset>=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!=obj}}.call(this)}.call(this,require("buffer").Buffer)},{"base64-js":111,buffer:113,ieee754:656}],114:[function(require,module,exports){"use strict";var GetIntrinsic=require("get-intrinsic"),callBind=require("./"),$indexOf=callBind(GetIntrinsic("String.prototype.indexOf"));module.exports=function(name,allowMissing){allowMissing=GetIntrinsic(name,!!allowMissing);return"function"==typeof allowMissing&&-1<$indexOf(name,".prototype.")?callBind(allowMissing):allowMissing}},{"./":115,"get-intrinsic":644}],115:[function(require,module,exports){"use strict";var bind=require("function-bind"),require=require("get-intrinsic"),$apply=require("%Function.prototype.apply%"),$call=require("%Function.prototype.call%"),$reflectApply=require("%Reflect.apply%",!0)||bind.call($call,$apply),$gOPD=require("%Object.getOwnPropertyDescriptor%",!0),$defineProperty=require("%Object.defineProperty%",!0),$max=require("%Math.max%");if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=null}module.exports=function(originalFunction){var func=$reflectApply(bind,$call,arguments);return $gOPD&&$defineProperty&&$gOPD(func,"length").configurable&&$defineProperty(func,"length",{value:1+$max(0,originalFunction.length-(arguments.length-1))}),func};function applyBind(){return $reflectApply(bind,$apply,arguments)}$defineProperty?$defineProperty(module.exports,"apply",{value:applyBind}):module.exports.apply=applyBind},{"function-bind":642,"get-intrinsic":644}],116:[function(require,module,exports){!function(){"use strict";var hasOwn={}.hasOwnProperty;function classNames(){for(var classes=[],i=0;i<arguments.length;i++){var arg=arguments[i];if(arg){var inner,argType=typeof arg;if("string"==argType||"number"==argType)classes.push(arg);else if(Array.isArray(arg))arg.length&&(inner=classNames.apply(null,arg))&&classes.push(inner);else if("object"==argType)if(arg.toString===Object.prototype.toString||arg.toString.toString().includes("[native code]"))for(var key in arg)hasOwn.call(arg,key)&&arg[key]&&classes.push(key);else classes.push(arg.toString())}}return classes.join(" ")}void 0!==module&&module.exports?module.exports=classNames.default=classNames:"function"==typeof define&&"object"==typeof define.amd&&define.amd?define("classnames",[],function(){return classNames}):window.classNames=classNames}()},{}],117:[function(require,module,exports){var isCallable=require("../internals/is-callable"),tryToString=require("../internals/try-to-string"),$TypeError=TypeError;module.exports=function(argument){if(isCallable(argument))return argument;throw $TypeError(tryToString(argument)+" is not a function")}},{"../internals/is-callable":232,"../internals/try-to-string":339}],118:[function(require,module,exports){var isConstructor=require("../internals/is-constructor"),tryToString=require("../internals/try-to-string"),$TypeError=TypeError;module.exports=function(argument){if(isConstructor(argument))return argument;throw $TypeError(tryToString(argument)+" is not a constructor")}},{"../internals/is-constructor":233,"../internals/try-to-string":339}],119:[function(require,module,exports){var isCallable=require("../internals/is-callable"),$String=String,$TypeError=TypeError;module.exports=function(argument){if("object"==typeof argument||isCallable(argument))return argument;throw $TypeError("Can't set "+$String(argument)+" as a prototype")}},{"../internals/is-callable":232}],120:[function(require,module,exports){var wellKnownSymbol=require("../internals/well-known-symbol"),create=require("../internals/object-create"),require=require("../internals/object-define-property").f,UNSCOPABLES=wellKnownSymbol("unscopables"),ArrayPrototype=Array.prototype;null==ArrayPrototype[UNSCOPABLES]&&require(ArrayPrototype,UNSCOPABLES,{configurable:!0,value:create(null)}),module.exports=function(key){ArrayPrototype[UNSCOPABLES][key]=!0}},{"../internals/object-create":265,"../internals/object-define-property":267,"../internals/well-known-symbol":353}],121:[function(require,module,exports){"use strict";var charAt=require("../internals/string-multibyte").charAt;module.exports=function(S,index,unicode){return index+(unicode?charAt(S,index).length:1)}},{"../internals/string-multibyte":310}],122:[function(require,module,exports){var isPrototypeOf=require("../internals/object-is-prototype-of"),$TypeError=TypeError;module.exports=function(it,Prototype){if(isPrototypeOf(Prototype,it))return it;throw $TypeError("Incorrect invocation")}},{"../internals/object-is-prototype-of":274}],123:[function(require,module,exports){var isObject=require("../internals/is-object"),$String=String,$TypeError=TypeError;module.exports=function(argument){if(isObject(argument))return argument;throw $TypeError($String(argument)+" is not an object")}},{"../internals/is-object":238}],124:[function(require,module,exports){module.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},{}],125:[function(require,module,exports){require=require("../internals/fails");module.exports=require(function(){var buffer;"function"==typeof ArrayBuffer&&(buffer=new ArrayBuffer(8),Object.isExtensible(buffer))&&Object.defineProperty(buffer,"a",{value:8})})},{"../internals/fails":197}],126:[function(require,module,exports){"use strict";function getTypedArrayConstructor(it){var state,it=getPrototypeOf(it);if(isObject(it))return(state=getInternalState(it))&&hasOwn(state,"TypedArrayConstructor")?state.TypedArrayConstructor:getTypedArrayConstructor(it)}function isTypedArray(it){return!!isObject(it)&&(it=classof(it),hasOwn(TypedArrayConstructorsList,it)||hasOwn(BigIntArrayConstructorsList,it))}var NAME,Constructor,Prototype,NATIVE_ARRAY_BUFFER=require("../internals/array-buffer-basic-detection"),DESCRIPTORS=require("../internals/descriptors"),global=require("../internals/global"),isCallable=require("../internals/is-callable"),isObject=require("../internals/is-object"),hasOwn=require("../internals/has-own-property"),classof=require("../internals/classof"),tryToString=require("../internals/try-to-string"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),defineBuiltIn=require("../internals/define-built-in"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),isPrototypeOf=require("../internals/object-is-prototype-of"),getPrototypeOf=require("../internals/object-get-prototype-of"),setPrototypeOf=require("../internals/object-set-prototype-of"),wellKnownSymbol=require("../internals/well-known-symbol"),uid=require("../internals/uid"),require=require("../internals/internal-state"),enforceInternalState=require.enforce,getInternalState=require.get,require=global.Int8Array,Int8ArrayPrototype=require&&require.prototype,Uint8ClampedArray=global.Uint8ClampedArray,Uint8ClampedArray=Uint8ClampedArray&&Uint8ClampedArray.prototype,TypedArray=require&&getPrototypeOf(require),TypedArrayPrototype=Int8ArrayPrototype&&getPrototypeOf(Int8ArrayPrototype),require=Object.prototype,TypeError=global.TypeError,wellKnownSymbol=wellKnownSymbol("toStringTag"),TYPED_ARRAY_TAG=uid("TYPED_ARRAY_TAG"),NATIVE_ARRAY_BUFFER_VIEWS=NATIVE_ARRAY_BUFFER&&!!setPrototypeOf&&"Opera"!==classof(global.opera),uid=!1,TypedArrayConstructorsList={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},BigIntArrayConstructorsList={BigInt64Array:8,BigUint64Array:8};for(NAME in TypedArrayConstructorsList)(Prototype=(Constructor=global[NAME])&&Constructor.prototype)?enforceInternalState(Prototype).TypedArrayConstructor=Constructor:NATIVE_ARRAY_BUFFER_VIEWS=!1;for(NAME in BigIntArrayConstructorsList)(Prototype=(Constructor=global[NAME])&&Constructor.prototype)&&(enforceInternalState(Prototype).TypedArrayConstructor=Constructor);if((!NATIVE_ARRAY_BUFFER_VIEWS||!isCallable(TypedArray)||TypedArray===Function.prototype)&&(TypedArray=function(){throw TypeError("Incorrect invocation")},NATIVE_ARRAY_BUFFER_VIEWS))for(NAME in TypedArrayConstructorsList)global[NAME]&&setPrototypeOf(global[NAME],TypedArray);if((!NATIVE_ARRAY_BUFFER_VIEWS||!TypedArrayPrototype||TypedArrayPrototype===require)&&(TypedArrayPrototype=TypedArray.prototype,NATIVE_ARRAY_BUFFER_VIEWS))for(NAME in TypedArrayConstructorsList)global[NAME]&&setPrototypeOf(global[NAME].prototype,TypedArrayPrototype);if(NATIVE_ARRAY_BUFFER_VIEWS&&getPrototypeOf(Uint8ClampedArray)!==TypedArrayPrototype&&setPrototypeOf(Uint8ClampedArray,TypedArrayPrototype),DESCRIPTORS&&!hasOwn(TypedArrayPrototype,wellKnownSymbol))for(NAME in defineBuiltInAccessor(TypedArrayPrototype,wellKnownSymbol,{configurable:uid=!0,get:function(){return isObject(this)?this[TYPED_ARRAY_TAG]:void 0}}),TypedArrayConstructorsList)global[NAME]&&createNonEnumerableProperty(global[NAME],TYPED_ARRAY_TAG,NAME);module.exports={NATIVE_ARRAY_BUFFER_VIEWS:NATIVE_ARRAY_BUFFER_VIEWS,TYPED_ARRAY_TAG:uid&&TYPED_ARRAY_TAG,aTypedArray:function(it){if(isTypedArray(it))return it;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(C){if(!isCallable(C)||setPrototypeOf&&!isPrototypeOf(TypedArray,C))throw TypeError(tryToString(C)+" is not a typed array constructor");return C},exportTypedArrayMethod:function(KEY,property,forced,options){if(DESCRIPTORS){if(forced)for(var ARRAY in TypedArrayConstructorsList){ARRAY=global[ARRAY];if(ARRAY&&hasOwn(ARRAY.prototype,KEY))try{delete ARRAY.prototype[KEY]}catch(error){try{ARRAY.prototype[KEY]=property}catch(error2){}}}TypedArrayPrototype[KEY]&&!forced||defineBuiltIn(TypedArrayPrototype,KEY,!forced&&NATIVE_ARRAY_BUFFER_VIEWS&&Int8ArrayPrototype[KEY]||property,options)}},exportTypedArrayStaticMethod:function(KEY,property,forced){var ARRAY,TypedArrayConstructor;if(DESCRIPTORS){if(setPrototypeOf){if(forced)for(ARRAY in TypedArrayConstructorsList)if((TypedArrayConstructor=global[ARRAY])&&hasOwn(TypedArrayConstructor,KEY))try{delete TypedArrayConstructor[KEY]}catch(error){}if(TypedArray[KEY]&&!forced)return;try{return defineBuiltIn(TypedArray,KEY,!forced&&NATIVE_ARRAY_BUFFER_VIEWS&&TypedArray[KEY]||property)}catch(error){}}for(ARRAY in TypedArrayConstructorsList)!(TypedArrayConstructor=global[ARRAY])||TypedArrayConstructor[KEY]&&!forced||defineBuiltIn(TypedArrayConstructor,KEY,property)}},getTypedArrayConstructor:getTypedArrayConstructor,isView:function(it){return!!isObject(it)&&("DataView"===(it=classof(it))||hasOwn(TypedArrayConstructorsList,it)||hasOwn(BigIntArrayConstructorsList,it))},isTypedArray:isTypedArray,TypedArray:TypedArray,TypedArrayPrototype:TypedArrayPrototype}},{"../internals/array-buffer-basic-detection":124,"../internals/classof":152,"../internals/create-non-enumerable-property":161,"../internals/define-built-in":167,"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/global":216,"../internals/has-own-property":217,"../internals/internal-state":228,"../internals/is-callable":232,"../internals/is-object":238,"../internals/object-get-prototype-of":272,"../internals/object-is-prototype-of":274,"../internals/object-set-prototype-of":279,"../internals/try-to-string":339,"../internals/uid":345,"../internals/well-known-symbol":353}],127:[function(require,module,exports){"use strict";function packInt8(number){return[255&number]}function packInt16(number){return[255&number,number>>8&255]}function packInt32(number){return[255&number,number>>8&255,number>>16&255,number>>24&255]}function unpackInt32(buffer){return buffer[3]<<24|buffer[2]<<16|buffer[1]<<8|buffer[0]}function packFloat32(number){return packIEEE754(number,23,4)}function packFloat64(number){return packIEEE754(number,52,8)}function addGetter(Constructor,key,getInternalState){defineBuiltInAccessor(Constructor.prototype,key,{configurable:!0,get:function(){return getInternalState(this)[key]}})}function get(view,count,index,isLittleEndian){if(index=toIndex(index),view=getInternalDataViewState(view),index+count>view.byteLength)throw RangeError("Wrong index");var bytes=view.bytes,index=index+view.byteOffset,view=arraySlice(bytes,index,index+count);return isLittleEndian?view:reverse(view)}function set(view,count,index,conversion,value,isLittleEndian){if(index=toIndex(index),view=getInternalDataViewState(view),index+count>view.byteLength)throw RangeError("Wrong index");for(var bytes=view.bytes,start=index+view.byteOffset,pack=conversion(+value),i=0;i<count;i++)bytes[start+i]=pack[isLittleEndian?i:count-i-1]}var global=require("../internals/global"),uncurryThis=require("../internals/function-uncurry-this"),DESCRIPTORS=require("../internals/descriptors"),NATIVE_ARRAY_BUFFER=require("../internals/array-buffer-basic-detection"),FunctionName=require("../internals/function-name"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),defineBuiltIns=require("../internals/define-built-ins"),fails=require("../internals/fails"),anInstance=require("../internals/an-instance"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),toLength=require("../internals/to-length"),toIndex=require("../internals/to-index"),IEEE754=require("../internals/ieee754"),getPrototypeOf=require("../internals/object-get-prototype-of"),setPrototypeOf=require("../internals/object-set-prototype-of"),getOwnPropertyNames=require("../internals/object-get-own-property-names").f,arrayFill=require("../internals/array-fill"),arraySlice=require("../internals/array-slice-simple"),setToStringTag=require("../internals/set-to-string-tag"),require=require("../internals/internal-state"),PROPER_FUNCTION_NAME=FunctionName.PROPER,CONFIGURABLE_FUNCTION_NAME=FunctionName.CONFIGURABLE,getInternalArrayBufferState=require.getterFor("ArrayBuffer"),getInternalDataViewState=require.getterFor("DataView"),setInternalState=require.set,NativeArrayBuffer=global.ArrayBuffer,$ArrayBuffer=NativeArrayBuffer,ArrayBufferPrototype=$ArrayBuffer&&$ArrayBuffer.prototype,FunctionName=global.DataView,DataViewPrototype=FunctionName&&FunctionName.prototype,require=Object.prototype,Array=global.Array,RangeError=global.RangeError,fill=uncurryThis(arrayFill),reverse=uncurryThis([].reverse),packIEEE754=IEEE754.pack,unpackIEEE754=IEEE754.unpack;if(NATIVE_ARRAY_BUFFER){var INCORRECT_ARRAY_BUFFER_NAME=PROPER_FUNCTION_NAME&&"ArrayBuffer"!==NativeArrayBuffer.name;if(fails(function(){NativeArrayBuffer(1)})&&fails(function(){new NativeArrayBuffer(-1)})&&!fails(function(){return new NativeArrayBuffer,new NativeArrayBuffer(1.5),new NativeArrayBuffer(NaN),1!=NativeArrayBuffer.length||INCORRECT_ARRAY_BUFFER_NAME&&!CONFIGURABLE_FUNCTION_NAME}))INCORRECT_ARRAY_BUFFER_NAME&&CONFIGURABLE_FUNCTION_NAME&&createNonEnumerableProperty(NativeArrayBuffer,"name","ArrayBuffer");else{($ArrayBuffer=function(length){return anInstance(this,ArrayBufferPrototype),new NativeArrayBuffer(toIndex(length))}).prototype=ArrayBufferPrototype;for(var key,keys=getOwnPropertyNames(NativeArrayBuffer),j=0;keys.length>j;)(key=keys[j++])in $ArrayBuffer||createNonEnumerableProperty($ArrayBuffer,key,NativeArrayBuffer[key]);ArrayBufferPrototype.constructor=$ArrayBuffer}setPrototypeOf&&getPrototypeOf(DataViewPrototype)!==require&&setPrototypeOf(DataViewPrototype,require);var global=new FunctionName(new $ArrayBuffer(2)),$setInt8=uncurryThis(DataViewPrototype.setInt8);global.setInt8(0,2147483648),global.setInt8(1,2147483649),!global.getInt8(0)&&global.getInt8(1)||defineBuiltIns(DataViewPrototype,{setInt8:function(byteOffset,value){$setInt8(this,byteOffset,value<<24>>24)},setUint8:function(byteOffset,value){$setInt8(this,byteOffset,value<<24>>24)}},{unsafe:!0})}else ArrayBufferPrototype=($ArrayBuffer=function(length){anInstance(this,ArrayBufferPrototype);length=toIndex(length);setInternalState(this,{type:"ArrayBuffer",bytes:fill(Array(length),0),byteLength:length}),DESCRIPTORS||(this.byteLength=length,this.detached=!1)}).prototype,DataViewPrototype=(FunctionName=function(buffer,byteOffset,byteLength){anInstance(this,DataViewPrototype),anInstance(buffer,ArrayBufferPrototype);var bufferState=getInternalArrayBufferState(buffer),bufferLength=bufferState.byteLength,byteOffset=toIntegerOrInfinity(byteOffset);if(byteOffset<0||bufferLength<byteOffset)throw RangeError("Wrong offset");if(bufferLength<byteOffset+(byteLength=void 0===byteLength?bufferLength-byteOffset:toLength(byteLength)))throw RangeError("Wrong length");setInternalState(this,{type:"DataView",buffer:buffer,byteLength:byteLength,byteOffset:byteOffset,bytes:bufferState.bytes}),DESCRIPTORS||(this.buffer=buffer,this.byteLength=byteLength,this.byteOffset=byteOffset)}).prototype,DESCRIPTORS&&(addGetter($ArrayBuffer,"byteLength",getInternalArrayBufferState),addGetter(FunctionName,"buffer",getInternalDataViewState),addGetter(FunctionName,"byteLength",getInternalDataViewState),addGetter(FunctionName,"byteOffset",getInternalDataViewState)),defineBuiltIns(DataViewPrototype,{getInt8:function(byteOffset){return get(this,1,byteOffset)[0]<<24>>24},getUint8:function(byteOffset){return get(this,1,byteOffset)[0]},getInt16:function(byteOffset){byteOffset=get(this,2,byteOffset,1<arguments.length?arguments[1]:void 0);return(byteOffset[1]<<8|byteOffset[0])<<16>>16},getUint16:function(byteOffset){byteOffset=get(this,2,byteOffset,1<arguments.length?arguments[1]:void 0);return byteOffset[1]<<8|byteOffset[0]},getInt32:function(byteOffset){return unpackInt32(get(this,4,byteOffset,1<arguments.length?arguments[1]:void 0))},getUint32:function(byteOffset){return unpackInt32(get(this,4,byteOffset,1<arguments.length?arguments[1]:void 0))>>>0},getFloat32:function(byteOffset){return unpackIEEE754(get(this,4,byteOffset,1<arguments.length?arguments[1]:void 0),23)},getFloat64:function(byteOffset){return unpackIEEE754(get(this,8,byteOffset,1<arguments.length?arguments[1]:void 0),52)},setInt8:function(byteOffset,value){set(this,1,byteOffset,packInt8,value)},setUint8:function(byteOffset,value){set(this,1,byteOffset,packInt8,value)},setInt16:function(byteOffset,value){set(this,2,byteOffset,packInt16,value,2<arguments.length?arguments[2]:void 0)},setUint16:function(byteOffset,value){set(this,2,byteOffset,packInt16,value,2<arguments.length?arguments[2]:void 0)},setInt32:function(byteOffset,value){set(this,4,byteOffset,packInt32,value,2<arguments.length?arguments[2]:void 0)},setUint32:function(byteOffset,value){set(this,4,byteOffset,packInt32,value,2<arguments.length?arguments[2]:void 0)},setFloat32:function(byteOffset,value){set(this,4,byteOffset,packFloat32,value,2<arguments.length?arguments[2]:void 0)},setFloat64:function(byteOffset,value){set(this,8,byteOffset,packFloat64,value,2<arguments.length?arguments[2]:void 0)}});setToStringTag($ArrayBuffer,"ArrayBuffer"),setToStringTag(FunctionName,"DataView"),module.exports={ArrayBuffer:$ArrayBuffer,DataView:FunctionName}},{"../internals/an-instance":122,"../internals/array-buffer-basic-detection":124,"../internals/array-fill":129,"../internals/array-slice-simple":141,"../internals/create-non-enumerable-property":161,"../internals/define-built-in-accessor":166,"../internals/define-built-ins":168,"../internals/descriptors":171,"../internals/fails":197,"../internals/function-name":206,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/ieee754":222,"../internals/internal-state":228,"../internals/object-get-own-property-names":270,"../internals/object-get-prototype-of":272,"../internals/object-set-prototype-of":279,"../internals/set-to-string-tag":304,"../internals/to-index":327,"../internals/to-integer-or-infinity":329,"../internals/to-length":330}],128:[function(require,module,exports){"use strict";var toObject=require("../internals/to-object"),toAbsoluteIndex=require("../internals/to-absolute-index"),lengthOfArrayLike=require("../internals/length-of-array-like"),deletePropertyOrThrow=require("../internals/delete-property-or-throw"),min=Math.min;module.exports=[].copyWithin||function(target,start){var O=toObject(this),len=lengthOfArrayLike(O),to=toAbsoluteIndex(target,len),from=toAbsoluteIndex(start,len),target=2<arguments.length?arguments[2]:void 0,count=min((void 0===target?len:toAbsoluteIndex(target,len))-from,len-to),inc=1;for(from<to&&to<from+count&&(inc=-1,from+=count-1,to+=count-1);0<count--;)from in O?O[to]=O[from]:deletePropertyOrThrow(O,to),to+=inc,from+=inc;return O}},{"../internals/delete-property-or-throw":170,"../internals/length-of-array-like":248,"../internals/to-absolute-index":325,"../internals/to-object":331}],129:[function(require,module,exports){"use strict";var toObject=require("../internals/to-object"),toAbsoluteIndex=require("../internals/to-absolute-index"),lengthOfArrayLike=require("../internals/length-of-array-like");module.exports=function(value){for(var O=toObject(this),length=lengthOfArrayLike(O),argumentsLength=arguments.length,index=toAbsoluteIndex(1<argumentsLength?arguments[1]:void 0,length),argumentsLength=2<argumentsLength?arguments[2]:void 0,endPos=void 0===argumentsLength?length:toAbsoluteIndex(argumentsLength,length);index<endPos;)O[index++]=value;return O}},{"../internals/length-of-array-like":248,"../internals/to-absolute-index":325,"../internals/to-object":331}],130:[function(require,module,exports){"use strict";var $forEach=require("../internals/array-iteration").forEach,require=require("../internals/array-method-is-strict")("forEach");module.exports=require?[].forEach:function(callbackfn){return $forEach(this,callbackfn,1<arguments.length?arguments[1]:void 0)}},{"../internals/array-iteration":135,"../internals/array-method-is-strict":138}],131:[function(require,module,exports){var lengthOfArrayLike=require("../internals/length-of-array-like");module.exports=function(Constructor,list){for(var index=0,length=lengthOfArrayLike(list),result=new Constructor(length);index<length;)result[index]=list[index++];return result}},{"../internals/length-of-array-like":248}],132:[function(require,module,exports){"use strict";var bind=require("../internals/function-bind-context"),call=require("../internals/function-call"),toObject=require("../internals/to-object"),callWithSafeIterationClosing=require("../internals/call-with-safe-iteration-closing"),isArrayIteratorMethod=require("../internals/is-array-iterator-method"),isConstructor=require("../internals/is-constructor"),lengthOfArrayLike=require("../internals/length-of-array-like"),createProperty=require("../internals/create-property"),getIterator=require("../internals/get-iterator"),getIteratorMethod=require("../internals/get-iterator-method"),$Array=Array;module.exports=function(arrayLike){var length,result,step,iterator,next,value,O=toObject(arrayLike),arrayLike=isConstructor(this),argumentsLength=arguments.length,mapfn=1<argumentsLength?arguments[1]:void 0,mapping=void 0!==mapfn,argumentsLength=(mapping&&(mapfn=bind(mapfn,2<argumentsLength?arguments[2]:void 0)),getIteratorMethod(O)),index=0;if(!argumentsLength||this===$Array&&isArrayIteratorMethod(argumentsLength))for(length=lengthOfArrayLike(O),result=arrayLike?new this(length):$Array(length);index<length;index++)value=mapping?mapfn(O[index],index):O[index],createProperty(result,index,value);else for(next=(iterator=getIterator(O,argumentsLength)).next,result=arrayLike?new this:[];!(step=call(next,iterator)).done;index++)value=mapping?callWithSafeIterationClosing(iterator,mapfn,[step.value,index],!0):step.value,createProperty(result,index,value);return result.length=index,result}},{"../internals/call-with-safe-iteration-closing":149,"../internals/create-property":163,"../internals/function-bind-context":202,"../internals/function-call":205,"../internals/get-iterator":212,"../internals/get-iterator-method":211,"../internals/is-array-iterator-method":229,"../internals/is-constructor":233,"../internals/length-of-array-like":248,"../internals/to-object":331}],133:[function(require,module,exports){function createMethod(IS_INCLUDES){return function($this,el,fromIndex){var value,O=toIndexedObject($this),length=lengthOfArrayLike(O),index=toAbsoluteIndex(fromIndex,length);if(IS_INCLUDES&&el!=el){for(;index<length;)if((value=O[index++])!=value)return!0}else for(;index<length;index++)if((IS_INCLUDES||index in O)&&O[index]===el)return IS_INCLUDES||index||0;return!IS_INCLUDES&&-1}}var toIndexedObject=require("../internals/to-indexed-object"),toAbsoluteIndex=require("../internals/to-absolute-index"),lengthOfArrayLike=require("../internals/length-of-array-like");module.exports={includes:createMethod(!0),indexOf:createMethod(!1)}},{"../internals/length-of-array-like":248,"../internals/to-absolute-index":325,"../internals/to-indexed-object":328}],134:[function(require,module,exports){function createMethod(TYPE){var IS_FIND_LAST_INDEX=1==TYPE;return function($this,callbackfn,that){for(var value,O=toObject($this),self=IndexedObject(O),boundFunction=bind(callbackfn,that),index=lengthOfArrayLike(self);0<index--;)if(boundFunction(value=self[index],index,O))switch(TYPE){case 0:return value;case 1:return index}return IS_FIND_LAST_INDEX?-1:void 0}}var bind=require("../internals/function-bind-context"),IndexedObject=require("../internals/indexed-object"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like");module.exports={findLast:createMethod(0),findLastIndex:createMethod(1)}},{"../internals/function-bind-context":202,"../internals/indexed-object":223,"../internals/length-of-array-like":248,"../internals/to-object":331}],135:[function(require,module,exports){function createMethod(TYPE){var IS_MAP=1==TYPE,IS_FILTER=2==TYPE,IS_SOME=3==TYPE,IS_EVERY=4==TYPE,IS_FIND_INDEX=6==TYPE,IS_FILTER_REJECT=7==TYPE,NO_HOLES=5==TYPE||IS_FIND_INDEX;return function($this,callbackfn,that,specificCreate){for(var value,result,O=toObject($this),self=IndexedObject(O),boundFunction=bind(callbackfn,that),length=lengthOfArrayLike(self),index=0,callbackfn=specificCreate||arraySpeciesCreate,target=IS_MAP?callbackfn($this,length):IS_FILTER||IS_FILTER_REJECT?callbackfn($this,0):void 0;index<length;index++)if((NO_HOLES||index in self)&&(result=boundFunction(value=self[index],index,O),TYPE))if(IS_MAP)target[index]=result;else if(result)switch(TYPE){case 3:return!0;case 5:return value;case 6:return index;case 2:push(target,value)}else switch(TYPE){case 4:return!1;case 7:push(target,value)}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:target}}var bind=require("../internals/function-bind-context"),uncurryThis=require("../internals/function-uncurry-this"),IndexedObject=require("../internals/indexed-object"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),arraySpeciesCreate=require("../internals/array-species-create"),push=uncurryThis([].push);module.exports={forEach:createMethod(0),map:createMethod(1),filter:createMethod(2),some:createMethod(3),every:createMethod(4),find:createMethod(5),findIndex:createMethod(6),filterReject:createMethod(7)}},{"../internals/array-species-create":145,"../internals/function-bind-context":202,"../internals/function-uncurry-this":209,"../internals/indexed-object":223,"../internals/length-of-array-like":248,"../internals/to-object":331}],136:[function(require,module,exports){"use strict";var apply=require("../internals/function-apply"),toIndexedObject=require("../internals/to-indexed-object"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),lengthOfArrayLike=require("../internals/length-of-array-like"),require=require("../internals/array-method-is-strict"),min=Math.min,$lastIndexOf=[].lastIndexOf,NEGATIVE_ZERO=!!$lastIndexOf&&1/[1].lastIndexOf(1,-0)<0,require=require("lastIndexOf");module.exports=NEGATIVE_ZERO||!require?function(searchElement){if(NEGATIVE_ZERO)return apply($lastIndexOf,this,arguments)||0;var O=toIndexedObject(this),length=lengthOfArrayLike(O),index=length-1;for((index=1<arguments.length?min(index,toIntegerOrInfinity(arguments[1])):index)<0&&(index=length+index);0<=index;index--)if(index in O&&O[index]===searchElement)return index||0;return-1}:$lastIndexOf},{"../internals/array-method-is-strict":138,"../internals/function-apply":201,"../internals/length-of-array-like":248,"../internals/to-indexed-object":328,"../internals/to-integer-or-infinity":329}],137:[function(require,module,exports){var fails=require("../internals/fails"),wellKnownSymbol=require("../internals/well-known-symbol"),V8_VERSION=require("../internals/engine-v8-version"),SPECIES=wellKnownSymbol("species");module.exports=function(METHOD_NAME){return 51<=V8_VERSION||!fails(function(){var array=[];return(array.constructor={})[SPECIES]=function(){return{foo:1}},1!==array[METHOD_NAME](Boolean).foo})}},{"../internals/engine-v8-version":188,"../internals/fails":197,"../internals/well-known-symbol":353}],138:[function(require,module,exports){"use strict";var fails=require("../internals/fails");module.exports=function(METHOD_NAME,argument){var method=[][METHOD_NAME];return!!method&&fails(function(){method.call(null,argument||function(){return 1},1)})}},{"../internals/fails":197}],139:[function(require,module,exports){function createMethod(IS_RIGHT){return function(that,callbackfn,argumentsLength,memo){aCallable(callbackfn);var O=toObject(that),self=IndexedObject(O),length=lengthOfArrayLike(O),index=IS_RIGHT?length-1:0,i=IS_RIGHT?-1:1;if(argumentsLength<2)for(;;){if(index in self){memo=self[index],index+=i;break}if(index+=i,IS_RIGHT?index<0:length<=index)throw $TypeError("Reduce of empty array with no initial value")}for(;IS_RIGHT?0<=index:index<length;index+=i)index in self&&(memo=callbackfn(memo,self[index],index,O));return memo}}var aCallable=require("../internals/a-callable"),toObject=require("../internals/to-object"),IndexedObject=require("../internals/indexed-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),$TypeError=TypeError;module.exports={left:createMethod(!1),right:createMethod(!0)}},{"../internals/a-callable":117,"../internals/indexed-object":223,"../internals/length-of-array-like":248,"../internals/to-object":331}],140:[function(require,module,exports){"use strict";var DESCRIPTORS=require("../internals/descriptors"),isArray=require("../internals/is-array"),$TypeError=TypeError,getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor,require=DESCRIPTORS&&!function(){if(void 0!==this)return 1;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(error){return error instanceof TypeError}}();module.exports=require?function(O,length){if(isArray(O)&&!getOwnPropertyDescriptor(O,"length").writable)throw $TypeError("Cannot set read only .length");return O.length=length}:function(O,length){return O.length=length}},{"../internals/descriptors":171,"../internals/is-array":230}],141:[function(require,module,exports){var toAbsoluteIndex=require("../internals/to-absolute-index"),lengthOfArrayLike=require("../internals/length-of-array-like"),createProperty=require("../internals/create-property"),$Array=Array,max=Math.max;module.exports=function(O,start,end){for(var length=lengthOfArrayLike(O),k=toAbsoluteIndex(start,length),fin=toAbsoluteIndex(void 0===end?length:end,length),result=$Array(max(fin-k,0)),n=0;k<fin;k++,n++)createProperty(result,n,O[k]);return result.length=n,result}},{"../internals/create-property":163,"../internals/length-of-array-like":248,"../internals/to-absolute-index":325}],142:[function(require,module,exports){require=require("../internals/function-uncurry-this");module.exports=require([].slice)},{"../internals/function-uncurry-this":209}],143:[function(require,module,exports){function mergeSort(array,comparefn){var length=array.length,middle=floor(length/2);return length<8?function(array,comparefn){var length=array.length,i=1,element,j;while(i<length){j=i;element=array[i];while(j&&comparefn(array[j-1],element)>0)array[j]=array[--j];if(j!==i++)array[j]=element}return array}(array,comparefn):function(array,left,right,comparefn){var llength=left.length,rlength=right.length,lindex=0,rindex=0;while(lindex<llength||rindex<rlength)array[lindex+rindex]=lindex<llength&&rindex<rlength?comparefn(left[lindex],right[rindex])<=0?left[lindex++]:right[rindex++]:lindex<llength?left[lindex++]:right[rindex++];return array}(array,mergeSort(arraySlice(array,0,middle),comparefn),mergeSort(arraySlice(array,middle),comparefn),comparefn)}var arraySlice=require("../internals/array-slice-simple"),floor=Math.floor;module.exports=mergeSort},{"../internals/array-slice-simple":141}],144:[function(require,module,exports){var isArray=require("../internals/is-array"),isConstructor=require("../internals/is-constructor"),isObject=require("../internals/is-object"),SPECIES=require("../internals/well-known-symbol")("species"),$Array=Array;module.exports=function(originalArray){var C;return void 0===(C=isArray(originalArray)&&(C=originalArray.constructor,isConstructor(C)&&(C===$Array||isArray(C.prototype))||isObject(C)&&null===(C=C[SPECIES]))?void 0:C)?$Array:C}},{"../internals/is-array":230,"../internals/is-constructor":233,"../internals/is-object":238,"../internals/well-known-symbol":353}],145:[function(require,module,exports){var arraySpeciesConstructor=require("../internals/array-species-constructor");module.exports=function(originalArray,length){return new(arraySpeciesConstructor(originalArray))(0===length?0:length)}},{"../internals/array-species-constructor":144}],146:[function(require,module,exports){var lengthOfArrayLike=require("../internals/length-of-array-like");module.exports=function(O,C){for(var len=lengthOfArrayLike(O),A=new C(len),k=0;k<len;k++)A[k]=O[len-k-1];return A}},{"../internals/length-of-array-like":248}],147:[function(require,module,exports){var lengthOfArrayLike=require("../internals/length-of-array-like"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),$RangeError=RangeError;module.exports=function(O,C,index,value){var len=lengthOfArrayLike(O),index=toIntegerOrInfinity(index),actualIndex=index<0?len+index:index;if(len<=actualIndex||actualIndex<0)throw $RangeError("Incorrect index");for(var A=new C(len),k=0;k<len;k++)A[k]=k===actualIndex?value:O[k];return A}},{"../internals/length-of-array-like":248,"../internals/to-integer-or-infinity":329}],148:[function(require,module,exports){for(var itoc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",ctoi={},index=0;index<66;index++)ctoi[itoc.charAt(index)]=index;module.exports={itoc:itoc,ctoi:ctoi}},{}],149:[function(require,module,exports){var anObject=require("../internals/an-object"),iteratorClose=require("../internals/iterator-close");module.exports=function(iterator,fn,value,ENTRIES){try{return ENTRIES?fn(anObject(value)[0],value[1]):fn(value)}catch(error){iteratorClose(iterator,"throw",error)}}},{"../internals/an-object":123,"../internals/iterator-close":243}],150:[function(require,module,exports){var ITERATOR=require("../internals/well-known-symbol")("iterator"),SAFE_CLOSING=!1;try{var called=0,iteratorWithReturn={next:function(){return{done:!!called++}},return:function(){SAFE_CLOSING=!0}};iteratorWithReturn[ITERATOR]=function(){return this},Array.from(iteratorWithReturn,function(){throw 2})}catch(error){}module.exports=function(exec,SKIP_CLOSING){if(!SKIP_CLOSING&&!SAFE_CLOSING)return!1;var ITERATION_SUPPORT=!1;try{var object={};object[ITERATOR]=function(){return{next:function(){return{done:ITERATION_SUPPORT=!0}}}},exec(object)}catch(error){}return ITERATION_SUPPORT}},{"../internals/well-known-symbol":353}],151:[function(require,module,exports){var require=require("../internals/function-uncurry-this"),toString=require({}.toString),stringSlice=require("".slice);module.exports=function(it){return stringSlice(toString(it),8,-1)}},{"../internals/function-uncurry-this":209}],152:[function(require,module,exports){var TO_STRING_TAG_SUPPORT=require("../internals/to-string-tag-support"),isCallable=require("../internals/is-callable"),classofRaw=require("../internals/classof-raw"),TO_STRING_TAG=require("../internals/well-known-symbol")("toStringTag"),$Object=Object,CORRECT_ARGUMENTS="Arguments"==classofRaw(function(){return arguments}());module.exports=TO_STRING_TAG_SUPPORT?classofRaw:function(it){var tag;return void 0===it?"Undefined":null===it?"Null":"string"==typeof(tag=function(it,key){try{return it[key]}catch(error){}}(it=$Object(it),TO_STRING_TAG))?tag:CORRECT_ARGUMENTS?classofRaw(it):"Object"==(tag=classofRaw(it))&&isCallable(it.callee)?"Arguments":tag}},{"../internals/classof-raw":151,"../internals/is-callable":232,"../internals/to-string-tag-support":336,"../internals/well-known-symbol":353}],153:[function(require,module,exports){"use strict";var create=require("../internals/object-create"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),defineBuiltIns=require("../internals/define-built-ins"),bind=require("../internals/function-bind-context"),anInstance=require("../internals/an-instance"),isNullOrUndefined=require("../internals/is-null-or-undefined"),iterate=require("../internals/iterate"),defineIterator=require("../internals/iterator-define"),createIterResultObject=require("../internals/create-iter-result-object"),setSpecies=require("../internals/set-species"),DESCRIPTORS=require("../internals/descriptors"),fastKey=require("../internals/internal-metadata").fastKey,require=require("../internals/internal-state"),setInternalState=require.set,internalStateGetterFor=require.getterFor;module.exports={getConstructor:function(wrapper,CONSTRUCTOR_NAME,IS_MAP,ADDER){function define(that,key,value){var index,state=getInternalState(that),entry=getEntry(that,key);return entry?entry.value=value:(state.last=entry={index:index=fastKey(key,!0),key:key,value:value,previous:key=state.last,next:void 0,removed:!1},state.first||(state.first=entry),key&&(key.next=entry),DESCRIPTORS?state.size++:that.size++,"F"!==index&&(state.index[index]=entry)),that}function getEntry(that,key){var entry,that=getInternalState(that),index=fastKey(key);if("F"!==index)return that.index[index];for(entry=that.first;entry;entry=entry.next)if(entry.key==key)return entry}var wrapper=wrapper(function(that,iterable){anInstance(that,Prototype),setInternalState(that,{type:CONSTRUCTOR_NAME,index:create(null),first:void 0,last:void 0,size:0}),DESCRIPTORS||(that.size=0),isNullOrUndefined(iterable)||iterate(iterable,that[ADDER],{that:that,AS_ENTRIES:IS_MAP})}),Prototype=wrapper.prototype,getInternalState=internalStateGetterFor(CONSTRUCTOR_NAME);return defineBuiltIns(Prototype,{clear:function(){for(var state=getInternalState(this),data=state.index,entry=state.first;entry;)entry.removed=!0,entry.previous&&(entry.previous=entry.previous.next=void 0),delete data[entry.index],entry=entry.next;state.first=state.last=void 0,DESCRIPTORS?state.size=0:this.size=0},delete:function(key){var next,prev,state=getInternalState(this),key=getEntry(this,key);return key&&(next=key.next,prev=key.previous,delete state.index[key.index],key.removed=!0,prev&&(prev.next=next),next&&(next.previous=prev),state.first==key&&(state.first=next),state.last==key&&(state.last=prev),DESCRIPTORS?state.size--:this.size--),!!key},forEach:function(callbackfn){for(var entry,state=getInternalState(this),boundFunction=bind(callbackfn,1<arguments.length?arguments[1]:void 0);entry=entry?entry.next:state.first;)for(boundFunction(entry.value,entry.key,this);entry&&entry.removed;)entry=entry.previous},has:function(key){return!!getEntry(this,key)}}),defineBuiltIns(Prototype,IS_MAP?{get:function(key){key=getEntry(this,key);return key&&key.value},set:function(key,value){return define(this,0===key?0:key,value)}}:{add:function(value){return define(this,value=0===value?0:value,value)}}),DESCRIPTORS&&defineBuiltInAccessor(Prototype,"size",{configurable:!0,get:function(){return getInternalState(this).size}}),wrapper},setStrong:function(Constructor,CONSTRUCTOR_NAME,IS_MAP){var ITERATOR_NAME=CONSTRUCTOR_NAME+" Iterator",getInternalCollectionState=internalStateGetterFor(CONSTRUCTOR_NAME),getInternalIteratorState=internalStateGetterFor(ITERATOR_NAME);defineIterator(Constructor,CONSTRUCTOR_NAME,function(iterated,kind){setInternalState(this,{type:ITERATOR_NAME,target:iterated,state:getInternalCollectionState(iterated),kind:kind,last:void 0})},function(){for(var state=getInternalIteratorState(this),kind=state.kind,entry=state.last;entry&&entry.removed;)entry=entry.previous;return state.target&&(state.last=entry=entry?entry.next:state.state.first)?createIterResultObject("keys"==kind?entry.key:"values"==kind?entry.value:[entry.key,entry.value],!1):(state.target=void 0,createIterResultObject(void 0,!0))},IS_MAP?"entries":"values",!IS_MAP,!0),setSpecies(CONSTRUCTOR_NAME)}}},{"../internals/an-instance":122,"../internals/create-iter-result-object":160,"../internals/define-built-in-accessor":166,"../internals/define-built-ins":168,"../internals/descriptors":171,"../internals/function-bind-context":202,"../internals/internal-metadata":227,"../internals/internal-state":228,"../internals/is-null-or-undefined":237,"../internals/iterate":242,"../internals/iterator-define":245,"../internals/object-create":265,"../internals/set-species":303}],154:[function(require,module,exports){"use strict";function uncaughtFrozenStore(state){return state.frozen||(state.frozen=new UncaughtFrozenStore)}function UncaughtFrozenStore(){this.entries=[]}function findUncaughtFrozen(store,key){return find(store.entries,function(it){return it[0]===key})}var uncurryThis=require("../internals/function-uncurry-this"),defineBuiltIns=require("../internals/define-built-ins"),getWeakData=require("../internals/internal-metadata").getWeakData,anInstance=require("../internals/an-instance"),anObject=require("../internals/an-object"),isNullOrUndefined=require("../internals/is-null-or-undefined"),isObject=require("../internals/is-object"),iterate=require("../internals/iterate"),ArrayIterationModule=require("../internals/array-iteration"),hasOwn=require("../internals/has-own-property"),require=require("../internals/internal-state"),setInternalState=require.set,internalStateGetterFor=require.getterFor,find=ArrayIterationModule.find,findIndex=ArrayIterationModule.findIndex,splice=uncurryThis([].splice),id=0;UncaughtFrozenStore.prototype={get:function(key){key=findUncaughtFrozen(this,key);if(key)return key[1]},has:function(key){return!!findUncaughtFrozen(this,key)},set:function(key,value){var entry=findUncaughtFrozen(this,key);entry?entry[1]=value:this.entries.push([key,value])},delete:function(key){var index=findIndex(this.entries,function(it){return it[0]===key});return~index&&splice(this.entries,index,1),!!~index}},module.exports={getConstructor:function(wrapper,CONSTRUCTOR_NAME,IS_MAP,ADDER){function define(that,key,value){var state=getInternalState(that),data=getWeakData(anObject(key),!0);return!0===data?uncaughtFrozenStore(state).set(key,value):data[state.id]=value,that}var wrapper=wrapper(function(that,iterable){anInstance(that,Prototype),setInternalState(that,{type:CONSTRUCTOR_NAME,id:id++,frozen:void 0}),isNullOrUndefined(iterable)||iterate(iterable,that[ADDER],{that:that,AS_ENTRIES:IS_MAP})}),Prototype=wrapper.prototype,getInternalState=internalStateGetterFor(CONSTRUCTOR_NAME);return defineBuiltIns(Prototype,{delete:function(key){var data,state=getInternalState(this);return!!isObject(key)&&(!0===(data=getWeakData(key))?uncaughtFrozenStore(state).delete(key):data&&hasOwn(data,state.id)&&delete data[state.id])},has:function(key){var data,state=getInternalState(this);return!!isObject(key)&&(!0===(data=getWeakData(key))?uncaughtFrozenStore(state).has(key):data&&hasOwn(data,state.id))}}),defineBuiltIns(Prototype,IS_MAP?{get:function(key){var data,state=getInternalState(this);if(isObject(key))return!0===(data=getWeakData(key))?uncaughtFrozenStore(state).get(key):data?data[state.id]:void 0},set:function(key,value){return define(this,key,value)}}:{add:function(value){return define(this,value,!0)}}),wrapper}}},{"../internals/an-instance":122,"../internals/an-object":123,"../internals/array-iteration":135,"../internals/define-built-ins":168,"../internals/function-uncurry-this":209,"../internals/has-own-property":217,"../internals/internal-metadata":227,"../internals/internal-state":228,"../internals/is-null-or-undefined":237,"../internals/is-object":238,"../internals/iterate":242}],155:[function(require,module,exports){"use strict";var $=require("../internals/export"),global=require("../internals/global"),uncurryThis=require("../internals/function-uncurry-this"),isForced=require("../internals/is-forced"),defineBuiltIn=require("../internals/define-built-in"),InternalMetadataModule=require("../internals/internal-metadata"),iterate=require("../internals/iterate"),anInstance=require("../internals/an-instance"),isCallable=require("../internals/is-callable"),isNullOrUndefined=require("../internals/is-null-or-undefined"),isObject=require("../internals/is-object"),fails=require("../internals/fails"),checkCorrectnessOfIteration=require("../internals/check-correctness-of-iteration"),setToStringTag=require("../internals/set-to-string-tag"),inheritIfRequired=require("../internals/inherit-if-required");module.exports=function(CONSTRUCTOR_NAME,wrapper,common){function fixMethod(KEY){var uncurriedNativeMethod=uncurryThis(NativePrototype[KEY]);defineBuiltIn(NativePrototype,KEY,"add"==KEY?function(value){return uncurriedNativeMethod(this,0===value?0:value),this}:"delete"==KEY?function(key){return!(IS_WEAK&&!isObject(key))&&uncurriedNativeMethod(this,0===key?0:key)}:"get"==KEY?function(key){return IS_WEAK&&!isObject(key)?void 0:uncurriedNativeMethod(this,0===key?0:key)}:"has"==KEY?function(key){return!(IS_WEAK&&!isObject(key))&&uncurriedNativeMethod(this,0===key?0:key)}:function(key,value){return uncurriedNativeMethod(this,0===key?0:key,value),this})}var instance,HASNT_CHAINING,THROWS_ON_PRIMITIVES,ACCEPT_ITERABLES,BUGGY_ZERO,IS_MAP=-1!==CONSTRUCTOR_NAME.indexOf("Map"),IS_WEAK=-1!==CONSTRUCTOR_NAME.indexOf("Weak"),ADDER=IS_MAP?"set":"add",NativeConstructor=global[CONSTRUCTOR_NAME],NativePrototype=NativeConstructor&&NativeConstructor.prototype,Constructor=NativeConstructor,exported={};return isForced(CONSTRUCTOR_NAME,!isCallable(NativeConstructor)||!(IS_WEAK||NativePrototype.forEach&&!fails(function(){(new NativeConstructor).entries().next()})))?(Constructor=common.getConstructor(wrapper,CONSTRUCTOR_NAME,IS_MAP,ADDER),InternalMetadataModule.enable()):isForced(CONSTRUCTOR_NAME,!0)&&(HASNT_CHAINING=(instance=new Constructor)[ADDER](IS_WEAK?{}:-0,1)!=instance,THROWS_ON_PRIMITIVES=fails(function(){instance.has(1)}),ACCEPT_ITERABLES=checkCorrectnessOfIteration(function(iterable){new NativeConstructor(iterable)}),BUGGY_ZERO=!IS_WEAK&&fails(function(){for(var $instance=new NativeConstructor,index=5;index--;)$instance[ADDER](index,index);return!$instance.has(-0)}),ACCEPT_ITERABLES||(((Constructor=wrapper(function(dummy,iterable){anInstance(dummy,NativePrototype);dummy=inheritIfRequired(new NativeConstructor,dummy,Constructor);return isNullOrUndefined(iterable)||iterate(iterable,dummy[ADDER],{that:dummy,AS_ENTRIES:IS_MAP}),dummy})).prototype=NativePrototype).constructor=Constructor),(THROWS_ON_PRIMITIVES||BUGGY_ZERO)&&(fixMethod("delete"),fixMethod("has"),IS_MAP)&&fixMethod("get"),(BUGGY_ZERO||HASNT_CHAINING)&&fixMethod(ADDER),IS_WEAK)&&NativePrototype.clear&&delete NativePrototype.clear,$({global:!0,constructor:!0,forced:(exported[CONSTRUCTOR_NAME]=Constructor)!=NativeConstructor},exported),setToStringTag(Constructor,CONSTRUCTOR_NAME),IS_WEAK||common.setStrong(Constructor,CONSTRUCTOR_NAME,IS_MAP),Constructor}},{"../internals/an-instance":122,"../internals/check-correctness-of-iteration":150,"../internals/define-built-in":167,"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/inherit-if-required":224,"../internals/internal-metadata":227,"../internals/is-callable":232,"../internals/is-forced":235,"../internals/is-null-or-undefined":237,"../internals/is-object":238,"../internals/iterate":242,"../internals/set-to-string-tag":304}],156:[function(require,module,exports){var hasOwn=require("../internals/has-own-property"),ownKeys=require("../internals/own-keys"),getOwnPropertyDescriptorModule=require("../internals/object-get-own-property-descriptor"),definePropertyModule=require("../internals/object-define-property");module.exports=function(target,source,exceptions){for(var keys=ownKeys(source),defineProperty=definePropertyModule.f,getOwnPropertyDescriptor=getOwnPropertyDescriptorModule.f,i=0;i<keys.length;i++){var key=keys[i];hasOwn(target,key)||exceptions&&hasOwn(exceptions,key)||defineProperty(target,key,getOwnPropertyDescriptor(source,key))}}},{"../internals/has-own-property":217,"../internals/object-define-property":267,"../internals/object-get-own-property-descriptor":268,"../internals/own-keys":283}],157:[function(require,module,exports){var MATCH=require("../internals/well-known-symbol")("match");module.exports=function(METHOD_NAME){var regexp=/./;try{"/./"[METHOD_NAME](regexp)}catch(error1){try{return regexp[MATCH]=!1,"/./"[METHOD_NAME](regexp)}catch(error2){}}return!1}},{"../internals/well-known-symbol":353}],158:[function(require,module,exports){require=require("../internals/fails");module.exports=!require(function(){function F(){}return F.prototype.constructor=null,Object.getPrototypeOf(new F)!==F.prototype})},{"../internals/fails":197}],159:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),requireObjectCoercible=require("../internals/require-object-coercible"),toString=require("../internals/to-string"),quot=/"/g,replace=uncurryThis("".replace);module.exports=function(string,tag,attribute,value){var string=toString(requireObjectCoercible(string)),p1="<"+tag;return""!==attribute&&(p1+=" "+attribute+'="'+replace(toString(value),quot,"&quot;")+'"'),p1+">"+string+"</"+tag+">"}},{"../internals/function-uncurry-this":209,"../internals/require-object-coercible":299,"../internals/to-string":337}],160:[function(require,module,exports){module.exports=function(value,done){return{value:value,done:done}}},{}],161:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),definePropertyModule=require("../internals/object-define-property"),createPropertyDescriptor=require("../internals/create-property-descriptor");module.exports=DESCRIPTORS?function(object,key,value){return definePropertyModule.f(object,key,createPropertyDescriptor(1,value))}:function(object,key,value){return object[key]=value,object}},{"../internals/create-property-descriptor":162,"../internals/descriptors":171,"../internals/object-define-property":267}],162:[function(require,module,exports){module.exports=function(bitmap,value){return{enumerable:!(1&bitmap),configurable:!(2&bitmap),writable:!(4&bitmap),value:value}}},{}],163:[function(require,module,exports){"use strict";var toPropertyKey=require("../internals/to-property-key"),definePropertyModule=require("../internals/object-define-property"),createPropertyDescriptor=require("../internals/create-property-descriptor");module.exports=function(object,key,value){key=toPropertyKey(key);key in object?definePropertyModule.f(object,key,createPropertyDescriptor(0,value)):object[key]=value}},{"../internals/create-property-descriptor":162,"../internals/object-define-property":267,"../internals/to-property-key":335}],164:[function(require,module,exports){"use strict";var uncurryThis=require("../internals/function-uncurry-this"),fails=require("../internals/fails"),padStart=require("../internals/string-pad").start,$RangeError=RangeError,$isFinite=isFinite,abs=Math.abs,require=Date.prototype,nativeDateToISOString=require.toISOString,thisTimeValue=uncurryThis(require.getTime),getUTCDate=uncurryThis(require.getUTCDate),getUTCFullYear=uncurryThis(require.getUTCFullYear),getUTCHours=uncurryThis(require.getUTCHours),getUTCMilliseconds=uncurryThis(require.getUTCMilliseconds),getUTCMinutes=uncurryThis(require.getUTCMinutes),getUTCMonth=uncurryThis(require.getUTCMonth),getUTCSeconds=uncurryThis(require.getUTCSeconds);module.exports=fails(function(){return"0385-07-25T07:06:39.999Z"!=nativeDateToISOString.call(new Date(-5e13-1))})||!fails(function(){nativeDateToISOString.call(new Date(NaN))})?function(){var year,milliseconds,sign;if($isFinite(thisTimeValue(this)))return year=getUTCFullYear(this),milliseconds=getUTCMilliseconds(this),(sign=year<0?"-":9999<year?"+":"")+padStart(abs(year),sign?6:4,0)+"-"+padStart(getUTCMonth(this)+1,2,0)+"-"+padStart(getUTCDate(this),2,0)+"T"+padStart(getUTCHours(this),2,0)+":"+padStart(getUTCMinutes(this),2,0)+":"+padStart(getUTCSeconds(this),2,0)+"."+padStart(milliseconds,3,0)+"Z";throw $RangeError("Invalid time value")}:nativeDateToISOString},{"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/string-pad":312}],165:[function(require,module,exports){"use strict";var anObject=require("../internals/an-object"),ordinaryToPrimitive=require("../internals/ordinary-to-primitive"),$TypeError=TypeError;module.exports=function(hint){if(anObject(this),"string"===hint||"default"===hint)hint="string";else if("number"!==hint)throw $TypeError("Incorrect hint");return ordinaryToPrimitive(this,hint)}},{"../internals/an-object":123,"../internals/ordinary-to-primitive":282}],166:[function(require,module,exports){var makeBuiltIn=require("../internals/make-built-in"),defineProperty=require("../internals/object-define-property");module.exports=function(target,name,descriptor){return descriptor.get&&makeBuiltIn(descriptor.get,name,{getter:!0}),descriptor.set&&makeBuiltIn(descriptor.set,name,{setter:!0}),defineProperty.f(target,name,descriptor)}},{"../internals/make-built-in":249,"../internals/object-define-property":267}],167:[function(require,module,exports){var isCallable=require("../internals/is-callable"),definePropertyModule=require("../internals/object-define-property"),makeBuiltIn=require("../internals/make-built-in"),defineGlobalProperty=require("../internals/define-global-property");module.exports=function(O,key,value,options){var simple=(options=options||{}).enumerable,name=void 0!==options.name?options.name:key;if(isCallable(value)&&makeBuiltIn(value,name,options),options.global)simple?O[key]=value:defineGlobalProperty(key,value);else{try{options.unsafe?O[key]&&(simple=!0):delete O[key]}catch(error){}simple?O[key]=value:definePropertyModule.f(O,key,{value:value,enumerable:!1,configurable:!options.nonConfigurable,writable:!options.nonWritable})}return O}},{"../internals/define-global-property":169,"../internals/is-callable":232,"../internals/make-built-in":249,"../internals/object-define-property":267}],168:[function(require,module,exports){var defineBuiltIn=require("../internals/define-built-in");module.exports=function(target,src,options){for(var key in src)defineBuiltIn(target,key,src[key],options);return target}},{"../internals/define-built-in":167}],169:[function(require,module,exports){var global=require("../internals/global"),defineProperty=Object.defineProperty;module.exports=function(key,value){try{defineProperty(global,key,{value:value,configurable:!0,writable:!0})}catch(error){global[key]=value}return value}},{"../internals/global":216}],170:[function(require,module,exports){"use strict";var tryToString=require("../internals/try-to-string"),$TypeError=TypeError;module.exports=function(O,P){if(!delete O[P])throw $TypeError("Cannot delete property "+tryToString(P)+" of "+tryToString(O))}},{"../internals/try-to-string":339}],171:[function(require,module,exports){require=require("../internals/fails");module.exports=!require(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})},{"../internals/fails":197}],172:[function(require,module,exports){var documentAll="object"==typeof document&&document.all;module.exports={all:documentAll,IS_HTMLDDA:void 0===documentAll&&void 0!==documentAll}},{}],173:[function(require,module,exports){var global=require("../internals/global"),require=require("../internals/is-object"),document=global.document,EXISTS=require(document)&&require(document.createElement);module.exports=function(it){return EXISTS?document.createElement(it):{}}},{"../internals/global":216,"../internals/is-object":238}],174:[function(require,module,exports){var $TypeError=TypeError;module.exports=function(it){if(9007199254740991<it)throw $TypeError("Maximum allowed index exceeded");return it}},{}],175:[function(require,module,exports){module.exports={IndexSizeError:{s:"INDEX_SIZE_ERR",c:1,m:1},DOMStringSizeError:{s:"DOMSTRING_SIZE_ERR",c:2,m:0},HierarchyRequestError:{s:"HIERARCHY_REQUEST_ERR",c:3,m:1},WrongDocumentError:{s:"WRONG_DOCUMENT_ERR",c:4,m:1},InvalidCharacterError:{s:"INVALID_CHARACTER_ERR",c:5,m:1},NoDataAllowedError:{s:"NO_DATA_ALLOWED_ERR",c:6,m:0},NoModificationAllowedError:{s:"NO_MODIFICATION_ALLOWED_ERR",c:7,m:1},NotFoundError:{s:"NOT_FOUND_ERR",c:8,m:1},NotSupportedError:{s:"NOT_SUPPORTED_ERR",c:9,m:1},InUseAttributeError:{s:"INUSE_ATTRIBUTE_ERR",c:10,m:1},InvalidStateError:{s:"INVALID_STATE_ERR",c:11,m:1},SyntaxError:{s:"SYNTAX_ERR",c:12,m:1},InvalidModificationError:{s:"INVALID_MODIFICATION_ERR",c:13,m:1},NamespaceError:{s:"NAMESPACE_ERR",c:14,m:1},InvalidAccessError:{s:"INVALID_ACCESS_ERR",c:15,m:1},ValidationError:{s:"VALIDATION_ERR",c:16,m:0},TypeMismatchError:{s:"TYPE_MISMATCH_ERR",c:17,m:1},SecurityError:{s:"SECURITY_ERR",c:18,m:1},NetworkError:{s:"NETWORK_ERR",c:19,m:1},AbortError:{s:"ABORT_ERR",c:20,m:1},URLMismatchError:{s:"URL_MISMATCH_ERR",c:21,m:1},QuotaExceededError:{s:"QUOTA_EXCEEDED_ERR",c:22,m:1},TimeoutError:{s:"TIMEOUT_ERR",c:23,m:1},InvalidNodeTypeError:{s:"INVALID_NODE_TYPE_ERR",c:24,m:1},DataCloneError:{s:"DATA_CLONE_ERR",c:25,m:1}}},{}],176:[function(require,module,exports){module.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},{}],177:[function(require,module,exports){require=require("../internals/document-create-element")("span").classList,require=require&&require.constructor&&require.constructor.prototype;module.exports=require===Object.prototype?void 0:require},{"../internals/document-create-element":173}],178:[function(require,module,exports){require=require("../internals/engine-user-agent").match(/firefox\/(\d+)/i);module.exports=!!require&&+require[1]},{"../internals/engine-user-agent":187}],179:[function(require,module,exports){var IS_DENO=require("../internals/engine-is-deno"),require=require("../internals/engine-is-node");module.exports=!IS_DENO&&!require&&"object"==typeof window&&"object"==typeof document},{"../internals/engine-is-deno":181,"../internals/engine-is-node":185}],180:[function(require,module,exports){module.exports="function"==typeof Bun&&Bun&&"string"==typeof Bun.version},{}],181:[function(require,module,exports){module.exports="object"==typeof Deno&&Deno&&"object"==typeof Deno.version},{}],182:[function(require,module,exports){require=require("../internals/engine-user-agent");module.exports=/MSIE|Trident/.test(require)},{"../internals/engine-user-agent":187}],183:[function(require,module,exports){require=require("../internals/engine-user-agent");module.exports=/ipad|iphone|ipod/i.test(require)&&"undefined"!=typeof Pebble},{"../internals/engine-user-agent":187}],184:[function(require,module,exports){require=require("../internals/engine-user-agent");module.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(require)},{"../internals/engine-user-agent":187}],185:[function(require,module,exports){!function(process){!function(){var classof=require("../internals/classof-raw");module.exports=void 0!==process&&"process"==classof(process)}.call(this)}.call(this,require("_process"))},{"../internals/classof-raw":151,_process:1042}],186:[function(require,module,exports){require=require("../internals/engine-user-agent");module.exports=/web0s(?!.*chrome)/i.test(require)},{"../internals/engine-user-agent":187}],187:[function(require,module,exports){module.exports="undefined"!=typeof navigator&&String(navigator.userAgent)||""},{}],188:[function(require,module,exports){var match,version,global=require("../internals/global"),require=require("../internals/engine-user-agent"),process=global.process,global=global.Deno,process=process&&process.versions||global&&global.version,global=process&&process.v8;!(version=global?0<(match=global.split("."))[0]&&match[0]<4?1:+(match[0]+match[1]):version)&&require&&(!(match=require.match(/Edge\/(\d+)/))||74<=match[1])&&(match=require.match(/Chrome\/(\d+)/))&&(version=+match[1]),module.exports=version},{"../internals/engine-user-agent":187,"../internals/global":216}],189:[function(require,module,exports){require=require("../internals/engine-user-agent").match(/AppleWebKit\/(\d+)\./);module.exports=!!require&&+require[1]},{"../internals/engine-user-agent":187}],190:[function(require,module,exports){var global=require("../internals/global");module.exports=function(CONSTRUCTOR){return global[CONSTRUCTOR].prototype}},{"../internals/global":216}],191:[function(require,module,exports){module.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},{}],192:[function(require,module,exports){var require=require("../internals/function-uncurry-this"),$Error=Error,replace=require("".replace),require=String($Error("zxcasd").stack),V8_OR_CHAKRA_STACK_ENTRY=/\n\s*at [^:]*:[^\n]*/,IS_V8_OR_CHAKRA_STACK=V8_OR_CHAKRA_STACK_ENTRY.test(require);module.exports=function(stack,dropEntries){if(IS_V8_OR_CHAKRA_STACK&&"string"==typeof stack&&!$Error.prepareStackTrace)for(;dropEntries--;)stack=replace(stack,V8_OR_CHAKRA_STACK_ENTRY,"");return stack}},{"../internals/function-uncurry-this":209}],193:[function(require,module,exports){var createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),clearErrorStack=require("../internals/error-stack-clear"),ERROR_STACK_INSTALLABLE=require("../internals/error-stack-installable"),captureStackTrace=Error.captureStackTrace;module.exports=function(error,C,stack,dropEntries){ERROR_STACK_INSTALLABLE&&(captureStackTrace?captureStackTrace(error,C):createNonEnumerableProperty(error,"stack",clearErrorStack(stack,dropEntries)))}},{"../internals/create-non-enumerable-property":161,"../internals/error-stack-clear":192,"../internals/error-stack-installable":194}],194:[function(require,module,exports){var fails=require("../internals/fails"),createPropertyDescriptor=require("../internals/create-property-descriptor");module.exports=!fails(function(){var error=Error("a");return!("stack"in error)||(Object.defineProperty(error,"stack",createPropertyDescriptor(1,7)),7!==error.stack)})},{"../internals/create-property-descriptor":162,"../internals/fails":197}],195:[function(require,module,exports){"use strict";var DESCRIPTORS=require("../internals/descriptors"),fails=require("../internals/fails"),anObject=require("../internals/an-object"),create=require("../internals/object-create"),normalizeStringArgument=require("../internals/normalize-string-argument"),nativeErrorToString=Error.prototype.toString,require=fails(function(){if(DESCRIPTORS){var object=create(Object.defineProperty({},"name",{get:function(){return this===object}}));if("true"!==nativeErrorToString.call(object))return!0}return"2: 1"!==nativeErrorToString.call({message:1,name:2})||"Error"!==nativeErrorToString.call({})});module.exports=require?function(){var O=anObject(this),name=normalizeStringArgument(O.name,"Error"),O=normalizeStringArgument(O.message);return name?O?name+": "+O:name:O}:nativeErrorToString},{"../internals/an-object":123,"../internals/descriptors":171,"../internals/fails":197,"../internals/normalize-string-argument":259,"../internals/object-create":265}],196:[function(require,module,exports){var global=require("../internals/global"),getOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f,createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),defineBuiltIn=require("../internals/define-built-in"),defineGlobalProperty=require("../internals/define-global-property"),copyConstructorProperties=require("../internals/copy-constructor-properties"),isForced=require("../internals/is-forced");module.exports=function(options,source){var key,sourceProperty,descriptor,TARGET=options.target,GLOBAL=options.global,STATIC=options.stat,target=GLOBAL?global:STATIC?global[TARGET]||defineGlobalProperty(TARGET,{}):(global[TARGET]||{}).prototype;if(target)for(key in source){if(sourceProperty=source[key],descriptor=options.dontCallGetSet?(descriptor=getOwnPropertyDescriptor(target,key))&&descriptor.value:target[key],!isForced(GLOBAL?key:TARGET+(STATIC?".":"#")+key,options.forced)&&void 0!==descriptor){if(typeof sourceProperty==typeof descriptor)continue;copyConstructorProperties(sourceProperty,descriptor)}(options.sham||descriptor&&descriptor.sham)&&createNonEnumerableProperty(sourceProperty,"sham",!0),defineBuiltIn(target,key,sourceProperty,options)}}},{"../internals/copy-constructor-properties":156,"../internals/create-non-enumerable-property":161,"../internals/define-built-in":167,"../internals/define-global-property":169,"../internals/global":216,"../internals/is-forced":235,"../internals/object-get-own-property-descriptor":268}],197:[function(require,module,exports){module.exports=function(exec){try{return!!exec()}catch(error){return!0}}},{}],198:[function(require,module,exports){"use strict";require("../modules/es.regexp.exec");var uncurryThis=require("../internals/function-uncurry-this-clause"),defineBuiltIn=require("../internals/define-built-in"),regexpExec=require("../internals/regexp-exec"),fails=require("../internals/fails"),wellKnownSymbol=require("../internals/well-known-symbol"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),SPECIES=wellKnownSymbol("species"),RegExpPrototype=RegExp.prototype;module.exports=function(KEY,exec,FORCED,SHAM){var uncurriedNativeRegExpMethod,SYMBOL=wellKnownSymbol(KEY),DELEGATES_TO_SYMBOL=!fails(function(){var O={};return O[SYMBOL]=function(){return 7},7!=""[KEY](O)}),DELEGATES_TO_EXEC=DELEGATES_TO_SYMBOL&&!fails(function(){var execCalled=!1,re=/a/;return"split"===KEY&&((re={constructor:{}}).constructor[SPECIES]=function(){return re},re.flags="",re[SYMBOL]=/./[SYMBOL]),re.exec=function(){return execCalled=!0,null},re[SYMBOL](""),!execCalled});DELEGATES_TO_SYMBOL&&DELEGATES_TO_EXEC&&!FORCED||(uncurriedNativeRegExpMethod=uncurryThis(/./[SYMBOL]),DELEGATES_TO_EXEC=exec(SYMBOL,""[KEY],function(nativeMethod,regexp,str,arg2,forceStringMethod){var nativeMethod=uncurryThis(nativeMethod),$exec=regexp.exec;return $exec===regexpExec||$exec===RegExpPrototype.exec?DELEGATES_TO_SYMBOL&&!forceStringMethod?{done:!0,value:uncurriedNativeRegExpMethod(regexp,str,arg2)}:{done:!0,value:nativeMethod(str,regexp,arg2)}:{done:!1}}),defineBuiltIn(String.prototype,KEY,DELEGATES_TO_EXEC[0]),defineBuiltIn(RegExpPrototype,SYMBOL,DELEGATES_TO_EXEC[1])),SHAM&&createNonEnumerableProperty(RegExpPrototype[SYMBOL],"sham",!0)}},{"../internals/create-non-enumerable-property":161,"../internals/define-built-in":167,"../internals/fails":197,"../internals/function-uncurry-this-clause":208,"../internals/regexp-exec":293,"../internals/well-known-symbol":353,"../modules/es.regexp.exec":508}],199:[function(require,module,exports){"use strict";function flattenIntoArray(target,original,source,sourceLen,start,depth,mapper,thisArg){for(var element,elementLen,targetIndex=start,sourceIndex=0,mapFn=!!mapper&&bind(mapper,thisArg);sourceIndex<sourceLen;)sourceIndex in source&&(element=mapFn?mapFn(source[sourceIndex],sourceIndex,original):source[sourceIndex],0<depth&&isArray(element)?(elementLen=lengthOfArrayLike(element),targetIndex=flattenIntoArray(target,original,element,elementLen,targetIndex,depth-1)-1):(doesNotExceedSafeInteger(targetIndex+1),target[targetIndex]=element),targetIndex++),sourceIndex++;return targetIndex}var isArray=require("../internals/is-array"),lengthOfArrayLike=require("../internals/length-of-array-like"),doesNotExceedSafeInteger=require("../internals/does-not-exceed-safe-integer"),bind=require("../internals/function-bind-context");module.exports=flattenIntoArray},{"../internals/does-not-exceed-safe-integer":174,"../internals/function-bind-context":202,"../internals/is-array":230,"../internals/length-of-array-like":248}],200:[function(require,module,exports){require=require("../internals/fails");module.exports=!require(function(){return Object.isExtensible(Object.preventExtensions({}))})},{"../internals/fails":197}],201:[function(require,module,exports){var require=require("../internals/function-bind-native"),FunctionPrototype=Function.prototype,apply=FunctionPrototype.apply,call=FunctionPrototype.call;module.exports="object"==typeof Reflect&&Reflect.apply||(require?call.bind(apply):function(){return call.apply(apply,arguments)})},{"../internals/function-bind-native":203}],202:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this-clause"),aCallable=require("../internals/a-callable"),NATIVE_BIND=require("../internals/function-bind-native"),bind=uncurryThis(uncurryThis.bind);module.exports=function(fn,that){return aCallable(fn),void 0===that?fn:NATIVE_BIND?bind(fn,that):function(){return fn.apply(that,arguments)}}},{"../internals/a-callable":117,"../internals/function-bind-native":203,"../internals/function-uncurry-this-clause":208}],203:[function(require,module,exports){require=require("../internals/fails");module.exports=!require(function(){var test=function(){}.bind();return"function"!=typeof test||test.hasOwnProperty("prototype")})},{"../internals/fails":197}],204:[function(require,module,exports){"use strict";var uncurryThis=require("../internals/function-uncurry-this"),aCallable=require("../internals/a-callable"),isObject=require("../internals/is-object"),hasOwn=require("../internals/has-own-property"),arraySlice=require("../internals/array-slice"),require=require("../internals/function-bind-native"),$Function=Function,concat=uncurryThis([].concat),join=uncurryThis([].join),factories={};module.exports=require?$Function.bind:function(that){var F=aCallable(this),Prototype=F.prototype,partArgs=arraySlice(arguments,1),boundFunction=function(){var args=concat(partArgs,arraySlice(arguments));return this instanceof boundFunction?function(C,argsLength,args){if(!hasOwn(factories,argsLength)){for(var list=[],i=0;i<argsLength;i++)list[i]="a["+i+"]";factories[argsLength]=$Function("C,a","return new C("+join(list,",")+")")}return factories[argsLength](C,args)}(F,args.length,args):F.apply(that,args)};return isObject(Prototype)&&(boundFunction.prototype=Prototype),boundFunction}},{"../internals/a-callable":117,"../internals/array-slice":142,"../internals/function-bind-native":203,"../internals/function-uncurry-this":209,"../internals/has-own-property":217,"../internals/is-object":238}],205:[function(require,module,exports){var require=require("../internals/function-bind-native"),call=Function.prototype.call;module.exports=require?call.bind(call):function(){return call.apply(call,arguments)}},{"../internals/function-bind-native":203}],206:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),require=require("../internals/has-own-property"),FunctionPrototype=Function.prototype,getDescriptor=DESCRIPTORS&&Object.getOwnPropertyDescriptor,require=require(FunctionPrototype,"name"),PROPER=require&&"something"===function(){}.name,DESCRIPTORS=require&&(!DESCRIPTORS||getDescriptor(FunctionPrototype,"name").configurable);module.exports={EXISTS:require,PROPER:PROPER,CONFIGURABLE:DESCRIPTORS}},{"../internals/descriptors":171,"../internals/has-own-property":217}],207:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),aCallable=require("../internals/a-callable");module.exports=function(object,key,method){try{return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object,key)[method]))}catch(error){}}},{"../internals/a-callable":117,"../internals/function-uncurry-this":209}],208:[function(require,module,exports){var classofRaw=require("../internals/classof-raw"),uncurryThis=require("../internals/function-uncurry-this");module.exports=function(fn){if("Function"===classofRaw(fn))return uncurryThis(fn)}},{"../internals/classof-raw":151,"../internals/function-uncurry-this":209}],209:[function(require,module,exports){var require=require("../internals/function-bind-native"),FunctionPrototype=Function.prototype,call=FunctionPrototype.call,FunctionPrototype=require&&FunctionPrototype.bind.bind(call,call);module.exports=require?FunctionPrototype:function(fn){return function(){return call.apply(fn,arguments)}}},{"../internals/function-bind-native":203}],210:[function(require,module,exports){var global=require("../internals/global"),isCallable=require("../internals/is-callable");module.exports=function(namespace,method){return arguments.length<2?(argument=global[namespace],isCallable(argument)?argument:void 0):global[namespace]&&global[namespace][method];var argument}},{"../internals/global":216,"../internals/is-callable":232}],211:[function(require,module,exports){var classof=require("../internals/classof"),getMethod=require("../internals/get-method"),isNullOrUndefined=require("../internals/is-null-or-undefined"),Iterators=require("../internals/iterators"),ITERATOR=require("../internals/well-known-symbol")("iterator");module.exports=function(it){if(!isNullOrUndefined(it))return getMethod(it,ITERATOR)||getMethod(it,"@@iterator")||Iterators[classof(it)]}},{"../internals/classof":152,"../internals/get-method":214,"../internals/is-null-or-undefined":237,"../internals/iterators":247,"../internals/well-known-symbol":353}],212:[function(require,module,exports){var call=require("../internals/function-call"),aCallable=require("../internals/a-callable"),anObject=require("../internals/an-object"),tryToString=require("../internals/try-to-string"),getIteratorMethod=require("../internals/get-iterator-method"),$TypeError=TypeError;module.exports=function(argument,usingIterator){var iteratorMethod=arguments.length<2?getIteratorMethod(argument):usingIterator;if(aCallable(iteratorMethod))return anObject(call(iteratorMethod,argument));throw $TypeError(tryToString(argument)+" is not iterable")}},{"../internals/a-callable":117,"../internals/an-object":123,"../internals/function-call":205,"../internals/get-iterator-method":211,"../internals/try-to-string":339}],213:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),isArray=require("../internals/is-array"),isCallable=require("../internals/is-callable"),classof=require("../internals/classof-raw"),toString=require("../internals/to-string"),push=uncurryThis([].push);module.exports=function(replacer){if(isCallable(replacer))return replacer;if(isArray(replacer)){for(var rawLength=replacer.length,keys=[],i=0;i<rawLength;i++){var element=replacer[i];"string"==typeof element?push(keys,element):"number"!=typeof element&&"Number"!=classof(element)&&"String"!=classof(element)||push(keys,toString(element))}var keysLength=keys.length,root=!0;return function(key,value){if(root)return root=!1,value;if(isArray(this))return value;for(var j=0;j<keysLength;j++)if(keys[j]===key)return value}}}},{"../internals/classof-raw":151,"../internals/function-uncurry-this":209,"../internals/is-array":230,"../internals/is-callable":232,"../internals/to-string":337}],214:[function(require,module,exports){var aCallable=require("../internals/a-callable"),isNullOrUndefined=require("../internals/is-null-or-undefined");module.exports=function(V,P){V=V[P];return isNullOrUndefined(V)?void 0:aCallable(V)}},{"../internals/a-callable":117,"../internals/is-null-or-undefined":237}],215:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),toObject=require("../internals/to-object"),floor=Math.floor,charAt=uncurryThis("".charAt),replace=uncurryThis("".replace),stringSlice=uncurryThis("".slice),SUBSTITUTION_SYMBOLS=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,SUBSTITUTION_SYMBOLS_NO_NAMED=/\$([$&'`]|\d{1,2})/g;module.exports=function(matched,str,position,captures,namedCaptures,replacement){var tailPos=position+matched.length,m=captures.length,symbols=SUBSTITUTION_SYMBOLS_NO_NAMED;return void 0!==namedCaptures&&(namedCaptures=toObject(namedCaptures),symbols=SUBSTITUTION_SYMBOLS),replace(replacement,symbols,function(match,ch){var capture;switch(charAt(ch,0)){case"$":return"$";case"&":return matched;case"`":return stringSlice(str,0,position);case"'":return stringSlice(str,tailPos);case"<":capture=namedCaptures[stringSlice(ch,1,-1)];break;default:var f,n=+ch;if(0==n)return match;if(m<n)return 0!==(f=floor(n/10))&&f<=m?void 0===captures[f-1]?charAt(ch,1):captures[f-1]+charAt(ch,1):match;capture=captures[n-1]}return void 0===capture?"":capture})}},{"../internals/function-uncurry-this":209,"../internals/to-object":331}],216:[function(require,module,exports){!function(global){!function(){function check(it){return it&&it.Math==Math&&it}module.exports=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof global&&global)||function(){return this}()||Function("return this")()}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],217:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),toObject=require("../internals/to-object"),hasOwnProperty=uncurryThis({}.hasOwnProperty);module.exports=Object.hasOwn||function(it,key){return hasOwnProperty(toObject(it),key)}},{"../internals/function-uncurry-this":209,"../internals/to-object":331}],218:[function(require,module,exports){module.exports={}},{}],219:[function(require,module,exports){module.exports=function(a,b){try{1==arguments.length?console.error(a):console.error(a,b)}catch(error){}}},{}],220:[function(require,module,exports){require=require("../internals/get-built-in");module.exports=require("document","documentElement")},{"../internals/get-built-in":210}],221:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),fails=require("../internals/fails"),createElement=require("../internals/document-create-element");module.exports=!DESCRIPTORS&&!fails(function(){return 7!=Object.defineProperty(createElement("div"),"a",{get:function(){return 7}}).a})},{"../internals/descriptors":171,"../internals/document-create-element":173,"../internals/fails":197}],222:[function(require,module,exports){var $Array=Array,abs=Math.abs,pow=Math.pow,floor=Math.floor,log=Math.log,LN2=Math.LN2;module.exports={pack:function(number,mantissaLength,bytes){var exponent,mantissa,c,buffer=$Array(bytes),exponentLength=8*bytes-mantissaLength-1,bytes=(1<<exponentLength)-1,eBias=bytes>>1,rt=23===mantissaLength?pow(2,-24)-pow(2,-77):0,sign=number<0||0===number&&1/number<0?1:0,index=0;for((number=abs(number))!=number||number===1/0?(mantissa=number!=number?1:0,exponent=bytes):(exponent=floor(log(number)/LN2),number*(c=pow(2,-exponent))<1&&(exponent--,c*=2),2<=(number+=1<=exponent+eBias?rt/c:rt*pow(2,1-eBias))*c&&(exponent++,c/=2),bytes<=exponent+eBias?(mantissa=0,exponent=bytes):1<=exponent+eBias?(mantissa=(number*c-1)*pow(2,mantissaLength),exponent+=eBias):(mantissa=number*pow(2,eBias-1)*pow(2,mantissaLength),exponent=0));8<=mantissaLength;)buffer[index++]=255&mantissa,mantissa/=256,mantissaLength-=8;for(exponent=exponent<<mantissaLength|mantissa,exponentLength+=mantissaLength;0<exponentLength;)buffer[index++]=255&exponent,exponent/=256,exponentLength-=8;return buffer[--index]|=128*sign,buffer},unpack:function(buffer,mantissaLength){var mantissa,bytes=buffer.length,exponentLength=8*bytes-mantissaLength-1,eMax=(1<<exponentLength)-1,eBias=eMax>>1,nBits=exponentLength-7,index=bytes-1,exponentLength=buffer[index--],exponent=127&exponentLength;for(exponentLength>>=7;0<nBits;)exponent=256*exponent+buffer[index--],nBits-=8;for(mantissa=exponent&(1<<-nBits)-1,exponent>>=-nBits,nBits+=mantissaLength;0<nBits;)mantissa=256*mantissa+buffer[index--],nBits-=8;if(0===exponent)exponent=1-eBias;else{if(exponent===eMax)return mantissa?NaN:exponentLength?-1/0:1/0;mantissa+=pow(2,mantissaLength),exponent-=eBias}return(exponentLength?-1:1)*mantissa*pow(2,exponent-mantissaLength)}}},{}],223:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),fails=require("../internals/fails"),classof=require("../internals/classof-raw"),$Object=Object,split=uncurryThis("".split);module.exports=fails(function(){return!$Object("z").propertyIsEnumerable(0)})?function(it){return"String"==classof(it)?split(it,""):$Object(it)}:$Object},{"../internals/classof-raw":151,"../internals/fails":197,"../internals/function-uncurry-this":209}],224:[function(require,module,exports){var isCallable=require("../internals/is-callable"),isObject=require("../internals/is-object"),setPrototypeOf=require("../internals/object-set-prototype-of");module.exports=function($this,dummy,Wrapper){return setPrototypeOf&&isCallable(dummy=dummy.constructor)&&dummy!==Wrapper&&isObject(dummy=dummy.prototype)&&dummy!==Wrapper.prototype&&setPrototypeOf($this,dummy),$this}},{"../internals/is-callable":232,"../internals/is-object":238,"../internals/object-set-prototype-of":279}],225:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),isCallable=require("../internals/is-callable"),require=require("../internals/shared-store"),functionToString=uncurryThis(Function.toString);isCallable(require.inspectSource)||(require.inspectSource=function(it){return functionToString(it)}),module.exports=require.inspectSource},{"../internals/function-uncurry-this":209,"../internals/is-callable":232,"../internals/shared-store":306}],226:[function(require,module,exports){var isObject=require("../internals/is-object"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property");module.exports=function(O,options){isObject(options)&&"cause"in options&&createNonEnumerableProperty(O,"cause",options.cause)}},{"../internals/create-non-enumerable-property":161,"../internals/is-object":238}],227:[function(require,module,exports){function setMetadata(it){defineProperty(it,METADATA,{value:{objectID:"O"+id++,weakData:{}}})}var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),hiddenKeys=require("../internals/hidden-keys"),isObject=require("../internals/is-object"),hasOwn=require("../internals/has-own-property"),defineProperty=require("../internals/object-define-property").f,getOwnPropertyNamesModule=require("../internals/object-get-own-property-names"),getOwnPropertyNamesExternalModule=require("../internals/object-get-own-property-names-external"),isExtensible=require("../internals/object-is-extensible"),uid=require("../internals/uid"),FREEZING=require("../internals/freezing"),REQUIRED=!1,METADATA=uid("meta"),id=0,meta=module.exports={enable:function(){meta.enable=function(){},REQUIRED=!0;var getOwnPropertyNames=getOwnPropertyNamesModule.f,splice=uncurryThis([].splice),test={};test[METADATA]=1,getOwnPropertyNames(test).length&&(getOwnPropertyNamesModule.f=function(it){for(var result=getOwnPropertyNames(it),i=0,length=result.length;i<length;i++)if(result[i]===METADATA){splice(result,i,1);break}return result},$({target:"Object",stat:!0,forced:!0},{getOwnPropertyNames:getOwnPropertyNamesExternalModule.f}))},fastKey:function(it,create){if(!isObject(it))return"symbol"==typeof it?it:("string"==typeof it?"S":"P")+it;if(!hasOwn(it,METADATA)){if(!isExtensible(it))return"F";if(!create)return"E";setMetadata(it)}return it[METADATA].objectID},getWeakData:function(it,create){if(!hasOwn(it,METADATA)){if(!isExtensible(it))return!0;if(!create)return!1;setMetadata(it)}return it[METADATA].weakData},onFreeze:function(it){return FREEZING&&REQUIRED&&isExtensible(it)&&!hasOwn(it,METADATA)&&setMetadata(it),it}};hiddenKeys[METADATA]=!0},{"../internals/export":196,"../internals/freezing":200,"../internals/function-uncurry-this":209,"../internals/has-own-property":217,"../internals/hidden-keys":218,"../internals/is-object":238,"../internals/object-define-property":267,"../internals/object-get-own-property-names":270,"../internals/object-get-own-property-names-external":269,"../internals/object-is-extensible":273,"../internals/uid":345}],228:[function(require,module,exports){var set,get,store,STATE,NATIVE_WEAK_MAP=require("../internals/weak-map-basic-detection"),global=require("../internals/global"),isObject=require("../internals/is-object"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),hasOwn=require("../internals/has-own-property"),shared=require("../internals/shared-store"),sharedKey=require("../internals/shared-key"),require=require("../internals/hidden-keys"),TypeError=global.TypeError,global=global.WeakMap,has=NATIVE_WEAK_MAP||shared.state?((store=shared.state||(shared.state=new global)).get=store.get,store.has=store.has,store.set=store.set,set=function(it,metadata){if(store.has(it))throw TypeError("Object already initialized");return metadata.facade=it,store.set(it,metadata),metadata},get=function(it){return store.get(it)||{}},function(it){return store.has(it)}):(require[STATE=sharedKey("state")]=!0,set=function(it,metadata){if(hasOwn(it,STATE))throw TypeError("Object already initialized");return metadata.facade=it,createNonEnumerableProperty(it,STATE,metadata),metadata},get=function(it){return hasOwn(it,STATE)?it[STATE]:{}},function(it){return hasOwn(it,STATE)});module.exports={set:set,get:get,has:has,enforce:function(it){return has(it)?get(it):set(it,{})},getterFor:function(TYPE){return function(it){if(isObject(it)&&(it=get(it)).type===TYPE)return it;throw TypeError("Incompatible receiver, "+TYPE+" required")}}}},{"../internals/create-non-enumerable-property":161,"../internals/global":216,"../internals/has-own-property":217,"../internals/hidden-keys":218,"../internals/is-object":238,"../internals/shared-key":305,"../internals/shared-store":306,"../internals/weak-map-basic-detection":350}],229:[function(require,module,exports){var wellKnownSymbol=require("../internals/well-known-symbol"),Iterators=require("../internals/iterators"),ITERATOR=wellKnownSymbol("iterator"),ArrayPrototype=Array.prototype;module.exports=function(it){return void 0!==it&&(Iterators.Array===it||ArrayPrototype[ITERATOR]===it)}},{"../internals/iterators":247,"../internals/well-known-symbol":353}],230:[function(require,module,exports){var classof=require("../internals/classof-raw");module.exports=Array.isArray||function(argument){return"Array"==classof(argument)}},{"../internals/classof-raw":151}],231:[function(require,module,exports){var classof=require("../internals/classof");module.exports=function(it){it=classof(it);return"BigInt64Array"==it||"BigUint64Array"==it}},{"../internals/classof":152}],232:[function(require,module,exports){var require=require("../internals/document-all"),documentAll=require.all;module.exports=require.IS_HTMLDDA?function(argument){return"function"==typeof argument||argument===documentAll}:function(argument){return"function"==typeof argument}},{"../internals/document-all":172}],233:[function(require,module,exports){function noop(){}function isConstructorModern(argument){if(!isCallable(argument))return!1;try{return construct(noop,empty,argument),!0}catch(error){return!1}}function isConstructorLegacy(argument){if(!isCallable(argument))return!1;switch(classof(argument)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return INCORRECT_TO_STRING||!!exec(constructorRegExp,inspectSource(argument))}catch(error){return!0}}var uncurryThis=require("../internals/function-uncurry-this"),fails=require("../internals/fails"),isCallable=require("../internals/is-callable"),classof=require("../internals/classof"),getBuiltIn=require("../internals/get-built-in"),inspectSource=require("../internals/inspect-source"),empty=[],construct=getBuiltIn("Reflect","construct"),constructorRegExp=/^\s*(?:class|function)\b/,exec=uncurryThis(constructorRegExp.exec),INCORRECT_TO_STRING=!constructorRegExp.exec(noop);isConstructorLegacy.sham=!0,module.exports=!construct||fails(function(){var called;return isConstructorModern(isConstructorModern.call)||!isConstructorModern(Object)||!isConstructorModern(function(){called=!0})||called})?isConstructorLegacy:isConstructorModern},{"../internals/classof":152,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/get-built-in":210,"../internals/inspect-source":225,"../internals/is-callable":232}],234:[function(require,module,exports){var hasOwn=require("../internals/has-own-property");module.exports=function(descriptor){return void 0!==descriptor&&(hasOwn(descriptor,"value")||hasOwn(descriptor,"writable"))}},{"../internals/has-own-property":217}],235:[function(require,module,exports){function isForced(feature,detection){return(feature=data[normalize(feature)])==POLYFILL||feature!=NATIVE&&(isCallable(detection)?fails(detection):!!detection)}var fails=require("../internals/fails"),isCallable=require("../internals/is-callable"),replacement=/#|\.prototype\./,normalize=isForced.normalize=function(string){return String(string).replace(replacement,".").toLowerCase()},data=isForced.data={},NATIVE=isForced.NATIVE="N",POLYFILL=isForced.POLYFILL="P";module.exports=isForced},{"../internals/fails":197,"../internals/is-callable":232}],236:[function(require,module,exports){var isObject=require("../internals/is-object"),floor=Math.floor;module.exports=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it}},{"../internals/is-object":238}],237:[function(require,module,exports){module.exports=function(it){return null==it}},{}],238:[function(require,module,exports){var isCallable=require("../internals/is-callable"),require=require("../internals/document-all"),documentAll=require.all;module.exports=require.IS_HTMLDDA?function(it){return"object"==typeof it?null!==it:isCallable(it)||it===documentAll}:function(it){return"object"==typeof it?null!==it:isCallable(it)}},{"../internals/document-all":172,"../internals/is-callable":232}],239:[function(require,module,exports){module.exports=!1},{}],240:[function(require,module,exports){var isObject=require("../internals/is-object"),classof=require("../internals/classof-raw"),MATCH=require("../internals/well-known-symbol")("match");module.exports=function(it){var isRegExp;return isObject(it)&&(void 0!==(isRegExp=it[MATCH])?!!isRegExp:"RegExp"==classof(it))}},{"../internals/classof-raw":151,"../internals/is-object":238,"../internals/well-known-symbol":353}],241:[function(require,module,exports){var getBuiltIn=require("../internals/get-built-in"),isCallable=require("../internals/is-callable"),isPrototypeOf=require("../internals/object-is-prototype-of"),require=require("../internals/use-symbol-as-uid"),$Object=Object;module.exports=require?function(it){return"symbol"==typeof it}:function(it){var $Symbol=getBuiltIn("Symbol");return isCallable($Symbol)&&isPrototypeOf($Symbol.prototype,$Object(it))}},{"../internals/get-built-in":210,"../internals/is-callable":232,"../internals/object-is-prototype-of":274,"../internals/use-symbol-as-uid":347}],242:[function(require,module,exports){function Result(stopped,result){this.stopped=stopped,this.result=result}var bind=require("../internals/function-bind-context"),call=require("../internals/function-call"),anObject=require("../internals/an-object"),tryToString=require("../internals/try-to-string"),isArrayIteratorMethod=require("../internals/is-array-iterator-method"),lengthOfArrayLike=require("../internals/length-of-array-like"),isPrototypeOf=require("../internals/object-is-prototype-of"),getIterator=require("../internals/get-iterator"),getIteratorMethod=require("../internals/get-iterator-method"),iteratorClose=require("../internals/iterator-close"),$TypeError=TypeError,ResultPrototype=Result.prototype;module.exports=function(iterable,unboundFunction,options){function stop(condition){return iterator&&iteratorClose(iterator,"normal",condition),new Result(!0,condition)}function callFn(value){return AS_ENTRIES?(anObject(value),INTERRUPTED?fn(value[0],value[1],stop):fn(value[0],value[1])):INTERRUPTED?fn(value,stop):fn(value)}var iterator,index,length,result,next,step,that=options&&options.that,AS_ENTRIES=!(!options||!options.AS_ENTRIES),IS_RECORD=!(!options||!options.IS_RECORD),IS_ITERATOR=!(!options||!options.IS_ITERATOR),INTERRUPTED=!(!options||!options.INTERRUPTED),fn=bind(unboundFunction,that);if(IS_RECORD)iterator=iterable.iterator;else if(IS_ITERATOR)iterator=iterable;else{if(!(options=getIteratorMethod(iterable)))throw $TypeError(tryToString(iterable)+" is not iterable");if(isArrayIteratorMethod(options)){for(index=0,length=lengthOfArrayLike(iterable);index<length;index++)if((result=callFn(iterable[index]))&&isPrototypeOf(ResultPrototype,result))return result;return new Result(!1)}iterator=getIterator(iterable,options)}for(next=(IS_RECORD?iterable:iterator).next;!(step=call(next,iterator)).done;){try{result=callFn(step.value)}catch(error){iteratorClose(iterator,"throw",error)}if("object"==typeof result&&result&&isPrototypeOf(ResultPrototype,result))return result}return new Result(!1)}},{"../internals/an-object":123,"../internals/function-bind-context":202,"../internals/function-call":205,"../internals/get-iterator":212,"../internals/get-iterator-method":211,"../internals/is-array-iterator-method":229,"../internals/iterator-close":243,"../internals/length-of-array-like":248,"../internals/object-is-prototype-of":274,"../internals/try-to-string":339}],243:[function(require,module,exports){var call=require("../internals/function-call"),anObject=require("../internals/an-object"),getMethod=require("../internals/get-method");module.exports=function(iterator,kind,value){var innerResult,innerError;anObject(iterator);try{if(!(innerResult=getMethod(iterator,"return"))){if("throw"===kind)throw value;return value}innerResult=call(innerResult,iterator)}catch(error){innerError=!0,innerResult=error}if("throw"===kind)throw value;if(innerError)throw innerResult;return anObject(innerResult),value}},{"../internals/an-object":123,"../internals/function-call":205,"../internals/get-method":214}],244:[function(require,module,exports){"use strict";function returnThis(){return this}var IteratorPrototype=require("../internals/iterators-core").IteratorPrototype,create=require("../internals/object-create"),createPropertyDescriptor=require("../internals/create-property-descriptor"),setToStringTag=require("../internals/set-to-string-tag"),Iterators=require("../internals/iterators");module.exports=function(IteratorConstructor,NAME,next,ENUMERABLE_NEXT){NAME+=" Iterator";return IteratorConstructor.prototype=create(IteratorPrototype,{next:createPropertyDescriptor(+!ENUMERABLE_NEXT,next)}),setToStringTag(IteratorConstructor,NAME,!1,!0),Iterators[NAME]=returnThis,IteratorConstructor}},{"../internals/create-property-descriptor":162,"../internals/iterators":247,"../internals/iterators-core":246,"../internals/object-create":265,"../internals/set-to-string-tag":304}],245:[function(require,module,exports){"use strict";function returnThis(){return this}var $=require("../internals/export"),call=require("../internals/function-call"),IS_PURE=require("../internals/is-pure"),FunctionName=require("../internals/function-name"),isCallable=require("../internals/is-callable"),createIteratorConstructor=require("../internals/iterator-create-constructor"),getPrototypeOf=require("../internals/object-get-prototype-of"),setPrototypeOf=require("../internals/object-set-prototype-of"),setToStringTag=require("../internals/set-to-string-tag"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),defineBuiltIn=require("../internals/define-built-in"),wellKnownSymbol=require("../internals/well-known-symbol"),Iterators=require("../internals/iterators"),require=require("../internals/iterators-core"),PROPER_FUNCTION_NAME=FunctionName.PROPER,CONFIGURABLE_FUNCTION_NAME=FunctionName.CONFIGURABLE,IteratorPrototype=require.IteratorPrototype,BUGGY_SAFARI_ITERATORS=require.BUGGY_SAFARI_ITERATORS,ITERATOR=wellKnownSymbol("iterator");module.exports=function(Iterable,NAME,IteratorConstructor,next,DEFAULT,IS_SET,FORCED){createIteratorConstructor(IteratorConstructor,NAME,next);function getIterationMethod(KIND){if(KIND===DEFAULT&&defaultIterator)return defaultIterator;if(!BUGGY_SAFARI_ITERATORS&&KIND in IterablePrototype)return IterablePrototype[KIND];switch(KIND){case"keys":case"values":case"entries":return function(){return new IteratorConstructor(this,KIND)}}return function(){return new IteratorConstructor(this)}}var methods,KEY,next=NAME+" Iterator",INCORRECT_VALUES_NAME=!1,IterablePrototype=Iterable.prototype,nativeIterator=IterablePrototype[ITERATOR]||IterablePrototype["@@iterator"]||DEFAULT&&IterablePrototype[DEFAULT],defaultIterator=!BUGGY_SAFARI_ITERATORS&&nativeIterator||getIterationMethod(DEFAULT),anyNativeIterator="Array"==NAME&&IterablePrototype.entries||nativeIterator;if(anyNativeIterator&&(anyNativeIterator=getPrototypeOf(anyNativeIterator.call(new Iterable)))!==Object.prototype&&anyNativeIterator.next&&(IS_PURE||getPrototypeOf(anyNativeIterator)===IteratorPrototype||(setPrototypeOf?setPrototypeOf(anyNativeIterator,IteratorPrototype):isCallable(anyNativeIterator[ITERATOR])||defineBuiltIn(anyNativeIterator,ITERATOR,returnThis)),setToStringTag(anyNativeIterator,next,!0,!0),IS_PURE)&&(Iterators[next]=returnThis),PROPER_FUNCTION_NAME&&"values"==DEFAULT&&nativeIterator&&"values"!==nativeIterator.name&&(!IS_PURE&&CONFIGURABLE_FUNCTION_NAME?createNonEnumerableProperty(IterablePrototype,"name","values"):(INCORRECT_VALUES_NAME=!0,defaultIterator=function(){return call(nativeIterator,this)})),DEFAULT)if(methods={values:getIterationMethod("values"),keys:IS_SET?defaultIterator:getIterationMethod("keys"),entries:getIterationMethod("entries")},FORCED)for(KEY in methods)!BUGGY_SAFARI_ITERATORS&&!INCORRECT_VALUES_NAME&&KEY in IterablePrototype||defineBuiltIn(IterablePrototype,KEY,methods[KEY]);else $({target:NAME,proto:!0,forced:BUGGY_SAFARI_ITERATORS||INCORRECT_VALUES_NAME},methods);return IS_PURE&&!FORCED||IterablePrototype[ITERATOR]===defaultIterator||defineBuiltIn(IterablePrototype,ITERATOR,defaultIterator,{name:DEFAULT}),Iterators[NAME]=defaultIterator,methods}},{"../internals/create-non-enumerable-property":161,"../internals/define-built-in":167,"../internals/export":196,"../internals/function-call":205,"../internals/function-name":206,"../internals/is-callable":232,"../internals/is-pure":239,"../internals/iterator-create-constructor":244,"../internals/iterators":247,"../internals/iterators-core":246,"../internals/object-get-prototype-of":272,"../internals/object-set-prototype-of":279,"../internals/set-to-string-tag":304,"../internals/well-known-symbol":353}],246:[function(require,module,exports){"use strict";var IteratorPrototype,arrayIterator,fails=require("../internals/fails"),isCallable=require("../internals/is-callable"),isObject=require("../internals/is-object"),create=require("../internals/object-create"),getPrototypeOf=require("../internals/object-get-prototype-of"),defineBuiltIn=require("../internals/define-built-in"),wellKnownSymbol=require("../internals/well-known-symbol"),require=require("../internals/is-pure"),ITERATOR=wellKnownSymbol("iterator"),wellKnownSymbol=!1;[].keys&&("next"in(arrayIterator=[].keys())?(getPrototypeOf=getPrototypeOf(getPrototypeOf(arrayIterator)))!==Object.prototype&&(IteratorPrototype=getPrototypeOf):wellKnownSymbol=!0),!isObject(IteratorPrototype)||fails(function(){var test={};return IteratorPrototype[ITERATOR].call(test)!==test})?IteratorPrototype={}:require&&(IteratorPrototype=create(IteratorPrototype)),isCallable(IteratorPrototype[ITERATOR])||defineBuiltIn(IteratorPrototype,ITERATOR,function(){return this}),module.exports={IteratorPrototype:IteratorPrototype,BUGGY_SAFARI_ITERATORS:wellKnownSymbol}},{"../internals/define-built-in":167,"../internals/fails":197,"../internals/is-callable":232,"../internals/is-object":238,"../internals/is-pure":239,"../internals/object-create":265,"../internals/object-get-prototype-of":272,"../internals/well-known-symbol":353}],247:[function(require,module,exports){arguments[4][218][0].apply(exports,arguments)},{dup:218}],248:[function(require,module,exports){var toLength=require("../internals/to-length");module.exports=function(obj){return toLength(obj.length)}},{"../internals/to-length":330}],249:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),fails=require("../internals/fails"),isCallable=require("../internals/is-callable"),hasOwn=require("../internals/has-own-property"),DESCRIPTORS=require("../internals/descriptors"),CONFIGURABLE_FUNCTION_NAME=require("../internals/function-name").CONFIGURABLE,inspectSource=require("../internals/inspect-source"),require=require("../internals/internal-state"),enforceInternalState=require.enforce,getInternalState=require.get,$String=String,defineProperty=Object.defineProperty,stringSlice=uncurryThis("".slice),replace=uncurryThis("".replace),join=uncurryThis([].join),CONFIGURABLE_LENGTH=DESCRIPTORS&&!fails(function(){return 8!==defineProperty(function(){},"length",{value:8}).length}),TEMPLATE=String(String).split("String"),require=module.exports=function(value,name,options){"Symbol("===stringSlice($String(name),0,7)&&(name="["+replace($String(name),/^Symbol\(([^)]*)\)/,"$1")+"]"),options&&options.getter&&(name="get "+name),options&&options.setter&&(name="set "+name),(!hasOwn(value,"name")||CONFIGURABLE_FUNCTION_NAME&&value.name!==name)&&(DESCRIPTORS?defineProperty(value,"name",{value:name,configurable:!0}):value.name=name),CONFIGURABLE_LENGTH&&options&&hasOwn(options,"arity")&&value.length!==options.arity&&defineProperty(value,"length",{value:options.arity});try{options&&hasOwn(options,"constructor")&&options.constructor?DESCRIPTORS&&defineProperty(value,"prototype",{writable:!1}):value.prototype&&(value.prototype=void 0)}catch(error){}options=enforceInternalState(value);return hasOwn(options,"source")||(options.source=join(TEMPLATE,"string"==typeof name?name:"")),value};Function.prototype.toString=require(function(){return isCallable(this)&&getInternalState(this).source||inspectSource(this)},"toString")},{"../internals/descriptors":171,"../internals/fails":197,"../internals/function-name":206,"../internals/function-uncurry-this":209,"../internals/has-own-property":217,"../internals/inspect-source":225,"../internals/internal-state":228,"../internals/is-callable":232}],250:[function(require,module,exports){var require=require("../internals/function-uncurry-this"),MapPrototype=Map.prototype;module.exports={Map:Map,set:require(MapPrototype.set),get:require(MapPrototype.get),has:require(MapPrototype.has),remove:require(MapPrototype.delete),proto:MapPrototype}},{"../internals/function-uncurry-this":209}],251:[function(require,module,exports){var $expm1=Math.expm1,exp=Math.exp;module.exports=!$expm1||22025.465794806718<$expm1(10)||$expm1(10)<22025.465794806718||-2e-17!=$expm1(-2e-17)?function(x){x=+x;return 0==x?x:-1e-6<x&&x<1e-6?x+x*x/2:exp(x)-1}:$expm1},{}],252:[function(require,module,exports){var sign=require("../internals/math-sign"),abs=Math.abs,require=Math.pow,EPSILON=require(2,-52),EPSILON32=require(2,-23),MAX32=require(2,127)*(2-EPSILON32),MIN32=require(2,-126);module.exports=Math.fround||function(x){var a,x=+x,$abs=abs(x),x=sign(x);return $abs<MIN32?x*($abs/MIN32/EPSILON32+1/EPSILON-1/EPSILON)*MIN32*EPSILON32:MAX32<(a=(a=(1+EPSILON32/EPSILON)*$abs)-(a-$abs))||a!=a?x*(1/0):x*a}},{"../internals/math-sign":255}],253:[function(require,module,exports){var log=Math.log,LOG10E=Math.LOG10E;module.exports=Math.log10||function(x){return log(x)*LOG10E}},{}],254:[function(require,module,exports){var log=Math.log;module.exports=Math.log1p||function(x){x=+x;return-1e-8<x&&x<1e-8?x-x*x/2:log(1+x)}},{}],255:[function(require,module,exports){module.exports=Math.sign||function(x){x=+x;return 0==x||x!=x?x:x<0?-1:1}},{}],256:[function(require,module,exports){var ceil=Math.ceil,floor=Math.floor;module.exports=Math.trunc||function(x){x=+x;return(0<x?floor:ceil)(x)}},{}],257:[function(require,module,exports){var toggle,node,then,queue,flush,notify,global=require("../internals/global"),bind=require("../internals/function-bind-context"),getOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f,macrotask=require("../internals/task").set,Queue=require("../internals/queue"),IS_IOS=require("../internals/engine-is-ios"),IS_IOS_PEBBLE=require("../internals/engine-is-ios-pebble"),IS_WEBOS_WEBKIT=require("../internals/engine-is-webos-webkit"),IS_NODE=require("../internals/engine-is-node"),require=global.MutationObserver||global.WebKitMutationObserver,document=global.document,process=global.process,Promise=global.Promise,getOwnPropertyDescriptor=getOwnPropertyDescriptor(global,"queueMicrotask"),getOwnPropertyDescriptor=getOwnPropertyDescriptor&&getOwnPropertyDescriptor.value;getOwnPropertyDescriptor||(queue=new Queue,flush=function(){var parent,fn;for(IS_NODE&&(parent=process.domain)&&parent.exit();fn=queue.get();)try{fn()}catch(error){throw queue.head&&notify(),error}parent&&parent.enter()},notify=IS_IOS||IS_NODE||IS_WEBOS_WEBKIT||!require||!document?!IS_IOS_PEBBLE&&Promise&&Promise.resolve?((Queue=Promise.resolve(void 0)).constructor=Promise,then=bind(Queue.then,Queue),function(){then(flush)}):IS_NODE?function(){process.nextTick(flush)}:(macrotask=bind(macrotask,global),function(){macrotask(flush)}):(toggle=!0,node=document.createTextNode(""),new require(flush).observe(node,{characterData:!0}),function(){node.data=toggle=!toggle}),getOwnPropertyDescriptor=function(fn){queue.head||notify(),queue.add(fn)}),module.exports=getOwnPropertyDescriptor},{"../internals/engine-is-ios":184,"../internals/engine-is-ios-pebble":183,"../internals/engine-is-node":185,"../internals/engine-is-webos-webkit":186,"../internals/function-bind-context":202,"../internals/global":216,"../internals/object-get-own-property-descriptor":268,"../internals/queue":291,"../internals/task":323}],258:[function(require,module,exports){"use strict";function PromiseCapability(C){var resolve,reject;this.promise=new C(function($$resolve,$$reject){if(void 0!==resolve||void 0!==reject)throw $TypeError("Bad Promise constructor");resolve=$$resolve,reject=$$reject}),this.resolve=aCallable(resolve),this.reject=aCallable(reject)}var aCallable=require("../internals/a-callable"),$TypeError=TypeError;module.exports.f=function(C){return new PromiseCapability(C)}},{"../internals/a-callable":117}],259:[function(require,module,exports){var toString=require("../internals/to-string");module.exports=function(argument,$default){return void 0===argument?arguments.length<2?"":$default:toString(argument)}},{"../internals/to-string":337}],260:[function(require,module,exports){var isRegExp=require("../internals/is-regexp"),$TypeError=TypeError;module.exports=function(it){if(isRegExp(it))throw $TypeError("The method doesn't accept regular expressions");return it}},{"../internals/is-regexp":240}],261:[function(require,module,exports){var globalIsFinite=require("../internals/global").isFinite;module.exports=Number.isFinite||function(it){return"number"==typeof it&&globalIsFinite(it)}},{"../internals/global":216}],262:[function(require,module,exports){var global=require("../internals/global"),fails=require("../internals/fails"),uncurryThis=require("../internals/function-uncurry-this"),toString=require("../internals/to-string"),trim=require("../internals/string-trim").trim,require=require("../internals/whitespaces"),charAt=uncurryThis("".charAt),$parseFloat=global.parseFloat,uncurryThis=global.Symbol,ITERATOR=uncurryThis&&uncurryThis.iterator,global=1/$parseFloat(require+"-0")!=-1/0||ITERATOR&&!fails(function(){$parseFloat(Object(ITERATOR))});module.exports=global?function(string){var string=trim(toString(string)),result=$parseFloat(string);return 0===result&&"-"==charAt(string,0)?-0:result}:$parseFloat},{"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/string-trim":318,"../internals/to-string":337,"../internals/whitespaces":354}],263:[function(require,module,exports){var global=require("../internals/global"),fails=require("../internals/fails"),uncurryThis=require("../internals/function-uncurry-this"),toString=require("../internals/to-string"),trim=require("../internals/string-trim").trim,require=require("../internals/whitespaces"),$parseInt=global.parseInt,global=global.Symbol,ITERATOR=global&&global.iterator,hex=/^[+-]?0x/i,exec=uncurryThis(hex.exec),global=8!==$parseInt(require+"08")||22!==$parseInt(require+"0x16")||ITERATOR&&!fails(function(){$parseInt(Object(ITERATOR))});module.exports=global?function(string,radix){string=trim(toString(string));return $parseInt(string,radix>>>0||(exec(hex,string)?16:10))}:$parseInt},{"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/string-trim":318,"../internals/to-string":337,"../internals/whitespaces":354}],264:[function(require,module,exports){"use strict";var DESCRIPTORS=require("../internals/descriptors"),uncurryThis=require("../internals/function-uncurry-this"),call=require("../internals/function-call"),fails=require("../internals/fails"),objectKeys=require("../internals/object-keys"),getOwnPropertySymbolsModule=require("../internals/object-get-own-property-symbols"),propertyIsEnumerableModule=require("../internals/object-property-is-enumerable"),toObject=require("../internals/to-object"),IndexedObject=require("../internals/indexed-object"),$assign=Object.assign,defineProperty=Object.defineProperty,concat=uncurryThis([].concat);module.exports=!$assign||fails(function(){var A,B,symbol;return!(!DESCRIPTORS||1===$assign({b:1},$assign(defineProperty({},"a",{enumerable:!0,get:function(){defineProperty(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)||(B={},(A={})[symbol=Symbol()]=7,"abcdefghijklmnopqrst".split("").forEach(function(chr){B[chr]=chr}),7!=$assign({},A)[symbol])||"abcdefghijklmnopqrst"!=objectKeys($assign({},B)).join("")})?function(target,source){for(var T=toObject(target),argumentsLength=arguments.length,index=1,getOwnPropertySymbols=getOwnPropertySymbolsModule.f,propertyIsEnumerable=propertyIsEnumerableModule.f;index<argumentsLength;)for(var key,S=IndexedObject(arguments[index++]),keys=getOwnPropertySymbols?concat(objectKeys(S),getOwnPropertySymbols(S)):objectKeys(S),length=keys.length,j=0;j<length;)key=keys[j++],DESCRIPTORS&&!call(propertyIsEnumerable,S,key)||(T[key]=S[key]);return T}:$assign},{"../internals/descriptors":171,"../internals/fails":197,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/indexed-object":223,"../internals/object-get-own-property-symbols":271,"../internals/object-keys":276,"../internals/object-property-is-enumerable":277,"../internals/to-object":331}],265:[function(require,module,exports){function EmptyConstructor(){}function NullProtoObjectViaActiveX(activeXDocument){activeXDocument.write(scriptTag("")),activeXDocument.close();var temp=activeXDocument.parentWindow.Object;return activeXDocument=null,temp}var activeXDocument,anObject=require("../internals/an-object"),definePropertiesModule=require("../internals/object-define-properties"),enumBugKeys=require("../internals/enum-bug-keys"),hiddenKeys=require("../internals/hidden-keys"),html=require("../internals/html"),documentCreateElement=require("../internals/document-create-element"),require=require("../internals/shared-key"),SCRIPT="script",IE_PROTO=require("IE_PROTO"),scriptTag=function(content){return"<"+SCRIPT+">"+content+"</"+SCRIPT+">"},NullProtoObject=function(){try{activeXDocument=new ActiveXObject("htmlfile")}catch(error){}NullProtoObject="undefined"==typeof document||document.domain&&activeXDocument?NullProtoObjectViaActiveX(activeXDocument):(iframe=documentCreateElement("iframe"),JS="java"+SCRIPT+":",iframe.style.display="none",html.appendChild(iframe),iframe.src=String(JS),(JS=iframe.contentWindow.document).open(),JS.write(scriptTag("document.F=Object")),JS.close(),JS.F);for(var iframe,JS,length=enumBugKeys.length;length--;)delete NullProtoObject.prototype[enumBugKeys[length]];return NullProtoObject()};hiddenKeys[IE_PROTO]=!0,module.exports=Object.create||function(O,Properties){var result;return null!==O?(EmptyConstructor.prototype=anObject(O),result=new EmptyConstructor,EmptyConstructor.prototype=null,result[IE_PROTO]=O):result=NullProtoObject(),void 0===Properties?result:definePropertiesModule.f(result,Properties)}},{"../internals/an-object":123,"../internals/document-create-element":173,"../internals/enum-bug-keys":191,"../internals/hidden-keys":218,"../internals/html":220,"../internals/object-define-properties":266,"../internals/shared-key":305}],266:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),V8_PROTOTYPE_DEFINE_BUG=require("../internals/v8-prototype-define-bug"),definePropertyModule=require("../internals/object-define-property"),anObject=require("../internals/an-object"),toIndexedObject=require("../internals/to-indexed-object"),objectKeys=require("../internals/object-keys");exports.f=DESCRIPTORS&&!V8_PROTOTYPE_DEFINE_BUG?Object.defineProperties:function(O,Properties){anObject(O);for(var key,props=toIndexedObject(Properties),keys=objectKeys(Properties),length=keys.length,index=0;index<length;)definePropertyModule.f(O,key=keys[index++],props[key]);return O}},{"../internals/an-object":123,"../internals/descriptors":171,"../internals/object-define-property":267,"../internals/object-keys":276,"../internals/to-indexed-object":328,"../internals/v8-prototype-define-bug":348}],267:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),IE8_DOM_DEFINE=require("../internals/ie8-dom-define"),V8_PROTOTYPE_DEFINE_BUG=require("../internals/v8-prototype-define-bug"),anObject=require("../internals/an-object"),toPropertyKey=require("../internals/to-property-key"),$TypeError=TypeError,$defineProperty=Object.defineProperty,$getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;exports.f=DESCRIPTORS?V8_PROTOTYPE_DEFINE_BUG?function(O,P,Attributes){var current;return anObject(O),P=toPropertyKey(P),anObject(Attributes),"function"==typeof O&&"prototype"===P&&"value"in Attributes&&"writable"in Attributes&&!Attributes.writable&&(current=$getOwnPropertyDescriptor(O,P))&&current.writable&&(O[P]=Attributes.value,Attributes={configurable:("configurable"in Attributes?Attributes:current).configurable,enumerable:("enumerable"in Attributes?Attributes:current).enumerable,writable:!1}),$defineProperty(O,P,Attributes)}:$defineProperty:function(O,P,Attributes){if(anObject(O),P=toPropertyKey(P),anObject(Attributes),IE8_DOM_DEFINE)try{return $defineProperty(O,P,Attributes)}catch(error){}if("get"in Attributes||"set"in Attributes)throw $TypeError("Accessors not supported");return"value"in Attributes&&(O[P]=Attributes.value),O}},{"../internals/an-object":123,"../internals/descriptors":171,"../internals/ie8-dom-define":221,"../internals/to-property-key":335,"../internals/v8-prototype-define-bug":348}],268:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),call=require("../internals/function-call"),propertyIsEnumerableModule=require("../internals/object-property-is-enumerable"),createPropertyDescriptor=require("../internals/create-property-descriptor"),toIndexedObject=require("../internals/to-indexed-object"),toPropertyKey=require("../internals/to-property-key"),hasOwn=require("../internals/has-own-property"),IE8_DOM_DEFINE=require("../internals/ie8-dom-define"),$getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;exports.f=DESCRIPTORS?$getOwnPropertyDescriptor:function(O,P){if(O=toIndexedObject(O),P=toPropertyKey(P),IE8_DOM_DEFINE)try{return $getOwnPropertyDescriptor(O,P)}catch(error){}if(hasOwn(O,P))return createPropertyDescriptor(!call(propertyIsEnumerableModule.f,O,P),O[P])}},{"../internals/create-property-descriptor":162,"../internals/descriptors":171,"../internals/function-call":205,"../internals/has-own-property":217,"../internals/ie8-dom-define":221,"../internals/object-property-is-enumerable":277,"../internals/to-indexed-object":328,"../internals/to-property-key":335}],269:[function(require,module,exports){var classof=require("../internals/classof-raw"),toIndexedObject=require("../internals/to-indexed-object"),$getOwnPropertyNames=require("../internals/object-get-own-property-names").f,arraySlice=require("../internals/array-slice-simple"),windowNames="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];module.exports.f=function(it){return windowNames&&"Window"==classof(it)?function(it){try{return $getOwnPropertyNames(it)}catch(error){return arraySlice(windowNames)}}(it):$getOwnPropertyNames(toIndexedObject(it))}},{"../internals/array-slice-simple":141,"../internals/classof-raw":151,"../internals/object-get-own-property-names":270,"../internals/to-indexed-object":328}],270:[function(require,module,exports){var internalObjectKeys=require("../internals/object-keys-internal"),hiddenKeys=require("../internals/enum-bug-keys").concat("length","prototype");exports.f=Object.getOwnPropertyNames||function(O){return internalObjectKeys(O,hiddenKeys)}},{"../internals/enum-bug-keys":191,"../internals/object-keys-internal":275}],271:[function(require,module,exports){exports.f=Object.getOwnPropertySymbols},{}],272:[function(require,module,exports){var hasOwn=require("../internals/has-own-property"),isCallable=require("../internals/is-callable"),toObject=require("../internals/to-object"),sharedKey=require("../internals/shared-key"),require=require("../internals/correct-prototype-getter"),IE_PROTO=sharedKey("IE_PROTO"),$Object=Object,ObjectPrototype=$Object.prototype;module.exports=require?$Object.getPrototypeOf:function(O){var constructor,O=toObject(O);return hasOwn(O,IE_PROTO)?O[IE_PROTO]:(constructor=O.constructor,isCallable(constructor)&&O instanceof constructor?constructor.prototype:O instanceof $Object?ObjectPrototype:null)}},{"../internals/correct-prototype-getter":158,"../internals/has-own-property":217,"../internals/is-callable":232,"../internals/shared-key":305,"../internals/to-object":331}],273:[function(require,module,exports){var fails=require("../internals/fails"),isObject=require("../internals/is-object"),classof=require("../internals/classof-raw"),ARRAY_BUFFER_NON_EXTENSIBLE=require("../internals/array-buffer-non-extensible"),$isExtensible=Object.isExtensible,require=fails(function(){$isExtensible(1)});module.exports=require||ARRAY_BUFFER_NON_EXTENSIBLE?function(it){return!(!isObject(it)||ARRAY_BUFFER_NON_EXTENSIBLE&&"ArrayBuffer"==classof(it))&&(!$isExtensible||$isExtensible(it))}:$isExtensible},{"../internals/array-buffer-non-extensible":125,"../internals/classof-raw":151,"../internals/fails":197,"../internals/is-object":238}],274:[function(require,module,exports){require=require("../internals/function-uncurry-this");module.exports=require({}.isPrototypeOf)},{"../internals/function-uncurry-this":209}],275:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),hasOwn=require("../internals/has-own-property"),toIndexedObject=require("../internals/to-indexed-object"),indexOf=require("../internals/array-includes").indexOf,hiddenKeys=require("../internals/hidden-keys"),push=uncurryThis([].push);module.exports=function(object,names){var key,O=toIndexedObject(object),i=0,result=[];for(key in O)!hasOwn(hiddenKeys,key)&&hasOwn(O,key)&&push(result,key);for(;names.length>i;)!hasOwn(O,key=names[i++])||~indexOf(result,key)||push(result,key);return result}},{"../internals/array-includes":133,"../internals/function-uncurry-this":209,"../internals/has-own-property":217,"../internals/hidden-keys":218,"../internals/to-indexed-object":328}],276:[function(require,module,exports){var internalObjectKeys=require("../internals/object-keys-internal"),enumBugKeys=require("../internals/enum-bug-keys");module.exports=Object.keys||function(O){return internalObjectKeys(O,enumBugKeys)}},{"../internals/enum-bug-keys":191,"../internals/object-keys-internal":275}],277:[function(require,module,exports){"use strict";var $propertyIsEnumerable={}.propertyIsEnumerable,getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor,NASHORN_BUG=getOwnPropertyDescriptor&&!$propertyIsEnumerable.call({1:2},1);exports.f=NASHORN_BUG?function(V){V=getOwnPropertyDescriptor(this,V);return!!V&&V.enumerable}:$propertyIsEnumerable},{}],278:[function(require,module,exports){"use strict";var IS_PURE=require("../internals/is-pure"),global=require("../internals/global"),fails=require("../internals/fails"),WEBKIT=require("../internals/engine-webkit-version");module.exports=IS_PURE||!fails(function(){var key;WEBKIT&&WEBKIT<535||(key=Math.random(),__defineSetter__.call(null,key,function(){}),delete global[key])})},{"../internals/engine-webkit-version":189,"../internals/fails":197,"../internals/global":216,"../internals/is-pure":239}],279:[function(require,module,exports){var uncurryThisAccessor=require("../internals/function-uncurry-this-accessor"),anObject=require("../internals/an-object"),aPossiblePrototype=require("../internals/a-possible-prototype");module.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var setter,CORRECT_SETTER=!1,test={};try{(setter=uncurryThisAccessor(Object.prototype,"__proto__","set"))(test,[]),CORRECT_SETTER=test instanceof Array}catch(error){}return function(O,proto){return anObject(O),aPossiblePrototype(proto),CORRECT_SETTER?setter(O,proto):O.__proto__=proto,O}}():void 0)},{"../internals/a-possible-prototype":119,"../internals/an-object":123,"../internals/function-uncurry-this-accessor":207}],280:[function(require,module,exports){function createMethod(TO_ENTRIES){return function(it){for(var key,O=toIndexedObject(it),keys=objectKeys(O),length=keys.length,i=0,result=[];i<length;)key=keys[i++],DESCRIPTORS&&!propertyIsEnumerable(O,key)||push(result,TO_ENTRIES?[key,O[key]]:O[key]);return result}}var DESCRIPTORS=require("../internals/descriptors"),uncurryThis=require("../internals/function-uncurry-this"),objectKeys=require("../internals/object-keys"),toIndexedObject=require("../internals/to-indexed-object"),propertyIsEnumerable=uncurryThis(require("../internals/object-property-is-enumerable").f),push=uncurryThis([].push);module.exports={entries:createMethod(!0),values:createMethod(!1)}},{"../internals/descriptors":171,"../internals/function-uncurry-this":209,"../internals/object-keys":276,"../internals/object-property-is-enumerable":277,"../internals/to-indexed-object":328}],281:[function(require,module,exports){"use strict";var TO_STRING_TAG_SUPPORT=require("../internals/to-string-tag-support"),classof=require("../internals/classof");module.exports=TO_STRING_TAG_SUPPORT?{}.toString:function(){return"[object "+classof(this)+"]"}},{"../internals/classof":152,"../internals/to-string-tag-support":336}],282:[function(require,module,exports){var call=require("../internals/function-call"),isCallable=require("../internals/is-callable"),isObject=require("../internals/is-object"),$TypeError=TypeError;module.exports=function(input,pref){var fn,val;if("string"===pref&&isCallable(fn=input.toString)&&!isObject(val=call(fn,input)))return val;if(isCallable(fn=input.valueOf)&&!isObject(val=call(fn,input)))return val;if("string"!==pref&&isCallable(fn=input.toString)&&!isObject(val=call(fn,input)))return val;throw $TypeError("Can't convert object to primitive value")}},{"../internals/function-call":205,"../internals/is-callable":232,"../internals/is-object":238}],283:[function(require,module,exports){var getBuiltIn=require("../internals/get-built-in"),uncurryThis=require("../internals/function-uncurry-this"),getOwnPropertyNamesModule=require("../internals/object-get-own-property-names"),getOwnPropertySymbolsModule=require("../internals/object-get-own-property-symbols"),anObject=require("../internals/an-object"),concat=uncurryThis([].concat);module.exports=getBuiltIn("Reflect","ownKeys")||function(it){var keys=getOwnPropertyNamesModule.f(anObject(it)),getOwnPropertySymbols=getOwnPropertySymbolsModule.f;return getOwnPropertySymbols?concat(keys,getOwnPropertySymbols(it)):keys}},{"../internals/an-object":123,"../internals/function-uncurry-this":209,"../internals/get-built-in":210,"../internals/object-get-own-property-names":270,"../internals/object-get-own-property-symbols":271}],284:[function(require,module,exports){require=require("../internals/global");module.exports=require},{"../internals/global":216}],285:[function(require,module,exports){module.exports=function(exec){try{return{error:!1,value:exec()}}catch(error){return{error:!0,value:error}}}},{}],286:[function(require,module,exports){var global=require("../internals/global"),NativePromiseConstructor=require("../internals/promise-native-constructor"),isCallable=require("../internals/is-callable"),isForced=require("../internals/is-forced"),inspectSource=require("../internals/inspect-source"),wellKnownSymbol=require("../internals/well-known-symbol"),IS_BROWSER=require("../internals/engine-is-browser"),IS_DENO=require("../internals/engine-is-deno"),IS_PURE=require("../internals/is-pure"),V8_VERSION=require("../internals/engine-v8-version"),NativePromisePrototype=NativePromiseConstructor&&NativePromiseConstructor.prototype,SPECIES=wellKnownSymbol("species"),SUBCLASSING=!1,NATIVE_PROMISE_REJECTION_EVENT=isCallable(global.PromiseRejectionEvent),require=isForced("Promise",function(){var PROMISE_CONSTRUCTOR_SOURCE=inspectSource(NativePromiseConstructor),GLOBAL_CORE_JS_PROMISE=PROMISE_CONSTRUCTOR_SOURCE!==String(NativePromiseConstructor);if(!GLOBAL_CORE_JS_PROMISE&&66===V8_VERSION)return!0;if(IS_PURE&&(!NativePromisePrototype.catch||!NativePromisePrototype.finally))return!0;if(!V8_VERSION||V8_VERSION<51||!/native code/.test(PROMISE_CONSTRUCTOR_SOURCE)){function FakePromise(exec){exec(function(){},function(){})}PROMISE_CONSTRUCTOR_SOURCE=new NativePromiseConstructor(function(resolve){resolve(1)});if((PROMISE_CONSTRUCTOR_SOURCE.constructor={})[SPECIES]=FakePromise,!(SUBCLASSING=PROMISE_CONSTRUCTOR_SOURCE.then(function(){})instanceof FakePromise))return!0}return!GLOBAL_CORE_JS_PROMISE&&(IS_BROWSER||IS_DENO)&&!NATIVE_PROMISE_REJECTION_EVENT});module.exports={CONSTRUCTOR:require,REJECTION_EVENT:NATIVE_PROMISE_REJECTION_EVENT,SUBCLASSING:SUBCLASSING}},{"../internals/engine-is-browser":179,"../internals/engine-is-deno":181,"../internals/engine-v8-version":188,"../internals/global":216,"../internals/inspect-source":225,"../internals/is-callable":232,"../internals/is-forced":235,"../internals/is-pure":239,"../internals/promise-native-constructor":287,"../internals/well-known-symbol":353}],287:[function(require,module,exports){require=require("../internals/global");module.exports=require.Promise},{"../internals/global":216}],288:[function(require,module,exports){var anObject=require("../internals/an-object"),isObject=require("../internals/is-object"),newPromiseCapability=require("../internals/new-promise-capability");module.exports=function(C,x){return anObject(C),isObject(x)&&x.constructor===C?x:((0,(C=newPromiseCapability.f(C)).resolve)(x),C.promise)}},{"../internals/an-object":123,"../internals/is-object":238,"../internals/new-promise-capability":258}],289:[function(require,module,exports){var NativePromiseConstructor=require("../internals/promise-native-constructor"),checkCorrectnessOfIteration=require("../internals/check-correctness-of-iteration"),require=require("../internals/promise-constructor-detection").CONSTRUCTOR;module.exports=require||!checkCorrectnessOfIteration(function(iterable){NativePromiseConstructor.all(iterable).then(void 0,function(){})})},{"../internals/check-correctness-of-iteration":150,"../internals/promise-constructor-detection":286,"../internals/promise-native-constructor":287}],290:[function(require,module,exports){var defineProperty=require("../internals/object-define-property").f;module.exports=function(Target,Source,key){key in Target||defineProperty(Target,key,{configurable:!0,get:function(){return Source[key]},set:function(it){Source[key]=it}})}},{"../internals/object-define-property":267}],291:[function(require,module,exports){function Queue(){this.head=null,this.tail=null}Queue.prototype={add:function(item){var item={item:item,next:null},tail=this.tail;tail?tail.next=item:this.head=item,this.tail=item},get:function(){var entry=this.head;if(entry)return null===(this.head=entry.next)&&(this.tail=null),entry.item}},module.exports=Queue},{}],292:[function(require,module,exports){var call=require("../internals/function-call"),anObject=require("../internals/an-object"),isCallable=require("../internals/is-callable"),classof=require("../internals/classof-raw"),regexpExec=require("../internals/regexp-exec"),$TypeError=TypeError;module.exports=function(R,S){var exec=R.exec;if(isCallable(exec))return null!==(exec=call(exec,R,S))&&anObject(exec),exec;if("RegExp"===classof(R))return call(regexpExec,R,S);throw $TypeError("RegExp#exec called on incompatible receiver")}},{"../internals/an-object":123,"../internals/classof-raw":151,"../internals/function-call":205,"../internals/is-callable":232,"../internals/regexp-exec":293}],293:[function(require,module,exports){"use strict";var call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this"),toString=require("../internals/to-string"),regexpFlags=require("../internals/regexp-flags"),stickyHelpers=require("../internals/regexp-sticky-helpers"),shared=require("../internals/shared"),create=require("../internals/object-create"),getInternalState=require("../internals/internal-state").get,UNSUPPORTED_DOT_ALL=require("../internals/regexp-unsupported-dot-all"),require=require("../internals/regexp-unsupported-ncg"),nativeReplace=shared("native-string-replace",String.prototype.replace),nativeExec=RegExp.prototype.exec,patchedExec=nativeExec,charAt=uncurryThis("".charAt),indexOf=uncurryThis("".indexOf),replace=uncurryThis("".replace),stringSlice=uncurryThis("".slice),UPDATES_LAST_INDEX_WRONG=(shared=/b*/g,call(nativeExec,uncurryThis=/a/,"a"),call(nativeExec,shared,"a"),0!==uncurryThis.lastIndex||0!==shared.lastIndex),UNSUPPORTED_Y=stickyHelpers.BROKEN_CARET,NPCG_INCLUDED=void 0!==/()??/.exec("")[1];(UPDATES_LAST_INDEX_WRONG||NPCG_INCLUDED||UNSUPPORTED_Y||UNSUPPORTED_DOT_ALL||require)&&(patchedExec=function(string){var reCopy,lastIndex,match,i,object,group,re=this,state=getInternalState(re),string=toString(string),raw=state.raw;if(raw)return raw.lastIndex=re.lastIndex,result=call(patchedExec,raw,string),re.lastIndex=raw.lastIndex,result;var groups=state.groups,raw=UNSUPPORTED_Y&&re.sticky,result=call(regexpFlags,re),state=re.source,charsAdded=0,strCopy=string;if(raw&&(result=replace(result,"y",""),-1===indexOf(result,"g")&&(result+="g"),strCopy=stringSlice(string,re.lastIndex),0<re.lastIndex&&(!re.multiline||re.multiline&&"\n"!==charAt(string,re.lastIndex-1))&&(state="(?: "+state+")",strCopy=" "+strCopy,charsAdded++),reCopy=new RegExp("^(?:"+state+")",result)),NPCG_INCLUDED&&(reCopy=new RegExp("^"+state+"$(?!\\s)",result)),UPDATES_LAST_INDEX_WRONG&&(lastIndex=re.lastIndex),match=call(nativeExec,raw?reCopy:re,strCopy),raw?match?(match.input=stringSlice(match.input,charsAdded),match[0]=stringSlice(match[0],charsAdded),match.index=re.lastIndex,re.lastIndex+=match[0].length):re.lastIndex=0:UPDATES_LAST_INDEX_WRONG&&match&&(re.lastIndex=re.global?match.index+match[0].length:lastIndex),NPCG_INCLUDED&&match&&1<match.length&&call(nativeReplace,match[0],reCopy,function(){for(i=1;i<arguments.length-2;i++)void 0===arguments[i]&&(match[i]=void 0)}),match&&groups)for(match.groups=object=create(null),i=0;i<groups.length;i++)object[(group=groups[i])[0]]=match[group[1]];return match}),module.exports=patchedExec},{"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/internal-state":228,"../internals/object-create":265,"../internals/regexp-flags":294,"../internals/regexp-sticky-helpers":296,"../internals/regexp-unsupported-dot-all":297,"../internals/regexp-unsupported-ncg":298,"../internals/shared":307,"../internals/to-string":337}],294:[function(require,module,exports){"use strict";var anObject=require("../internals/an-object");module.exports=function(){var that=anObject(this),result="";return that.hasIndices&&(result+="d"),that.global&&(result+="g"),that.ignoreCase&&(result+="i"),that.multiline&&(result+="m"),that.dotAll&&(result+="s"),that.unicode&&(result+="u"),that.unicodeSets&&(result+="v"),that.sticky&&(result+="y"),result}},{"../internals/an-object":123}],295:[function(require,module,exports){var call=require("../internals/function-call"),hasOwn=require("../internals/has-own-property"),isPrototypeOf=require("../internals/object-is-prototype-of"),regExpFlags=require("../internals/regexp-flags"),RegExpPrototype=RegExp.prototype;module.exports=function(R){var flags=R.flags;return void 0!==flags||"flags"in RegExpPrototype||hasOwn(R,"flags")||!isPrototypeOf(RegExpPrototype,R)?flags:call(regExpFlags,R)}},{"../internals/function-call":205,"../internals/has-own-property":217,"../internals/object-is-prototype-of":274,"../internals/regexp-flags":294}],296:[function(require,module,exports){var fails=require("../internals/fails"),$RegExp=require("../internals/global").RegExp,require=fails(function(){var re=$RegExp("a","y");return re.lastIndex=2,null!=re.exec("abcd")}),MISSED_STICKY=require||fails(function(){return!$RegExp("a","y").sticky}),fails=require||fails(function(){var re=$RegExp("^r","gy");return re.lastIndex=2,null!=re.exec("str")});module.exports={BROKEN_CARET:fails,MISSED_STICKY:MISSED_STICKY,UNSUPPORTED_Y:require}},{"../internals/fails":197,"../internals/global":216}],297:[function(require,module,exports){var fails=require("../internals/fails"),$RegExp=require("../internals/global").RegExp;module.exports=fails(function(){var re=$RegExp(".","s");return!(re.dotAll&&re.exec("\n")&&"s"===re.flags)})},{"../internals/fails":197,"../internals/global":216}],298:[function(require,module,exports){var fails=require("../internals/fails"),$RegExp=require("../internals/global").RegExp;module.exports=fails(function(){var re=$RegExp("(?<a>b)","g");return"b"!==re.exec("b").groups.a||"bc"!=="b".replace(re,"$<a>c")})},{"../internals/fails":197,"../internals/global":216}],299:[function(require,module,exports){var isNullOrUndefined=require("../internals/is-null-or-undefined"),$TypeError=TypeError;module.exports=function(it){if(isNullOrUndefined(it))throw $TypeError("Can't call method on "+it);return it}},{"../internals/is-null-or-undefined":237}],300:[function(require,module,exports){module.exports=Object.is||function(x,y){return x===y?0!==x||1/x==1/y:x!=x&&y!=y}},{}],301:[function(require,module,exports){"use strict";var global=require("../internals/global"),apply=require("../internals/function-apply"),isCallable=require("../internals/is-callable"),ENGINE_IS_BUN=require("../internals/engine-is-bun"),USER_AGENT=require("../internals/engine-user-agent"),arraySlice=require("../internals/array-slice"),validateArgumentsLength=require("../internals/validate-arguments-length"),Function=global.Function,WRAP=/MSIE .\./.test(USER_AGENT)||ENGINE_IS_BUN&&((require=global.Bun.version.split(".")).length<3||0==require[0]&&(require[1]<3||3==require[1]&&0==require[2]));module.exports=function(scheduler,hasTimeArg){var firstParamIndex=hasTimeArg?2:1;return WRAP?function(handler,timeout){var boundArgs=validateArgumentsLength(arguments.length,1)>firstParamIndex,fn=isCallable(handler)?handler:Function(handler),params=boundArgs?arraySlice(arguments,firstParamIndex):[],handler=boundArgs?function(){apply(fn,this,params)}:fn;return hasTimeArg?scheduler(handler,timeout):scheduler(handler)}:scheduler}},{"../internals/array-slice":142,"../internals/engine-is-bun":180,"../internals/engine-user-agent":187,"../internals/function-apply":201,"../internals/global":216,"../internals/is-callable":232,"../internals/validate-arguments-length":349}],302:[function(require,module,exports){var require=require("../internals/function-uncurry-this"),SetPrototype=Set.prototype;module.exports={Set:Set,add:require(SetPrototype.add),has:require(SetPrototype.has),remove:require(SetPrototype.delete),proto:SetPrototype}},{"../internals/function-uncurry-this":209}],303:[function(require,module,exports){"use strict";var getBuiltIn=require("../internals/get-built-in"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),wellKnownSymbol=require("../internals/well-known-symbol"),DESCRIPTORS=require("../internals/descriptors"),SPECIES=wellKnownSymbol("species");module.exports=function(CONSTRUCTOR_NAME){CONSTRUCTOR_NAME=getBuiltIn(CONSTRUCTOR_NAME);DESCRIPTORS&&CONSTRUCTOR_NAME&&!CONSTRUCTOR_NAME[SPECIES]&&defineBuiltInAccessor(CONSTRUCTOR_NAME,SPECIES,{configurable:!0,get:function(){return this}})}},{"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/get-built-in":210,"../internals/well-known-symbol":353}],304:[function(require,module,exports){var defineProperty=require("../internals/object-define-property").f,hasOwn=require("../internals/has-own-property"),TO_STRING_TAG=require("../internals/well-known-symbol")("toStringTag");module.exports=function(target,TAG,STATIC){(target=target&&!STATIC?target.prototype:target)&&!hasOwn(target,TO_STRING_TAG)&&defineProperty(target,TO_STRING_TAG,{configurable:!0,value:TAG})}},{"../internals/has-own-property":217,"../internals/object-define-property":267,"../internals/well-known-symbol":353}],305:[function(require,module,exports){var shared=require("../internals/shared"),uid=require("../internals/uid"),keys=shared("keys");module.exports=function(key){return keys[key]||(keys[key]=uid(key))}},{"../internals/shared":307,"../internals/uid":345}],306:[function(require,module,exports){var global=require("../internals/global"),require=require("../internals/define-global-property"),global=global["__core-js_shared__"]||require("__core-js_shared__",{});module.exports=global},{"../internals/define-global-property":169,"../internals/global":216}],307:[function(require,module,exports){var IS_PURE=require("../internals/is-pure"),store=require("../internals/shared-store");(module.exports=function(key,value){return store[key]||(store[key]=void 0!==value?value:{})})("versions",[]).push({version:"3.30.0",mode:IS_PURE?"pure":"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"})},{"../internals/is-pure":239,"../internals/shared-store":306}],308:[function(require,module,exports){var anObject=require("../internals/an-object"),aConstructor=require("../internals/a-constructor"),isNullOrUndefined=require("../internals/is-null-or-undefined"),SPECIES=require("../internals/well-known-symbol")("species");module.exports=function(O,defaultConstructor){var O=anObject(O).constructor;return void 0===O||isNullOrUndefined(O=anObject(O)[SPECIES])?defaultConstructor:aConstructor(O)}},{"../internals/a-constructor":118,"../internals/an-object":123,"../internals/is-null-or-undefined":237,"../internals/well-known-symbol":353}],309:[function(require,module,exports){var fails=require("../internals/fails");module.exports=function(METHOD_NAME){return fails(function(){var test=""[METHOD_NAME]('"');return test!==test.toLowerCase()||3<test.split('"').length})}},{"../internals/fails":197}],310:[function(require,module,exports){function createMethod(CONVERT_TO_STRING){return function($this,pos){var first,$this=toString(requireObjectCoercible($this)),pos=toIntegerOrInfinity(pos),size=$this.length;return pos<0||size<=pos?CONVERT_TO_STRING?"":void 0:(first=charCodeAt($this,pos))<55296||56319<first||pos+1===size||(size=charCodeAt($this,pos+1))<56320||57343<size?CONVERT_TO_STRING?charAt($this,pos):first:CONVERT_TO_STRING?stringSlice($this,pos,pos+2):size-56320+(first-55296<<10)+65536}}var uncurryThis=require("../internals/function-uncurry-this"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),toString=require("../internals/to-string"),requireObjectCoercible=require("../internals/require-object-coercible"),charAt=uncurryThis("".charAt),charCodeAt=uncurryThis("".charCodeAt),stringSlice=uncurryThis("".slice);module.exports={codeAt:createMethod(!1),charAt:createMethod(!0)}},{"../internals/function-uncurry-this":209,"../internals/require-object-coercible":299,"../internals/to-integer-or-infinity":329,"../internals/to-string":337}],311:[function(require,module,exports){require=require("../internals/engine-user-agent");module.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(require)},{"../internals/engine-user-agent":187}],312:[function(require,module,exports){function createMethod(IS_END){return function($this,maxLength,fillString){var $this=toString(requireObjectCoercible($this)),maxLength=toLength(maxLength),stringLength=$this.length,fillString=void 0===fillString?" ":toString(fillString);return maxLength<=stringLength||""==fillString?$this:((stringLength=repeat(fillString,ceil((maxLength=maxLength-stringLength)/fillString.length))).length>maxLength&&(stringLength=stringSlice(stringLength,0,maxLength)),IS_END?$this+stringLength:stringLength+$this)}}var uncurryThis=require("../internals/function-uncurry-this"),toLength=require("../internals/to-length"),toString=require("../internals/to-string"),$repeat=require("../internals/string-repeat"),requireObjectCoercible=require("../internals/require-object-coercible"),repeat=uncurryThis($repeat),stringSlice=uncurryThis("".slice),ceil=Math.ceil;module.exports={start:createMethod(!1),end:createMethod(!0)}},{"../internals/function-uncurry-this":209,"../internals/require-object-coercible":299,"../internals/string-repeat":314,"../internals/to-length":330,"../internals/to-string":337}],313:[function(require,module,exports){function digitToBasic(digit){return digit+22+75*(digit<26)}function encode(input){var currentValue,output=[],inputLength=(input=function(string){for(var output=[],counter=0,length=string.length;counter<length;){var extra,value=charCodeAt(string,counter++);55296<=value&&value<=56319&&counter<length?56320==(64512&(extra=charCodeAt(string,counter++)))?push(output,((1023&value)<<10)+(1023&extra)+65536):(push(output,value),counter--):push(output,value)}return output}(input)).length,n=128,delta=0,bias=72;for(i=0;i<input.length;i++)(currentValue=input[i])<128&&push(output,fromCharCode(currentValue));var basicLength=output.length,handledCPCount=basicLength;for(basicLength&&push(output,"-");handledCPCount<inputLength;){for(var m=2147483647,i=0;i<input.length;i++)n<=(currentValue=input[i])&&currentValue<m&&(m=currentValue);var handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((2147483647-delta)/handledCPCountPlusOne))throw $RangeError(OVERFLOW_ERROR);for(delta+=(m-n)*handledCPCountPlusOne,n=m,i=0;i<input.length;i++){if((currentValue=input[i])<n&&2147483647<++delta)throw $RangeError(OVERFLOW_ERROR);if(currentValue==n){for(var q=delta,k=base;;){var t=k<=bias?1:bias+tMax<=k?tMax:k-bias;if(q<t)break;var qMinusT=q-t,baseMinusT=base-t;push(output,fromCharCode(digitToBasic(t+qMinusT%baseMinusT))),q=floor(qMinusT/baseMinusT),k+=base}push(output,fromCharCode(digitToBasic(q))),bias=function(delta,numPoints,firstTime){var k=0;for(delta=firstTime?floor(delta/damp):delta>>1,delta+=floor(delta/numPoints);baseMinusTMin*tMax>>1<delta;)delta=floor(delta/baseMinusTMin),k+=base;return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}(delta,handledCPCountPlusOne,handledCPCount==basicLength),delta=0,handledCPCount++}}delta++,n++}return join(output,"")}var require=require("../internals/function-uncurry-this"),base=36,tMax=26,skew=38,damp=700,regexNonASCII=/[^\0-\u007E]/,regexSeparators=/[.\u3002\uFF0E\uFF61]/g,OVERFLOW_ERROR="Overflow: input needs wider integers to process",baseMinusTMin=base-1,$RangeError=RangeError,exec=require(regexSeparators.exec),floor=Math.floor,fromCharCode=String.fromCharCode,charCodeAt=require("".charCodeAt),join=require([].join),push=require([].push),replace=require("".replace),split=require("".split),toLowerCase=require("".toLowerCase);module.exports=function(input){for(var label,encoded=[],labels=split(replace(toLowerCase(input),regexSeparators,"."),"."),i=0;i<labels.length;i++)label=labels[i],push(encoded,exec(regexNonASCII,label)?"xn--"+encode(label):label);return join(encoded,".")}},{"../internals/function-uncurry-this":209}],314:[function(require,module,exports){"use strict";var toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),toString=require("../internals/to-string"),requireObjectCoercible=require("../internals/require-object-coercible"),$RangeError=RangeError;module.exports=function(count){var str=toString(requireObjectCoercible(this)),result="",n=toIntegerOrInfinity(count);if(n<0||n==1/0)throw $RangeError("Wrong number of repetitions");for(;0<n;(n>>>=1)&&(str+=str))1&n&&(result+=str);return result}},{"../internals/require-object-coercible":299,"../internals/to-integer-or-infinity":329,"../internals/to-string":337}],315:[function(require,module,exports){"use strict";var $trimEnd=require("../internals/string-trim").end,require=require("../internals/string-trim-forced");module.exports=require("trimEnd")?function(){return $trimEnd(this)}:"".trimEnd},{"../internals/string-trim":318,"../internals/string-trim-forced":316}],316:[function(require,module,exports){var PROPER_FUNCTION_NAME=require("../internals/function-name").PROPER,fails=require("../internals/fails"),whitespaces=require("../internals/whitespaces");module.exports=function(METHOD_NAME){return fails(function(){return!!whitespaces[METHOD_NAME]()||"​᠎"!=="​᠎"[METHOD_NAME]()||PROPER_FUNCTION_NAME&&whitespaces[METHOD_NAME].name!==METHOD_NAME})}},{"../internals/fails":197,"../internals/function-name":206,"../internals/whitespaces":354}],317:[function(require,module,exports){"use strict";var $trimStart=require("../internals/string-trim").start,require=require("../internals/string-trim-forced");module.exports=require("trimStart")?function(){return $trimStart(this)}:"".trimStart},{"../internals/string-trim":318,"../internals/string-trim-forced":316}],318:[function(require,module,exports){function createMethod(TYPE){return function($this){$this=toString(requireObjectCoercible($this));return 1&TYPE&&($this=replace($this,ltrim,"")),$this=2&TYPE?replace($this,rtrim,"$1"):$this}}var uncurryThis=require("../internals/function-uncurry-this"),requireObjectCoercible=require("../internals/require-object-coercible"),toString=require("../internals/to-string"),require=require("../internals/whitespaces"),replace=uncurryThis("".replace),ltrim=RegExp("^["+require+"]+"),rtrim=RegExp("(^|[^"+require+"])["+require+"]+$");module.exports={start:createMethod(1),end:createMethod(2),trim:createMethod(3)}},{"../internals/function-uncurry-this":209,"../internals/require-object-coercible":299,"../internals/to-string":337,"../internals/whitespaces":354}],319:[function(require,module,exports){var global=require("../internals/global"),fails=require("../internals/fails"),V8=require("../internals/engine-v8-version"),IS_BROWSER=require("../internals/engine-is-browser"),IS_DENO=require("../internals/engine-is-deno"),IS_NODE=require("../internals/engine-is-node"),structuredClone=global.structuredClone;module.exports=!!structuredClone&&!fails(function(){var buffer,clone;return!(IS_DENO&&92<V8||IS_NODE&&94<V8||IS_BROWSER&&97<V8)&&(buffer=new ArrayBuffer(8),clone=structuredClone(buffer,{transfer:[buffer]}),0!=buffer.byteLength||8!=clone.byteLength)})},{"../internals/engine-is-browser":179,"../internals/engine-is-deno":181,"../internals/engine-is-node":185,"../internals/engine-v8-version":188,"../internals/fails":197,"../internals/global":216}],320:[function(require,module,exports){var V8_VERSION=require("../internals/engine-v8-version"),require=require("../internals/fails");module.exports=!!Object.getOwnPropertySymbols&&!require(function(){var symbol=Symbol();return!String(symbol)||!(Object(symbol)instanceof Symbol)||!Symbol.sham&&V8_VERSION&&V8_VERSION<41})},{"../internals/engine-v8-version":188,"../internals/fails":197}],321:[function(require,module,exports){var call=require("../internals/function-call"),getBuiltIn=require("../internals/get-built-in"),wellKnownSymbol=require("../internals/well-known-symbol"),defineBuiltIn=require("../internals/define-built-in");module.exports=function(){var Symbol=getBuiltIn("Symbol"),Symbol=Symbol&&Symbol.prototype,valueOf=Symbol&&Symbol.valueOf,TO_PRIMITIVE=wellKnownSymbol("toPrimitive");Symbol&&!Symbol[TO_PRIMITIVE]&&defineBuiltIn(Symbol,TO_PRIMITIVE,function(hint){return call(valueOf,this)},{arity:1})}},{"../internals/define-built-in":167,"../internals/function-call":205,"../internals/get-built-in":210,"../internals/well-known-symbol":353}],322:[function(require,module,exports){require=require("../internals/symbol-constructor-detection");module.exports=require&&!!Symbol.for&&!!Symbol.keyFor},{"../internals/symbol-constructor-detection":320}],323:[function(require,module,exports){function runner(id){return function(){run(id)}}function eventListener(event){run(event.data)}function globalPostMessageDefer(id){global.postMessage(String(id),$location.protocol+"//"+$location.host)}var $location,defer,global=require("../internals/global"),apply=require("../internals/function-apply"),bind=require("../internals/function-bind-context"),isCallable=require("../internals/is-callable"),hasOwn=require("../internals/has-own-property"),fails=require("../internals/fails"),html=require("../internals/html"),arraySlice=require("../internals/array-slice"),createElement=require("../internals/document-create-element"),validateArgumentsLength=require("../internals/validate-arguments-length"),IS_IOS=require("../internals/engine-is-ios"),require=require("../internals/engine-is-node"),set=global.setImmediate,clear=global.clearImmediate,process=global.process,Dispatch=global.Dispatch,Function=global.Function,MessageChannel=global.MessageChannel,String=global.String,counter=0,queue={},run=(fails(function(){$location=global.location}),function(id){var fn;hasOwn(queue,id)&&(fn=queue[id],delete queue[id],fn())});set&&clear||(set=function(handler){validateArgumentsLength(arguments.length,1);var fn=isCallable(handler)?handler:Function(handler),args=arraySlice(arguments,1);return queue[++counter]=function(){apply(fn,void 0,args)},defer(counter),counter},clear=function(id){delete queue[id]},require?defer=function(id){process.nextTick(runner(id))}:Dispatch&&Dispatch.now?defer=function(id){Dispatch.now(runner(id))}:MessageChannel&&!IS_IOS?(IS_IOS=(require=new MessageChannel).port2,require.port1.onmessage=eventListener,defer=bind(IS_IOS.postMessage,IS_IOS)):global.addEventListener&&isCallable(global.postMessage)&&!global.importScripts&&$location&&"file:"!==$location.protocol&&!fails(globalPostMessageDefer)?(defer=globalPostMessageDefer,global.addEventListener("message",eventListener,!1)):defer="onreadystatechange"in createElement("script")?function(id){html.appendChild(createElement("script")).onreadystatechange=function(){html.removeChild(this),run(id)}}:function(id){setTimeout(runner(id),0)}),module.exports={set:set,clear:clear}},{"../internals/array-slice":142,"../internals/document-create-element":173,"../internals/engine-is-ios":184,"../internals/engine-is-node":185,"../internals/fails":197,"../internals/function-apply":201,"../internals/function-bind-context":202,"../internals/global":216,"../internals/has-own-property":217,"../internals/html":220,"../internals/is-callable":232,"../internals/validate-arguments-length":349}],324:[function(require,module,exports){require=require("../internals/function-uncurry-this");module.exports=require(1..valueOf)},{"../internals/function-uncurry-this":209}],325:[function(require,module,exports){var toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),max=Math.max,min=Math.min;module.exports=function(index,length){index=toIntegerOrInfinity(index);return index<0?max(index+length,0):min(index,length)}},{"../internals/to-integer-or-infinity":329}],326:[function(require,module,exports){var toPrimitive=require("../internals/to-primitive"),$TypeError=TypeError;module.exports=function(argument){argument=toPrimitive(argument,"number");if("number"==typeof argument)throw $TypeError("Can't convert number to bigint");return BigInt(argument)}},{"../internals/to-primitive":334}],327:[function(require,module,exports){var toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),toLength=require("../internals/to-length"),$RangeError=RangeError;module.exports=function(it){if(void 0===it)return 0;var it=toIntegerOrInfinity(it),length=toLength(it);if(it!==length)throw $RangeError("Wrong length or index");return length}},{"../internals/to-integer-or-infinity":329,"../internals/to-length":330}],328:[function(require,module,exports){var IndexedObject=require("../internals/indexed-object"),requireObjectCoercible=require("../internals/require-object-coercible");module.exports=function(it){return IndexedObject(requireObjectCoercible(it))}},{"../internals/indexed-object":223,"../internals/require-object-coercible":299}],329:[function(require,module,exports){var trunc=require("../internals/math-trunc");module.exports=function(argument){argument=+argument;return argument!=argument||0==argument?0:trunc(argument)}},{"../internals/math-trunc":256}],330:[function(require,module,exports){var toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),min=Math.min;module.exports=function(argument){return 0<argument?min(toIntegerOrInfinity(argument),9007199254740991):0}},{"../internals/to-integer-or-infinity":329}],331:[function(require,module,exports){var requireObjectCoercible=require("../internals/require-object-coercible"),$Object=Object;module.exports=function(argument){return $Object(requireObjectCoercible(argument))}},{"../internals/require-object-coercible":299}],332:[function(require,module,exports){var toPositiveInteger=require("../internals/to-positive-integer"),$RangeError=RangeError;module.exports=function(it,BYTES){it=toPositiveInteger(it);if(it%BYTES)throw $RangeError("Wrong offset");return it}},{"../internals/to-positive-integer":333}],333:[function(require,module,exports){var toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),$RangeError=RangeError;module.exports=function(it){it=toIntegerOrInfinity(it);if(it<0)throw $RangeError("The argument can't be less than 0");return it}},{"../internals/to-integer-or-infinity":329}],334:[function(require,module,exports){var call=require("../internals/function-call"),isObject=require("../internals/is-object"),isSymbol=require("../internals/is-symbol"),getMethod=require("../internals/get-method"),ordinaryToPrimitive=require("../internals/ordinary-to-primitive"),require=require("../internals/well-known-symbol"),$TypeError=TypeError,TO_PRIMITIVE=require("toPrimitive");module.exports=function(input,pref){if(!isObject(input)||isSymbol(input))return input;var exoticToPrim=getMethod(input,TO_PRIMITIVE);if(exoticToPrim){if(exoticToPrim=call(exoticToPrim,input,pref=void 0===pref?"default":pref),!isObject(exoticToPrim)||isSymbol(exoticToPrim))return exoticToPrim;throw $TypeError("Can't convert object to primitive value")}return ordinaryToPrimitive(input,pref=void 0===pref?"number":pref)}},{"../internals/function-call":205,"../internals/get-method":214,"../internals/is-object":238,"../internals/is-symbol":241,"../internals/ordinary-to-primitive":282,"../internals/well-known-symbol":353}],335:[function(require,module,exports){var toPrimitive=require("../internals/to-primitive"),isSymbol=require("../internals/is-symbol");module.exports=function(argument){argument=toPrimitive(argument,"string");return isSymbol(argument)?argument:argument+""}},{"../internals/is-symbol":241,"../internals/to-primitive":334}],336:[function(require,module,exports){var test={};test[require("../internals/well-known-symbol")("toStringTag")]="z",module.exports="[object z]"===String(test)},{"../internals/well-known-symbol":353}],337:[function(require,module,exports){var classof=require("../internals/classof"),$String=String;module.exports=function(argument){if("Symbol"===classof(argument))throw TypeError("Cannot convert a Symbol value to a string");return $String(argument)}},{"../internals/classof":152}],338:[function(require,module,exports){var IS_NODE=require("../internals/engine-is-node");module.exports=function(name){try{if(IS_NODE)return Function('return require("'+name+'")')()}catch(error){}}},{"../internals/engine-is-node":185}],339:[function(require,module,exports){var $String=String;module.exports=function(argument){try{return $String(argument)}catch(error){return"Object"}}},{}],340:[function(require,module,exports){"use strict";function fromList(C,list){aTypedArrayConstructor(C);for(var index=0,length=list.length,result=new C(length);index<length;)result[index]=list[index++];return result}function addGetter(it,key){defineBuiltInAccessor(it,key,{configurable:!0,get:function(){return getInternalState(this)[key]}})}function isArrayBuffer(it){return isPrototypeOf(ArrayBufferPrototype,it)||"ArrayBuffer"==(it=classof(it))||"SharedArrayBuffer"==it}function isTypedArrayIndex(target,key){return isTypedArray(target)&&!isSymbol(key)&&key in target&&isIntegralNumber(+key)&&0<=key}function wrappedGetOwnPropertyDescriptor(target,key){return key=toPropertyKey(key),isTypedArrayIndex(target,key)?createPropertyDescriptor(2,target[key]):nativeGetOwnPropertyDescriptor(target,key)}function wrappedDefineProperty(target,key,descriptor){return key=toPropertyKey(key),!(isTypedArrayIndex(target,key)&&isObject(descriptor)&&hasOwn(descriptor,"value"))||hasOwn(descriptor,"get")||hasOwn(descriptor,"set")||descriptor.configurable||hasOwn(descriptor,"writable")&&!descriptor.writable||hasOwn(descriptor,"enumerable")&&!descriptor.enumerable?nativeDefineProperty(target,key,descriptor):(target[key]=descriptor.value,target)}var $=require("../internals/export"),global=require("../internals/global"),call=require("../internals/function-call"),DESCRIPTORS=require("../internals/descriptors"),TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS=require("../internals/typed-array-constructors-require-wrappers"),ArrayBufferViewCore=require("../internals/array-buffer-view-core"),ArrayBufferModule=require("../internals/array-buffer"),anInstance=require("../internals/an-instance"),createPropertyDescriptor=require("../internals/create-property-descriptor"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),isIntegralNumber=require("../internals/is-integral-number"),toLength=require("../internals/to-length"),toIndex=require("../internals/to-index"),toOffset=require("../internals/to-offset"),toPropertyKey=require("../internals/to-property-key"),hasOwn=require("../internals/has-own-property"),classof=require("../internals/classof"),isObject=require("../internals/is-object"),isSymbol=require("../internals/is-symbol"),create=require("../internals/object-create"),isPrototypeOf=require("../internals/object-is-prototype-of"),setPrototypeOf=require("../internals/object-set-prototype-of"),getOwnPropertyNames=require("../internals/object-get-own-property-names").f,typedArrayFrom=require("../internals/typed-array-from"),forEach=require("../internals/array-iteration").forEach,setSpecies=require("../internals/set-species"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),definePropertyModule=require("../internals/object-define-property"),getOwnPropertyDescriptorModule=require("../internals/object-get-own-property-descriptor"),InternalStateModule=require("../internals/internal-state"),inheritIfRequired=require("../internals/inherit-if-required"),getInternalState=InternalStateModule.get,setInternalState=InternalStateModule.set,enforceInternalState=InternalStateModule.enforce,nativeDefineProperty=definePropertyModule.f,nativeGetOwnPropertyDescriptor=getOwnPropertyDescriptorModule.f,round=Math.round,RangeError=global.RangeError,ArrayBuffer=ArrayBufferModule.ArrayBuffer,ArrayBufferPrototype=ArrayBuffer.prototype,DataView=ArrayBufferModule.DataView,NATIVE_ARRAY_BUFFER_VIEWS=ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS,TYPED_ARRAY_TAG=ArrayBufferViewCore.TYPED_ARRAY_TAG,TypedArray=ArrayBufferViewCore.TypedArray,TypedArrayPrototype=ArrayBufferViewCore.TypedArrayPrototype,aTypedArrayConstructor=ArrayBufferViewCore.aTypedArrayConstructor,isTypedArray=ArrayBufferViewCore.isTypedArray;DESCRIPTORS?(NATIVE_ARRAY_BUFFER_VIEWS||(getOwnPropertyDescriptorModule.f=wrappedGetOwnPropertyDescriptor,definePropertyModule.f=wrappedDefineProperty,addGetter(TypedArrayPrototype,"buffer"),addGetter(TypedArrayPrototype,"byteOffset"),addGetter(TypedArrayPrototype,"byteLength"),addGetter(TypedArrayPrototype,"length")),$({target:"Object",stat:!0,forced:!NATIVE_ARRAY_BUFFER_VIEWS},{getOwnPropertyDescriptor:wrappedGetOwnPropertyDescriptor,defineProperty:wrappedDefineProperty}),module.exports=function(TYPE,wrapper,CLAMPED){function addElement(that,index){nativeDefineProperty(that,index,{get:function(){return function(that,index){that=getInternalState(that);return that.view[GETTER](index*BYTES+that.byteOffset,!0)}(this,index)},set:function(value){return function(that,index,value){that=getInternalState(that);CLAMPED&&(value=(value=round(value))<0?0:255<value?255:255&value),that.view[SETTER](index*BYTES+that.byteOffset,value,!0)}(this,index,value)},enumerable:!0})}var BYTES=TYPE.match(/\d+/)[0]/8,CONSTRUCTOR_NAME=TYPE+(CLAMPED?"Clamped":"")+"Array",GETTER="get"+TYPE,SETTER="set"+TYPE,NativeTypedArrayConstructor=global[CONSTRUCTOR_NAME],TypedArrayConstructor=NativeTypedArrayConstructor,TypedArrayConstructorPrototype=TypedArrayConstructor&&TypedArrayConstructor.prototype,TYPE={},wrapper=(NATIVE_ARRAY_BUFFER_VIEWS?TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS&&(TypedArrayConstructor=wrapper(function(dummy,data,typedArrayOffset,$length){return anInstance(dummy,TypedArrayConstructorPrototype),inheritIfRequired(isObject(data)?isArrayBuffer(data)?void 0!==$length?new NativeTypedArrayConstructor(data,toOffset(typedArrayOffset,BYTES),$length):void 0!==typedArrayOffset?new NativeTypedArrayConstructor(data,toOffset(typedArrayOffset,BYTES)):new NativeTypedArrayConstructor(data):isTypedArray(data)?fromList(TypedArrayConstructor,data):call(typedArrayFrom,TypedArrayConstructor,data):new NativeTypedArrayConstructor(toIndex(data)),dummy,TypedArrayConstructor)}),setPrototypeOf&&setPrototypeOf(TypedArrayConstructor,TypedArray),forEach(getOwnPropertyNames(NativeTypedArrayConstructor),function(key){key in TypedArrayConstructor||createNonEnumerableProperty(TypedArrayConstructor,key,NativeTypedArrayConstructor[key])}),TypedArrayConstructor.prototype=TypedArrayConstructorPrototype):(TypedArrayConstructor=wrapper(function(that,data,offset,$length){anInstance(that,TypedArrayConstructorPrototype);var byteLength,length,index=0,byteOffset=0;if(isObject(data)){if(!isArrayBuffer(data))return isTypedArray(data)?fromList(TypedArrayConstructor,data):call(typedArrayFrom,TypedArrayConstructor,data);var buffer=data,byteOffset=toOffset(offset,BYTES),offset=data.byteLength;if(void 0===$length){if(offset%BYTES)throw RangeError("Wrong length");if((byteLength=offset-byteOffset)<0)throw RangeError("Wrong length")}else if(offset<(byteLength=toLength($length)*BYTES)+byteOffset)throw RangeError("Wrong length");length=byteLength/BYTES}else length=toIndex(data),buffer=new ArrayBuffer(byteLength=length*BYTES);for(setInternalState(that,{buffer:buffer,byteOffset:byteOffset,byteLength:byteLength,length:length,view:new DataView(buffer)});index<length;)addElement(that,index++)}),setPrototypeOf&&setPrototypeOf(TypedArrayConstructor,TypedArray),TypedArrayConstructorPrototype=TypedArrayConstructor.prototype=create(TypedArrayPrototype)),TypedArrayConstructorPrototype.constructor!==TypedArrayConstructor&&createNonEnumerableProperty(TypedArrayConstructorPrototype,"constructor",TypedArrayConstructor),enforceInternalState(TypedArrayConstructorPrototype).TypedArrayConstructor=TypedArrayConstructor,TYPED_ARRAY_TAG&&createNonEnumerableProperty(TypedArrayConstructorPrototype,TYPED_ARRAY_TAG,CONSTRUCTOR_NAME),TypedArrayConstructor!=NativeTypedArrayConstructor);TYPE[CONSTRUCTOR_NAME]=TypedArrayConstructor,$({global:!0,constructor:!0,forced:wrapper,sham:!NATIVE_ARRAY_BUFFER_VIEWS},TYPE),"BYTES_PER_ELEMENT"in TypedArrayConstructor||createNonEnumerableProperty(TypedArrayConstructor,"BYTES_PER_ELEMENT",BYTES),"BYTES_PER_ELEMENT"in TypedArrayConstructorPrototype||createNonEnumerableProperty(TypedArrayConstructorPrototype,"BYTES_PER_ELEMENT",BYTES),setSpecies(CONSTRUCTOR_NAME)}):module.exports=function(){}},{"../internals/an-instance":122,"../internals/array-buffer":127,"../internals/array-buffer-view-core":126,"../internals/array-iteration":135,"../internals/classof":152,"../internals/create-non-enumerable-property":161,"../internals/create-property-descriptor":162,"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/export":196,"../internals/function-call":205,"../internals/global":216,"../internals/has-own-property":217,"../internals/inherit-if-required":224,"../internals/internal-state":228,"../internals/is-integral-number":236,"../internals/is-object":238,"../internals/is-symbol":241,"../internals/object-create":265,"../internals/object-define-property":267,"../internals/object-get-own-property-descriptor":268,"../internals/object-get-own-property-names":270,"../internals/object-is-prototype-of":274,"../internals/object-set-prototype-of":279,"../internals/set-species":303,"../internals/to-index":327,"../internals/to-length":330,"../internals/to-offset":332,"../internals/to-property-key":335,"../internals/typed-array-constructors-require-wrappers":341,"../internals/typed-array-from":343}],341:[function(require,module,exports){var global=require("../internals/global"),fails=require("../internals/fails"),checkCorrectnessOfIteration=require("../internals/check-correctness-of-iteration"),require=require("../internals/array-buffer-view-core").NATIVE_ARRAY_BUFFER_VIEWS,ArrayBuffer=global.ArrayBuffer,Int8Array=global.Int8Array;module.exports=!require||!fails(function(){Int8Array(1)})||!fails(function(){new Int8Array(-1)})||!checkCorrectnessOfIteration(function(iterable){new Int8Array,new Int8Array(null),new Int8Array(1.5),new Int8Array(iterable)},!0)||fails(function(){return 1!==new Int8Array(new ArrayBuffer(2),1,void 0).length})},{"../internals/array-buffer-view-core":126,"../internals/check-correctness-of-iteration":150,"../internals/fails":197,"../internals/global":216}],342:[function(require,module,exports){var arrayFromConstructorAndList=require("../internals/array-from-constructor-and-list"),typedArraySpeciesConstructor=require("../internals/typed-array-species-constructor");module.exports=function(instance,list){return arrayFromConstructorAndList(typedArraySpeciesConstructor(instance),list)}},{"../internals/array-from-constructor-and-list":131,"../internals/typed-array-species-constructor":344}],343:[function(require,module,exports){var bind=require("../internals/function-bind-context"),call=require("../internals/function-call"),aConstructor=require("../internals/a-constructor"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),getIterator=require("../internals/get-iterator"),getIteratorMethod=require("../internals/get-iterator-method"),isArrayIteratorMethod=require("../internals/is-array-iterator-method"),isBigIntArray=require("../internals/is-big-int-array"),aTypedArrayConstructor=require("../internals/array-buffer-view-core").aTypedArrayConstructor,toBigInt=require("../internals/to-big-int");module.exports=function(source){var i,length,result,thisIsBigIntArray,value,step,iterator,next,C=aConstructor(this),O=toObject(source),argumentsLength=arguments.length,mapfn=1<argumentsLength?arguments[1]:void 0,mapping=void 0!==mapfn,iteratorMethod=getIteratorMethod(O);if(iteratorMethod&&!isArrayIteratorMethod(iteratorMethod))for(next=(iterator=getIterator(O,iteratorMethod)).next,O=[];!(step=call(next,iterator)).done;)O.push(step.value);for(mapping&&2<argumentsLength&&(mapfn=bind(mapfn,arguments[2])),length=lengthOfArrayLike(O),result=new(aTypedArrayConstructor(C))(length),thisIsBigIntArray=isBigIntArray(result),i=0;i<length;i++)value=mapping?mapfn(O[i],i):O[i],result[i]=thisIsBigIntArray?toBigInt(value):+value;return result}},{"../internals/a-constructor":118,"../internals/array-buffer-view-core":126,"../internals/function-bind-context":202,"../internals/function-call":205,"../internals/get-iterator":212,"../internals/get-iterator-method":211,"../internals/is-array-iterator-method":229,"../internals/is-big-int-array":231,"../internals/length-of-array-like":248,"../internals/to-big-int":326,"../internals/to-object":331}],344:[function(require,module,exports){var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),speciesConstructor=require("../internals/species-constructor"),aTypedArrayConstructor=ArrayBufferViewCore.aTypedArrayConstructor,getTypedArrayConstructor=ArrayBufferViewCore.getTypedArrayConstructor;module.exports=function(originalArray){return aTypedArrayConstructor(speciesConstructor(originalArray,getTypedArrayConstructor(originalArray)))}},{"../internals/array-buffer-view-core":126,"../internals/species-constructor":308}],345:[function(require,module,exports){var require=require("../internals/function-uncurry-this"),id=0,postfix=Math.random(),toString=require(1..toString);module.exports=function(key){return"Symbol("+(void 0===key?"":key)+")_"+toString(++id+postfix,36)}},{"../internals/function-uncurry-this":209}],346:[function(require,module,exports){var fails=require("../internals/fails"),wellKnownSymbol=require("../internals/well-known-symbol"),DESCRIPTORS=require("../internals/descriptors"),IS_PURE=require("../internals/is-pure"),ITERATOR=wellKnownSymbol("iterator");module.exports=!fails(function(){var url=new URL("b?a=1&b=2&c=3","http://a"),searchParams=url.searchParams,result="";return url.pathname="c%20d",searchParams.forEach(function(value,key){searchParams.delete("b"),result+=key+value}),IS_PURE&&!url.toJSON||!searchParams.size&&(IS_PURE||!DESCRIPTORS)||!searchParams.sort||"http://a/c%20d?a=1&c=3"!==url.href||"3"!==searchParams.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!searchParams[ITERATOR]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==result||"x"!==new URL("http://x",void 0).host})},{"../internals/descriptors":171,"../internals/fails":197,"../internals/is-pure":239,"../internals/well-known-symbol":353}],347:[function(require,module,exports){require=require("../internals/symbol-constructor-detection");module.exports=require&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},{"../internals/symbol-constructor-detection":320}],348:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),require=require("../internals/fails");module.exports=DESCRIPTORS&&require(function(){return 42!=Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype})},{"../internals/descriptors":171,"../internals/fails":197}],349:[function(require,module,exports){var $TypeError=TypeError;module.exports=function(passed,required){if(passed<required)throw $TypeError("Not enough arguments");return passed}},{}],350:[function(require,module,exports){var global=require("../internals/global"),require=require("../internals/is-callable"),global=global.WeakMap;module.exports=require(global)&&/native code/.test(String(global))},{"../internals/global":216,"../internals/is-callable":232}],351:[function(require,module,exports){var path=require("../internals/path"),hasOwn=require("../internals/has-own-property"),wrappedWellKnownSymbolModule=require("../internals/well-known-symbol-wrapped"),defineProperty=require("../internals/object-define-property").f;module.exports=function(NAME){var Symbol=path.Symbol||(path.Symbol={});hasOwn(Symbol,NAME)||defineProperty(Symbol,NAME,{value:wrappedWellKnownSymbolModule.f(NAME)})}},{"../internals/has-own-property":217,"../internals/object-define-property":267,"../internals/path":284,"../internals/well-known-symbol-wrapped":352}],352:[function(require,module,exports){require=require("../internals/well-known-symbol");exports.f=require},{"../internals/well-known-symbol":353}],353:[function(require,module,exports){var global=require("../internals/global"),shared=require("../internals/shared"),hasOwn=require("../internals/has-own-property"),uid=require("../internals/uid"),NATIVE_SYMBOL=require("../internals/symbol-constructor-detection"),require=require("../internals/use-symbol-as-uid"),Symbol=global.Symbol,WellKnownSymbolsStore=shared("wks"),createWellKnownSymbol=require?Symbol.for||Symbol:Symbol&&Symbol.withoutSetter||uid;module.exports=function(name){return hasOwn(WellKnownSymbolsStore,name)||(WellKnownSymbolsStore[name]=NATIVE_SYMBOL&&hasOwn(Symbol,name)?Symbol[name]:createWellKnownSymbol("Symbol."+name)),WellKnownSymbolsStore[name]}},{"../internals/global":216,"../internals/has-own-property":217,"../internals/shared":307,"../internals/symbol-constructor-detection":320,"../internals/uid":345,"../internals/use-symbol-as-uid":347}],354:[function(require,module,exports){module.exports="\t\n\v\f\r                　\u2028\u2029\ufeff"},{}],355:[function(require,module,exports){"use strict";var getBuiltIn=require("../internals/get-built-in"),hasOwn=require("../internals/has-own-property"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),isPrototypeOf=require("../internals/object-is-prototype-of"),setPrototypeOf=require("../internals/object-set-prototype-of"),copyConstructorProperties=require("../internals/copy-constructor-properties"),proxyAccessor=require("../internals/proxy-accessor"),inheritIfRequired=require("../internals/inherit-if-required"),normalizeStringArgument=require("../internals/normalize-string-argument"),installErrorCause=require("../internals/install-error-cause"),installErrorStack=require("../internals/error-stack-install"),DESCRIPTORS=require("../internals/descriptors"),IS_PURE=require("../internals/is-pure");module.exports=function(FULL_NAME,wrapper,FORCED,IS_AGGREGATE_ERROR){var OPTIONS_POSITION=IS_AGGREGATE_ERROR?2:1,FULL_NAME=FULL_NAME.split("."),ERROR_NAME=FULL_NAME[FULL_NAME.length-1],OriginalError=getBuiltIn.apply(null,FULL_NAME);if(OriginalError){var OriginalErrorPrototype=OriginalError.prototype;if(!IS_PURE&&hasOwn(OriginalErrorPrototype,"cause")&&delete OriginalErrorPrototype.cause,!FORCED)return OriginalError;var FULL_NAME=getBuiltIn("Error"),WrappedError=wrapper(function(a,b){b=normalizeStringArgument(IS_AGGREGATE_ERROR?b:a,void 0),a=IS_AGGREGATE_ERROR?new OriginalError(a):new OriginalError;return void 0!==b&&createNonEnumerableProperty(a,"message",b),installErrorStack(a,WrappedError,a.stack,2),this&&isPrototypeOf(OriginalErrorPrototype,this)&&inheritIfRequired(a,this,WrappedError),OPTIONS_POSITION<arguments.length&&installErrorCause(a,arguments[OPTIONS_POSITION]),a});if(WrappedError.prototype=OriginalErrorPrototype,"Error"!==ERROR_NAME?setPrototypeOf?setPrototypeOf(WrappedError,FULL_NAME):copyConstructorProperties(WrappedError,FULL_NAME,{name:!0}):DESCRIPTORS&&"stackTraceLimit"in OriginalError&&(proxyAccessor(WrappedError,OriginalError,"stackTraceLimit"),proxyAccessor(WrappedError,OriginalError,"prepareStackTrace")),copyConstructorProperties(WrappedError,OriginalError),!IS_PURE)try{OriginalErrorPrototype.name!==ERROR_NAME&&createNonEnumerableProperty(OriginalErrorPrototype,"name",ERROR_NAME),OriginalErrorPrototype.constructor=WrappedError}catch(error){}return WrappedError}}},{"../internals/copy-constructor-properties":156,"../internals/create-non-enumerable-property":161,"../internals/descriptors":171,"../internals/error-stack-install":193,"../internals/get-built-in":210,"../internals/has-own-property":217,"../internals/inherit-if-required":224,"../internals/install-error-cause":226,"../internals/is-pure":239,"../internals/normalize-string-argument":259,"../internals/object-is-prototype-of":274,"../internals/object-set-prototype-of":279,"../internals/proxy-accessor":290}],356:[function(require,module,exports){var $=require("../internals/export"),getBuiltIn=require("../internals/get-built-in"),apply=require("../internals/function-apply"),fails=require("../internals/fails"),require=require("../internals/wrap-error-constructor-with-cause"),$AggregateError=getBuiltIn("AggregateError"),getBuiltIn=!fails(function(){return 1!==$AggregateError([1]).errors[0]})&&fails(function(){return 7!==$AggregateError([1],"AggregateError",{cause:7}).cause});$({global:!0,constructor:!0,arity:2,forced:getBuiltIn},{AggregateError:require("AggregateError",function(init){return function(errors,message){return apply(init,this,arguments)}},getBuiltIn,!0)})},{"../internals/export":196,"../internals/fails":197,"../internals/function-apply":201,"../internals/get-built-in":210,"../internals/wrap-error-constructor-with-cause":355}],357:[function(require,module,exports){"use strict";function $AggregateError(errors,message){var that,isInstance=isPrototypeOf(AggregateErrorPrototype,this);return setPrototypeOf?that=setPrototypeOf($Error(),isInstance?getPrototypeOf(this):AggregateErrorPrototype):(that=isInstance?this:create(AggregateErrorPrototype),createNonEnumerableProperty(that,TO_STRING_TAG,"Error")),void 0!==message&&createNonEnumerableProperty(that,"message",normalizeStringArgument(message)),installErrorStack(that,$AggregateError,that.stack,1),2<arguments.length&&installErrorCause(that,arguments[2]),iterate(errors,push,{that:isInstance=[]}),createNonEnumerableProperty(that,"errors",isInstance),that}var $=require("../internals/export"),isPrototypeOf=require("../internals/object-is-prototype-of"),getPrototypeOf=require("../internals/object-get-prototype-of"),setPrototypeOf=require("../internals/object-set-prototype-of"),copyConstructorProperties=require("../internals/copy-constructor-properties"),create=require("../internals/object-create"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),createPropertyDescriptor=require("../internals/create-property-descriptor"),installErrorCause=require("../internals/install-error-cause"),installErrorStack=require("../internals/error-stack-install"),iterate=require("../internals/iterate"),normalizeStringArgument=require("../internals/normalize-string-argument"),TO_STRING_TAG=require("../internals/well-known-symbol")("toStringTag"),$Error=Error,push=[].push,AggregateErrorPrototype=(setPrototypeOf?setPrototypeOf($AggregateError,$Error):copyConstructorProperties($AggregateError,$Error,{name:!0}),$AggregateError.prototype=create($Error.prototype,{constructor:createPropertyDescriptor(1,$AggregateError),message:createPropertyDescriptor(1,""),name:createPropertyDescriptor(1,"AggregateError")}));$({global:!0,constructor:!0,arity:2},{AggregateError:$AggregateError})},{"../internals/copy-constructor-properties":156,"../internals/create-non-enumerable-property":161,"../internals/create-property-descriptor":162,"../internals/error-stack-install":193,"../internals/export":196,"../internals/install-error-cause":226,"../internals/iterate":242,"../internals/normalize-string-argument":259,"../internals/object-create":265,"../internals/object-get-prototype-of":272,"../internals/object-is-prototype-of":274,"../internals/object-set-prototype-of":279,"../internals/well-known-symbol":353}],358:[function(require,module,exports){require("../modules/es.aggregate-error.constructor")},{"../modules/es.aggregate-error.constructor":357}],359:[function(require,module,exports){"use strict";var $=require("../internals/export"),global=require("../internals/global"),arrayBufferModule=require("../internals/array-buffer"),require=require("../internals/set-species"),arrayBufferModule=arrayBufferModule.ArrayBuffer;$({global:!0,constructor:!0,forced:global.ArrayBuffer!==arrayBufferModule},{ArrayBuffer:arrayBufferModule}),require("ArrayBuffer")},{"../internals/array-buffer":127,"../internals/export":196,"../internals/global":216,"../internals/set-species":303}],360:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/array-buffer-view-core");$({target:"ArrayBuffer",stat:!0,forced:!require.NATIVE_ARRAY_BUFFER_VIEWS},{isView:require.isView})},{"../internals/array-buffer-view-core":126,"../internals/export":196}],361:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this-clause"),fails=require("../internals/fails"),ArrayBufferModule=require("../internals/array-buffer"),anObject=require("../internals/an-object"),toAbsoluteIndex=require("../internals/to-absolute-index"),toLength=require("../internals/to-length"),speciesConstructor=require("../internals/species-constructor"),ArrayBuffer=ArrayBufferModule.ArrayBuffer,DataView=ArrayBufferModule.DataView,require=DataView.prototype,nativeArrayBufferSlice=uncurryThis(ArrayBuffer.prototype.slice),getUint8=uncurryThis(require.getUint8),setUint8=uncurryThis(require.setUint8);$({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:fails(function(){return!new ArrayBuffer(2).slice(1,void 0).byteLength})},{slice:function(start,end){if(nativeArrayBufferSlice&&void 0===end)return nativeArrayBufferSlice(anObject(this),start);for(var length=anObject(this).byteLength,first=toAbsoluteIndex(start,length),fin=toAbsoluteIndex(void 0===end?length:end,length),start=new(speciesConstructor(this,ArrayBuffer))(toLength(fin-first)),viewSource=new DataView(this),viewTarget=new DataView(start),index=0;first<fin;)setUint8(viewTarget,index++,getUint8(viewSource,first++));return start}})},{"../internals/an-object":123,"../internals/array-buffer":127,"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this-clause":208,"../internals/species-constructor":308,"../internals/to-absolute-index":325,"../internals/to-length":330}],362:[function(require,module,exports){"use strict";var $=require("../internals/export"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),require=require("../internals/add-to-unscopables");$({target:"Array",proto:!0},{at:function(index){var O=toObject(this),len=lengthOfArrayLike(O),index=toIntegerOrInfinity(index),index=0<=index?index:len+index;return index<0||len<=index?void 0:O[index]}}),require("at")},{"../internals/add-to-unscopables":120,"../internals/export":196,"../internals/length-of-array-like":248,"../internals/to-integer-or-infinity":329,"../internals/to-object":331}],363:[function(require,module,exports){"use strict";var $=require("../internals/export"),fails=require("../internals/fails"),isArray=require("../internals/is-array"),isObject=require("../internals/is-object"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),doesNotExceedSafeInteger=require("../internals/does-not-exceed-safe-integer"),createProperty=require("../internals/create-property"),arraySpeciesCreate=require("../internals/array-species-create"),arrayMethodHasSpeciesSupport=require("../internals/array-method-has-species-support"),wellKnownSymbol=require("../internals/well-known-symbol"),require=require("../internals/engine-v8-version"),IS_CONCAT_SPREADABLE=wellKnownSymbol("isConcatSpreadable"),wellKnownSymbol=51<=require||!fails(function(){var array=[];return array[IS_CONCAT_SPREADABLE]=!1,array.concat()[0]!==array});$({target:"Array",proto:!0,arity:1,forced:!wellKnownSymbol||!arrayMethodHasSpeciesSupport("concat")},{concat:function(arg){for(var k,len,E,O=toObject(this),A=arraySpeciesCreate(O,0),n=0,i=-1,length=arguments.length;i<length;i++)if(function(O){var spreadable;return!!isObject(O)&&(void 0!==(spreadable=O[IS_CONCAT_SPREADABLE])?!!spreadable:isArray(O))}(E=-1===i?O:arguments[i]))for(len=lengthOfArrayLike(E),doesNotExceedSafeInteger(n+len),k=0;k<len;k++,n++)k in E&&createProperty(A,n,E[k]);else doesNotExceedSafeInteger(n+1),createProperty(A,n++,E);return A.length=n,A}})},{"../internals/array-method-has-species-support":137,"../internals/array-species-create":145,"../internals/create-property":163,"../internals/does-not-exceed-safe-integer":174,"../internals/engine-v8-version":188,"../internals/export":196,"../internals/fails":197,"../internals/is-array":230,"../internals/is-object":238,"../internals/length-of-array-like":248,"../internals/to-object":331,"../internals/well-known-symbol":353}],364:[function(require,module,exports){var $=require("../internals/export"),copyWithin=require("../internals/array-copy-within"),require=require("../internals/add-to-unscopables");$({target:"Array",proto:!0},{copyWithin:copyWithin}),require("copyWithin")},{"../internals/add-to-unscopables":120,"../internals/array-copy-within":128,"../internals/export":196}],365:[function(require,module,exports){"use strict";var $=require("../internals/export"),$every=require("../internals/array-iteration").every;$({target:"Array",proto:!0,forced:!require("../internals/array-method-is-strict")("every")},{every:function(callbackfn){return $every(this,callbackfn,1<arguments.length?arguments[1]:void 0)}})},{"../internals/array-iteration":135,"../internals/array-method-is-strict":138,"../internals/export":196}],366:[function(require,module,exports){var $=require("../internals/export"),fill=require("../internals/array-fill"),require=require("../internals/add-to-unscopables");$({target:"Array",proto:!0},{fill:fill}),require("fill")},{"../internals/add-to-unscopables":120,"../internals/array-fill":129,"../internals/export":196}],367:[function(require,module,exports){"use strict";var $=require("../internals/export"),$filter=require("../internals/array-iteration").filter;$({target:"Array",proto:!0,forced:!require("../internals/array-method-has-species-support")("filter")},{filter:function(callbackfn){return $filter(this,callbackfn,1<arguments.length?arguments[1]:void 0)}})},{"../internals/array-iteration":135,"../internals/array-method-has-species-support":137,"../internals/export":196}],368:[function(require,module,exports){"use strict";var $=require("../internals/export"),$findIndex=require("../internals/array-iteration").findIndex,require=require("../internals/add-to-unscopables"),SKIPS_HOLES=!0;"findIndex"in[]&&Array(1).findIndex(function(){SKIPS_HOLES=!1}),$({target:"Array",proto:!0,forced:SKIPS_HOLES},{findIndex:function(callbackfn){return $findIndex(this,callbackfn,1<arguments.length?arguments[1]:void 0)}}),require("findIndex")},{"../internals/add-to-unscopables":120,"../internals/array-iteration":135,"../internals/export":196}],369:[function(require,module,exports){"use strict";var $=require("../internals/export"),$findLastIndex=require("../internals/array-iteration-from-last").findLastIndex,require=require("../internals/add-to-unscopables");$({target:"Array",proto:!0},{findLastIndex:function(callbackfn){return $findLastIndex(this,callbackfn,1<arguments.length?arguments[1]:void 0)}}),require("findLastIndex")},{"../internals/add-to-unscopables":120,"../internals/array-iteration-from-last":134,"../internals/export":196}],370:[function(require,module,exports){"use strict";var $=require("../internals/export"),$findLast=require("../internals/array-iteration-from-last").findLast,require=require("../internals/add-to-unscopables");$({target:"Array",proto:!0},{findLast:function(callbackfn){return $findLast(this,callbackfn,1<arguments.length?arguments[1]:void 0)}}),require("findLast")},{"../internals/add-to-unscopables":120,"../internals/array-iteration-from-last":134,"../internals/export":196}],371:[function(require,module,exports){"use strict";var $=require("../internals/export"),$find=require("../internals/array-iteration").find,require=require("../internals/add-to-unscopables"),SKIPS_HOLES=!0;"find"in[]&&Array(1).find(function(){SKIPS_HOLES=!1}),$({target:"Array",proto:!0,forced:SKIPS_HOLES},{find:function(callbackfn){return $find(this,callbackfn,1<arguments.length?arguments[1]:void 0)}}),require("find")},{"../internals/add-to-unscopables":120,"../internals/array-iteration":135,"../internals/export":196}],372:[function(require,module,exports){"use strict";var $=require("../internals/export"),flattenIntoArray=require("../internals/flatten-into-array"),aCallable=require("../internals/a-callable"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),arraySpeciesCreate=require("../internals/array-species-create");$({target:"Array",proto:!0},{flatMap:function(callbackfn){var A,O=toObject(this),sourceLen=lengthOfArrayLike(O);return aCallable(callbackfn),(A=arraySpeciesCreate(O,0)).length=flattenIntoArray(A,O,O,sourceLen,0,1,callbackfn,1<arguments.length?arguments[1]:void 0),A}})},{"../internals/a-callable":117,"../internals/array-species-create":145,"../internals/export":196,"../internals/flatten-into-array":199,"../internals/length-of-array-like":248,"../internals/to-object":331}],373:[function(require,module,exports){"use strict";var $=require("../internals/export"),flattenIntoArray=require("../internals/flatten-into-array"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),arraySpeciesCreate=require("../internals/array-species-create");$({target:"Array",proto:!0},{flat:function(){var depthArg=arguments.length?arguments[0]:void 0,O=toObject(this),sourceLen=lengthOfArrayLike(O),A=arraySpeciesCreate(O,0);return A.length=flattenIntoArray(A,O,O,sourceLen,0,void 0===depthArg?1:toIntegerOrInfinity(depthArg)),A}})},{"../internals/array-species-create":145,"../internals/export":196,"../internals/flatten-into-array":199,"../internals/length-of-array-like":248,"../internals/to-integer-or-infinity":329,"../internals/to-object":331}],374:[function(require,module,exports){"use strict";var $=require("../internals/export"),require=require("../internals/array-for-each");$({target:"Array",proto:!0,forced:[].forEach!=require},{forEach:require})},{"../internals/array-for-each":130,"../internals/export":196}],375:[function(require,module,exports){var $=require("../internals/export"),from=require("../internals/array-from");$({target:"Array",stat:!0,forced:!require("../internals/check-correctness-of-iteration")(function(iterable){Array.from(iterable)})},{from:from})},{"../internals/array-from":132,"../internals/check-correctness-of-iteration":150,"../internals/export":196}],376:[function(require,module,exports){"use strict";var $=require("../internals/export"),$includes=require("../internals/array-includes").includes,fails=require("../internals/fails"),require=require("../internals/add-to-unscopables");$({target:"Array",proto:!0,forced:fails(function(){return!Array(1).includes()})},{includes:function(el){return $includes(this,el,1<arguments.length?arguments[1]:void 0)}}),require("includes")},{"../internals/add-to-unscopables":120,"../internals/array-includes":133,"../internals/export":196,"../internals/fails":197}],377:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this-clause"),$indexOf=require("../internals/array-includes").indexOf,require=require("../internals/array-method-is-strict"),nativeIndexOf=uncurryThis([].indexOf),NEGATIVE_ZERO=!!nativeIndexOf&&1/nativeIndexOf([1],1,-0)<0;$({target:"Array",proto:!0,forced:NEGATIVE_ZERO||!require("indexOf")},{indexOf:function(searchElement){var fromIndex=1<arguments.length?arguments[1]:void 0;return NEGATIVE_ZERO?nativeIndexOf(this,searchElement,fromIndex)||0:$indexOf(this,searchElement,fromIndex)}})},{"../internals/array-includes":133,"../internals/array-method-is-strict":138,"../internals/export":196,"../internals/function-uncurry-this-clause":208}],378:[function(require,module,exports){require("../internals/export")({target:"Array",stat:!0},{isArray:require("../internals/is-array")})},{"../internals/export":196,"../internals/is-array":230}],379:[function(require,module,exports){"use strict";var toIndexedObject=require("../internals/to-indexed-object"),addToUnscopables=require("../internals/add-to-unscopables"),Iterators=require("../internals/iterators"),InternalStateModule=require("../internals/internal-state"),defineProperty=require("../internals/object-define-property").f,defineIterator=require("../internals/iterator-define"),createIterResultObject=require("../internals/create-iter-result-object"),IS_PURE=require("../internals/is-pure"),require=require("../internals/descriptors"),setInternalState=InternalStateModule.set,getInternalState=InternalStateModule.getterFor("Array Iterator"),InternalStateModule=(module.exports=defineIterator(Array,"Array",function(iterated,kind){setInternalState(this,{type:"Array Iterator",target:toIndexedObject(iterated),index:0,kind:kind})},function(){var state=getInternalState(this),target=state.target,kind=state.kind,index=state.index++;return!target||index>=target.length?(state.target=void 0,createIterResultObject(void 0,!0)):createIterResultObject("keys"==kind?index:"values"==kind?target[index]:[index,target[index]],!1)},"values"),Iterators.Arguments=Iterators.Array);if(addToUnscopables("keys"),addToUnscopables("values"),addToUnscopables("entries"),!IS_PURE&&require&&"values"!==InternalStateModule.name)try{defineProperty(InternalStateModule,"name",{value:"values"})}catch(error){}},{"../internals/add-to-unscopables":120,"../internals/create-iter-result-object":160,"../internals/descriptors":171,"../internals/internal-state":228,"../internals/is-pure":239,"../internals/iterator-define":245,"../internals/iterators":247,"../internals/object-define-property":267,"../internals/to-indexed-object":328}],380:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),IndexedObject=require("../internals/indexed-object"),toIndexedObject=require("../internals/to-indexed-object"),require=require("../internals/array-method-is-strict"),nativeJoin=uncurryThis([].join);$({target:"Array",proto:!0,forced:IndexedObject!=Object||!require("join",",")},{join:function(separator){return nativeJoin(toIndexedObject(this),void 0===separator?",":separator)}})},{"../internals/array-method-is-strict":138,"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/indexed-object":223,"../internals/to-indexed-object":328}],381:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/array-last-index-of");$({target:"Array",proto:!0,forced:require!==[].lastIndexOf},{lastIndexOf:require})},{"../internals/array-last-index-of":136,"../internals/export":196}],382:[function(require,module,exports){"use strict";var $=require("../internals/export"),$map=require("../internals/array-iteration").map;$({target:"Array",proto:!0,forced:!require("../internals/array-method-has-species-support")("map")},{map:function(callbackfn){return $map(this,callbackfn,1<arguments.length?arguments[1]:void 0)}})},{"../internals/array-iteration":135,"../internals/array-method-has-species-support":137,"../internals/export":196}],383:[function(require,module,exports){"use strict";var $=require("../internals/export"),fails=require("../internals/fails"),isConstructor=require("../internals/is-constructor"),createProperty=require("../internals/create-property"),$Array=Array;$({target:"Array",stat:!0,forced:fails(function(){function F(){}return!($Array.of.call(F)instanceof F)})},{of:function(){for(var index=0,argumentsLength=arguments.length,result=new(isConstructor(this)?this:$Array)(argumentsLength);index<argumentsLength;)createProperty(result,index,arguments[index++]);return result.length=argumentsLength,result}})},{"../internals/create-property":163,"../internals/export":196,"../internals/fails":197,"../internals/is-constructor":233}],384:[function(require,module,exports){"use strict";var $=require("../internals/export"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),setArrayLength=require("../internals/array-set-length"),doesNotExceedSafeInteger=require("../internals/does-not-exceed-safe-integer");$({target:"Array",proto:!0,arity:1,forced:require("../internals/fails")(function(){return 4294967297!==[].push.call({length:4294967296},1)})||!function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(error){return error instanceof TypeError}}()},{push:function(item){var O=toObject(this),len=lengthOfArrayLike(O),argCount=arguments.length;doesNotExceedSafeInteger(len+argCount);for(var i=0;i<argCount;i++)O[len]=arguments[i],len++;return setArrayLength(O,len),len}})},{"../internals/array-set-length":140,"../internals/does-not-exceed-safe-integer":174,"../internals/export":196,"../internals/fails":197,"../internals/length-of-array-like":248,"../internals/to-object":331}],385:[function(require,module,exports){"use strict";var $=require("../internals/export"),$reduceRight=require("../internals/array-reduce").right,arrayMethodIsStrict=require("../internals/array-method-is-strict"),CHROME_VERSION=require("../internals/engine-v8-version");$({target:"Array",proto:!0,forced:!require("../internals/engine-is-node")&&79<CHROME_VERSION&&CHROME_VERSION<83||!arrayMethodIsStrict("reduceRight")},{reduceRight:function(callbackfn){return $reduceRight(this,callbackfn,arguments.length,1<arguments.length?arguments[1]:void 0)}})},{"../internals/array-method-is-strict":138,"../internals/array-reduce":139,"../internals/engine-is-node":185,"../internals/engine-v8-version":188,"../internals/export":196}],386:[function(require,module,exports){"use strict";var $=require("../internals/export"),$reduce=require("../internals/array-reduce").left,arrayMethodIsStrict=require("../internals/array-method-is-strict"),CHROME_VERSION=require("../internals/engine-v8-version");$({target:"Array",proto:!0,forced:!require("../internals/engine-is-node")&&79<CHROME_VERSION&&CHROME_VERSION<83||!arrayMethodIsStrict("reduce")},{reduce:function(callbackfn){var length=arguments.length;return $reduce(this,callbackfn,length,1<length?arguments[1]:void 0)}})},{"../internals/array-method-is-strict":138,"../internals/array-reduce":139,"../internals/engine-is-node":185,"../internals/engine-v8-version":188,"../internals/export":196}],387:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),isArray=require("../internals/is-array"),nativeReverse=uncurryThis([].reverse),require=[1,2];$({target:"Array",proto:!0,forced:String(require)===String(require.reverse())},{reverse:function(){return isArray(this)&&(this.length=this.length),nativeReverse(this)}})},{"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/is-array":230}],388:[function(require,module,exports){"use strict";var $=require("../internals/export"),isArray=require("../internals/is-array"),isConstructor=require("../internals/is-constructor"),isObject=require("../internals/is-object"),toAbsoluteIndex=require("../internals/to-absolute-index"),lengthOfArrayLike=require("../internals/length-of-array-like"),toIndexedObject=require("../internals/to-indexed-object"),createProperty=require("../internals/create-property"),wellKnownSymbol=require("../internals/well-known-symbol"),arrayMethodHasSpeciesSupport=require("../internals/array-method-has-species-support"),nativeSlice=require("../internals/array-slice"),require=arrayMethodHasSpeciesSupport("slice"),SPECIES=wellKnownSymbol("species"),$Array=Array,max=Math.max;$({target:"Array",proto:!0,forced:!require},{slice:function(start,end){var Constructor,result,n,O=toIndexedObject(this),length=lengthOfArrayLike(O),k=toAbsoluteIndex(start,length),fin=toAbsoluteIndex(void 0===end?length:end,length);if(isArray(O)&&(Constructor=O.constructor,(Constructor=isConstructor(Constructor)&&(Constructor===$Array||isArray(Constructor.prototype))||isObject(Constructor)&&null===(Constructor=Constructor[SPECIES])?void 0:Constructor)===$Array||void 0===Constructor))return nativeSlice(O,k,fin);for(result=new(void 0===Constructor?$Array:Constructor)(max(fin-k,0)),n=0;k<fin;k++,n++)k in O&&createProperty(result,n,O[k]);return result.length=n,result}})},{"../internals/array-method-has-species-support":137,"../internals/array-slice":142,"../internals/create-property":163,"../internals/export":196,"../internals/is-array":230,"../internals/is-constructor":233,"../internals/is-object":238,"../internals/length-of-array-like":248,"../internals/to-absolute-index":325,"../internals/to-indexed-object":328,"../internals/well-known-symbol":353}],389:[function(require,module,exports){"use strict";var $=require("../internals/export"),$some=require("../internals/array-iteration").some;$({target:"Array",proto:!0,forced:!require("../internals/array-method-is-strict")("some")},{some:function(callbackfn){return $some(this,callbackfn,1<arguments.length?arguments[1]:void 0)}})},{"../internals/array-iteration":135,"../internals/array-method-is-strict":138,"../internals/export":196}],390:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),aCallable=require("../internals/a-callable"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),deletePropertyOrThrow=require("../internals/delete-property-or-throw"),toString=require("../internals/to-string"),fails=require("../internals/fails"),internalSort=require("../internals/array-sort"),arrayMethodIsStrict=require("../internals/array-method-is-strict"),FF=require("../internals/engine-ff-version"),IE_OR_EDGE=require("../internals/engine-is-ie-or-edge"),V8=require("../internals/engine-v8-version"),WEBKIT=require("../internals/engine-webkit-version"),test=[],nativeSort=uncurryThis(test.sort),push=uncurryThis(test.push),require=fails(function(){test.sort(void 0)}),uncurryThis=fails(function(){test.sort(null)}),arrayMethodIsStrict=arrayMethodIsStrict("sort"),STABLE_SORT=!fails(function(){if(V8)return V8<70;if(!(FF&&3<FF)){if(IE_OR_EDGE)return!0;if(WEBKIT)return WEBKIT<603;for(var chr,value,index,result="",code=65;code<76;code++){switch(chr=String.fromCharCode(code),code){case 66:case 69:case 70:case 72:value=3;break;case 68:case 71:value=4;break;default:value=2}for(index=0;index<47;index++)test.push({k:chr+index,v:value})}for(test.sort(function(a,b){return b.v-a.v}),index=0;index<test.length;index++)chr=test[index].k.charAt(0),result.charAt(result.length-1)!==chr&&(result+=chr);return"DGBEFHACIJK"!==result}});$({target:"Array",proto:!0,forced:require||!uncurryThis||!arrayMethodIsStrict||!STABLE_SORT},{sort:function(comparefn){void 0!==comparefn&&aCallable(comparefn);var array=toObject(this);if(STABLE_SORT)return void 0===comparefn?nativeSort(array):nativeSort(array,comparefn);for(var itemsLength,items=[],arrayLength=lengthOfArrayLike(array),index=0;index<arrayLength;index++)index in array&&push(items,array[index]);for(internalSort(items,function(comparefn){return function(x,y){return void 0===y?-1:void 0===x?1:void 0!==comparefn?+comparefn(x,y)||0:toString(x)>toString(y)?1:-1}}(comparefn)),itemsLength=lengthOfArrayLike(items),index=0;index<itemsLength;)array[index]=items[index++];for(;index<arrayLength;)deletePropertyOrThrow(array,index++);return array}})},{"../internals/a-callable":117,"../internals/array-method-is-strict":138,"../internals/array-sort":143,"../internals/delete-property-or-throw":170,"../internals/engine-ff-version":178,"../internals/engine-is-ie-or-edge":182,"../internals/engine-v8-version":188,"../internals/engine-webkit-version":189,"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/length-of-array-like":248,"../internals/to-object":331,"../internals/to-string":337}],391:[function(require,module,exports){require("../internals/set-species")("Array")},{"../internals/set-species":303}],392:[function(require,module,exports){"use strict";var $=require("../internals/export"),toObject=require("../internals/to-object"),toAbsoluteIndex=require("../internals/to-absolute-index"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),lengthOfArrayLike=require("../internals/length-of-array-like"),setArrayLength=require("../internals/array-set-length"),doesNotExceedSafeInteger=require("../internals/does-not-exceed-safe-integer"),arraySpeciesCreate=require("../internals/array-species-create"),createProperty=require("../internals/create-property"),deletePropertyOrThrow=require("../internals/delete-property-or-throw"),require=require("../internals/array-method-has-species-support")("splice"),max=Math.max,min=Math.min;$({target:"Array",proto:!0,forced:!require},{splice:function(start,deleteCount){var insertCount,actualDeleteCount,A,k,from,to,O=toObject(this),len=lengthOfArrayLike(O),actualStart=toAbsoluteIndex(start,len),start=arguments.length;for(0===start?insertCount=actualDeleteCount=0:actualDeleteCount=1===start?(insertCount=0,len-actualStart):(insertCount=start-2,min(max(toIntegerOrInfinity(deleteCount),0),len-actualStart)),doesNotExceedSafeInteger(len+insertCount-actualDeleteCount),A=arraySpeciesCreate(O,actualDeleteCount),k=0;k<actualDeleteCount;k++)(from=actualStart+k)in O&&createProperty(A,k,O[from]);if(insertCount<(A.length=actualDeleteCount)){for(k=actualStart;k<len-actualDeleteCount;k++)to=k+insertCount,(from=k+actualDeleteCount)in O?O[to]=O[from]:deletePropertyOrThrow(O,to);for(k=len;len-actualDeleteCount+insertCount<k;k--)deletePropertyOrThrow(O,k-1)}else if(actualDeleteCount<insertCount)for(k=len-actualDeleteCount;actualStart<k;k--)to=k+insertCount-1,(from=k+actualDeleteCount-1)in O?O[to]=O[from]:deletePropertyOrThrow(O,to);for(k=0;k<insertCount;k++)O[k+actualStart]=arguments[k+2];return setArrayLength(O,len-actualDeleteCount+insertCount),A}})},{"../internals/array-method-has-species-support":137,"../internals/array-set-length":140,"../internals/array-species-create":145,"../internals/create-property":163,"../internals/delete-property-or-throw":170,"../internals/does-not-exceed-safe-integer":174,"../internals/export":196,"../internals/length-of-array-like":248,"../internals/to-absolute-index":325,"../internals/to-integer-or-infinity":329,"../internals/to-object":331}],393:[function(require,module,exports){"use strict";var $=require("../internals/export"),arrayToReversed=require("../internals/array-to-reversed"),toIndexedObject=require("../internals/to-indexed-object"),require=require("../internals/add-to-unscopables"),$Array=Array;$({target:"Array",proto:!0},{toReversed:function(){return arrayToReversed(toIndexedObject(this),$Array)}}),require("toReversed")},{"../internals/add-to-unscopables":120,"../internals/array-to-reversed":146,"../internals/export":196,"../internals/to-indexed-object":328}],394:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),aCallable=require("../internals/a-callable"),toIndexedObject=require("../internals/to-indexed-object"),arrayFromConstructorAndList=require("../internals/array-from-constructor-and-list"),getVirtual=require("../internals/entry-virtual"),require=require("../internals/add-to-unscopables"),$Array=Array,sort=uncurryThis(getVirtual("Array").sort);$({target:"Array",proto:!0},{toSorted:function(compareFn){void 0!==compareFn&&aCallable(compareFn);var O=toIndexedObject(this),O=arrayFromConstructorAndList($Array,O);return sort(O,compareFn)}}),require("toSorted")},{"../internals/a-callable":117,"../internals/add-to-unscopables":120,"../internals/array-from-constructor-and-list":131,"../internals/entry-virtual":190,"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/to-indexed-object":328}],395:[function(require,module,exports){"use strict";var $=require("../internals/export"),addToUnscopables=require("../internals/add-to-unscopables"),doesNotExceedSafeInteger=require("../internals/does-not-exceed-safe-integer"),lengthOfArrayLike=require("../internals/length-of-array-like"),toAbsoluteIndex=require("../internals/to-absolute-index"),toIndexedObject=require("../internals/to-indexed-object"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),$Array=Array,max=Math.max,min=Math.min;$({target:"Array",proto:!0},{toSpliced:function(start,deleteCount){var insertCount,actualDeleteCount,newLen,A,O=toIndexedObject(this),len=lengthOfArrayLike(O),actualStart=toAbsoluteIndex(start,len),start=arguments.length,k=0;for(0===start?insertCount=actualDeleteCount=0:actualDeleteCount=1===start?(insertCount=0,len-actualStart):(insertCount=start-2,min(max(toIntegerOrInfinity(deleteCount),0),len-actualStart)),newLen=doesNotExceedSafeInteger(len+insertCount-actualDeleteCount),A=$Array(newLen);k<actualStart;k++)A[k]=O[k];for(;k<actualStart+insertCount;k++)A[k]=arguments[k-actualStart+2];for(;k<newLen;k++)A[k]=O[k+actualDeleteCount-insertCount];return A}}),addToUnscopables("toSpliced")},{"../internals/add-to-unscopables":120,"../internals/does-not-exceed-safe-integer":174,"../internals/export":196,"../internals/length-of-array-like":248,"../internals/to-absolute-index":325,"../internals/to-indexed-object":328,"../internals/to-integer-or-infinity":329}],396:[function(require,module,exports){require("../internals/add-to-unscopables")("flatMap")},{"../internals/add-to-unscopables":120}],397:[function(require,module,exports){require("../internals/add-to-unscopables")("flat")},{"../internals/add-to-unscopables":120}],398:[function(require,module,exports){"use strict";var $=require("../internals/export"),toObject=require("../internals/to-object"),lengthOfArrayLike=require("../internals/length-of-array-like"),setArrayLength=require("../internals/array-set-length"),deletePropertyOrThrow=require("../internals/delete-property-or-throw"),doesNotExceedSafeInteger=require("../internals/does-not-exceed-safe-integer");$({target:"Array",proto:!0,arity:1,forced:1!==[].unshift(0)||!function(){try{Object.defineProperty([],"length",{writable:!1}).unshift()}catch(error){return error instanceof TypeError}}()},{unshift:function(item){var O=toObject(this),len=lengthOfArrayLike(O),argCount=arguments.length;if(argCount){doesNotExceedSafeInteger(len+argCount);for(var k=len;k--;){var to=k+argCount;k in O?O[to]=O[k]:deletePropertyOrThrow(O,to)}for(var j=0;j<argCount;j++)O[j]=arguments[j]}return setArrayLength(O,len+argCount)}})},{"../internals/array-set-length":140,"../internals/delete-property-or-throw":170,"../internals/does-not-exceed-safe-integer":174,"../internals/export":196,"../internals/length-of-array-like":248,"../internals/to-object":331}],399:[function(require,module,exports){"use strict";var $=require("../internals/export"),arrayWith=require("../internals/array-with"),toIndexedObject=require("../internals/to-indexed-object"),$Array=Array;$({target:"Array",proto:!0},{with:function(index,value){return arrayWith(toIndexedObject(this),$Array,index,value)}})},{"../internals/array-with":147,"../internals/export":196,"../internals/to-indexed-object":328}],400:[function(require,module,exports){var $=require("../internals/export"),ArrayBufferModule=require("../internals/array-buffer");$({global:!0,constructor:!0,forced:!require("../internals/array-buffer-basic-detection")},{DataView:ArrayBufferModule.DataView})},{"../internals/array-buffer":127,"../internals/array-buffer-basic-detection":124,"../internals/export":196}],401:[function(require,module,exports){require("../modules/es.data-view.constructor")},{"../modules/es.data-view.constructor":400}],402:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),require=require("../internals/fails")(function(){return 120!==new Date(16e11).getYear()}),getFullYear=uncurryThis(Date.prototype.getFullYear);$({target:"Date",proto:!0,forced:require},{getYear:function(){return getFullYear(this)-1900}})},{"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209}],403:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/function-uncurry-this"),$Date=Date,thisTimeValue=require($Date.prototype.getTime);$({target:"Date",stat:!0},{now:function(){return thisTimeValue(new $Date)}})},{"../internals/export":196,"../internals/function-uncurry-this":209}],404:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),require=Date.prototype,thisTimeValue=uncurryThis(require.getTime),setFullYear=uncurryThis(require.setFullYear);$({target:"Date",proto:!0},{setYear:function(year){thisTimeValue(this);year=toIntegerOrInfinity(year);return setFullYear(this,0<=year&&year<=99?year+1900:year)}})},{"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/to-integer-or-infinity":329}],405:[function(require,module,exports){require("../internals/export")({target:"Date",proto:!0},{toGMTString:Date.prototype.toUTCString})},{"../internals/export":196}],406:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/date-to-iso-string");$({target:"Date",proto:!0,forced:Date.prototype.toISOString!==require},{toISOString:require})},{"../internals/date-to-iso-string":164,"../internals/export":196}],407:[function(require,module,exports){"use strict";var $=require("../internals/export"),fails=require("../internals/fails"),toObject=require("../internals/to-object"),toPrimitive=require("../internals/to-primitive");$({target:"Date",proto:!0,arity:1,forced:fails(function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function(){return 1}})})},{toJSON:function(key){var O=toObject(this),pv=toPrimitive(O,"number");return"number"!=typeof pv||isFinite(pv)?O.toISOString():null}})},{"../internals/export":196,"../internals/fails":197,"../internals/to-object":331,"../internals/to-primitive":334}],408:[function(require,module,exports){var hasOwn=require("../internals/has-own-property"),defineBuiltIn=require("../internals/define-built-in"),dateToPrimitive=require("../internals/date-to-primitive"),require=require("../internals/well-known-symbol")("toPrimitive"),DatePrototype=Date.prototype;hasOwn(DatePrototype,require)||defineBuiltIn(DatePrototype,require,dateToPrimitive)},{"../internals/date-to-primitive":165,"../internals/define-built-in":167,"../internals/has-own-property":217,"../internals/well-known-symbol":353}],409:[function(require,module,exports){var uncurryThis=require("../internals/function-uncurry-this"),require=require("../internals/define-built-in"),DatePrototype=Date.prototype,nativeDateToString=uncurryThis(DatePrototype.toString),thisTimeValue=uncurryThis(DatePrototype.getTime);"Invalid Date"!=String(new Date(NaN))&&require(DatePrototype,"toString",function(){var value=thisTimeValue(this);return value==value?nativeDateToString(this):"Invalid Date"})},{"../internals/define-built-in":167,"../internals/function-uncurry-this":209}],410:[function(require,module,exports){function exportGlobalErrorCauseWrapper(ERROR_NAME,wrapper){var O={};O[ERROR_NAME]=wrapErrorConstructorWithCause(ERROR_NAME,wrapper,FORCED),$({global:!0,constructor:!0,arity:1,forced:FORCED},O)}function exportWebAssemblyErrorCauseWrapper(ERROR_NAME,wrapper){var O;WebAssembly&&WebAssembly[ERROR_NAME]&&((O={})[ERROR_NAME]=wrapErrorConstructorWithCause("WebAssembly."+ERROR_NAME,wrapper,FORCED),$({target:"WebAssembly",stat:!0,constructor:!0,arity:1,forced:FORCED},O))}var $=require("../internals/export"),global=require("../internals/global"),apply=require("../internals/function-apply"),wrapErrorConstructorWithCause=require("../internals/wrap-error-constructor-with-cause"),WebAssembly=global.WebAssembly,FORCED=7!==Error("e",{cause:7}).cause;exportGlobalErrorCauseWrapper("Error",function(init){return function(message){return apply(init,this,arguments)}}),exportGlobalErrorCauseWrapper("EvalError",function(init){return function(message){return apply(init,this,arguments)}}),exportGlobalErrorCauseWrapper("RangeError",function(init){return function(message){return apply(init,this,arguments)}}),exportGlobalErrorCauseWrapper("ReferenceError",function(init){return function(message){return apply(init,this,arguments)}}),exportGlobalErrorCauseWrapper("SyntaxError",function(init){return function(message){return apply(init,this,arguments)}}),exportGlobalErrorCauseWrapper("TypeError",function(init){return function(message){return apply(init,this,arguments)}}),exportGlobalErrorCauseWrapper("URIError",function(init){return function(message){return apply(init,this,arguments)}}),exportWebAssemblyErrorCauseWrapper("CompileError",function(init){return function(message){return apply(init,this,arguments)}}),exportWebAssemblyErrorCauseWrapper("LinkError",function(init){return function(message){return apply(init,this,arguments)}}),exportWebAssemblyErrorCauseWrapper("RuntimeError",function(init){return function(message){return apply(init,this,arguments)}})},{"../internals/export":196,"../internals/function-apply":201,"../internals/global":216,"../internals/wrap-error-constructor-with-cause":355}],411:[function(require,module,exports){var defineBuiltIn=require("../internals/define-built-in"),require=require("../internals/error-to-string"),ErrorPrototype=Error.prototype;ErrorPrototype.toString!==require&&defineBuiltIn(ErrorPrototype,"toString",require)},{"../internals/define-built-in":167,"../internals/error-to-string":195}],412:[function(require,module,exports){"use strict";function hex(code,length){for(var result=numberToString(code,16);result.length<length;)result="0"+result;return result}var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),toString=require("../internals/to-string"),charAt=uncurryThis("".charAt),charCodeAt=uncurryThis("".charCodeAt),exec=uncurryThis(/./.exec),numberToString=uncurryThis(1..toString),toUpperCase=uncurryThis("".toUpperCase),raw=/[\w*+\-./@]/;$({global:!0},{escape:function(string){for(var chr,str=toString(string),result="",length=str.length,index=0;index<length;)chr=charAt(str,index++),exec(raw,chr)?result+=chr:result+=(chr=charCodeAt(chr,0))<256?"%"+hex(chr,2):"%u"+toUpperCase(hex(chr,4));return result}})},{"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/to-string":337}],413:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/function-bind");$({target:"Function",proto:!0,forced:Function.bind!==require},{bind:require})},{"../internals/export":196,"../internals/function-bind":204}],414:[function(require,module,exports){"use strict";var isCallable=require("../internals/is-callable"),isObject=require("../internals/is-object"),definePropertyModule=require("../internals/object-define-property"),getPrototypeOf=require("../internals/object-get-prototype-of"),wellKnownSymbol=require("../internals/well-known-symbol"),require=require("../internals/make-built-in"),wellKnownSymbol=wellKnownSymbol("hasInstance"),FunctionPrototype=Function.prototype;wellKnownSymbol in FunctionPrototype||definePropertyModule.f(FunctionPrototype,wellKnownSymbol,{value:require(function(O){if(isCallable(this)&&isObject(O)){var P=this.prototype;if(!isObject(P))return O instanceof this;for(;O=getPrototypeOf(O);)if(P===O)return!0}return!1},wellKnownSymbol)})},{"../internals/is-callable":232,"../internals/is-object":238,"../internals/make-built-in":249,"../internals/object-define-property":267,"../internals/object-get-prototype-of":272,"../internals/well-known-symbol":353}],415:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),FUNCTION_NAME_EXISTS=require("../internals/function-name").EXISTS,uncurryThis=require("../internals/function-uncurry-this"),require=require("../internals/define-built-in-accessor"),FunctionPrototype=Function.prototype,functionToString=uncurryThis(FunctionPrototype.toString),nameRE=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,regExpExec=uncurryThis(nameRE.exec);DESCRIPTORS&&!FUNCTION_NAME_EXISTS&&require(FunctionPrototype,"name",{configurable:!0,get:function(){try{return regExpExec(nameRE,functionToString(this))[1]}catch(error){return""}}})},{"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/function-name":206,"../internals/function-uncurry-this":209}],416:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/global");$({global:!0,forced:require.globalThis!==require},{globalThis:require})},{"../internals/export":196,"../internals/global":216}],417:[function(require,module,exports){function stringifyWithSymbolsFix(it,replacer){var args=arraySlice(arguments),$replacer=getReplacerFunction(replacer);if(isCallable($replacer)||void 0!==it&&!isSymbol(it))return args[1]=function(key,value){if(isCallable($replacer)&&(value=call($replacer,this,$String(key),value)),!isSymbol(value))return value},apply($stringify,null,args)}function fixIllFormed(match,offset,string){var prev=charAt(string,offset-1),string=charAt(string,offset+1);return exec(low,match)&&!exec(hi,string)||exec(hi,match)&&!exec(low,prev)?"\\u"+numberToString(charCodeAt(match,0),16):match}var $=require("../internals/export"),getBuiltIn=require("../internals/get-built-in"),apply=require("../internals/function-apply"),call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this"),fails=require("../internals/fails"),isCallable=require("../internals/is-callable"),isSymbol=require("../internals/is-symbol"),arraySlice=require("../internals/array-slice"),getReplacerFunction=require("../internals/get-json-replacer-function"),require=require("../internals/symbol-constructor-detection"),$String=String,$stringify=getBuiltIn("JSON","stringify"),exec=uncurryThis(/./.exec),charAt=uncurryThis("".charAt),charCodeAt=uncurryThis("".charCodeAt),replace=uncurryThis("".replace),numberToString=uncurryThis(1..toString),tester=/[\uD800-\uDFFF]/g,low=/^[\uD800-\uDBFF]$/,hi=/^[\uDC00-\uDFFF]$/,WRONG_SYMBOLS_CONVERSION=!require||fails(function(){var symbol=getBuiltIn("Symbol")();return"[null]"!=$stringify([symbol])||"{}"!=$stringify({a:symbol})||"{}"!=$stringify(Object(symbol))}),ILL_FORMED_UNICODE=fails(function(){return'"\\udf06\\ud834"'!==$stringify("\udf06\ud834")||'"\\udead"'!==$stringify("\udead")});$stringify&&$({target:"JSON",stat:!0,arity:3,forced:WRONG_SYMBOLS_CONVERSION||ILL_FORMED_UNICODE},{stringify:function(it,replacer,space){var args=arraySlice(arguments),args=apply(WRONG_SYMBOLS_CONVERSION?stringifyWithSymbolsFix:$stringify,null,args);return ILL_FORMED_UNICODE&&"string"==typeof args?replace(args,tester,fixIllFormed):args}})},{"../internals/array-slice":142,"../internals/export":196,"../internals/fails":197,"../internals/function-apply":201,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/get-built-in":210,"../internals/get-json-replacer-function":213,"../internals/is-callable":232,"../internals/is-symbol":241,"../internals/symbol-constructor-detection":320}],418:[function(require,module,exports){var global=require("../internals/global");require("../internals/set-to-string-tag")(global.JSON,"JSON",!0)},{"../internals/global":216,"../internals/set-to-string-tag":304}],419:[function(require,module,exports){"use strict";require("../internals/collection")("Map",function(init){return function(){return init(this,arguments.length?arguments[0]:void 0)}},require("../internals/collection-strong"))},{"../internals/collection":155,"../internals/collection-strong":153}],420:[function(require,module,exports){require("../modules/es.map.constructor")},{"../modules/es.map.constructor":419}],421:[function(require,module,exports){var $=require("../internals/export"),log1p=require("../internals/math-log1p"),require=Math.acosh,log=Math.log,sqrt=Math.sqrt,LN2=Math.LN2;$({target:"Math",stat:!0,forced:!require||710!=Math.floor(require(Number.MAX_VALUE))||require(1/0)!=1/0},{acosh:function(x){x=+x;return x<1?NaN:94906265.62425156<x?log(x)+LN2:log1p(x-1+sqrt(x-1)*sqrt(1+x))}})},{"../internals/export":196,"../internals/math-log1p":254}],422:[function(require,module,exports){var require=require("../internals/export"),$asinh=Math.asinh,log=Math.log,sqrt=Math.sqrt;require({target:"Math",stat:!0,forced:!($asinh&&0<1/$asinh(0))},{asinh:function asinh(x){x=+x;return isFinite(x)&&0!=x?x<0?-asinh(-x):log(x+sqrt(x*x+1)):x}})},{"../internals/export":196}],423:[function(require,module,exports){var require=require("../internals/export"),$atanh=Math.atanh,log=Math.log;require({target:"Math",stat:!0,forced:!($atanh&&1/$atanh(-0)<0)},{atanh:function(x){x=+x;return 0==x?x:log((1+x)/(1-x))/2}})},{"../internals/export":196}],424:[function(require,module,exports){var $=require("../internals/export"),sign=require("../internals/math-sign"),abs=Math.abs,pow=Math.pow;$({target:"Math",stat:!0},{cbrt:function(x){x=+x;return sign(x)*pow(abs(x),1/3)}})},{"../internals/export":196,"../internals/math-sign":255}],425:[function(require,module,exports){var require=require("../internals/export"),floor=Math.floor,log=Math.log,LOG2E=Math.LOG2E;require({target:"Math",stat:!0},{clz32:function(x){x>>>=0;return x?31-floor(log(.5+x)*LOG2E):32}})},{"../internals/export":196}],426:[function(require,module,exports){var $=require("../internals/export"),expm1=require("../internals/math-expm1"),require=Math.cosh,abs=Math.abs,E=Math.E;$({target:"Math",stat:!0,forced:!require||require(710)===1/0},{cosh:function(x){x=expm1(abs(x)-1)+1;return(x+1/(x*E*E))*(E/2)}})},{"../internals/export":196,"../internals/math-expm1":251}],427:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/math-expm1");$({target:"Math",stat:!0,forced:require!=Math.expm1},{expm1:require})},{"../internals/export":196,"../internals/math-expm1":251}],428:[function(require,module,exports){require("../internals/export")({target:"Math",stat:!0},{fround:require("../internals/math-fround")})},{"../internals/export":196,"../internals/math-fround":252}],429:[function(require,module,exports){var require=require("../internals/export"),$hypot=Math.hypot,abs=Math.abs,sqrt=Math.sqrt;require({target:"Math",stat:!0,arity:2,forced:!!$hypot&&$hypot(1/0,NaN)!==1/0},{hypot:function(value1,value2){for(var arg,div,sum=0,i=0,aLen=arguments.length,larg=0;i<aLen;)larg<(arg=abs(arguments[i++]))?(sum=sum*(div=larg/arg)*div+1,larg=arg):sum+=0<arg?(div=arg/larg)*div:arg;return larg===1/0?1/0:larg*sqrt(sum)}})},{"../internals/export":196}],430:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/fails"),$imul=Math.imul;$({target:"Math",stat:!0,forced:require(function(){return-5!=$imul(4294967295,5)||2!=$imul.length})},{imul:function(x,y){var x=+x,y=+y,xl=65535&x,yl=65535&y;return 0|xl*yl+((65535&x>>>16)*yl+xl*(65535&y>>>16)<<16>>>0)}})},{"../internals/export":196,"../internals/fails":197}],431:[function(require,module,exports){require("../internals/export")({target:"Math",stat:!0},{log10:require("../internals/math-log10")})},{"../internals/export":196,"../internals/math-log10":253}],432:[function(require,module,exports){require("../internals/export")({target:"Math",stat:!0},{log1p:require("../internals/math-log1p")})},{"../internals/export":196,"../internals/math-log1p":254}],433:[function(require,module,exports){var require=require("../internals/export"),log=Math.log,LN2=Math.LN2;require({target:"Math",stat:!0},{log2:function(x){return log(x)/LN2}})},{"../internals/export":196}],434:[function(require,module,exports){require("../internals/export")({target:"Math",stat:!0},{sign:require("../internals/math-sign")})},{"../internals/export":196,"../internals/math-sign":255}],435:[function(require,module,exports){var $=require("../internals/export"),fails=require("../internals/fails"),expm1=require("../internals/math-expm1"),abs=Math.abs,exp=Math.exp,E=Math.E;$({target:"Math",stat:!0,forced:fails(function(){return-2e-17!=Math.sinh(-2e-17)})},{sinh:function(x){x=+x;return abs(x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)}})},{"../internals/export":196,"../internals/fails":197,"../internals/math-expm1":251}],436:[function(require,module,exports){var $=require("../internals/export"),expm1=require("../internals/math-expm1"),exp=Math.exp;$({target:"Math",stat:!0},{tanh:function(x){var x=+x,a=expm1(x),b=expm1(-x);return a==1/0?1:b==1/0?-1:(a-b)/(exp(x)+exp(-x))}})},{"../internals/export":196,"../internals/math-expm1":251}],437:[function(require,module,exports){require("../internals/set-to-string-tag")(Math,"Math",!0)},{"../internals/set-to-string-tag":304}],438:[function(require,module,exports){require("../internals/export")({target:"Math",stat:!0},{trunc:require("../internals/math-trunc")})},{"../internals/export":196,"../internals/math-trunc":256}],439:[function(require,module,exports){"use strict";function NumberWrapper(value){var dummy,value=arguments.length<1?0:NativeNumber(function(value){value=toPrimitive(value,"number");return"bigint"==typeof value?value:toNumber(value)}(value));return isPrototypeOf(NumberPrototype,dummy=this)&&fails(function(){thisNumberValue(dummy)})?inheritIfRequired(Object(value),this,NumberWrapper):value}function copyConstructorProperties(target,source){for(var key,keys=DESCRIPTORS?getOwnPropertyNames(source):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),j=0;keys.length>j;j++)hasOwn(source,key=keys[j])&&!hasOwn(target,key)&&defineProperty(target,key,getOwnPropertyDescriptor(source,key))}var $=require("../internals/export"),IS_PURE=require("../internals/is-pure"),DESCRIPTORS=require("../internals/descriptors"),global=require("../internals/global"),path=require("../internals/path"),uncurryThis=require("../internals/function-uncurry-this"),isForced=require("../internals/is-forced"),hasOwn=require("../internals/has-own-property"),inheritIfRequired=require("../internals/inherit-if-required"),isPrototypeOf=require("../internals/object-is-prototype-of"),isSymbol=require("../internals/is-symbol"),toPrimitive=require("../internals/to-primitive"),fails=require("../internals/fails"),getOwnPropertyNames=require("../internals/object-get-own-property-names").f,getOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f,defineProperty=require("../internals/object-define-property").f,thisNumberValue=require("../internals/this-number-value"),trim=require("../internals/string-trim").trim,NativeNumber=global.Number,require=path.Number,NumberPrototype=NativeNumber.prototype,TypeError=global.TypeError,stringSlice=uncurryThis("".slice),charCodeAt=uncurryThis("".charCodeAt),toNumber=function(argument){var third,radix,maxCode,digits,length,index,code,it=toPrimitive(argument,"number");if(isSymbol(it))throw TypeError("Cannot convert a Symbol value to a number");if("string"==typeof it&&2<it.length)if(it=trim(it),43===(argument=charCodeAt(it,0))||45===argument){if(88===(third=charCodeAt(it,2))||120===third)return NaN}else if(48===argument){switch(charCodeAt(it,1)){case 66:case 98:radix=2,maxCode=49;break;case 79:case 111:radix=8,maxCode=55;break;default:return+it}for(length=(digits=stringSlice(it,2)).length,index=0;index<length;index++)if((code=charCodeAt(digits,index))<48||maxCode<code)return NaN;return parseInt(digits,radix)}return+it},global=isForced("Number",!NativeNumber(" 0o1")||!NativeNumber("0b1")||NativeNumber("+0x1"));NumberWrapper.prototype=NumberPrototype,global&&!IS_PURE&&(NumberPrototype.constructor=NumberWrapper),$({global:!0,constructor:!0,wrap:!0,forced:global},{Number:NumberWrapper});IS_PURE&&require&&copyConstructorProperties(path.Number,require),(global||IS_PURE)&&copyConstructorProperties(path.Number,NativeNumber)},{"../internals/descriptors":171,"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/has-own-property":217,"../internals/inherit-if-required":224,"../internals/is-forced":235,"../internals/is-pure":239,"../internals/is-symbol":241,"../internals/object-define-property":267,"../internals/object-get-own-property-descriptor":268,"../internals/object-get-own-property-names":270,"../internals/object-is-prototype-of":274,"../internals/path":284,"../internals/string-trim":318,"../internals/this-number-value":324,"../internals/to-primitive":334}],440:[function(require,module,exports){require("../internals/export")({target:"Number",stat:!0,nonConfigurable:!0,nonWritable:!0},{EPSILON:Math.pow(2,-52)})},{"../internals/export":196}],441:[function(require,module,exports){require("../internals/export")({target:"Number",stat:!0},{isFinite:require("../internals/number-is-finite")})},{"../internals/export":196,"../internals/number-is-finite":261}],442:[function(require,module,exports){require("../internals/export")({target:"Number",stat:!0},{isInteger:require("../internals/is-integral-number")})},{"../internals/export":196,"../internals/is-integral-number":236}],443:[function(require,module,exports){require("../internals/export")({target:"Number",stat:!0},{isNaN:function(number){return number!=number}})},{"../internals/export":196}],444:[function(require,module,exports){var $=require("../internals/export"),isIntegralNumber=require("../internals/is-integral-number"),abs=Math.abs;$({target:"Number",stat:!0},{isSafeInteger:function(number){return isIntegralNumber(number)&&abs(number)<=9007199254740991}})},{"../internals/export":196,"../internals/is-integral-number":236}],445:[function(require,module,exports){require("../internals/export")({target:"Number",stat:!0,nonConfigurable:!0,nonWritable:!0},{MAX_SAFE_INTEGER:9007199254740991})},{"../internals/export":196}],446:[function(require,module,exports){require("../internals/export")({target:"Number",stat:!0,nonConfigurable:!0,nonWritable:!0},{MIN_SAFE_INTEGER:-9007199254740991})},{"../internals/export":196}],447:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/number-parse-float");$({target:"Number",stat:!0,forced:Number.parseFloat!=require},{parseFloat:require})},{"../internals/export":196,"../internals/number-parse-float":262}],448:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/number-parse-int");$({target:"Number",stat:!0,forced:Number.parseInt!=require},{parseInt:require})},{"../internals/export":196,"../internals/number-parse-int":263}],449:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),thisNumberValue=require("../internals/this-number-value"),$repeat=require("../internals/string-repeat"),log10=require("../internals/math-log10"),require=require("../internals/fails"),$RangeError=RangeError,$String=String,$isFinite=isFinite,abs=Math.abs,floor=Math.floor,pow=Math.pow,round=Math.round,nativeToExponential=uncurryThis(1..toExponential),repeat=uncurryThis($repeat),stringSlice=uncurryThis("".slice),ROUNDS_PROPERLY="-6.9000e-11"===nativeToExponential(-69e-12,4)&&"1.25e+0"===nativeToExponential(1.255,2)&&"1.235e+4"===nativeToExponential(12345,3)&&"3e+1"===nativeToExponential(25,0);$({target:"Number",proto:!0,forced:!ROUNDS_PROPERLY||!(require(function(){nativeToExponential(1,1/0)})&&require(function(){nativeToExponential(1,-1/0)}))||!!require(function(){nativeToExponential(1/0,1/0),nativeToExponential(NaN,1/0)})},{toExponential:function(fractionDigits){var x=thisNumberValue(this);if(void 0===fractionDigits)return nativeToExponential(x);var s,m,c,d,e,w,l,fractionDigits=toIntegerOrInfinity(fractionDigits);if(!$isFinite(x))return String(x);if(fractionDigits<0||20<fractionDigits)throw $RangeError("Incorrect fraction digits");return ROUNDS_PROPERLY?nativeToExponential(x,fractionDigits):(d=c=m=s="",x<(e=0)&&(s="-",x=-x),m=0===x?(e=0,repeat("0",fractionDigits+1)):(l=log10(x),e=floor(l),l=0,w=pow(10,e-fractionDigits),(2*(l=round(x/w))+1)*w<=2*x&&(l+=1),l>=pow(10,fractionDigits+1)&&(l/=10,e+=1),$String(l)),0!==fractionDigits&&(m=stringSlice(m,0,1)+"."+stringSlice(m,1)),d=0===e?(c="+","0"):(c=0<e?"+":"-",$String(abs(e))),s+(m+="e"+c+d))}})},{"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/math-log10":253,"../internals/string-repeat":314,"../internals/this-number-value":324,"../internals/to-integer-or-infinity":329}],450:[function(require,module,exports){"use strict";function pow(x,n,acc){return 0===n?acc:n%2==1?pow(x,n-1,acc*x):pow(x*x,n/2,acc)}function multiply(data,n,c){for(var index=-1,c2=c;++index<6;)c2+=n*data[index],data[index]=c2%1e7,c2=floor(c2/1e7)}function divide(data,n){for(var index=6,c=0;0<=--index;)c+=data[index],data[index]=floor(c/n),c=c%n*1e7}function dataToString(data){for(var t,index=6,s="";0<=--index;)""===s&&0!==index&&0===data[index]||(t=$String(data[index]),s=""===s?t:s+repeat("0",7-t.length)+t);return s}var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),thisNumberValue=require("../internals/this-number-value"),$repeat=require("../internals/string-repeat"),require=require("../internals/fails"),$RangeError=RangeError,$String=String,floor=Math.floor,repeat=uncurryThis($repeat),stringSlice=uncurryThis("".slice),nativeToFixed=uncurryThis(1..toFixed);$({target:"Number",proto:!0,forced:require(function(){return"0.000"!==nativeToFixed(8e-5,3)||"1"!==nativeToFixed(.9,0)||"1.25"!==nativeToFixed(1.255,2)||"1000000000000000128"!==nativeToFixed(0xde0b6b3a7640080,0)})||!require(function(){nativeToFixed({})})},{toFixed:function(fractionDigits){var e,j,number=thisNumberValue(this),fractionDigits=toIntegerOrInfinity(fractionDigits),data=[0,0,0,0,0,0],sign="",result="0";if(fractionDigits<0||20<fractionDigits)throw $RangeError("Incorrect fraction digits");if(number!=number)return"NaN";if(number<=-1e21||1e21<=number)return $String(number);if(number<0&&(sign="-",number=-number),1e-21<number)if(number=(e=function(x){for(var n=0,x2=x;4096<=x2;)n+=12,x2/=4096;for(;2<=x2;)n+=1,x2/=2;return n}(number*pow(2,69,1))-69)<0?number*pow(2,-e,1):number/pow(2,e,1),number*=4503599627370496,0<(e=52-e)){for(multiply(data,0,number),j=fractionDigits;7<=j;)multiply(data,1e7,0),j-=7;for(multiply(data,pow(10,j,1),0),j=e-1;23<=j;)divide(data,1<<23),j-=23;divide(data,1<<j),multiply(data,1,1),divide(data,2),result=dataToString(data)}else multiply(data,0,number),multiply(data,1<<-e,0),result=dataToString(data)+repeat("0",fractionDigits);return result=0<fractionDigits?sign+((number=result.length)<=fractionDigits?"0."+repeat("0",fractionDigits-number)+result:stringSlice(result,0,number-fractionDigits)+"."+stringSlice(result,number-fractionDigits)):sign+result}})},{"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/string-repeat":314,"../internals/this-number-value":324,"../internals/to-integer-or-infinity":329}],451:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),fails=require("../internals/fails"),thisNumberValue=require("../internals/this-number-value"),nativeToPrecision=uncurryThis(1..toPrecision);$({target:"Number",proto:!0,forced:fails(function(){return"1"!==nativeToPrecision(1,void 0)})||!fails(function(){nativeToPrecision({})})},{toPrecision:function(precision){return void 0===precision?nativeToPrecision(thisNumberValue(this)):nativeToPrecision(thisNumberValue(this),precision)}})},{"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/this-number-value":324}],452:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/object-assign");$({target:"Object",stat:!0,arity:2,forced:Object.assign!==require},{assign:require})},{"../internals/export":196,"../internals/object-assign":264}],453:[function(require,module,exports){require("../internals/export")({target:"Object",stat:!0,sham:!require("../internals/descriptors")},{create:require("../internals/object-create")})},{"../internals/descriptors":171,"../internals/export":196,"../internals/object-create":265}],454:[function(require,module,exports){"use strict";var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),FORCED=require("../internals/object-prototype-accessors-forced"),aCallable=require("../internals/a-callable"),toObject=require("../internals/to-object"),definePropertyModule=require("../internals/object-define-property");DESCRIPTORS&&$({target:"Object",proto:!0,forced:FORCED},{__defineGetter__:function(P,getter){definePropertyModule.f(toObject(this),P,{get:aCallable(getter),enumerable:!0,configurable:!0})}})},{"../internals/a-callable":117,"../internals/descriptors":171,"../internals/export":196,"../internals/object-define-property":267,"../internals/object-prototype-accessors-forced":278,"../internals/to-object":331}],455:[function(require,module,exports){var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),require=require("../internals/object-define-properties").f;$({target:"Object",stat:!0,forced:Object.defineProperties!==require,sham:!DESCRIPTORS},{defineProperties:require})},{"../internals/descriptors":171,"../internals/export":196,"../internals/object-define-properties":266}],456:[function(require,module,exports){var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),require=require("../internals/object-define-property").f;$({target:"Object",stat:!0,forced:Object.defineProperty!==require,sham:!DESCRIPTORS},{defineProperty:require})},{"../internals/descriptors":171,"../internals/export":196,"../internals/object-define-property":267}],457:[function(require,module,exports){"use strict";var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),FORCED=require("../internals/object-prototype-accessors-forced"),aCallable=require("../internals/a-callable"),toObject=require("../internals/to-object"),definePropertyModule=require("../internals/object-define-property");DESCRIPTORS&&$({target:"Object",proto:!0,forced:FORCED},{__defineSetter__:function(P,setter){definePropertyModule.f(toObject(this),P,{set:aCallable(setter),enumerable:!0,configurable:!0})}})},{"../internals/a-callable":117,"../internals/descriptors":171,"../internals/export":196,"../internals/object-define-property":267,"../internals/object-prototype-accessors-forced":278,"../internals/to-object":331}],458:[function(require,module,exports){var $=require("../internals/export"),$entries=require("../internals/object-to-array").entries;$({target:"Object",stat:!0},{entries:function(O){return $entries(O)}})},{"../internals/export":196,"../internals/object-to-array":280}],459:[function(require,module,exports){var $=require("../internals/export"),FREEZING=require("../internals/freezing"),fails=require("../internals/fails"),isObject=require("../internals/is-object"),onFreeze=require("../internals/internal-metadata").onFreeze,$freeze=Object.freeze;$({target:"Object",stat:!0,forced:fails(function(){$freeze(1)}),sham:!FREEZING},{freeze:function(it){return $freeze&&isObject(it)?$freeze(onFreeze(it)):it}})},{"../internals/export":196,"../internals/fails":197,"../internals/freezing":200,"../internals/internal-metadata":227,"../internals/is-object":238}],460:[function(require,module,exports){var $=require("../internals/export"),iterate=require("../internals/iterate"),createProperty=require("../internals/create-property");$({target:"Object",stat:!0},{fromEntries:function(iterable){var obj={};return iterate(iterable,function(k,v){createProperty(obj,k,v)},{AS_ENTRIES:!0}),obj}})},{"../internals/create-property":163,"../internals/export":196,"../internals/iterate":242}],461:[function(require,module,exports){var $=require("../internals/export"),fails=require("../internals/fails"),toIndexedObject=require("../internals/to-indexed-object"),nativeGetOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f,require=require("../internals/descriptors");$({target:"Object",stat:!0,forced:!require||fails(function(){nativeGetOwnPropertyDescriptor(1)}),sham:!require},{getOwnPropertyDescriptor:function(it,key){return nativeGetOwnPropertyDescriptor(toIndexedObject(it),key)}})},{"../internals/descriptors":171,"../internals/export":196,"../internals/fails":197,"../internals/object-get-own-property-descriptor":268,"../internals/to-indexed-object":328}],462:[function(require,module,exports){var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),ownKeys=require("../internals/own-keys"),toIndexedObject=require("../internals/to-indexed-object"),getOwnPropertyDescriptorModule=require("../internals/object-get-own-property-descriptor"),createProperty=require("../internals/create-property");$({target:"Object",stat:!0,sham:!DESCRIPTORS},{getOwnPropertyDescriptors:function(object){for(var key,descriptor,O=toIndexedObject(object),getOwnPropertyDescriptor=getOwnPropertyDescriptorModule.f,keys=ownKeys(O),result={},index=0;keys.length>index;)void 0!==(descriptor=getOwnPropertyDescriptor(O,key=keys[index++]))&&createProperty(result,key,descriptor);return result}})},{"../internals/create-property":163,"../internals/descriptors":171,"../internals/export":196,"../internals/object-get-own-property-descriptor":268,"../internals/own-keys":283,"../internals/to-indexed-object":328}],463:[function(require,module,exports){var $=require("../internals/export"),fails=require("../internals/fails"),require=require("../internals/object-get-own-property-names-external").f;$({target:"Object",stat:!0,forced:fails(function(){return!Object.getOwnPropertyNames(1)})},{getOwnPropertyNames:require})},{"../internals/export":196,"../internals/fails":197,"../internals/object-get-own-property-names-external":269}],464:[function(require,module,exports){var $=require("../internals/export"),NATIVE_SYMBOL=require("../internals/symbol-constructor-detection"),fails=require("../internals/fails"),getOwnPropertySymbolsModule=require("../internals/object-get-own-property-symbols"),toObject=require("../internals/to-object");$({target:"Object",stat:!0,forced:!NATIVE_SYMBOL||fails(function(){getOwnPropertySymbolsModule.f(1)})},{getOwnPropertySymbols:function(it){var $getOwnPropertySymbols=getOwnPropertySymbolsModule.f;return $getOwnPropertySymbols?$getOwnPropertySymbols(toObject(it)):[]}})},{"../internals/export":196,"../internals/fails":197,"../internals/object-get-own-property-symbols":271,"../internals/symbol-constructor-detection":320,"../internals/to-object":331}],465:[function(require,module,exports){var $=require("../internals/export"),fails=require("../internals/fails"),toObject=require("../internals/to-object"),nativeGetPrototypeOf=require("../internals/object-get-prototype-of"),require=require("../internals/correct-prototype-getter");$({target:"Object",stat:!0,forced:fails(function(){nativeGetPrototypeOf(1)}),sham:!require},{getPrototypeOf:function(it){return nativeGetPrototypeOf(toObject(it))}})},{"../internals/correct-prototype-getter":158,"../internals/export":196,"../internals/fails":197,"../internals/object-get-prototype-of":272,"../internals/to-object":331}],466:[function(require,module,exports){require("../internals/export")({target:"Object",stat:!0},{hasOwn:require("../internals/has-own-property")})},{"../internals/export":196,"../internals/has-own-property":217}],467:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/object-is-extensible");$({target:"Object",stat:!0,forced:Object.isExtensible!==require},{isExtensible:require})},{"../internals/export":196,"../internals/object-is-extensible":273}],468:[function(require,module,exports){var $=require("../internals/export"),fails=require("../internals/fails"),isObject=require("../internals/is-object"),classof=require("../internals/classof-raw"),ARRAY_BUFFER_NON_EXTENSIBLE=require("../internals/array-buffer-non-extensible"),$isFrozen=Object.isFrozen;$({target:"Object",stat:!0,forced:ARRAY_BUFFER_NON_EXTENSIBLE||fails(function(){$isFrozen(1)})},{isFrozen:function(it){return!isObject(it)||!(!ARRAY_BUFFER_NON_EXTENSIBLE||"ArrayBuffer"!=classof(it))||!!$isFrozen&&$isFrozen(it)}})},{"../internals/array-buffer-non-extensible":125,"../internals/classof-raw":151,"../internals/export":196,"../internals/fails":197,"../internals/is-object":238}],469:[function(require,module,exports){var $=require("../internals/export"),fails=require("../internals/fails"),isObject=require("../internals/is-object"),classof=require("../internals/classof-raw"),ARRAY_BUFFER_NON_EXTENSIBLE=require("../internals/array-buffer-non-extensible"),$isSealed=Object.isSealed;$({target:"Object",stat:!0,forced:ARRAY_BUFFER_NON_EXTENSIBLE||fails(function(){$isSealed(1)})},{isSealed:function(it){return!isObject(it)||!(!ARRAY_BUFFER_NON_EXTENSIBLE||"ArrayBuffer"!=classof(it))||!!$isSealed&&$isSealed(it)}})},{"../internals/array-buffer-non-extensible":125,"../internals/classof-raw":151,"../internals/export":196,"../internals/fails":197,"../internals/is-object":238}],470:[function(require,module,exports){require("../internals/export")({target:"Object",stat:!0},{is:require("../internals/same-value")})},{"../internals/export":196,"../internals/same-value":300}],471:[function(require,module,exports){var $=require("../internals/export"),toObject=require("../internals/to-object"),nativeKeys=require("../internals/object-keys");$({target:"Object",stat:!0,forced:require("../internals/fails")(function(){nativeKeys(1)})},{keys:function(it){return nativeKeys(toObject(it))}})},{"../internals/export":196,"../internals/fails":197,"../internals/object-keys":276,"../internals/to-object":331}],472:[function(require,module,exports){"use strict";var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),FORCED=require("../internals/object-prototype-accessors-forced"),toObject=require("../internals/to-object"),toPropertyKey=require("../internals/to-property-key"),getPrototypeOf=require("../internals/object-get-prototype-of"),getOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f;DESCRIPTORS&&$({target:"Object",proto:!0,forced:FORCED},{__lookupGetter__:function(P){var desc,O=toObject(this),key=toPropertyKey(P);do{if(desc=getOwnPropertyDescriptor(O,key))return desc.get}while(O=getPrototypeOf(O))}})},{"../internals/descriptors":171,"../internals/export":196,"../internals/object-get-own-property-descriptor":268,"../internals/object-get-prototype-of":272,"../internals/object-prototype-accessors-forced":278,"../internals/to-object":331,"../internals/to-property-key":335}],473:[function(require,module,exports){"use strict";var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),FORCED=require("../internals/object-prototype-accessors-forced"),toObject=require("../internals/to-object"),toPropertyKey=require("../internals/to-property-key"),getPrototypeOf=require("../internals/object-get-prototype-of"),getOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f;DESCRIPTORS&&$({target:"Object",proto:!0,forced:FORCED},{__lookupSetter__:function(P){var desc,O=toObject(this),key=toPropertyKey(P);do{if(desc=getOwnPropertyDescriptor(O,key))return desc.set}while(O=getPrototypeOf(O))}})},{"../internals/descriptors":171,"../internals/export":196,"../internals/object-get-own-property-descriptor":268,"../internals/object-get-prototype-of":272,"../internals/object-prototype-accessors-forced":278,"../internals/to-object":331,"../internals/to-property-key":335}],474:[function(require,module,exports){var $=require("../internals/export"),isObject=require("../internals/is-object"),onFreeze=require("../internals/internal-metadata").onFreeze,FREEZING=require("../internals/freezing"),require=require("../internals/fails"),$preventExtensions=Object.preventExtensions;$({target:"Object",stat:!0,forced:require(function(){$preventExtensions(1)}),sham:!FREEZING},{preventExtensions:function(it){return $preventExtensions&&isObject(it)?$preventExtensions(onFreeze(it)):it}})},{"../internals/export":196,"../internals/fails":197,"../internals/freezing":200,"../internals/internal-metadata":227,"../internals/is-object":238}],475:[function(require,module,exports){"use strict";var DESCRIPTORS=require("../internals/descriptors"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),isObject=require("../internals/is-object"),toObject=require("../internals/to-object"),requireObjectCoercible=require("../internals/require-object-coercible"),getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,require=Object.prototype;if(DESCRIPTORS&&getPrototypeOf&&setPrototypeOf&&!("__proto__"in require))try{defineBuiltInAccessor(require,"__proto__",{configurable:!0,get:function(){return getPrototypeOf(toObject(this))},set:function(proto){var O=requireObjectCoercible(this);(isObject(proto)||null===proto)&&isObject(O)&&setPrototypeOf(O,proto)}})}catch(error){}},{"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/is-object":238,"../internals/require-object-coercible":299,"../internals/to-object":331}],476:[function(require,module,exports){var $=require("../internals/export"),isObject=require("../internals/is-object"),onFreeze=require("../internals/internal-metadata").onFreeze,FREEZING=require("../internals/freezing"),require=require("../internals/fails"),$seal=Object.seal;$({target:"Object",stat:!0,forced:require(function(){$seal(1)}),sham:!FREEZING},{seal:function(it){return $seal&&isObject(it)?$seal(onFreeze(it)):it}})},{"../internals/export":196,"../internals/fails":197,"../internals/freezing":200,"../internals/internal-metadata":227,"../internals/is-object":238}],477:[function(require,module,exports){require("../internals/export")({target:"Object",stat:!0},{setPrototypeOf:require("../internals/object-set-prototype-of")})},{"../internals/export":196,"../internals/object-set-prototype-of":279}],478:[function(require,module,exports){var TO_STRING_TAG_SUPPORT=require("../internals/to-string-tag-support"),defineBuiltIn=require("../internals/define-built-in"),require=require("../internals/object-to-string");TO_STRING_TAG_SUPPORT||defineBuiltIn(Object.prototype,"toString",require,{unsafe:!0})},{"../internals/define-built-in":167,"../internals/object-to-string":281,"../internals/to-string-tag-support":336}],479:[function(require,module,exports){var $=require("../internals/export"),$values=require("../internals/object-to-array").values;$({target:"Object",stat:!0},{values:function(O){return $values(O)}})},{"../internals/export":196,"../internals/object-to-array":280}],480:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/number-parse-float");$({global:!0,forced:parseFloat!=require},{parseFloat:require})},{"../internals/export":196,"../internals/number-parse-float":262}],481:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/number-parse-int");$({global:!0,forced:parseInt!=require},{parseInt:require})},{"../internals/export":196,"../internals/number-parse-int":263}],482:[function(require,module,exports){"use strict";var $=require("../internals/export"),call=require("../internals/function-call"),aCallable=require("../internals/a-callable"),newPromiseCapabilityModule=require("../internals/new-promise-capability"),perform=require("../internals/perform"),iterate=require("../internals/iterate");$({target:"Promise",stat:!0,forced:require("../internals/promise-statics-incorrect-iteration")},{allSettled:function(iterable){var C=this,capability=newPromiseCapabilityModule.f(C),resolve=capability.resolve,reject=capability.reject,result=perform(function(){var promiseResolve=aCallable(C.resolve),values=[],counter=0,remaining=1;iterate(iterable,function(promise){var index=counter++,alreadyCalled=!1;remaining++,call(promiseResolve,C,promise).then(function(value){alreadyCalled||(alreadyCalled=!0,values[index]={status:"fulfilled",value:value},--remaining)||resolve(values)},function(error){alreadyCalled||(alreadyCalled=!0,values[index]={status:"rejected",reason:error},--remaining)||resolve(values)})}),--remaining||resolve(values)});return result.error&&reject(result.value),capability.promise}})},{"../internals/a-callable":117,"../internals/export":196,"../internals/function-call":205,"../internals/iterate":242,"../internals/new-promise-capability":258,"../internals/perform":285,"../internals/promise-statics-incorrect-iteration":289}],483:[function(require,module,exports){"use strict";var $=require("../internals/export"),call=require("../internals/function-call"),aCallable=require("../internals/a-callable"),newPromiseCapabilityModule=require("../internals/new-promise-capability"),perform=require("../internals/perform"),iterate=require("../internals/iterate");$({target:"Promise",stat:!0,forced:require("../internals/promise-statics-incorrect-iteration")},{all:function(iterable){var C=this,capability=newPromiseCapabilityModule.f(C),resolve=capability.resolve,reject=capability.reject,result=perform(function(){var $promiseResolve=aCallable(C.resolve),values=[],counter=0,remaining=1;iterate(iterable,function(promise){var index=counter++,alreadyCalled=!1;remaining++,call($promiseResolve,C,promise).then(function(value){alreadyCalled||(alreadyCalled=!0,values[index]=value,--remaining)||resolve(values)},reject)}),--remaining||resolve(values)});return result.error&&reject(result.value),capability.promise}})},{"../internals/a-callable":117,"../internals/export":196,"../internals/function-call":205,"../internals/iterate":242,"../internals/new-promise-capability":258,"../internals/perform":285,"../internals/promise-statics-incorrect-iteration":289}],484:[function(require,module,exports){"use strict";var $=require("../internals/export"),call=require("../internals/function-call"),aCallable=require("../internals/a-callable"),getBuiltIn=require("../internals/get-built-in"),newPromiseCapabilityModule=require("../internals/new-promise-capability"),perform=require("../internals/perform"),iterate=require("../internals/iterate"),require=require("../internals/promise-statics-incorrect-iteration");$({target:"Promise",stat:!0,forced:require},{any:function(iterable){var C=this,AggregateError=getBuiltIn("AggregateError"),capability=newPromiseCapabilityModule.f(C),resolve=capability.resolve,reject=capability.reject,result=perform(function(){var promiseResolve=aCallable(C.resolve),errors=[],counter=0,remaining=1,alreadyResolved=!1;iterate(iterable,function(promise){var index=counter++,alreadyRejected=!1;remaining++,call(promiseResolve,C,promise).then(function(value){alreadyRejected||alreadyResolved||(alreadyResolved=!0,resolve(value))},function(error){alreadyRejected||alreadyResolved||(alreadyRejected=!0,errors[index]=error,--remaining)||reject(new AggregateError(errors,"No one promise resolved"))})}),--remaining||reject(new AggregateError(errors,"No one promise resolved"))});return result.error&&reject(result.value),capability.promise}})},{"../internals/a-callable":117,"../internals/export":196,"../internals/function-call":205,"../internals/get-built-in":210,"../internals/iterate":242,"../internals/new-promise-capability":258,"../internals/perform":285,"../internals/promise-statics-incorrect-iteration":289}],485:[function(require,module,exports){"use strict";var $=require("../internals/export"),IS_PURE=require("../internals/is-pure"),FORCED_PROMISE_CONSTRUCTOR=require("../internals/promise-constructor-detection").CONSTRUCTOR,NativePromiseConstructor=require("../internals/promise-native-constructor"),getBuiltIn=require("../internals/get-built-in"),isCallable=require("../internals/is-callable"),require=require("../internals/define-built-in"),NativePromisePrototype=NativePromiseConstructor&&NativePromiseConstructor.prototype;$({target:"Promise",proto:!0,forced:FORCED_PROMISE_CONSTRUCTOR,real:!0},{catch:function(onRejected){return this.then(void 0,onRejected)}}),!IS_PURE&&isCallable(NativePromiseConstructor)&&($=getBuiltIn("Promise").prototype.catch,NativePromisePrototype.catch!==$)&&require(NativePromisePrototype,"catch",$,{unsafe:!0})},{"../internals/define-built-in":167,"../internals/export":196,"../internals/get-built-in":210,"../internals/is-callable":232,"../internals/is-pure":239,"../internals/promise-constructor-detection":286,"../internals/promise-native-constructor":287}],486:[function(require,module,exports){"use strict";function callReaction(reaction,state){var result,then,exited,value=state.value,ok=state.state==FULFILLED,handler=ok?reaction.ok:reaction.fail,resolve=reaction.resolve,reject=reaction.reject,domain=reaction.domain;try{handler?(ok||(state.rejection===UNHANDLED&&function(state){call(task,global,function(){var promise=state.facade;if(IS_NODE)process.emit("rejectionHandled",promise);else dispatchEvent(REJECTION_HANDLED,promise,state.value)})}(state),state.rejection=HANDLED),!0===handler?result=value:(domain&&domain.enter(),result=handler(value),domain&&(domain.exit(),exited=!0)),result===reaction.promise?reject(TypeError("Promise-chain cycle")):(then=isThenable(result))?call(then,result,resolve,reject):resolve(result)):reject(value)}catch(error){domain&&!exited&&domain.exit(),reject(error)}}var Internal,OwnPromiseCapability,nativeThen,$=require("../internals/export"),IS_PURE=require("../internals/is-pure"),IS_NODE=require("../internals/engine-is-node"),global=require("../internals/global"),call=require("../internals/function-call"),defineBuiltIn=require("../internals/define-built-in"),setPrototypeOf=require("../internals/object-set-prototype-of"),setToStringTag=require("../internals/set-to-string-tag"),setSpecies=require("../internals/set-species"),aCallable=require("../internals/a-callable"),isCallable=require("../internals/is-callable"),isObject=require("../internals/is-object"),anInstance=require("../internals/an-instance"),speciesConstructor=require("../internals/species-constructor"),task=require("../internals/task").set,microtask=require("../internals/microtask"),hostReportErrors=require("../internals/host-report-errors"),perform=require("../internals/perform"),Queue=require("../internals/queue"),InternalStateModule=require("../internals/internal-state"),NativePromiseConstructor=require("../internals/promise-native-constructor"),PromiseConstructorDetection=require("../internals/promise-constructor-detection"),require=require("../internals/new-promise-capability"),FORCED_PROMISE_CONSTRUCTOR=PromiseConstructorDetection.CONSTRUCTOR,NATIVE_PROMISE_REJECTION_EVENT=PromiseConstructorDetection.REJECTION_EVENT,PromiseConstructorDetection=PromiseConstructorDetection.SUBCLASSING,getInternalPromiseState=InternalStateModule.getterFor("Promise"),setInternalState=InternalStateModule.set,InternalStateModule=NativePromiseConstructor&&NativePromiseConstructor.prototype,PromiseConstructor=NativePromiseConstructor,PromisePrototype=InternalStateModule,TypeError=global.TypeError,document=global.document,process=global.process,newPromiseCapability=require.f,newGenericPromiseCapability=newPromiseCapability,DISPATCH_EVENT=!!(document&&document.createEvent&&global.dispatchEvent),UNHANDLED_REJECTION="unhandledrejection",REJECTION_HANDLED="rejectionhandled",FULFILLED=1,REJECTED=2,HANDLED=1,UNHANDLED=2,isThenable=function(it){var then;return!(!isObject(it)||!isCallable(then=it.then))&&then},notify=function(state,isReject){state.notified||(state.notified=!0,microtask(function(){for(var reaction,reactions=state.reactions;reaction=reactions.get();)callReaction(reaction,state);state.notified=!1,isReject&&!state.rejection&&function(state){call(task,global,function(){var promise=state.facade;var value=state.value;var IS_UNHANDLED=isUnhandled(state);var result;if(IS_UNHANDLED){result=perform(function(){if(IS_NODE)process.emit("unhandledRejection",value,promise);else dispatchEvent(UNHANDLED_REJECTION,promise,value)});state.rejection=IS_NODE||isUnhandled(state)?UNHANDLED:HANDLED;if(result.error)throw result.value}})}(state)}))},dispatchEvent=function(name,promise,reason){var event;DISPATCH_EVENT?((event=document.createEvent("Event")).promise=promise,event.reason=reason,event.initEvent(name,!1,!0),global.dispatchEvent(event)):event={promise:promise,reason:reason},!NATIVE_PROMISE_REJECTION_EVENT&&(promise=global["on"+name])?promise(event):name===UNHANDLED_REJECTION&&hostReportErrors("Unhandled promise rejection",reason)},isUnhandled=function(state){return state.rejection!==HANDLED&&!state.parent},bind=function(fn,state,unwrap){return function(value){fn(state,value,unwrap)}},internalReject=function(state,value,unwrap){state.done||(state.done=!0,(state=unwrap?unwrap:state).value=value,state.state=REJECTED,notify(state,!0))},internalResolve=function(state,value,unwrap){if(!state.done){state.done=!0,unwrap&&(state=unwrap);try{if(state.facade===value)throw TypeError("Promise can't be resolved itself");var then=isThenable(value);then?microtask(function(){var wrapper={done:!1};try{call(then,value,bind(internalResolve,wrapper,state),bind(internalReject,wrapper,state))}catch(error){internalReject(wrapper,error,state)}}):(state.value=value,state.state=FULFILLED,notify(state,!1))}catch(error){internalReject({done:!1},error,state)}}};if(FORCED_PROMISE_CONSTRUCTOR&&(PromisePrototype=(PromiseConstructor=function(executor){anInstance(this,PromisePrototype),aCallable(executor),call(Internal,this);var state=getInternalPromiseState(this);try{executor(bind(internalResolve,state),bind(internalReject,state))}catch(error){internalReject(state,error)}}).prototype,(Internal=function(executor){setInternalState(this,{type:"Promise",done:!1,notified:!1,parent:!1,reactions:new Queue,rejection:!1,state:0,value:void 0})}).prototype=defineBuiltIn(PromisePrototype,"then",function(onFulfilled,onRejected){var state=getInternalPromiseState(this),reaction=newPromiseCapability(speciesConstructor(this,PromiseConstructor));return state.parent=!0,reaction.ok=!isCallable(onFulfilled)||onFulfilled,reaction.fail=isCallable(onRejected)&&onRejected,reaction.domain=IS_NODE?process.domain:void 0,0==state.state?state.reactions.add(reaction):microtask(function(){callReaction(reaction,state)}),reaction.promise}),OwnPromiseCapability=function(){var promise=new Internal,state=getInternalPromiseState(promise);this.promise=promise,this.resolve=bind(internalResolve,state),this.reject=bind(internalReject,state)},require.f=newPromiseCapability=function(C){return C===PromiseConstructor||void 0===C?new OwnPromiseCapability:newGenericPromiseCapability(C)},!IS_PURE)&&isCallable(NativePromiseConstructor)&&InternalStateModule!==Object.prototype){nativeThen=InternalStateModule.then,PromiseConstructorDetection||defineBuiltIn(InternalStateModule,"then",function(onFulfilled,onRejected){var that=this;return new PromiseConstructor(function(resolve,reject){call(nativeThen,that,resolve,reject)}).then(onFulfilled,onRejected)},{unsafe:!0});try{delete InternalStateModule.constructor}catch(error){}setPrototypeOf&&setPrototypeOf(InternalStateModule,PromisePrototype)}$({global:!0,constructor:!0,wrap:!0,forced:FORCED_PROMISE_CONSTRUCTOR},{Promise:PromiseConstructor}),setToStringTag(PromiseConstructor,"Promise",!1,!0),setSpecies("Promise")},{"../internals/a-callable":117,"../internals/an-instance":122,"../internals/define-built-in":167,"../internals/engine-is-node":185,"../internals/export":196,"../internals/function-call":205,"../internals/global":216,"../internals/host-report-errors":219,"../internals/internal-state":228,"../internals/is-callable":232,"../internals/is-object":238,"../internals/is-pure":239,"../internals/microtask":257,"../internals/new-promise-capability":258,"../internals/object-set-prototype-of":279,"../internals/perform":285,"../internals/promise-constructor-detection":286,"../internals/promise-native-constructor":287,"../internals/queue":291,"../internals/set-species":303,"../internals/set-to-string-tag":304,"../internals/species-constructor":308,"../internals/task":323}],487:[function(require,module,exports){"use strict";var $=require("../internals/export"),IS_PURE=require("../internals/is-pure"),NativePromiseConstructor=require("../internals/promise-native-constructor"),fails=require("../internals/fails"),getBuiltIn=require("../internals/get-built-in"),isCallable=require("../internals/is-callable"),speciesConstructor=require("../internals/species-constructor"),promiseResolve=require("../internals/promise-resolve"),require=require("../internals/define-built-in"),NativePromisePrototype=NativePromiseConstructor&&NativePromiseConstructor.prototype;$({target:"Promise",proto:!0,real:!0,forced:!!NativePromiseConstructor&&fails(function(){NativePromisePrototype.finally.call({then:function(){}},function(){})})},{finally:function(onFinally){var C=speciesConstructor(this,getBuiltIn("Promise")),isFunction=isCallable(onFinally);return this.then(isFunction?function(x){return promiseResolve(C,onFinally()).then(function(){return x})}:onFinally,isFunction?function(e){return promiseResolve(C,onFinally()).then(function(){throw e})}:onFinally)}}),!IS_PURE&&isCallable(NativePromiseConstructor)&&($=getBuiltIn("Promise").prototype.finally,NativePromisePrototype.finally!==$)&&require(NativePromisePrototype,"finally",$,{unsafe:!0})},{"../internals/define-built-in":167,"../internals/export":196,"../internals/fails":197,"../internals/get-built-in":210,"../internals/is-callable":232,"../internals/is-pure":239,"../internals/promise-native-constructor":287,"../internals/promise-resolve":288,"../internals/species-constructor":308}],488:[function(require,module,exports){require("../modules/es.promise.constructor"),require("../modules/es.promise.all"),require("../modules/es.promise.catch"),require("../modules/es.promise.race"),require("../modules/es.promise.reject"),require("../modules/es.promise.resolve")},{"../modules/es.promise.all":483,"../modules/es.promise.catch":485,"../modules/es.promise.constructor":486,"../modules/es.promise.race":489,"../modules/es.promise.reject":490,"../modules/es.promise.resolve":491}],489:[function(require,module,exports){"use strict";var $=require("../internals/export"),call=require("../internals/function-call"),aCallable=require("../internals/a-callable"),newPromiseCapabilityModule=require("../internals/new-promise-capability"),perform=require("../internals/perform"),iterate=require("../internals/iterate");$({target:"Promise",stat:!0,forced:require("../internals/promise-statics-incorrect-iteration")},{race:function(iterable){var C=this,capability=newPromiseCapabilityModule.f(C),reject=capability.reject,result=perform(function(){var $promiseResolve=aCallable(C.resolve);iterate(iterable,function(promise){call($promiseResolve,C,promise).then(capability.resolve,reject)})});return result.error&&reject(result.value),capability.promise}})},{"../internals/a-callable":117,"../internals/export":196,"../internals/function-call":205,"../internals/iterate":242,"../internals/new-promise-capability":258,"../internals/perform":285,"../internals/promise-statics-incorrect-iteration":289}],490:[function(require,module,exports){"use strict";var $=require("../internals/export"),call=require("../internals/function-call"),newPromiseCapabilityModule=require("../internals/new-promise-capability");$({target:"Promise",stat:!0,forced:require("../internals/promise-constructor-detection").CONSTRUCTOR},{reject:function(r){var capability=newPromiseCapabilityModule.f(this);return call(capability.reject,void 0,r),capability.promise}})},{"../internals/export":196,"../internals/function-call":205,"../internals/new-promise-capability":258,"../internals/promise-constructor-detection":286}],491:[function(require,module,exports){"use strict";var $=require("../internals/export"),getBuiltIn=require("../internals/get-built-in"),IS_PURE=require("../internals/is-pure"),NativePromiseConstructor=require("../internals/promise-native-constructor"),FORCED_PROMISE_CONSTRUCTOR=require("../internals/promise-constructor-detection").CONSTRUCTOR,promiseResolve=require("../internals/promise-resolve"),PromiseConstructorWrapper=getBuiltIn("Promise"),CHECK_WRAPPER=IS_PURE&&!FORCED_PROMISE_CONSTRUCTOR;$({target:"Promise",stat:!0,forced:IS_PURE||FORCED_PROMISE_CONSTRUCTOR},{resolve:function(x){return promiseResolve(CHECK_WRAPPER&&this===PromiseConstructorWrapper?NativePromiseConstructor:this,x)}})},{"../internals/export":196,"../internals/get-built-in":210,"../internals/is-pure":239,"../internals/promise-constructor-detection":286,"../internals/promise-native-constructor":287,"../internals/promise-resolve":288}],492:[function(require,module,exports){var $=require("../internals/export"),functionApply=require("../internals/function-apply"),aCallable=require("../internals/a-callable"),anObject=require("../internals/an-object");$({target:"Reflect",stat:!0,forced:!require("../internals/fails")(function(){Reflect.apply(function(){})})},{apply:function(target,thisArgument,argumentsList){return functionApply(aCallable(target),thisArgument,anObject(argumentsList))}})},{"../internals/a-callable":117,"../internals/an-object":123,"../internals/export":196,"../internals/fails":197,"../internals/function-apply":201}],493:[function(require,module,exports){var $=require("../internals/export"),getBuiltIn=require("../internals/get-built-in"),apply=require("../internals/function-apply"),bind=require("../internals/function-bind"),aConstructor=require("../internals/a-constructor"),anObject=require("../internals/an-object"),isObject=require("../internals/is-object"),create=require("../internals/object-create"),require=require("../internals/fails"),nativeConstruct=getBuiltIn("Reflect","construct"),ObjectPrototype=Object.prototype,push=[].push,NEW_TARGET_BUG=require(function(){function F(){}return!(nativeConstruct(function(){},[],F)instanceof F)}),ARGS_BUG=!require(function(){nativeConstruct(function(){})}),getBuiltIn=NEW_TARGET_BUG||ARGS_BUG;$({target:"Reflect",stat:!0,forced:getBuiltIn,sham:getBuiltIn},{construct:function(Target,args){aConstructor(Target),anObject(args);var newTarget=arguments.length<3?Target:aConstructor(arguments[2]);if(ARGS_BUG&&!NEW_TARGET_BUG)return nativeConstruct(Target,args,newTarget);if(Target==newTarget){switch(args.length){case 0:return new Target;case 1:return new Target(args[0]);case 2:return new Target(args[0],args[1]);case 3:return new Target(args[0],args[1],args[2]);case 4:return new Target(args[0],args[1],args[2],args[3])}var $args=[null];return apply(push,$args,args),new(apply(bind,Target,$args))}$args=newTarget.prototype,newTarget=create(isObject($args)?$args:ObjectPrototype),$args=apply(Target,newTarget,args);return isObject($args)?$args:newTarget}})},{"../internals/a-constructor":118,"../internals/an-object":123,"../internals/export":196,"../internals/fails":197,"../internals/function-apply":201,"../internals/function-bind":204,"../internals/get-built-in":210,"../internals/is-object":238,"../internals/object-create":265}],494:[function(require,module,exports){var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),anObject=require("../internals/an-object"),toPropertyKey=require("../internals/to-property-key"),definePropertyModule=require("../internals/object-define-property");$({target:"Reflect",stat:!0,forced:require("../internals/fails")(function(){Reflect.defineProperty(definePropertyModule.f({},1,{value:1}),1,{value:2})}),sham:!DESCRIPTORS},{defineProperty:function(target,propertyKey,attributes){anObject(target);propertyKey=toPropertyKey(propertyKey);anObject(attributes);try{return definePropertyModule.f(target,propertyKey,attributes),!0}catch(error){return!1}}})},{"../internals/an-object":123,"../internals/descriptors":171,"../internals/export":196,"../internals/fails":197,"../internals/object-define-property":267,"../internals/to-property-key":335}],495:[function(require,module,exports){var $=require("../internals/export"),anObject=require("../internals/an-object"),getOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f;$({target:"Reflect",stat:!0},{deleteProperty:function(target,propertyKey){var descriptor=getOwnPropertyDescriptor(anObject(target),propertyKey);return!(descriptor&&!descriptor.configurable)&&delete target[propertyKey]}})},{"../internals/an-object":123,"../internals/export":196,"../internals/object-get-own-property-descriptor":268}],496:[function(require,module,exports){var $=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),anObject=require("../internals/an-object"),getOwnPropertyDescriptorModule=require("../internals/object-get-own-property-descriptor");$({target:"Reflect",stat:!0,sham:!DESCRIPTORS},{getOwnPropertyDescriptor:function(target,propertyKey){return getOwnPropertyDescriptorModule.f(anObject(target),propertyKey)}})},{"../internals/an-object":123,"../internals/descriptors":171,"../internals/export":196,"../internals/object-get-own-property-descriptor":268}],497:[function(require,module,exports){var $=require("../internals/export"),anObject=require("../internals/an-object"),objectGetPrototypeOf=require("../internals/object-get-prototype-of");$({target:"Reflect",stat:!0,sham:!require("../internals/correct-prototype-getter")},{getPrototypeOf:function(target){return objectGetPrototypeOf(anObject(target))}})},{"../internals/an-object":123,"../internals/correct-prototype-getter":158,"../internals/export":196,"../internals/object-get-prototype-of":272}],498:[function(require,module,exports){var $=require("../internals/export"),call=require("../internals/function-call"),isObject=require("../internals/is-object"),anObject=require("../internals/an-object"),isDataDescriptor=require("../internals/is-data-descriptor"),getOwnPropertyDescriptorModule=require("../internals/object-get-own-property-descriptor"),getPrototypeOf=require("../internals/object-get-prototype-of");$({target:"Reflect",stat:!0},{get:function get(target,propertyKey){var descriptor,receiver=arguments.length<3?target:arguments[2];return anObject(target)===receiver?target[propertyKey]:(descriptor=getOwnPropertyDescriptorModule.f(target,propertyKey))?isDataDescriptor(descriptor)?descriptor.value:void 0===descriptor.get?void 0:call(descriptor.get,receiver):isObject(descriptor=getPrototypeOf(target))?get(descriptor,propertyKey,receiver):void 0}})},{"../internals/an-object":123,"../internals/export":196,"../internals/function-call":205,"../internals/is-data-descriptor":234,"../internals/is-object":238,"../internals/object-get-own-property-descriptor":268,"../internals/object-get-prototype-of":272}],499:[function(require,module,exports){require("../internals/export")({target:"Reflect",stat:!0},{has:function(target,propertyKey){return propertyKey in target}})},{"../internals/export":196}],500:[function(require,module,exports){var $=require("../internals/export"),anObject=require("../internals/an-object"),$isExtensible=require("../internals/object-is-extensible");$({target:"Reflect",stat:!0},{isExtensible:function(target){return anObject(target),$isExtensible(target)}})},{"../internals/an-object":123,"../internals/export":196,"../internals/object-is-extensible":273}],501:[function(require,module,exports){require("../internals/export")({target:"Reflect",stat:!0},{ownKeys:require("../internals/own-keys")})},{"../internals/export":196,"../internals/own-keys":283}],502:[function(require,module,exports){var $=require("../internals/export"),getBuiltIn=require("../internals/get-built-in"),anObject=require("../internals/an-object");$({target:"Reflect",stat:!0,sham:!require("../internals/freezing")},{preventExtensions:function(target){anObject(target);try{var objectPreventExtensions=getBuiltIn("Object","preventExtensions");return objectPreventExtensions&&objectPreventExtensions(target),!0}catch(error){return!1}}})},{"../internals/an-object":123,"../internals/export":196,"../internals/freezing":200,"../internals/get-built-in":210}],503:[function(require,module,exports){var $=require("../internals/export"),anObject=require("../internals/an-object"),aPossiblePrototype=require("../internals/a-possible-prototype"),objectSetPrototypeOf=require("../internals/object-set-prototype-of");objectSetPrototypeOf&&$({target:"Reflect",stat:!0},{setPrototypeOf:function(target,proto){anObject(target),aPossiblePrototype(proto);try{return objectSetPrototypeOf(target,proto),!0}catch(error){return!1}}})},{"../internals/a-possible-prototype":119,"../internals/an-object":123,"../internals/export":196,"../internals/object-set-prototype-of":279}],504:[function(require,module,exports){var $=require("../internals/export"),call=require("../internals/function-call"),anObject=require("../internals/an-object"),isObject=require("../internals/is-object"),isDataDescriptor=require("../internals/is-data-descriptor"),fails=require("../internals/fails"),definePropertyModule=require("../internals/object-define-property"),getOwnPropertyDescriptorModule=require("../internals/object-get-own-property-descriptor"),getPrototypeOf=require("../internals/object-get-prototype-of"),createPropertyDescriptor=require("../internals/create-property-descriptor");$({target:"Reflect",stat:!0,forced:fails(function(){function Constructor(){}var object=definePropertyModule.f(new Constructor,"a",{configurable:!0});return!1!==Reflect.set(Constructor.prototype,"a",1,object)})},{set:function set(target,propertyKey,V){var prototype,receiver=arguments.length<4?target:arguments[3],ownDescriptor=getOwnPropertyDescriptorModule.f(anObject(target),propertyKey);if(!ownDescriptor){if(isObject(prototype=getPrototypeOf(target)))return set(prototype,propertyKey,V,receiver);ownDescriptor=createPropertyDescriptor(0)}if(isDataDescriptor(ownDescriptor)){if(!1===ownDescriptor.writable||!isObject(receiver))return!1;if(prototype=getOwnPropertyDescriptorModule.f(receiver,propertyKey)){if(prototype.get||prototype.set||!1===prototype.writable)return!1;prototype.value=V,definePropertyModule.f(receiver,propertyKey,prototype)}else definePropertyModule.f(receiver,propertyKey,createPropertyDescriptor(0,V))}else{if(void 0===(prototype=ownDescriptor.set))return!1;call(prototype,receiver,V)}return!0}})},{"../internals/an-object":123,"../internals/create-property-descriptor":162,"../internals/export":196,"../internals/fails":197,"../internals/function-call":205,"../internals/is-data-descriptor":234,"../internals/is-object":238,"../internals/object-define-property":267,"../internals/object-get-own-property-descriptor":268,"../internals/object-get-prototype-of":272}],505:[function(require,module,exports){var $=require("../internals/export"),global=require("../internals/global"),require=require("../internals/set-to-string-tag");$({global:!0},{Reflect:{}}),require(global.Reflect,"Reflect",!0)},{"../internals/export":196,"../internals/global":216,"../internals/set-to-string-tag":304}],506:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),global=require("../internals/global"),uncurryThis=require("../internals/function-uncurry-this"),isForced=require("../internals/is-forced"),inheritIfRequired=require("../internals/inherit-if-required"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),getOwnPropertyNames=require("../internals/object-get-own-property-names").f,isPrototypeOf=require("../internals/object-is-prototype-of"),isRegExp=require("../internals/is-regexp"),toString=require("../internals/to-string"),getRegExpFlags=require("../internals/regexp-get-flags"),stickyHelpers=require("../internals/regexp-sticky-helpers"),proxyAccessor=require("../internals/proxy-accessor"),defineBuiltIn=require("../internals/define-built-in"),fails=require("../internals/fails"),hasOwn=require("../internals/has-own-property"),enforceInternalState=require("../internals/internal-state").enforce,setSpecies=require("../internals/set-species"),wellKnownSymbol=require("../internals/well-known-symbol"),UNSUPPORTED_DOT_ALL=require("../internals/regexp-unsupported-dot-all"),UNSUPPORTED_NCG=require("../internals/regexp-unsupported-ncg"),MATCH=wellKnownSymbol("match"),NativeRegExp=global.RegExp,RegExpPrototype=NativeRegExp.prototype,SyntaxError=global.SyntaxError,exec=uncurryThis(RegExpPrototype.exec),charAt=uncurryThis("".charAt),replace=uncurryThis("".replace),stringIndexOf=uncurryThis("".indexOf),stringSlice=uncurryThis("".slice),IS_NCG=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,re1=/a/g,re2=/a/g,require=new NativeRegExp(re1)!==re1,MISSED_STICKY=stickyHelpers.MISSED_STICKY,UNSUPPORTED_Y=stickyHelpers.UNSUPPORTED_Y,wellKnownSymbol=DESCRIPTORS&&(!require||MISSED_STICKY||UNSUPPORTED_DOT_ALL||UNSUPPORTED_NCG||fails(function(){return re2[MATCH]=!1,NativeRegExp(re1)!=re1||NativeRegExp(re2)==re2||"/a/i"!=NativeRegExp(re1,"i")}));if(isForced("RegExp",wellKnownSymbol)){function RegExpWrapper(pattern,flags){var dotAll,sticky,thisIsRegExp=isPrototypeOf(RegExpPrototype,this),patternIsRegExp=isRegExp(pattern),flagsAreUndefined=void 0===flags,groups=[],rawPattern=pattern;if(!thisIsRegExp&&patternIsRegExp&&flagsAreUndefined&&pattern.constructor===RegExpWrapper)return pattern;if((patternIsRegExp||isPrototypeOf(RegExpPrototype,pattern))&&(pattern=pattern.source,flagsAreUndefined)&&(flags=getRegExpFlags(rawPattern)),pattern=void 0===pattern?"":toString(pattern),flags=void 0===flags?"":toString(flags),rawPattern=pattern,patternIsRegExp=flags=UNSUPPORTED_DOT_ALL&&"dotAll"in re1&&(dotAll=!!flags&&-1<stringIndexOf(flags,"s"))?replace(flags,/s/g,""):flags,MISSED_STICKY&&"sticky"in re1&&(sticky=!!flags&&-1<stringIndexOf(flags,"y"))&&UNSUPPORTED_Y&&(flags=replace(flags,/y/g,"")),UNSUPPORTED_NCG&&(pattern=(flagsAreUndefined=function(string){for(var chr,length=string.length,index=0,result="",named=[],names={},brackets=!1,ncg=!1,groupid=0,groupname="";index<=length;index++){if("\\"===(chr=charAt(string,index)))chr+=charAt(string,++index);else if("]"===chr)brackets=!1;else if(!brackets)switch(!0){case"["===chr:brackets=!0;break;case"("===chr:exec(IS_NCG,stringSlice(string,index+1))&&(index+=2,ncg=!0),result+=chr,groupid++;continue;case">"===chr&&ncg:if(""===groupname||hasOwn(names,groupname))throw new SyntaxError("Invalid capture group name");names[groupname]=!0,ncg=!(named[named.length]=[groupname,groupid]),groupname="";continue}ncg?groupname+=chr:result+=chr}return[result,named]}(pattern))[0],groups=flagsAreUndefined[1]),flagsAreUndefined=inheritIfRequired(NativeRegExp(pattern,flags),thisIsRegExp?this:RegExpPrototype,RegExpWrapper),(dotAll||sticky||groups.length)&&(flags=enforceInternalState(flagsAreUndefined),dotAll&&(flags.dotAll=!0,flags.raw=RegExpWrapper(function(string){for(var chr,length=string.length,index=0,result="",brackets=!1;index<=length;index++)"\\"===(chr=charAt(string,index))?result+=chr+charAt(string,++index):brackets||"."!==chr?("["===chr?brackets=!0:"]"===chr&&(brackets=!1),result+=chr):result+="[\\s\\S]";return result}(pattern),patternIsRegExp)),sticky&&(flags.sticky=!0),groups.length)&&(flags.groups=groups),pattern!==rawPattern)try{createNonEnumerableProperty(flagsAreUndefined,"source",""===rawPattern?"(?:)":rawPattern)}catch(error){}return flagsAreUndefined}for(var keys=getOwnPropertyNames(NativeRegExp),index=0;keys.length>index;)proxyAccessor(RegExpWrapper,NativeRegExp,keys[index++]);(RegExpPrototype.constructor=RegExpWrapper).prototype=RegExpPrototype,defineBuiltIn(global,"RegExp",RegExpWrapper,{constructor:!0})}setSpecies("RegExp")},{"../internals/create-non-enumerable-property":161,"../internals/define-built-in":167,"../internals/descriptors":171,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/has-own-property":217,"../internals/inherit-if-required":224,"../internals/internal-state":228,"../internals/is-forced":235,"../internals/is-regexp":240,"../internals/object-get-own-property-names":270,"../internals/object-is-prototype-of":274,"../internals/proxy-accessor":290,"../internals/regexp-get-flags":295,"../internals/regexp-sticky-helpers":296,"../internals/regexp-unsupported-dot-all":297,"../internals/regexp-unsupported-ncg":298,"../internals/set-species":303,"../internals/to-string":337,"../internals/well-known-symbol":353}],507:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),UNSUPPORTED_DOT_ALL=require("../internals/regexp-unsupported-dot-all"),classof=require("../internals/classof-raw"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),getInternalState=require("../internals/internal-state").get,RegExpPrototype=RegExp.prototype,$TypeError=TypeError;DESCRIPTORS&&UNSUPPORTED_DOT_ALL&&defineBuiltInAccessor(RegExpPrototype,"dotAll",{configurable:!0,get:function(){if(this!==RegExpPrototype){if("RegExp"===classof(this))return!!getInternalState(this).dotAll;throw $TypeError("Incompatible receiver, RegExp required")}}})},{"../internals/classof-raw":151,"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/internal-state":228,"../internals/regexp-unsupported-dot-all":297}],508:[function(require,module,exports){"use strict";var $=require("../internals/export"),require=require("../internals/regexp-exec");$({target:"RegExp",proto:!0,forced:/./.exec!==require},{exec:require})},{"../internals/export":196,"../internals/regexp-exec":293}],509:[function(require,module,exports){var global=require("../internals/global"),DESCRIPTORS=require("../internals/descriptors"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),regExpFlags=require("../internals/regexp-flags"),require=require("../internals/fails"),RegExp=global.RegExp,RegExpPrototype=RegExp.prototype;DESCRIPTORS&&require(function(){var INDICES_SUPPORT=!0;try{RegExp(".","d")}catch(error){INDICES_SUPPORT=!1}var key,O={},calls="",expected=INDICES_SUPPORT?"dgimsy":"gimsy",pairs={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(key in INDICES_SUPPORT&&(pairs.hasIndices="d"),pairs)!function(key,chr){Object.defineProperty(O,key,{get:function(){return calls+=chr,!0}})}(key,pairs[key]);return Object.getOwnPropertyDescriptor(RegExpPrototype,"flags").get.call(O)!==expected||calls!==expected})&&defineBuiltInAccessor(RegExpPrototype,"flags",{configurable:!0,get:regExpFlags})},{"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/fails":197,"../internals/global":216,"../internals/regexp-flags":294}],510:[function(require,module,exports){var DESCRIPTORS=require("../internals/descriptors"),MISSED_STICKY=require("../internals/regexp-sticky-helpers").MISSED_STICKY,classof=require("../internals/classof-raw"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),getInternalState=require("../internals/internal-state").get,RegExpPrototype=RegExp.prototype,$TypeError=TypeError;DESCRIPTORS&&MISSED_STICKY&&defineBuiltInAccessor(RegExpPrototype,"sticky",{configurable:!0,get:function(){if(this!==RegExpPrototype){if("RegExp"===classof(this))return!!getInternalState(this).sticky;throw $TypeError("Incompatible receiver, RegExp required")}}})},{"../internals/classof-raw":151,"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/internal-state":228,"../internals/regexp-sticky-helpers":296}],511:[function(require,module,exports){"use strict";require("../modules/es.regexp.exec");var execCalled,$=require("../internals/export"),call=require("../internals/function-call"),isCallable=require("../internals/is-callable"),anObject=require("../internals/an-object"),toString=require("../internals/to-string"),require=(execCalled=!1,(require=/[ac]/).exec=function(){return execCalled=!0,/./.exec.apply(this,arguments)},!0===require.test("abc")&&execCalled),nativeTest=/./.test;$({target:"RegExp",proto:!0,forced:!require},{test:function(S){var R=anObject(this),S=toString(S),exec=R.exec;return isCallable(exec)?null!==(exec=call(exec,R,S))&&(anObject(exec),!0):call(nativeTest,R,S)}})},{"../internals/an-object":123,"../internals/export":196,"../internals/function-call":205,"../internals/is-callable":232,"../internals/to-string":337,"../modules/es.regexp.exec":508}],512:[function(require,module,exports){"use strict";var PROPER_FUNCTION_NAME=require("../internals/function-name").PROPER,defineBuiltIn=require("../internals/define-built-in"),anObject=require("../internals/an-object"),$toString=require("../internals/to-string"),fails=require("../internals/fails"),getRegExpFlags=require("../internals/regexp-get-flags"),nativeToString=RegExp.prototype.toString,require=fails(function(){return"/a/b"!=nativeToString.call({source:"a",flags:"b"})}),fails=PROPER_FUNCTION_NAME&&"toString"!=nativeToString.name;(require||fails)&&defineBuiltIn(RegExp.prototype,"toString",function(){var R=anObject(this);return"/"+$toString(R.source)+"/"+$toString(getRegExpFlags(R))},{unsafe:!0})},{"../internals/an-object":123,"../internals/define-built-in":167,"../internals/fails":197,"../internals/function-name":206,"../internals/regexp-get-flags":295,"../internals/to-string":337}],513:[function(require,module,exports){"use strict";require("../internals/collection")("Set",function(init){return function(){return init(this,arguments.length?arguments[0]:void 0)}},require("../internals/collection-strong"))},{"../internals/collection":155,"../internals/collection-strong":153}],514:[function(require,module,exports){require("../modules/es.set.constructor")},{"../modules/es.set.constructor":513}],515:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("anchor")},{anchor:function(name){return createHTML(this,"a","name",name)}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],516:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),requireObjectCoercible=require("../internals/require-object-coercible"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),toString=require("../internals/to-string"),require=require("../internals/fails"),charAt=uncurryThis("".charAt);$({target:"String",proto:!0,forced:require(function(){return"\ud842"!=="𠮷".at(-2)})},{at:function(index){var S=toString(requireObjectCoercible(this)),len=S.length,index=toIntegerOrInfinity(index),index=0<=index?index:len+index;return index<0||len<=index?void 0:charAt(S,index)}})},{"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/require-object-coercible":299,"../internals/to-integer-or-infinity":329,"../internals/to-string":337}],517:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("big")},{big:function(){return createHTML(this,"big","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],518:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("blink")},{blink:function(){return createHTML(this,"blink","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],519:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("bold")},{bold:function(){return createHTML(this,"b","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],520:[function(require,module,exports){"use strict";var $=require("../internals/export"),codeAt=require("../internals/string-multibyte").codeAt;$({target:"String",proto:!0},{codePointAt:function(pos){return codeAt(this,pos)}})},{"../internals/export":196,"../internals/string-multibyte":310}],521:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this-clause"),getOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f,toLength=require("../internals/to-length"),toString=require("../internals/to-string"),notARegExp=require("../internals/not-a-regexp"),requireObjectCoercible=require("../internals/require-object-coercible"),correctIsRegExpLogic=require("../internals/correct-is-regexp-logic"),require=require("../internals/is-pure"),nativeEndsWith=uncurryThis("".endsWith),slice=uncurryThis("".slice),min=Math.min,uncurryThis=correctIsRegExpLogic("endsWith");$({target:"String",proto:!0,forced:!!(require||uncurryThis||!(correctIsRegExpLogic=getOwnPropertyDescriptor(String.prototype,"endsWith"))||correctIsRegExpLogic.writable)&&!uncurryThis},{endsWith:function(searchString){var that=toString(requireObjectCoercible(this)),endPosition=(notARegExp(searchString),1<arguments.length?arguments[1]:void 0),len=that.length,endPosition=void 0===endPosition?len:min(toLength(endPosition),len),len=toString(searchString);return nativeEndsWith?nativeEndsWith(that,len,endPosition):slice(that,endPosition-len.length,endPosition)===len}})},{"../internals/correct-is-regexp-logic":157,"../internals/export":196,"../internals/function-uncurry-this-clause":208,"../internals/is-pure":239,"../internals/not-a-regexp":260,"../internals/object-get-own-property-descriptor":268,"../internals/require-object-coercible":299,"../internals/to-length":330,"../internals/to-string":337}],522:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("fixed")},{fixed:function(){return createHTML(this,"tt","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],523:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("fontcolor")},{fontcolor:function(color){return createHTML(this,"font","color",color)}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],524:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("fontsize")},{fontsize:function(size){return createHTML(this,"font","size",size)}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],525:[function(require,module,exports){var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),toAbsoluteIndex=require("../internals/to-absolute-index"),$RangeError=RangeError,fromCharCode=String.fromCharCode,require=String.fromCodePoint,join=uncurryThis([].join);$({target:"String",stat:!0,arity:1,forced:!!require&&1!=require.length},{fromCodePoint:function(x){for(var code,elements=[],length=arguments.length,i=0;i<length;){if(code=+arguments[i++],toAbsoluteIndex(code,1114111)!==code)throw $RangeError(code+" is not a valid code point");elements[i]=code<65536?fromCharCode(code):fromCharCode(55296+((code-=65536)>>10),code%1024+56320)}return join(elements,"")}})},{"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/to-absolute-index":325}],526:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),notARegExp=require("../internals/not-a-regexp"),requireObjectCoercible=require("../internals/require-object-coercible"),toString=require("../internals/to-string"),require=require("../internals/correct-is-regexp-logic"),stringIndexOf=uncurryThis("".indexOf);$({target:"String",proto:!0,forced:!require("includes")},{includes:function(searchString){return!!~stringIndexOf(toString(requireObjectCoercible(this)),toString(notARegExp(searchString)),1<arguments.length?arguments[1]:void 0)}})},{"../internals/correct-is-regexp-logic":157,"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/not-a-regexp":260,"../internals/require-object-coercible":299,"../internals/to-string":337}],527:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("italics")},{italics:function(){return createHTML(this,"i","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],528:[function(require,module,exports){"use strict";var charAt=require("../internals/string-multibyte").charAt,toString=require("../internals/to-string"),InternalStateModule=require("../internals/internal-state"),defineIterator=require("../internals/iterator-define"),createIterResultObject=require("../internals/create-iter-result-object"),setInternalState=InternalStateModule.set,getInternalState=InternalStateModule.getterFor("String Iterator");defineIterator(String,"String",function(iterated){setInternalState(this,{type:"String Iterator",string:toString(iterated),index:0})},function(){var state=getInternalState(this),string=state.string,index=state.index;return index>=string.length?createIterResultObject(void 0,!0):(string=charAt(string,index),state.index+=string.length,createIterResultObject(string,!1))})},{"../internals/create-iter-result-object":160,"../internals/internal-state":228,"../internals/iterator-define":245,"../internals/string-multibyte":310,"../internals/to-string":337}],529:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("link")},{link:function(url){return createHTML(this,"a","href",url)}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],530:[function(require,module,exports){"use strict";function $matchAll(string){var R=anObject(this),string=toString(string),C=speciesConstructor(R,RegExp),flags=toString(getRegExpFlags(R)),C=new C(C===RegExp?R.source:R,flags),$global=!!~stringIndexOf(flags,"g"),flags=!!~stringIndexOf(flags,"u");return C.lastIndex=toLength(R.lastIndex),new $RegExpStringIterator(C,string,$global,flags)}var $=require("../internals/export"),call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this-clause"),createIteratorConstructor=require("../internals/iterator-create-constructor"),createIterResultObject=require("../internals/create-iter-result-object"),requireObjectCoercible=require("../internals/require-object-coercible"),toLength=require("../internals/to-length"),toString=require("../internals/to-string"),anObject=require("../internals/an-object"),isNullOrUndefined=require("../internals/is-null-or-undefined"),classof=require("../internals/classof-raw"),isRegExp=require("../internals/is-regexp"),getRegExpFlags=require("../internals/regexp-get-flags"),getMethod=require("../internals/get-method"),defineBuiltIn=require("../internals/define-built-in"),fails=require("../internals/fails"),wellKnownSymbol=require("../internals/well-known-symbol"),speciesConstructor=require("../internals/species-constructor"),advanceStringIndex=require("../internals/advance-string-index"),regExpExec=require("../internals/regexp-exec-abstract"),InternalStateModule=require("../internals/internal-state"),IS_PURE=require("../internals/is-pure"),MATCH_ALL=wellKnownSymbol("matchAll"),setInternalState=InternalStateModule.set,getInternalState=InternalStateModule.getterFor("RegExp String Iterator"),require=RegExp.prototype,$TypeError=TypeError,stringIndexOf=uncurryThis("".indexOf),nativeMatchAll=uncurryThis("".matchAll),WORKS_WITH_NON_GLOBAL_REGEX=!!nativeMatchAll&&!fails(function(){nativeMatchAll("a",/./)}),$RegExpStringIterator=createIteratorConstructor(function(regexp,string,$global,fullUnicode){setInternalState(this,{type:"RegExp String Iterator",regexp:regexp,string:string,global:$global,unicode:fullUnicode,done:!1})},"RegExp String",function(){var R,S,match,state=getInternalState(this);return state.done?createIterResultObject(void 0,!0):(R=state.regexp,S=state.string,null===(match=regExpExec(R,S))?(state.done=!0,createIterResultObject(void 0,!0)):(state.global?""===toString(match[0])&&(R.lastIndex=advanceStringIndex(S,toLength(R.lastIndex),state.unicode)):state.done=!0,createIterResultObject(match,!1)))});$({target:"String",proto:!0,forced:WORKS_WITH_NON_GLOBAL_REGEX},{matchAll:function(regexp){var flags,O=requireObjectCoercible(this);if(isNullOrUndefined(regexp)){if(WORKS_WITH_NON_GLOBAL_REGEX)return nativeMatchAll(O,regexp)}else{if(isRegExp(regexp)&&(flags=toString(requireObjectCoercible(getRegExpFlags(regexp))),!~stringIndexOf(flags,"g")))throw $TypeError("`.matchAll` does not allow non-global regexes");if(WORKS_WITH_NON_GLOBAL_REGEX)return nativeMatchAll(O,regexp);if(flags=void 0===(flags=getMethod(regexp,MATCH_ALL))&&IS_PURE&&"RegExp"==classof(regexp)?$matchAll:flags)return call(flags,regexp,O)}return flags=toString(O),O=new RegExp(regexp,"g"),IS_PURE?call($matchAll,O,flags):O[MATCH_ALL](flags)}}),IS_PURE||MATCH_ALL in require||defineBuiltIn(require,MATCH_ALL,$matchAll)},{"../internals/advance-string-index":121,"../internals/an-object":123,"../internals/classof-raw":151,"../internals/create-iter-result-object":160,"../internals/define-built-in":167,"../internals/export":196,"../internals/fails":197,"../internals/function-call":205,"../internals/function-uncurry-this-clause":208,"../internals/get-method":214,"../internals/internal-state":228,"../internals/is-null-or-undefined":237,"../internals/is-pure":239,"../internals/is-regexp":240,"../internals/iterator-create-constructor":244,"../internals/regexp-exec-abstract":292,"../internals/regexp-get-flags":295,"../internals/require-object-coercible":299,"../internals/species-constructor":308,"../internals/to-length":330,"../internals/to-string":337,"../internals/well-known-symbol":353}],531:[function(require,module,exports){"use strict";var call=require("../internals/function-call"),fixRegExpWellKnownSymbolLogic=require("../internals/fix-regexp-well-known-symbol-logic"),anObject=require("../internals/an-object"),isNullOrUndefined=require("../internals/is-null-or-undefined"),toLength=require("../internals/to-length"),toString=require("../internals/to-string"),requireObjectCoercible=require("../internals/require-object-coercible"),getMethod=require("../internals/get-method"),advanceStringIndex=require("../internals/advance-string-index"),regExpExec=require("../internals/regexp-exec-abstract");fixRegExpWellKnownSymbolLogic("match",function(MATCH,nativeMatch,maybeCallNative){return[function(regexp){var O=requireObjectCoercible(this),matcher=isNullOrUndefined(regexp)?void 0:getMethod(regexp,MATCH);return matcher?call(matcher,regexp,O):new RegExp(regexp)[MATCH](toString(O))},function(string){var rx=anObject(this),S=toString(string),string=maybeCallNative(nativeMatch,rx,S);if(string.done)return string.value;if(!rx.global)return regExpExec(rx,S);for(var fullUnicode=rx.unicode,A=[],n=rx.lastIndex=0;null!==(result=regExpExec(rx,S));){var result=toString(result[0]);""===(A[n]=result)&&(rx.lastIndex=advanceStringIndex(S,toLength(rx.lastIndex),fullUnicode)),n++}return 0===n?null:A}]})},{"../internals/advance-string-index":121,"../internals/an-object":123,"../internals/fix-regexp-well-known-symbol-logic":198,"../internals/function-call":205,"../internals/get-method":214,"../internals/is-null-or-undefined":237,"../internals/regexp-exec-abstract":292,"../internals/require-object-coercible":299,"../internals/to-length":330,"../internals/to-string":337}],532:[function(require,module,exports){"use strict";var $=require("../internals/export"),$padEnd=require("../internals/string-pad").end;$({target:"String",proto:!0,forced:require("../internals/string-pad-webkit-bug")},{padEnd:function(maxLength){return $padEnd(this,maxLength,1<arguments.length?arguments[1]:void 0)}})},{"../internals/export":196,"../internals/string-pad":312,"../internals/string-pad-webkit-bug":311}],533:[function(require,module,exports){"use strict";var $=require("../internals/export"),$padStart=require("../internals/string-pad").start;$({target:"String",proto:!0,forced:require("../internals/string-pad-webkit-bug")},{padStart:function(maxLength){return $padStart(this,maxLength,1<arguments.length?arguments[1]:void 0)}})},{"../internals/export":196,"../internals/string-pad":312,"../internals/string-pad-webkit-bug":311}],534:[function(require,module,exports){var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),toIndexedObject=require("../internals/to-indexed-object"),toObject=require("../internals/to-object"),toString=require("../internals/to-string"),lengthOfArrayLike=require("../internals/length-of-array-like"),push=uncurryThis([].push),join=uncurryThis([].join);$({target:"String",stat:!0},{raw:function(template){var rawTemplate=toIndexedObject(toObject(template).raw),literalSegments=lengthOfArrayLike(rawTemplate);if(!literalSegments)return"";for(var argumentsLength=arguments.length,elements=[],i=0;;){if(push(elements,toString(rawTemplate[i++])),i===literalSegments)return join(elements,"");i<argumentsLength&&push(elements,toString(arguments[i]))}}})},{"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/length-of-array-like":248,"../internals/to-indexed-object":328,"../internals/to-object":331,"../internals/to-string":337}],535:[function(require,module,exports){require("../internals/export")({target:"String",proto:!0},{repeat:require("../internals/string-repeat")})},{"../internals/export":196,"../internals/string-repeat":314}],536:[function(require,module,exports){"use strict";function stringIndexOf(string,searchValue,fromIndex){return fromIndex>string.length?-1:""===searchValue?fromIndex:indexOf(string,searchValue,fromIndex)}var $=require("../internals/export"),call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this"),requireObjectCoercible=require("../internals/require-object-coercible"),isCallable=require("../internals/is-callable"),isNullOrUndefined=require("../internals/is-null-or-undefined"),isRegExp=require("../internals/is-regexp"),toString=require("../internals/to-string"),getMethod=require("../internals/get-method"),getRegExpFlags=require("../internals/regexp-get-flags"),getSubstitution=require("../internals/get-substitution"),wellKnownSymbol=require("../internals/well-known-symbol"),IS_PURE=require("../internals/is-pure"),REPLACE=wellKnownSymbol("replace"),$TypeError=TypeError,indexOf=uncurryThis("".indexOf),replace=uncurryThis("".replace),stringSlice=uncurryThis("".slice),max=Math.max;$({target:"String",proto:!0},{replaceAll:function(searchValue,replaceValue){var IS_REG_EXP,flags,string,searchString,functionalReplace,searchLength,advanceBy,replacement,O=requireObjectCoercible(this),position=0,endOfLastMatch=0,result="";if(!isNullOrUndefined(searchValue)){if((IS_REG_EXP=isRegExp(searchValue))&&(flags=toString(requireObjectCoercible(getRegExpFlags(searchValue))),!~indexOf(flags,"g")))throw $TypeError("`.replaceAll` does not allow non-global regexes");if(flags=getMethod(searchValue,REPLACE))return call(flags,searchValue,O,replaceValue);if(IS_PURE&&IS_REG_EXP)return replace(toString(O),searchValue,replaceValue)}for(string=toString(O),searchString=toString(searchValue),(functionalReplace=isCallable(replaceValue))||(replaceValue=toString(replaceValue)),searchLength=searchString.length,advanceBy=max(1,searchLength),position=stringIndexOf(string,searchString,0);-1!==position;)replacement=functionalReplace?toString(replaceValue(searchString,position,string)):getSubstitution(searchString,string,position,[],void 0,replaceValue),result+=stringSlice(string,endOfLastMatch,position)+replacement,endOfLastMatch=position+searchLength,position=stringIndexOf(string,searchString,position+advanceBy);return endOfLastMatch<string.length&&(result+=stringSlice(string,endOfLastMatch)),result}})},{"../internals/export":196,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/get-method":214,"../internals/get-substitution":215,"../internals/is-callable":232,"../internals/is-null-or-undefined":237,"../internals/is-pure":239,"../internals/is-regexp":240,"../internals/regexp-get-flags":295,"../internals/require-object-coercible":299,"../internals/to-string":337,"../internals/well-known-symbol":353}],537:[function(require,module,exports){"use strict";var apply=require("../internals/function-apply"),call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this"),fixRegExpWellKnownSymbolLogic=require("../internals/fix-regexp-well-known-symbol-logic"),fails=require("../internals/fails"),anObject=require("../internals/an-object"),isCallable=require("../internals/is-callable"),isNullOrUndefined=require("../internals/is-null-or-undefined"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),toLength=require("../internals/to-length"),toString=require("../internals/to-string"),requireObjectCoercible=require("../internals/require-object-coercible"),advanceStringIndex=require("../internals/advance-string-index"),getMethod=require("../internals/get-method"),getSubstitution=require("../internals/get-substitution"),regExpExec=require("../internals/regexp-exec-abstract"),REPLACE=require("../internals/well-known-symbol")("replace"),max=Math.max,min=Math.min,concat=uncurryThis([].concat),push=uncurryThis([].push),stringIndexOf=uncurryThis("".indexOf),stringSlice=uncurryThis("".slice),require="$0"==="a".replace(/./,"$0"),REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE=!!/./[REPLACE]&&""===/./[REPLACE]("a","$0");fixRegExpWellKnownSymbolLogic("replace",function(_,nativeReplace,maybeCallNative){var UNSAFE_SUBSTITUTE=REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE?"$":"$0";return[function(searchValue,replaceValue){var O=requireObjectCoercible(this),replacer=isNullOrUndefined(searchValue)?void 0:getMethod(searchValue,REPLACE);return replacer?call(replacer,searchValue,O,replaceValue):call(nativeReplace,toString(O),searchValue,replaceValue)},function(string,replaceValue){var rx=anObject(this),S=toString(string);if("string"==typeof replaceValue&&-1===stringIndexOf(replaceValue,UNSAFE_SUBSTITUTE)&&-1===stringIndexOf(replaceValue,"$<")){string=maybeCallNative(nativeReplace,rx,S,replaceValue);if(string.done)return string.value}for(var fullUnicode,functionalReplace=isCallable(replaceValue),global=(functionalReplace||(replaceValue=toString(replaceValue)),rx.global),results=(global&&(fullUnicode=rx.unicode,rx.lastIndex=0),[]);null!==(result=regExpExec(rx,S))&&(push(results,result),global);)""===toString(result[0])&&(rx.lastIndex=advanceStringIndex(S,toLength(rx.lastIndex),fullUnicode));for(var it,accumulatedResult="",nextSourcePosition=0,i=0;i<results.length;i++){for(var result,matched=toString((result=results[i])[0]),position=max(min(toIntegerOrInfinity(result.index),S.length),0),captures=[],j=1;j<result.length;j++)push(captures,void 0===(it=result[j])?it:String(it));var namedCaptures=result.groups,replacerArgs=functionalReplace?(replacerArgs=concat([matched],captures,position,S),void 0!==namedCaptures&&push(replacerArgs,namedCaptures),toString(apply(replaceValue,void 0,replacerArgs))):getSubstitution(matched,S,position,captures,namedCaptures,replaceValue);nextSourcePosition<=position&&(accumulatedResult+=stringSlice(S,nextSourcePosition,position)+replacerArgs,nextSourcePosition=position+matched.length)}return accumulatedResult+stringSlice(S,nextSourcePosition)}]},!!fails(function(){var re=/./;return re.exec=function(){var result=[];return result.groups={a:"7"},result},"7"!=="".replace(re,"$<a>")})||!require||REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE)},{"../internals/advance-string-index":121,"../internals/an-object":123,"../internals/fails":197,"../internals/fix-regexp-well-known-symbol-logic":198,"../internals/function-apply":201,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/get-method":214,"../internals/get-substitution":215,"../internals/is-callable":232,"../internals/is-null-or-undefined":237,"../internals/regexp-exec-abstract":292,"../internals/require-object-coercible":299,"../internals/to-integer-or-infinity":329,"../internals/to-length":330,"../internals/to-string":337,"../internals/well-known-symbol":353}],538:[function(require,module,exports){"use strict";var call=require("../internals/function-call"),fixRegExpWellKnownSymbolLogic=require("../internals/fix-regexp-well-known-symbol-logic"),anObject=require("../internals/an-object"),isNullOrUndefined=require("../internals/is-null-or-undefined"),requireObjectCoercible=require("../internals/require-object-coercible"),sameValue=require("../internals/same-value"),toString=require("../internals/to-string"),getMethod=require("../internals/get-method"),regExpExec=require("../internals/regexp-exec-abstract");fixRegExpWellKnownSymbolLogic("search",function(SEARCH,nativeSearch,maybeCallNative){return[function(regexp){var O=requireObjectCoercible(this),searcher=isNullOrUndefined(regexp)?void 0:getMethod(regexp,SEARCH);return searcher?call(searcher,regexp,O):new RegExp(regexp)[SEARCH](toString(O))},function(string){var rx=anObject(this),string=toString(string),res=maybeCallNative(nativeSearch,rx,string);return res.done?res.value:(res=rx.lastIndex,sameValue(res,0)||(rx.lastIndex=0),string=regExpExec(rx,string),sameValue(rx.lastIndex,res)||(rx.lastIndex=res),null===string?-1:string.index)}]})},{"../internals/an-object":123,"../internals/fix-regexp-well-known-symbol-logic":198,"../internals/function-call":205,"../internals/get-method":214,"../internals/is-null-or-undefined":237,"../internals/regexp-exec-abstract":292,"../internals/require-object-coercible":299,"../internals/same-value":300,"../internals/to-string":337}],539:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("small")},{small:function(){return createHTML(this,"small","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],540:[function(require,module,exports){"use strict";var apply=require("../internals/function-apply"),call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this"),fixRegExpWellKnownSymbolLogic=require("../internals/fix-regexp-well-known-symbol-logic"),anObject=require("../internals/an-object"),isNullOrUndefined=require("../internals/is-null-or-undefined"),isRegExp=require("../internals/is-regexp"),requireObjectCoercible=require("../internals/require-object-coercible"),speciesConstructor=require("../internals/species-constructor"),advanceStringIndex=require("../internals/advance-string-index"),toLength=require("../internals/to-length"),toString=require("../internals/to-string"),getMethod=require("../internals/get-method"),arraySlice=require("../internals/array-slice-simple"),callRegExpExec=require("../internals/regexp-exec-abstract"),regexpExec=require("../internals/regexp-exec"),stickyHelpers=require("../internals/regexp-sticky-helpers"),require=require("../internals/fails"),UNSUPPORTED_Y=stickyHelpers.UNSUPPORTED_Y,min=Math.min,$push=[].push,exec=uncurryThis(/./.exec),push=uncurryThis($push),stringSlice=uncurryThis("".slice);fixRegExpWellKnownSymbolLogic("split",function(SPLIT,nativeSplit,maybeCallNative){var internalSplit="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||1<".".split(/()()/).length||"".split(/.?/).length?function(separator,limit){var string=toString(requireObjectCoercible(this)),lim=void 0===limit?4294967295:limit>>>0;if(0==lim)return[];if(void 0===separator)return[string];if(!isRegExp(separator))return call(nativeSplit,string,separator,lim);for(var match,lastIndex,lastLength,output=[],limit=(separator.ignoreCase?"i":"")+(separator.multiline?"m":"")+(separator.unicode?"u":"")+(separator.sticky?"y":""),lastLastIndex=0,separatorCopy=new RegExp(separator.source,limit+"g");(match=call(regexpExec,separatorCopy,string))&&!(lastLastIndex<(lastIndex=separatorCopy.lastIndex)&&(push(output,stringSlice(string,lastLastIndex,match.index)),1<match.length&&match.index<string.length&&apply($push,output,arraySlice(match,1)),lastLength=match[0].length,lastLastIndex=lastIndex,lim<=output.length));)separatorCopy.lastIndex===match.index&&separatorCopy.lastIndex++;return lastLastIndex===string.length?!lastLength&&exec(separatorCopy,"")||push(output,""):push(output,stringSlice(string,lastLastIndex)),lim<output.length?arraySlice(output,0,lim):output}:"0".split(void 0,0).length?function(separator,limit){return void 0===separator&&0===limit?[]:call(nativeSplit,this,separator,limit)}:nativeSplit;return[function(separator,limit){var O=requireObjectCoercible(this),splitter=isNullOrUndefined(separator)?void 0:getMethod(separator,SPLIT);return splitter?call(splitter,separator,O,limit):call(internalSplit,toString(O),separator,limit)},function(string,limit){var rx=anObject(this),S=toString(string),string=maybeCallNative(internalSplit,rx,S,limit,internalSplit!==nativeSplit);if(string.done)return string.value;var string=speciesConstructor(rx,RegExp),unicodeMatching=rx.unicode,flags=(rx.ignoreCase?"i":"")+(rx.multiline?"m":"")+(rx.unicode?"u":"")+(UNSUPPORTED_Y?"g":"y"),splitter=new string(UNSUPPORTED_Y?"^(?:"+rx.source+")":rx,flags),lim=void 0===limit?4294967295:limit>>>0;if(0==lim)return[];if(0===S.length)return null===callRegExpExec(splitter,S)?[S]:[];for(var p=0,q=0,A=[];q<S.length;){splitter.lastIndex=UNSUPPORTED_Y?0:q;var e,z=callRegExpExec(splitter,UNSUPPORTED_Y?stringSlice(S,q):S);if(null===z||(e=min(toLength(splitter.lastIndex+(UNSUPPORTED_Y?q:0)),S.length))===p)q=advanceStringIndex(S,q,unicodeMatching);else{if(push(A,stringSlice(S,p,q)),A.length===lim)return A;for(var i=1;i<=z.length-1;i++)if(push(A,z[i]),A.length===lim)return A;q=p=e}}return push(A,stringSlice(S,p)),A}]},!!require(function(){var re=/(?:)/,originalExec=re.exec,re=(re.exec=function(){return originalExec.apply(this,arguments)},"ab".split(re));return 2!==re.length||"a"!==re[0]||"b"!==re[1]}),UNSUPPORTED_Y)},{"../internals/advance-string-index":121,"../internals/an-object":123,"../internals/array-slice-simple":141,"../internals/fails":197,"../internals/fix-regexp-well-known-symbol-logic":198,"../internals/function-apply":201,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/get-method":214,"../internals/is-null-or-undefined":237,"../internals/is-regexp":240,"../internals/regexp-exec":293,"../internals/regexp-exec-abstract":292,"../internals/regexp-sticky-helpers":296,"../internals/require-object-coercible":299,"../internals/species-constructor":308,"../internals/to-length":330,"../internals/to-string":337}],541:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this-clause"),getOwnPropertyDescriptor=require("../internals/object-get-own-property-descriptor").f,toLength=require("../internals/to-length"),toString=require("../internals/to-string"),notARegExp=require("../internals/not-a-regexp"),requireObjectCoercible=require("../internals/require-object-coercible"),correctIsRegExpLogic=require("../internals/correct-is-regexp-logic"),require=require("../internals/is-pure"),nativeStartsWith=uncurryThis("".startsWith),stringSlice=uncurryThis("".slice),min=Math.min,uncurryThis=correctIsRegExpLogic("startsWith");$({target:"String",proto:!0,forced:!!(require||uncurryThis||!(correctIsRegExpLogic=getOwnPropertyDescriptor(String.prototype,"startsWith"))||correctIsRegExpLogic.writable)&&!uncurryThis},{startsWith:function(searchString){var that=toString(requireObjectCoercible(this)),index=(notARegExp(searchString),toLength(min(1<arguments.length?arguments[1]:void 0,that.length))),searchString=toString(searchString);return nativeStartsWith?nativeStartsWith(that,searchString,index):stringSlice(that,index,index+searchString.length)===searchString}})},{"../internals/correct-is-regexp-logic":157,"../internals/export":196,"../internals/function-uncurry-this-clause":208,"../internals/is-pure":239,"../internals/not-a-regexp":260,"../internals/object-get-own-property-descriptor":268,"../internals/require-object-coercible":299,"../internals/to-length":330,"../internals/to-string":337}],542:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("strike")},{strike:function(){return createHTML(this,"strike","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],543:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("sub")},{sub:function(){return createHTML(this,"sub","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],544:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),requireObjectCoercible=require("../internals/require-object-coercible"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),toString=require("../internals/to-string"),stringSlice=uncurryThis("".slice),max=Math.max,min=Math.min;$({target:"String",proto:!0,forced:!"".substr||"b"!=="ab".substr(-1)},{substr:function(start,length){var that=toString(requireObjectCoercible(this)),size=that.length,start=toIntegerOrInfinity(start);return(start=start===1/0?0:start)<0&&(start=max(size+start,0)),(length=void 0===length?size:toIntegerOrInfinity(length))<=0||length===1/0||(length=min(start+length,size))<=start?"":stringSlice(that,start,length)}})},{"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/require-object-coercible":299,"../internals/to-integer-or-infinity":329,"../internals/to-string":337}],545:[function(require,module,exports){"use strict";var $=require("../internals/export"),createHTML=require("../internals/create-html");$({target:"String",proto:!0,forced:require("../internals/string-html-forced")("sup")},{sup:function(){return createHTML(this,"sup","","")}})},{"../internals/create-html":159,"../internals/export":196,"../internals/string-html-forced":309}],546:[function(require,module,exports){require("../modules/es.string.trim-right");var $=require("../internals/export"),require=require("../internals/string-trim-end");$({target:"String",proto:!0,name:"trimEnd",forced:"".trimEnd!==require},{trimEnd:require})},{"../internals/export":196,"../internals/string-trim-end":315,"../modules/es.string.trim-right":548}],547:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/string-trim-start");$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==require},{trimLeft:require})},{"../internals/export":196,"../internals/string-trim-start":317}],548:[function(require,module,exports){var $=require("../internals/export"),require=require("../internals/string-trim-end");$({target:"String",proto:!0,name:"trimEnd",forced:"".trimRight!==require},{trimRight:require})},{"../internals/export":196,"../internals/string-trim-end":315}],549:[function(require,module,exports){require("../modules/es.string.trim-left");var $=require("../internals/export"),require=require("../internals/string-trim-start");$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==require},{trimStart:require})},{"../internals/export":196,"../internals/string-trim-start":317,"../modules/es.string.trim-left":547}],550:[function(require,module,exports){"use strict";var $=require("../internals/export"),$trim=require("../internals/string-trim").trim;$({target:"String",proto:!0,forced:require("../internals/string-trim-forced")("trim")},{trim:function(){return $trim(this)}})},{"../internals/export":196,"../internals/string-trim":318,"../internals/string-trim-forced":316}],551:[function(require,module,exports){require("../internals/well-known-symbol-define")("asyncIterator")},{"../internals/well-known-symbol-define":351}],552:[function(require,module,exports){"use strict";function wrap(tag,description){var symbol=AllSymbols[tag]=nativeObjectCreate(SymbolPrototype);return setInternalState(symbol,{type:SYMBOL,tag:tag,description:description}),DESCRIPTORS||(symbol.description=description),symbol}function $defineProperty(O,P,Attributes){return O===ObjectPrototype&&$defineProperty(ObjectPrototypeSymbols,P,Attributes),anObject(O),P=toPropertyKey(P),anObject(Attributes),(hasOwn(AllSymbols,P)?(Attributes.enumerable?(hasOwn(O,HIDDEN)&&O[HIDDEN][P]&&(O[HIDDEN][P]=!1),Attributes=nativeObjectCreate(Attributes,{enumerable:createPropertyDescriptor(0,!1)})):(hasOwn(O,HIDDEN)||nativeDefineProperty(O,HIDDEN,createPropertyDescriptor(1,{})),O[HIDDEN][P]=!0),setSymbolDescriptor):nativeDefineProperty)(O,P,Attributes)}function $defineProperties(O,Properties){anObject(O);var properties=toIndexedObject(Properties),Properties=objectKeys(properties).concat($getOwnPropertySymbols(properties));return $forEach(Properties,function(key){DESCRIPTORS&&!call($propertyIsEnumerable,properties,key)||$defineProperty(O,key,properties[key])}),O}function $propertyIsEnumerable(V){var V=toPropertyKey(V),enumerable=call(nativePropertyIsEnumerable,this,V);return!(this===ObjectPrototype&&hasOwn(AllSymbols,V)&&!hasOwn(ObjectPrototypeSymbols,V))&&(!(enumerable||!hasOwn(this,V)||!hasOwn(AllSymbols,V)||hasOwn(this,HIDDEN)&&this[HIDDEN][V])||enumerable)}function $getOwnPropertyDescriptor(O,P){var descriptor,O=toIndexedObject(O),P=toPropertyKey(P);if(O!==ObjectPrototype||!hasOwn(AllSymbols,P)||hasOwn(ObjectPrototypeSymbols,P))return!(descriptor=nativeGetOwnPropertyDescriptor(O,P))||!hasOwn(AllSymbols,P)||hasOwn(O,HIDDEN)&&O[HIDDEN][P]||(descriptor.enumerable=!0),descriptor}function $getOwnPropertyNames(O){var O=nativeGetOwnPropertyNames(toIndexedObject(O)),result=[];return $forEach(O,function(key){hasOwn(AllSymbols,key)||hasOwn(hiddenKeys,key)||push(result,key)}),result}function $getOwnPropertySymbols(O){var IS_OBJECT_PROTOTYPE=O===ObjectPrototype,O=nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE?ObjectPrototypeSymbols:toIndexedObject(O)),result=[];return $forEach(O,function(key){!hasOwn(AllSymbols,key)||IS_OBJECT_PROTOTYPE&&!hasOwn(ObjectPrototype,key)||push(result,AllSymbols[key])}),result}var $=require("../internals/export"),global=require("../internals/global"),call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this"),IS_PURE=require("../internals/is-pure"),DESCRIPTORS=require("../internals/descriptors"),NATIVE_SYMBOL=require("../internals/symbol-constructor-detection"),fails=require("../internals/fails"),hasOwn=require("../internals/has-own-property"),isPrototypeOf=require("../internals/object-is-prototype-of"),anObject=require("../internals/an-object"),toIndexedObject=require("../internals/to-indexed-object"),toPropertyKey=require("../internals/to-property-key"),$toString=require("../internals/to-string"),createPropertyDescriptor=require("../internals/create-property-descriptor"),nativeObjectCreate=require("../internals/object-create"),objectKeys=require("../internals/object-keys"),getOwnPropertyNamesModule=require("../internals/object-get-own-property-names"),getOwnPropertyNamesExternal=require("../internals/object-get-own-property-names-external"),getOwnPropertySymbolsModule=require("../internals/object-get-own-property-symbols"),getOwnPropertyDescriptorModule=require("../internals/object-get-own-property-descriptor"),definePropertyModule=require("../internals/object-define-property"),definePropertiesModule=require("../internals/object-define-properties"),propertyIsEnumerableModule=require("../internals/object-property-is-enumerable"),defineBuiltIn=require("../internals/define-built-in"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),shared=require("../internals/shared"),sharedKey=require("../internals/shared-key"),hiddenKeys=require("../internals/hidden-keys"),uid=require("../internals/uid"),wellKnownSymbol=require("../internals/well-known-symbol"),wrappedWellKnownSymbolModule=require("../internals/well-known-symbol-wrapped"),defineWellKnownSymbol=require("../internals/well-known-symbol-define"),defineSymbolToPrimitive=require("../internals/symbol-define-to-primitive"),setToStringTag=require("../internals/set-to-string-tag"),InternalStateModule=require("../internals/internal-state"),$forEach=require("../internals/array-iteration").forEach,HIDDEN=sharedKey("hidden"),SYMBOL="Symbol",setInternalState=InternalStateModule.set,getInternalState=InternalStateModule.getterFor(SYMBOL),ObjectPrototype=Object.prototype,require=global.Symbol,SymbolPrototype=require&&require.prototype,TypeError=global.TypeError,sharedKey=global.QObject,nativeGetOwnPropertyDescriptor=getOwnPropertyDescriptorModule.f,nativeDefineProperty=definePropertyModule.f,nativeGetOwnPropertyNames=getOwnPropertyNamesExternal.f,nativePropertyIsEnumerable=propertyIsEnumerableModule.f,push=uncurryThis([].push),AllSymbols=shared("symbols"),ObjectPrototypeSymbols=shared("op-symbols"),InternalStateModule=shared("wks"),USE_SETTER=!sharedKey||!sharedKey.prototype||!sharedKey.prototype.findChild,setSymbolDescriptor=DESCRIPTORS&&fails(function(){return 7!=nativeObjectCreate(nativeDefineProperty({},"a",{get:function(){return nativeDefineProperty(this,"a",{value:7}).a}})).a})?function(O,P,Attributes){var ObjectPrototypeDescriptor=nativeGetOwnPropertyDescriptor(ObjectPrototype,P);ObjectPrototypeDescriptor&&delete ObjectPrototype[P],nativeDefineProperty(O,P,Attributes),ObjectPrototypeDescriptor&&O!==ObjectPrototype&&nativeDefineProperty(ObjectPrototype,P,ObjectPrototypeDescriptor)}:nativeDefineProperty;NATIVE_SYMBOL||(defineBuiltIn(SymbolPrototype=(require=function(){if(isPrototypeOf(SymbolPrototype,this))throw TypeError("Symbol is not a constructor");var description=arguments.length&&void 0!==arguments[0]?$toString(arguments[0]):void 0,tag=uid(description),setter=function(value){this===ObjectPrototype&&call(setter,ObjectPrototypeSymbols,value),hasOwn(this,HIDDEN)&&hasOwn(this[HIDDEN],tag)&&(this[HIDDEN][tag]=!1),setSymbolDescriptor(this,tag,createPropertyDescriptor(1,value))};return DESCRIPTORS&&USE_SETTER&&setSymbolDescriptor(ObjectPrototype,tag,{configurable:!0,set:setter}),wrap(tag,description)}).prototype,"toString",function(){return getInternalState(this).tag}),defineBuiltIn(require,"withoutSetter",function(description){return wrap(uid(description),description)}),propertyIsEnumerableModule.f=$propertyIsEnumerable,definePropertyModule.f=$defineProperty,definePropertiesModule.f=$defineProperties,getOwnPropertyDescriptorModule.f=$getOwnPropertyDescriptor,getOwnPropertyNamesModule.f=getOwnPropertyNamesExternal.f=$getOwnPropertyNames,getOwnPropertySymbolsModule.f=$getOwnPropertySymbols,wrappedWellKnownSymbolModule.f=function(name){return wrap(wellKnownSymbol(name),name)},DESCRIPTORS&&(defineBuiltInAccessor(SymbolPrototype,"description",{configurable:!0,get:function(){return getInternalState(this).description}}),IS_PURE||defineBuiltIn(ObjectPrototype,"propertyIsEnumerable",$propertyIsEnumerable,{unsafe:!0}))),$({global:!0,constructor:!0,wrap:!0,forced:!NATIVE_SYMBOL,sham:!NATIVE_SYMBOL},{Symbol:require}),$forEach(objectKeys(InternalStateModule),function(name){defineWellKnownSymbol(name)}),$({target:SYMBOL,stat:!0,forced:!NATIVE_SYMBOL},{useSetter:function(){USE_SETTER=!0},useSimple:function(){USE_SETTER=!1}}),$({target:"Object",stat:!0,forced:!NATIVE_SYMBOL,sham:!DESCRIPTORS},{create:function(O,Properties){return void 0===Properties?nativeObjectCreate(O):$defineProperties(nativeObjectCreate(O),Properties)},defineProperty:$defineProperty,defineProperties:$defineProperties,getOwnPropertyDescriptor:$getOwnPropertyDescriptor}),$({target:"Object",stat:!0,forced:!NATIVE_SYMBOL},{getOwnPropertyNames:$getOwnPropertyNames}),defineSymbolToPrimitive(),setToStringTag(require,SYMBOL),hiddenKeys[HIDDEN]=!0},{"../internals/an-object":123,"../internals/array-iteration":135,"../internals/create-property-descriptor":162,"../internals/define-built-in":167,"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/export":196,"../internals/fails":197,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/has-own-property":217,"../internals/hidden-keys":218,"../internals/internal-state":228,"../internals/is-pure":239,"../internals/object-create":265,"../internals/object-define-properties":266,"../internals/object-define-property":267,"../internals/object-get-own-property-descriptor":268,"../internals/object-get-own-property-names":270,"../internals/object-get-own-property-names-external":269,"../internals/object-get-own-property-symbols":271,"../internals/object-is-prototype-of":274,"../internals/object-keys":276,"../internals/object-property-is-enumerable":277,"../internals/set-to-string-tag":304,"../internals/shared":307,"../internals/shared-key":305,"../internals/symbol-constructor-detection":320,"../internals/symbol-define-to-primitive":321,"../internals/to-indexed-object":328,"../internals/to-property-key":335,"../internals/to-string":337,"../internals/uid":345,"../internals/well-known-symbol":353,"../internals/well-known-symbol-define":351,"../internals/well-known-symbol-wrapped":352}],553:[function(require,module,exports){"use strict";var EmptyStringDescriptionStore,NATIVE_SYMBOL,thisSymbolValue,symbolDescriptiveString,regexp,replace,stringSlice,$=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),global=require("../internals/global"),uncurryThis=require("../internals/function-uncurry-this"),hasOwn=require("../internals/has-own-property"),isCallable=require("../internals/is-callable"),isPrototypeOf=require("../internals/object-is-prototype-of"),toString=require("../internals/to-string"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),require=require("../internals/copy-constructor-properties"),NativeSymbol=global.Symbol,SymbolPrototype=NativeSymbol&&NativeSymbol.prototype;!DESCRIPTORS||!isCallable(NativeSymbol)||"description"in SymbolPrototype&&void 0===NativeSymbol().description||(EmptyStringDescriptionStore={},require(global=function(){var description=arguments.length<1||void 0===arguments[0]?void 0:toString(arguments[0]),result=isPrototypeOf(SymbolPrototype,this)?new NativeSymbol(description):void 0===description?NativeSymbol():NativeSymbol(description);return""===description&&(EmptyStringDescriptionStore[result]=!0),result},NativeSymbol),(global.prototype=SymbolPrototype).constructor=global,NATIVE_SYMBOL="Symbol(test)"==String(NativeSymbol("test")),thisSymbolValue=uncurryThis(SymbolPrototype.valueOf),symbolDescriptiveString=uncurryThis(SymbolPrototype.toString),regexp=/^Symbol\((.*)\)[^)]+$/,replace=uncurryThis("".replace),stringSlice=uncurryThis("".slice),defineBuiltInAccessor(SymbolPrototype,"description",{configurable:!0,get:function(){var symbol=thisSymbolValue(this);return hasOwn(EmptyStringDescriptionStore,symbol)?"":(symbol=symbolDescriptiveString(symbol),""===(symbol=NATIVE_SYMBOL?stringSlice(symbol,7,-1):replace(symbol,regexp,"$1"))?void 0:symbol)}}),$({global:!0,constructor:!0,forced:!0},{Symbol:global}))},{"../internals/copy-constructor-properties":156,"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/has-own-property":217,"../internals/is-callable":232,"../internals/object-is-prototype-of":274,"../internals/to-string":337}],554:[function(require,module,exports){var $=require("../internals/export"),getBuiltIn=require("../internals/get-built-in"),hasOwn=require("../internals/has-own-property"),toString=require("../internals/to-string"),shared=require("../internals/shared"),require=require("../internals/symbol-registry-detection"),StringToSymbolRegistry=shared("string-to-symbol-registry"),SymbolToStringRegistry=shared("symbol-to-string-registry");$({target:"Symbol",stat:!0,forced:!require},{for:function(key){var symbol,key=toString(key);return hasOwn(StringToSymbolRegistry,key)?StringToSymbolRegistry[key]:(symbol=getBuiltIn("Symbol")(key),StringToSymbolRegistry[key]=symbol,SymbolToStringRegistry[symbol]=key,symbol)}})},{"../internals/export":196,"../internals/get-built-in":210,"../internals/has-own-property":217,"../internals/shared":307,"../internals/symbol-registry-detection":322,"../internals/to-string":337}],555:[function(require,module,exports){require("../internals/well-known-symbol-define")("hasInstance")},{"../internals/well-known-symbol-define":351}],556:[function(require,module,exports){require("../internals/well-known-symbol-define")("isConcatSpreadable")},{"../internals/well-known-symbol-define":351}],557:[function(require,module,exports){require("../internals/well-known-symbol-define")("iterator")},{"../internals/well-known-symbol-define":351}],558:[function(require,module,exports){require("../modules/es.symbol.constructor"),require("../modules/es.symbol.for"),require("../modules/es.symbol.key-for"),require("../modules/es.json.stringify"),require("../modules/es.object.get-own-property-symbols")},{"../modules/es.json.stringify":417,"../modules/es.object.get-own-property-symbols":464,"../modules/es.symbol.constructor":552,"../modules/es.symbol.for":554,"../modules/es.symbol.key-for":559}],559:[function(require,module,exports){var $=require("../internals/export"),hasOwn=require("../internals/has-own-property"),isSymbol=require("../internals/is-symbol"),tryToString=require("../internals/try-to-string"),shared=require("../internals/shared"),require=require("../internals/symbol-registry-detection"),SymbolToStringRegistry=shared("symbol-to-string-registry");$({target:"Symbol",stat:!0,forced:!require},{keyFor:function(sym){if(!isSymbol(sym))throw TypeError(tryToString(sym)+" is not a symbol");if(hasOwn(SymbolToStringRegistry,sym))return SymbolToStringRegistry[sym]}})},{"../internals/export":196,"../internals/has-own-property":217,"../internals/is-symbol":241,"../internals/shared":307,"../internals/symbol-registry-detection":322,"../internals/try-to-string":339}],560:[function(require,module,exports){require("../internals/well-known-symbol-define")("matchAll")},{"../internals/well-known-symbol-define":351}],561:[function(require,module,exports){require("../internals/well-known-symbol-define")("match")},{"../internals/well-known-symbol-define":351}],562:[function(require,module,exports){require("../internals/well-known-symbol-define")("replace")},{"../internals/well-known-symbol-define":351}],563:[function(require,module,exports){require("../internals/well-known-symbol-define")("search")},{"../internals/well-known-symbol-define":351}],564:[function(require,module,exports){require("../internals/well-known-symbol-define")("species")},{"../internals/well-known-symbol-define":351}],565:[function(require,module,exports){require("../internals/well-known-symbol-define")("split")},{"../internals/well-known-symbol-define":351}],566:[function(require,module,exports){var defineWellKnownSymbol=require("../internals/well-known-symbol-define"),require=require("../internals/symbol-define-to-primitive");defineWellKnownSymbol("toPrimitive"),require()},{"../internals/symbol-define-to-primitive":321,"../internals/well-known-symbol-define":351}],567:[function(require,module,exports){var getBuiltIn=require("../internals/get-built-in"),defineWellKnownSymbol=require("../internals/well-known-symbol-define"),require=require("../internals/set-to-string-tag");defineWellKnownSymbol("toStringTag"),require(getBuiltIn("Symbol"),"Symbol")},{"../internals/get-built-in":210,"../internals/set-to-string-tag":304,"../internals/well-known-symbol-define":351}],568:[function(require,module,exports){require("../internals/well-known-symbol-define")("unscopables")},{"../internals/well-known-symbol-define":351}],569:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),lengthOfArrayLike=require("../internals/length-of-array-like"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("at",function(index){var O=aTypedArray(this),len=lengthOfArrayLike(O),index=toIntegerOrInfinity(index),index=0<=index?index:len+index;return index<0||len<=index?void 0:O[index]})},{"../internals/array-buffer-view-core":126,"../internals/length-of-array-like":248,"../internals/to-integer-or-infinity":329}],570:[function(require,module,exports){"use strict";var uncurryThis=require("../internals/function-uncurry-this"),ArrayBufferViewCore=require("../internals/array-buffer-view-core"),u$ArrayCopyWithin=uncurryThis(require("../internals/array-copy-within")),aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("copyWithin",function(target,start){return u$ArrayCopyWithin(aTypedArray(this),target,start,2<arguments.length?arguments[2]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-copy-within":128,"../internals/function-uncurry-this":209}],571:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$every=require("../internals/array-iteration").every,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("every",function(callbackfn){return $every(aTypedArray(this),callbackfn,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration":135}],572:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$fill=require("../internals/array-fill"),toBigInt=require("../internals/to-big-int"),classof=require("../internals/classof"),call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this"),require=require("../internals/fails"),aTypedArray=ArrayBufferViewCore.aTypedArray,ArrayBufferViewCore=ArrayBufferViewCore.exportTypedArrayMethod,slice=uncurryThis("".slice);ArrayBufferViewCore("fill",function(value){var length=arguments.length,value=(aTypedArray(this),"Big"===slice(classof(this),0,3)?toBigInt(value):+value);return call($fill,this,value,1<length?arguments[1]:void 0,2<length?arguments[2]:void 0)},require(function(){var count=0;return new Int8Array(2).fill({valueOf:function(){return count++}}),1!==count}))},{"../internals/array-buffer-view-core":126,"../internals/array-fill":129,"../internals/classof":152,"../internals/fails":197,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/to-big-int":326}],573:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$filter=require("../internals/array-iteration").filter,fromSpeciesAndList=require("../internals/typed-array-from-species-and-list"),aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("filter",function(callbackfn){callbackfn=$filter(aTypedArray(this),callbackfn,1<arguments.length?arguments[1]:void 0);return fromSpeciesAndList(this,callbackfn)})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration":135,"../internals/typed-array-from-species-and-list":342}],574:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$findIndex=require("../internals/array-iteration").findIndex,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("findIndex",function(predicate){return $findIndex(aTypedArray(this),predicate,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration":135}],575:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$findLastIndex=require("../internals/array-iteration-from-last").findLastIndex,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("findLastIndex",function(predicate){return $findLastIndex(aTypedArray(this),predicate,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration-from-last":134}],576:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$findLast=require("../internals/array-iteration-from-last").findLast,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("findLast",function(predicate){return $findLast(aTypedArray(this),predicate,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration-from-last":134}],577:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$find=require("../internals/array-iteration").find,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("find",function(predicate){return $find(aTypedArray(this),predicate,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration":135}],578:[function(require,module,exports){require("../internals/typed-array-constructor")("Float32",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}})},{"../internals/typed-array-constructor":340}],579:[function(require,module,exports){require("../internals/typed-array-constructor")("Float64",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}})},{"../internals/typed-array-constructor":340}],580:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$forEach=require("../internals/array-iteration").forEach,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("forEach",function(callbackfn){$forEach(aTypedArray(this),callbackfn,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration":135}],581:[function(require,module,exports){"use strict";var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS=require("../internals/typed-array-constructors-require-wrappers");(0,require("../internals/array-buffer-view-core").exportTypedArrayStaticMethod)("from",require("../internals/typed-array-from"),TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS)},{"../internals/array-buffer-view-core":126,"../internals/typed-array-constructors-require-wrappers":341,"../internals/typed-array-from":343}],582:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$includes=require("../internals/array-includes").includes,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("includes",function(searchElement){return $includes(aTypedArray(this),searchElement,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-includes":133}],583:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$indexOf=require("../internals/array-includes").indexOf,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("indexOf",function(searchElement){return $indexOf(aTypedArray(this),searchElement,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-includes":133}],584:[function(require,module,exports){require("../internals/typed-array-constructor")("Int16",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}})},{"../internals/typed-array-constructor":340}],585:[function(require,module,exports){require("../internals/typed-array-constructor")("Int32",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}})},{"../internals/typed-array-constructor":340}],586:[function(require,module,exports){require("../internals/typed-array-constructor")("Int8",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}})},{"../internals/typed-array-constructor":340}],587:[function(require,module,exports){"use strict";function typedArrayValues(){return arrayValues(aTypedArray(this))}var global=require("../internals/global"),fails=require("../internals/fails"),uncurryThis=require("../internals/function-uncurry-this"),ArrayBufferViewCore=require("../internals/array-buffer-view-core"),ArrayIterators=require("../modules/es.array.iterator"),ITERATOR=require("../internals/well-known-symbol")("iterator"),require=global.Uint8Array,arrayValues=uncurryThis(ArrayIterators.values),arrayKeys=uncurryThis(ArrayIterators.keys),arrayEntries=uncurryThis(ArrayIterators.entries),aTypedArray=ArrayBufferViewCore.aTypedArray,global=ArrayBufferViewCore.exportTypedArrayMethod,TypedArrayPrototype=require&&require.prototype,uncurryThis=!fails(function(){TypedArrayPrototype[ITERATOR].call([1])}),ArrayIterators=!!TypedArrayPrototype&&TypedArrayPrototype.values&&TypedArrayPrototype[ITERATOR]===TypedArrayPrototype.values&&"values"===TypedArrayPrototype.values.name;global("entries",function(){return arrayEntries(aTypedArray(this))},uncurryThis),global("keys",function(){return arrayKeys(aTypedArray(this))},uncurryThis),global("values",typedArrayValues,uncurryThis||!ArrayIterators,{name:"values"}),global(ITERATOR,typedArrayValues,uncurryThis||!ArrayIterators,{name:"values"})},{"../internals/array-buffer-view-core":126,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/well-known-symbol":353,"../modules/es.array.iterator":379}],588:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),require=require("../internals/function-uncurry-this"),aTypedArray=ArrayBufferViewCore.aTypedArray,ArrayBufferViewCore=ArrayBufferViewCore.exportTypedArrayMethod,$join=require([].join);ArrayBufferViewCore("join",function(separator){return $join(aTypedArray(this),separator)})},{"../internals/array-buffer-view-core":126,"../internals/function-uncurry-this":209}],589:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),apply=require("../internals/function-apply"),$lastIndexOf=require("../internals/array-last-index-of"),aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("lastIndexOf",function(searchElement){var length=arguments.length;return apply($lastIndexOf,aTypedArray(this),1<length?[searchElement,arguments[1]]:[searchElement])})},{"../internals/array-buffer-view-core":126,"../internals/array-last-index-of":136,"../internals/function-apply":201}],590:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$map=require("../internals/array-iteration").map,typedArraySpeciesConstructor=require("../internals/typed-array-species-constructor"),aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("map",function(mapfn){return $map(aTypedArray(this),mapfn,1<arguments.length?arguments[1]:void 0,function(O,length){return new(typedArraySpeciesConstructor(O))(length)})})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration":135,"../internals/typed-array-species-constructor":344}],591:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),require=require("../internals/typed-array-constructors-require-wrappers"),aTypedArrayConstructor=ArrayBufferViewCore.aTypedArrayConstructor;(0,ArrayBufferViewCore.exportTypedArrayStaticMethod)("of",function(){for(var index=0,length=arguments.length,result=new(aTypedArrayConstructor(this))(length);index<length;)result[index]=arguments[index++];return result},require)},{"../internals/array-buffer-view-core":126,"../internals/typed-array-constructors-require-wrappers":341}],592:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$reduceRight=require("../internals/array-reduce").right,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("reduceRight",function(callbackfn){var length=arguments.length;return $reduceRight(aTypedArray(this),callbackfn,length,1<length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-reduce":139}],593:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$reduce=require("../internals/array-reduce").left,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("reduce",function(callbackfn){var length=arguments.length;return $reduce(aTypedArray(this),callbackfn,length,1<length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-reduce":139}],594:[function(require,module,exports){"use strict";var require=require("../internals/array-buffer-view-core"),aTypedArray=require.aTypedArray,require=require.exportTypedArrayMethod,floor=Math.floor;require("reverse",function(){for(var value,length=aTypedArray(this).length,middle=floor(length/2),index=0;index<middle;)value=this[index],this[index++]=this[--length],this[length]=value;return this})},{"../internals/array-buffer-view-core":126}],595:[function(require,module,exports){"use strict";var global=require("../internals/global"),call=require("../internals/function-call"),ArrayBufferViewCore=require("../internals/array-buffer-view-core"),lengthOfArrayLike=require("../internals/length-of-array-like"),toOffset=require("../internals/to-offset"),toIndexedObject=require("../internals/to-object"),require=require("../internals/fails"),RangeError=global.RangeError,Int8Array=global.Int8Array,global=Int8Array&&Int8Array.prototype,$set=global&&global.set,aTypedArray=ArrayBufferViewCore.aTypedArray,global=ArrayBufferViewCore.exportTypedArrayMethod,WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS=!require(function(){var array=new Uint8ClampedArray(2);return call($set,array,{length:1,0:3},1),3!==array[1]}),ArrayBufferViewCore=WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS&&ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS&&require(function(){var array=new Int8Array(2);return array.set(1),array.set("2",1),0!==array[0]||2!==array[1]});global("set",function(arrayLike){aTypedArray(this);var offset=toOffset(1<arguments.length?arguments[1]:void 0,1),src=toIndexedObject(arrayLike);if(WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS)return call($set,this,src,offset);var arrayLike=this.length,len=lengthOfArrayLike(src),index=0;if(arrayLike<len+offset)throw RangeError("Wrong length");for(;index<len;)this[offset+index]=src[index++]},!WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS||ArrayBufferViewCore)},{"../internals/array-buffer-view-core":126,"../internals/fails":197,"../internals/function-call":205,"../internals/global":216,"../internals/length-of-array-like":248,"../internals/to-object":331,"../internals/to-offset":332}],596:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),typedArraySpeciesConstructor=require("../internals/typed-array-species-constructor"),fails=require("../internals/fails"),arraySlice=require("../internals/array-slice"),aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("slice",function(start,end){for(var list=arraySlice(aTypedArray(this),start,end),start=typedArraySpeciesConstructor(this),index=0,length=list.length,result=new start(length);index<length;)result[index]=list[index++];return result},fails(function(){new Int8Array(1).slice()}))},{"../internals/array-buffer-view-core":126,"../internals/array-slice":142,"../internals/fails":197,"../internals/typed-array-species-constructor":344}],597:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),$some=require("../internals/array-iteration").some,aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("some",function(callbackfn){return $some(aTypedArray(this),callbackfn,1<arguments.length?arguments[1]:void 0)})},{"../internals/array-buffer-view-core":126,"../internals/array-iteration":135}],598:[function(require,module,exports){"use strict";var global=require("../internals/global"),uncurryThis=require("../internals/function-uncurry-this-clause"),fails=require("../internals/fails"),aCallable=require("../internals/a-callable"),internalSort=require("../internals/array-sort"),ArrayBufferViewCore=require("../internals/array-buffer-view-core"),FF=require("../internals/engine-ff-version"),IE_OR_EDGE=require("../internals/engine-is-ie-or-edge"),V8=require("../internals/engine-v8-version"),WEBKIT=require("../internals/engine-webkit-version"),aTypedArray=ArrayBufferViewCore.aTypedArray,require=ArrayBufferViewCore.exportTypedArrayMethod,Uint16Array=global.Uint16Array,nativeSort=Uint16Array&&uncurryThis(Uint16Array.prototype.sort),ArrayBufferViewCore=!(!nativeSort||fails(function(){nativeSort(new Uint16Array(2),null)})&&fails(function(){nativeSort(new Uint16Array(2),{})})),STABLE_SORT=!!nativeSort&&!fails(function(){if(V8)return V8<74;if(FF)return FF<67;if(IE_OR_EDGE)return!0;if(WEBKIT)return WEBKIT<602;for(var mod,array=new Uint16Array(516),expected=Array(516),index=0;index<516;index++)mod=index%4,array[index]=515-index,expected[index]=index-2*mod+3;for(nativeSort(array,function(a,b){return(a/4|0)-(b/4|0)}),index=0;index<516;index++)if(array[index]!==expected[index])return!0});require("sort",function(comparefn){return void 0!==comparefn&&aCallable(comparefn),STABLE_SORT?nativeSort(this,comparefn):internalSort(aTypedArray(this),function(comparefn){return function(x,y){return void 0!==comparefn?+comparefn(x,y)||0:y!=y?-1:x!=x?1:0===x&&0===y?0<1/x&&1/y<0?1:-1:y<x}}(comparefn))},!STABLE_SORT||ArrayBufferViewCore)},{"../internals/a-callable":117,"../internals/array-buffer-view-core":126,"../internals/array-sort":143,"../internals/engine-ff-version":178,"../internals/engine-is-ie-or-edge":182,"../internals/engine-v8-version":188,"../internals/engine-webkit-version":189,"../internals/fails":197,"../internals/function-uncurry-this-clause":208,"../internals/global":216}],599:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),toLength=require("../internals/to-length"),toAbsoluteIndex=require("../internals/to-absolute-index"),typedArraySpeciesConstructor=require("../internals/typed-array-species-constructor"),aTypedArray=ArrayBufferViewCore.aTypedArray;(0,ArrayBufferViewCore.exportTypedArrayMethod)("subarray",function(begin,end){var O=aTypedArray(this),length=O.length,begin=toAbsoluteIndex(begin,length);return new(typedArraySpeciesConstructor(O))(O.buffer,O.byteOffset+begin*O.BYTES_PER_ELEMENT,toLength((void 0===end?length:toAbsoluteIndex(end,length))-begin))})},{"../internals/array-buffer-view-core":126,"../internals/to-absolute-index":325,"../internals/to-length":330,"../internals/typed-array-species-constructor":344}],600:[function(require,module,exports){"use strict";var global=require("../internals/global"),apply=require("../internals/function-apply"),ArrayBufferViewCore=require("../internals/array-buffer-view-core"),fails=require("../internals/fails"),arraySlice=require("../internals/array-slice"),Int8Array=global.Int8Array,aTypedArray=ArrayBufferViewCore.aTypedArray,require=ArrayBufferViewCore.exportTypedArrayMethod,$toLocaleString=[].toLocaleString,TO_LOCALE_STRING_BUG=!!Int8Array&&fails(function(){$toLocaleString.call(new Int8Array(1))});require("toLocaleString",function(){return apply($toLocaleString,TO_LOCALE_STRING_BUG?arraySlice(aTypedArray(this)):aTypedArray(this),arraySlice(arguments))},fails(function(){return[1,2].toLocaleString()!=new Int8Array([1,2]).toLocaleString()})||!fails(function(){Int8Array.prototype.toLocaleString.call([1,2])}))},{"../internals/array-buffer-view-core":126,"../internals/array-slice":142,"../internals/fails":197,"../internals/function-apply":201,"../internals/global":216}],601:[function(require,module,exports){"use strict";var arrayToReversed=require("../internals/array-to-reversed"),require=require("../internals/array-buffer-view-core"),aTypedArray=require.aTypedArray,exportTypedArrayMethod=require.exportTypedArrayMethod,getTypedArrayConstructor=require.getTypedArrayConstructor;exportTypedArrayMethod("toReversed",function(){return arrayToReversed(aTypedArray(this),getTypedArrayConstructor(this))})},{"../internals/array-buffer-view-core":126,"../internals/array-to-reversed":146}],602:[function(require,module,exports){"use strict";var ArrayBufferViewCore=require("../internals/array-buffer-view-core"),uncurryThis=require("../internals/function-uncurry-this"),aCallable=require("../internals/a-callable"),arrayFromConstructorAndList=require("../internals/array-from-constructor-and-list"),aTypedArray=ArrayBufferViewCore.aTypedArray,getTypedArrayConstructor=ArrayBufferViewCore.getTypedArrayConstructor,require=ArrayBufferViewCore.exportTypedArrayMethod,sort=uncurryThis(ArrayBufferViewCore.TypedArrayPrototype.sort);require("toSorted",function(compareFn){void 0!==compareFn&&aCallable(compareFn);var O=aTypedArray(this),O=arrayFromConstructorAndList(getTypedArrayConstructor(O),O);return sort(O,compareFn)})},{"../internals/a-callable":117,"../internals/array-buffer-view-core":126,"../internals/array-from-constructor-and-list":131,"../internals/function-uncurry-this":209}],603:[function(require,module,exports){"use strict";var exportTypedArrayMethod=require("../internals/array-buffer-view-core").exportTypedArrayMethod,fails=require("../internals/fails"),global=require("../internals/global"),require=require("../internals/function-uncurry-this"),global=global.Uint8Array,global=global&&global.prototype||{},arrayToString=[].toString,join=require([].join),require=(fails(function(){arrayToString.call({})})&&(arrayToString=function(){return join(this)}),global.toString!=arrayToString);exportTypedArrayMethod("toString",arrayToString,require)},{"../internals/array-buffer-view-core":126,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/global":216}],604:[function(require,module,exports){require("../internals/typed-array-constructor")("Uint16",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}})},{"../internals/typed-array-constructor":340}],605:[function(require,module,exports){require("../internals/typed-array-constructor")("Uint32",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}})},{"../internals/typed-array-constructor":340}],606:[function(require,module,exports){require("../internals/typed-array-constructor")("Uint8",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}})},{"../internals/typed-array-constructor":340}],607:[function(require,module,exports){require("../internals/typed-array-constructor")("Uint8",function(init){return function(data,byteOffset,length){return init(this,data,byteOffset,length)}},!0)},{"../internals/typed-array-constructor":340}],608:[function(require,module,exports){"use strict";var arrayWith=require("../internals/array-with"),ArrayBufferViewCore=require("../internals/array-buffer-view-core"),isBigIntArray=require("../internals/is-big-int-array"),toIntegerOrInfinity=require("../internals/to-integer-or-infinity"),toBigInt=require("../internals/to-big-int"),aTypedArray=ArrayBufferViewCore.aTypedArray,getTypedArrayConstructor=ArrayBufferViewCore.getTypedArrayConstructor;(0,ArrayBufferViewCore.exportTypedArrayMethod)("with",function(index,value){var O=aTypedArray(this),index=toIntegerOrInfinity(index),value=isBigIntArray(O)?toBigInt(value):+value;return arrayWith(O,getTypedArrayConstructor(O),index,value)},!!!function(){try{new Int8Array(1).with(2,{valueOf:function(){throw 8}})}catch(error){return 8===error}}())},{"../internals/array-buffer-view-core":126,"../internals/array-with":147,"../internals/is-big-int-array":231,"../internals/to-big-int":326,"../internals/to-integer-or-infinity":329}],609:[function(require,module,exports){"use strict";var $=require("../internals/export"),uncurryThis=require("../internals/function-uncurry-this"),toString=require("../internals/to-string"),fromCharCode=String.fromCharCode,charAt=uncurryThis("".charAt),exec=uncurryThis(/./.exec),stringSlice=uncurryThis("".slice),hex2=/^[\da-f]{2}$/i,hex4=/^[\da-f]{4}$/i;$({global:!0},{unescape:function(string){for(var chr,part,str=toString(string),result="",length=str.length,index=0;index<length;){if("%"===(chr=charAt(str,index++)))if("u"===charAt(str,index)){if(part=stringSlice(str,index+1,index+5),exec(hex4,part)){result+=fromCharCode(parseInt(part,16)),index+=5;continue}}else if(part=stringSlice(str,index,index+2),exec(hex2,part)){result+=fromCharCode(parseInt(part,16)),index+=2;continue}result+=chr}return result}})},{"../internals/export":196,"../internals/function-uncurry-this":209,"../internals/to-string":337}],610:[function(require,module,exports){"use strict";function wrapper(init){return function(){return init(this,arguments.length?arguments[0]:void 0)}}var InternalWeakMap,nativeDelete,nativeHas,nativeGet,FREEZING=require("../internals/freezing"),global=require("../internals/global"),uncurryThis=require("../internals/function-uncurry-this"),defineBuiltIns=require("../internals/define-built-ins"),InternalMetadataModule=require("../internals/internal-metadata"),collection=require("../internals/collection"),collectionWeak=require("../internals/collection-weak"),isObject=require("../internals/is-object"),enforceInternalState=require("../internals/internal-state").enforce,fails=require("../internals/fails"),require=require("../internals/weak-map-basic-detection"),$Object=Object,isArray=Array.isArray,isExtensible=$Object.isExtensible,isFrozen=$Object.isFrozen,isSealed=$Object.isSealed,freeze=$Object.freeze,seal=$Object.seal,FROZEN={},SEALED={},$Object=!global.ActiveXObject&&"ActiveXObject"in global,$WeakMap=collection("WeakMap",wrapper,collectionWeak),global=$WeakMap.prototype,nativeSet=uncurryThis(global.set);require&&($Object?(InternalWeakMap=collectionWeak.getConstructor(wrapper,"WeakMap",!0),InternalMetadataModule.enable(),nativeDelete=uncurryThis(global.delete),nativeHas=uncurryThis(global.has),nativeGet=uncurryThis(global.get),defineBuiltIns(global,{delete:function(key){var state;return isObject(key)&&!isExtensible(key)?((state=enforceInternalState(this)).frozen||(state.frozen=new InternalWeakMap),nativeDelete(this,key)||state.frozen.delete(key)):nativeDelete(this,key)},has:function(key){var state;return isObject(key)&&!isExtensible(key)?((state=enforceInternalState(this)).frozen||(state.frozen=new InternalWeakMap),nativeHas(this,key)||state.frozen.has(key)):nativeHas(this,key)},get:function(key){var state;return!isObject(key)||isExtensible(key)||((state=enforceInternalState(this)).frozen||(state.frozen=new InternalWeakMap),nativeHas(this,key))?nativeGet(this,key):state.frozen.get(key)},set:function(key,value){var state;return!isObject(key)||isExtensible(key)||((state=enforceInternalState(this)).frozen||(state.frozen=new InternalWeakMap),nativeHas(this,key))?nativeSet(this,key,value):state.frozen.set(key,value),this}})):FREEZING&&fails(function(){var frozenArray=freeze([]);return nativeSet(new $WeakMap,frozenArray,1),!isFrozen(frozenArray)})&&defineBuiltIns(global,{set:function(key,value){var arrayIntegrityLevel;return isArray(key)&&(isFrozen(key)?arrayIntegrityLevel=FROZEN:isSealed(key)&&(arrayIntegrityLevel=SEALED)),nativeSet(this,key,value),arrayIntegrityLevel==FROZEN&&freeze(key),arrayIntegrityLevel==SEALED&&seal(key),this}}))},{"../internals/collection":155,"../internals/collection-weak":154,"../internals/define-built-ins":168,"../internals/fails":197,"../internals/freezing":200,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/internal-metadata":227,"../internals/internal-state":228,"../internals/is-object":238,"../internals/weak-map-basic-detection":350}],611:[function(require,module,exports){require("../modules/es.weak-map.constructor")},{"../modules/es.weak-map.constructor":610}],612:[function(require,module,exports){"use strict";require("../internals/collection")("WeakSet",function(init){return function(){return init(this,arguments.length?arguments[0]:void 0)}},require("../internals/collection-weak"))},{"../internals/collection":155,"../internals/collection-weak":154}],613:[function(require,module,exports){require("../modules/es.weak-set.constructor")},{"../modules/es.weak-set.constructor":612}],614:[function(require,module,exports){var $=require("../internals/export"),global=require("../internals/global"),getBuiltIn=require("../internals/get-built-in"),uncurryThis=require("../internals/function-uncurry-this"),call=require("../internals/function-call"),fails=require("../internals/fails"),toString=require("../internals/to-string"),hasOwn=require("../internals/has-own-property"),validateArgumentsLength=require("../internals/validate-arguments-length"),ctoi=require("../internals/base64-map").ctoi,disallowed=/[^\d+/a-z]/i,whitespaces=/[\t\n\f\r ]+/g,finalEq=/[=]{1,2}$/,$atob=getBuiltIn("atob"),fromCharCode=String.fromCharCode,charAt=uncurryThis("".charAt),replace=uncurryThis("".replace),exec=uncurryThis(disallowed.exec),require=fails(function(){return""!==$atob(" ")}),uncurryThis=!fails(function(){$atob("a")}),NO_ARG_RECEIVING_CHECK=!require&&!uncurryThis&&!fails(function(){$atob()}),WRONG_ARITY=!require&&!uncurryThis&&1!==$atob.length;$({global:!0,bind:!0,enumerable:!0,forced:require||uncurryThis||NO_ARG_RECEIVING_CHECK||WRONG_ARITY},{atob:function(data){if(validateArgumentsLength(arguments.length,1),NO_ARG_RECEIVING_CHECK||WRONG_ARITY)return call($atob,global,data);var chr,bs,string=replace(toString(data),whitespaces,""),output="",position=0,bc=0;if((string=string.length%4==0?replace(string,finalEq,""):string).length%4==1||exec(disallowed,string))throw new(getBuiltIn("DOMException"))("The string is not correctly encoded","InvalidCharacterError");for(;chr=charAt(string,position++);)hasOwn(ctoi,chr)&&(bs=bc%4?64*bs+ctoi[chr]:ctoi[chr],bc++%4)&&(output+=fromCharCode(255&bs>>(-2*bc&6)));return output}})},{"../internals/base64-map":148,"../internals/export":196,"../internals/fails":197,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/get-built-in":210,"../internals/global":216,"../internals/has-own-property":217,"../internals/to-string":337,"../internals/validate-arguments-length":349}],615:[function(require,module,exports){var $=require("../internals/export"),global=require("../internals/global"),getBuiltIn=require("../internals/get-built-in"),uncurryThis=require("../internals/function-uncurry-this"),call=require("../internals/function-call"),fails=require("../internals/fails"),toString=require("../internals/to-string"),validateArgumentsLength=require("../internals/validate-arguments-length"),itoc=require("../internals/base64-map").itoc,$btoa=getBuiltIn("btoa"),charAt=uncurryThis("".charAt),charCodeAt=uncurryThis("".charCodeAt),NO_ARG_RECEIVING_CHECK=!!$btoa&&!fails(function(){$btoa()}),WRONG_ARG_CONVERSION=!!$btoa&&fails(function(){return"bnVsbA=="!==$btoa(null)}),WRONG_ARITY=!!$btoa&&1!==$btoa.length;$({global:!0,bind:!0,enumerable:!0,forced:NO_ARG_RECEIVING_CHECK||WRONG_ARG_CONVERSION||WRONG_ARITY},{btoa:function(data){if(validateArgumentsLength(arguments.length,1),NO_ARG_RECEIVING_CHECK||WRONG_ARG_CONVERSION||WRONG_ARITY)return call($btoa,global,toString(data));for(var block,charCode,string=toString(data),output="",position=0,map=itoc;charAt(string,position)||(map="=",position%1);){if(255<(charCode=charCodeAt(string,position+=.75)))throw new(getBuiltIn("DOMException"))("The string contains characters outside of the Latin1 range","InvalidCharacterError");output+=charAt(map,63&(block=block<<8|charCode)>>8-position%1*8)}return output}})},{"../internals/base64-map":148,"../internals/export":196,"../internals/fails":197,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/get-built-in":210,"../internals/global":216,"../internals/to-string":337,"../internals/validate-arguments-length":349}],616:[function(require,module,exports){var $=require("../internals/export"),global=require("../internals/global"),require=require("../internals/task").clear;$({global:!0,bind:!0,enumerable:!0,forced:global.clearImmediate!==require},{clearImmediate:require})},{"../internals/export":196,"../internals/global":216,"../internals/task":323}],617:[function(require,module,exports){function handlePrototype(CollectionPrototype){if(CollectionPrototype&&CollectionPrototype.forEach!==forEach)try{createNonEnumerableProperty(CollectionPrototype,"forEach",forEach)}catch(error){CollectionPrototype.forEach=forEach}}var COLLECTION_NAME,global=require("../internals/global"),DOMIterables=require("../internals/dom-iterables"),DOMTokenListPrototype=require("../internals/dom-token-list-prototype"),forEach=require("../internals/array-for-each"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property");for(COLLECTION_NAME in DOMIterables)DOMIterables[COLLECTION_NAME]&&handlePrototype(global[COLLECTION_NAME]&&global[COLLECTION_NAME].prototype);handlePrototype(DOMTokenListPrototype)},{"../internals/array-for-each":130,"../internals/create-non-enumerable-property":161,"../internals/dom-iterables":176,"../internals/dom-token-list-prototype":177,"../internals/global":216}],618:[function(require,module,exports){function handlePrototype(CollectionPrototype,COLLECTION_NAME){if(CollectionPrototype){if(CollectionPrototype[ITERATOR]!==ArrayValues)try{createNonEnumerableProperty(CollectionPrototype,ITERATOR,ArrayValues)}catch(error){CollectionPrototype[ITERATOR]=ArrayValues}if(CollectionPrototype[TO_STRING_TAG]||createNonEnumerableProperty(CollectionPrototype,TO_STRING_TAG,COLLECTION_NAME),DOMIterables[COLLECTION_NAME])for(var METHOD_NAME in ArrayIteratorMethods)if(CollectionPrototype[METHOD_NAME]!==ArrayIteratorMethods[METHOD_NAME])try{createNonEnumerableProperty(CollectionPrototype,METHOD_NAME,ArrayIteratorMethods[METHOD_NAME])}catch(error){CollectionPrototype[METHOD_NAME]=ArrayIteratorMethods[METHOD_NAME]}}}var COLLECTION_NAME,global=require("../internals/global"),DOMIterables=require("../internals/dom-iterables"),DOMTokenListPrototype=require("../internals/dom-token-list-prototype"),ArrayIteratorMethods=require("../modules/es.array.iterator"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),require=require("../internals/well-known-symbol"),ITERATOR=require("iterator"),TO_STRING_TAG=require("toStringTag"),ArrayValues=ArrayIteratorMethods.values;for(COLLECTION_NAME in DOMIterables)handlePrototype(global[COLLECTION_NAME]&&global[COLLECTION_NAME].prototype,COLLECTION_NAME);handlePrototype(DOMTokenListPrototype,"DOMTokenList")},{"../internals/create-non-enumerable-property":161,"../internals/dom-iterables":176,"../internals/dom-token-list-prototype":177,"../internals/global":216,"../internals/well-known-symbol":353,"../modules/es.array.iterator":379}],619:[function(require,module,exports){"use strict";function codeFor(name){return hasOwn(DOMExceptionConstants,name)&&DOMExceptionConstants[name].m?DOMExceptionConstants[name].c:0}function $DOMException(){anInstance(this,DOMExceptionPrototype);var message=normalizeStringArgument((argumentsLength=arguments.length)<1?void 0:arguments[0]),argumentsLength=normalizeStringArgument(argumentsLength<2?void 0:arguments[1],"Error"),code=codeFor(argumentsLength);setInternalState(this,{type:"DOMException",name:argumentsLength,message:message,code:code}),DESCRIPTORS||(this.name=argumentsLength,this.message=message,this.code=code),HAS_STACK&&((argumentsLength=Error(message)).name="DOMException",defineProperty(this,"stack",createPropertyDescriptor(1,clearErrorStack(argumentsLength.stack,1))))}function createGetterDescriptor(get){return{enumerable:!0,configurable:!0,get:get}}function getterFor(key){return createGetterDescriptor(function(){return getInternalState(this)[key]})}var key,constantName,constant,$=require("../internals/export"),tryNodeRequire=require("../internals/try-node-require"),getBuiltIn=require("../internals/get-built-in"),fails=require("../internals/fails"),create=require("../internals/object-create"),createPropertyDescriptor=require("../internals/create-property-descriptor"),defineProperty=require("../internals/object-define-property").f,defineBuiltIn=require("../internals/define-built-in"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),hasOwn=require("../internals/has-own-property"),anInstance=require("../internals/an-instance"),anObject=require("../internals/an-object"),errorToString=require("../internals/error-to-string"),normalizeStringArgument=require("../internals/normalize-string-argument"),DOMExceptionConstants=require("../internals/dom-exception-constants"),clearErrorStack=require("../internals/error-stack-clear"),InternalStateModule=require("../internals/internal-state"),DESCRIPTORS=require("../internals/descriptors"),require=require("../internals/is-pure"),Error=getBuiltIn("Error"),NativeDOMException=getBuiltIn("DOMException")||function(){try{(new(getBuiltIn("MessageChannel")||tryNodeRequire("worker_threads").MessageChannel)).port1.postMessage(new WeakMap)}catch(error){if("DATA_CLONE_ERR"==error.name&&25==error.code)return error.constructor}}(),NativeDOMExceptionPrototype=NativeDOMException&&NativeDOMException.prototype,ErrorPrototype=Error.prototype,setInternalState=InternalStateModule.set,getInternalState=InternalStateModule.getterFor("DOMException"),HAS_STACK="stack"in Error("DOMException"),DOMExceptionPrototype=$DOMException.prototype=create(ErrorPrototype),InternalStateModule=(DESCRIPTORS&&(defineBuiltInAccessor(DOMExceptionPrototype,"code",getterFor("code")),defineBuiltInAccessor(DOMExceptionPrototype,"message",getterFor("message")),defineBuiltInAccessor(DOMExceptionPrototype,"name",getterFor("name"))),defineProperty(DOMExceptionPrototype,"constructor",createPropertyDescriptor(1,$DOMException)),fails(function(){return!(new NativeDOMException instanceof Error)})),create=InternalStateModule||fails(function(){return ErrorPrototype.toString!==errorToString||"2: 1"!==String(new NativeDOMException(1,2))}),fails=InternalStateModule||fails(function(){return 25!==new NativeDOMException(1,"DataCloneError").code}),NativeDOMExceptionPrototype=InternalStateModule||25!==NativeDOMException.DATA_CLONE_ERR||25!==NativeDOMExceptionPrototype.DATA_CLONE_ERR,NativeDOMExceptionPrototype=require?create||fails||NativeDOMExceptionPrototype:InternalStateModule,PolyfilledDOMException=($({global:!0,constructor:!0,forced:NativeDOMExceptionPrototype},{DOMException:NativeDOMExceptionPrototype?$DOMException:NativeDOMException}),getBuiltIn("DOMException")),PolyfilledDOMExceptionPrototype=PolyfilledDOMException.prototype;for(key in create&&(require||NativeDOMException===PolyfilledDOMException)&&defineBuiltIn(PolyfilledDOMExceptionPrototype,"toString",errorToString),fails&&DESCRIPTORS&&NativeDOMException===PolyfilledDOMException&&defineBuiltInAccessor(PolyfilledDOMExceptionPrototype,"code",createGetterDescriptor(function(){return codeFor(anObject(this).name)})),DOMExceptionConstants)hasOwn(DOMExceptionConstants,key)&&(constantName=(constant=DOMExceptionConstants[key]).s,constant=createPropertyDescriptor(6,constant.c),hasOwn(PolyfilledDOMException,constantName)||defineProperty(PolyfilledDOMException,constantName,constant),hasOwn(PolyfilledDOMExceptionPrototype,constantName)||defineProperty(PolyfilledDOMExceptionPrototype,constantName,constant))},{"../internals/an-instance":122,"../internals/an-object":123,"../internals/create-property-descriptor":162,"../internals/define-built-in":167,"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/dom-exception-constants":175,"../internals/error-stack-clear":192,"../internals/error-to-string":195,"../internals/export":196,"../internals/fails":197,"../internals/get-built-in":210,"../internals/has-own-property":217,"../internals/internal-state":228,"../internals/is-pure":239,"../internals/normalize-string-argument":259,"../internals/object-create":265,"../internals/object-define-property":267,"../internals/try-node-require":338}],620:[function(require,module,exports){"use strict";function $DOMException(){anInstance(this,DOMExceptionPrototype);var message=normalizeStringArgument((argumentsLength=arguments.length)<1?void 0:arguments[0]),argumentsLength=normalizeStringArgument(argumentsLength<2?void 0:arguments[1],"Error"),argumentsLength=new NativeDOMException(message,argumentsLength);return(message=Error(message)).name="DOMException",defineProperty(argumentsLength,"stack",createPropertyDescriptor(1,clearErrorStack(message.stack,1))),inheritIfRequired(argumentsLength,this,$DOMException),argumentsLength}var constantName,$=require("../internals/export"),global=require("../internals/global"),getBuiltIn=require("../internals/get-built-in"),createPropertyDescriptor=require("../internals/create-property-descriptor"),defineProperty=require("../internals/object-define-property").f,hasOwn=require("../internals/has-own-property"),anInstance=require("../internals/an-instance"),inheritIfRequired=require("../internals/inherit-if-required"),normalizeStringArgument=require("../internals/normalize-string-argument"),DOMExceptionConstants=require("../internals/dom-exception-constants"),clearErrorStack=require("../internals/error-stack-clear"),DESCRIPTORS=require("../internals/descriptors"),require=require("../internals/is-pure"),Error=getBuiltIn("Error"),NativeDOMException=getBuiltIn("DOMException"),DOMExceptionPrototype=$DOMException.prototype=NativeDOMException.prototype,ERROR_HAS_STACK="stack"in Error("DOMException"),DOM_EXCEPTION_HAS_STACK="stack"in new NativeDOMException(1,2),DESCRIPTORS=NativeDOMException&&DESCRIPTORS&&Object.getOwnPropertyDescriptor(global,"DOMException"),global=!(!DESCRIPTORS||DESCRIPTORS.writable&&DESCRIPTORS.configurable),DESCRIPTORS=ERROR_HAS_STACK&&!global&&!DOM_EXCEPTION_HAS_STACK,PolyfilledDOMException=($({global:!0,constructor:!0,forced:require||DESCRIPTORS},{DOMException:DESCRIPTORS?$DOMException:NativeDOMException}),getBuiltIn("DOMException")),ERROR_HAS_STACK=PolyfilledDOMException.prototype;if(ERROR_HAS_STACK.constructor!==PolyfilledDOMException)for(var key in require||defineProperty(ERROR_HAS_STACK,"constructor",createPropertyDescriptor(1,PolyfilledDOMException)),DOMExceptionConstants)!hasOwn(DOMExceptionConstants,key)||hasOwn(PolyfilledDOMException,constantName=(key=DOMExceptionConstants[key]).s)||defineProperty(PolyfilledDOMException,constantName,createPropertyDescriptor(6,key.c))},{"../internals/an-instance":122,"../internals/create-property-descriptor":162,"../internals/descriptors":171,"../internals/dom-exception-constants":175,"../internals/error-stack-clear":192,"../internals/export":196,"../internals/get-built-in":210,"../internals/global":216,"../internals/has-own-property":217,"../internals/inherit-if-required":224,"../internals/is-pure":239,"../internals/normalize-string-argument":259,"../internals/object-define-property":267}],621:[function(require,module,exports){var getBuiltIn=require("../internals/get-built-in");require("../internals/set-to-string-tag")(getBuiltIn("DOMException"),"DOMException")},{"../internals/get-built-in":210,"../internals/set-to-string-tag":304}],622:[function(require,module,exports){require("../modules/web.clear-immediate"),require("../modules/web.set-immediate")},{"../modules/web.clear-immediate":616,"../modules/web.set-immediate":625}],623:[function(require,module,exports){var $=require("../internals/export"),global=require("../internals/global"),microtask=require("../internals/microtask"),aCallable=require("../internals/a-callable"),validateArgumentsLength=require("../internals/validate-arguments-length"),IS_NODE=require("../internals/engine-is-node"),process=global.process;$({global:!0,enumerable:!0,dontCallGetSet:!0},{queueMicrotask:function(fn){validateArgumentsLength(arguments.length,1),aCallable(fn);var domain=IS_NODE&&process.domain;microtask(domain?domain.bind(fn):fn)}})},{"../internals/a-callable":117,"../internals/engine-is-node":185,"../internals/export":196,"../internals/global":216,"../internals/microtask":257,"../internals/validate-arguments-length":349}],624:[function(require,module,exports){"use strict";var descriptor,$=require("../internals/export"),global=require("../internals/global"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),require=require("../internals/descriptors"),$TypeError=TypeError,defineProperty=Object.defineProperty,INCORRECT_VALUE=global.self!==global;try{require?(descriptor=Object.getOwnPropertyDescriptor(global,"self"),!INCORRECT_VALUE&&descriptor&&descriptor.get&&descriptor.enumerable||defineBuiltInAccessor(global,"self",{get:function(){return global},set:function(value){if(this!==global)throw $TypeError("Illegal invocation");defineProperty(global,"self",{value:value,writable:!0,configurable:!0,enumerable:!0})},configurable:!0,enumerable:!0})):$({global:!0,simple:!0,forced:INCORRECT_VALUE},{self:global})}catch(error){}},{"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/export":196,"../internals/global":216}],625:[function(require,module,exports){var $=require("../internals/export"),global=require("../internals/global"),setTask=require("../internals/task").set,require=require("../internals/schedulers-fix"),require=global.setImmediate?require(setTask,!1):setTask;$({global:!0,bind:!0,enumerable:!0,forced:global.setImmediate!==require},{setImmediate:require})},{"../internals/export":196,"../internals/global":216,"../internals/schedulers-fix":301,"../internals/task":323}],626:[function(require,module,exports){var $=require("../internals/export"),global=require("../internals/global"),require=require("../internals/schedulers-fix")(global.setInterval,!0);$({global:!0,bind:!0,forced:global.setInterval!==require},{setInterval:require})},{"../internals/export":196,"../internals/global":216,"../internals/schedulers-fix":301}],627:[function(require,module,exports){var $=require("../internals/export"),global=require("../internals/global"),require=require("../internals/schedulers-fix")(global.setTimeout,!0);$({global:!0,bind:!0,forced:global.setTimeout!==require},{setTimeout:require})},{"../internals/export":196,"../internals/global":216,"../internals/schedulers-fix":301}],628:[function(require,module,exports){function checkBasicSemantic(structuredCloneImplementation){return!fails(function(){var set1=new global.Set([7]),set2=structuredCloneImplementation(set1),number=structuredCloneImplementation(Object(7));return set2==set1||!set2.has(7)||"object"!=typeof number||7!=number})&&structuredCloneImplementation}function checkErrorsCloning(structuredCloneImplementation,$Error){return!fails(function(){var error=new $Error,test=structuredCloneImplementation({a:error,b:error});return!(test&&test.a===test.b&&test.a instanceof $Error&&test.a.stack===error.stack)})}function throwUncloneable(type){throw new DOMException("Uncloneable type: "+type,DATA_CLONE_ERROR)}function throwUnpolyfillable(type,action){throw new DOMException((action||"Cloning")+" of "+type+" cannot be properly polyfilled in this engine",DATA_CLONE_ERROR)}function structuredCloneInternal(value,map){if(isSymbol(value)&&throwUncloneable("Symbol"),!isObject(value))return value;if(map){if(mapHas(map,value))return mapGet(map,value)}else map=new Map;var C,name,cloned,dataTransfer,i,length,keys,key,source,target,options,type=classof(value),deep=!1;switch(type){case"Array":cloned=Array(lengthOfArrayLike(value)),deep=!0;break;case"Object":cloned={},deep=!0;break;case"Map":cloned=new Map,deep=!0;break;case"Set":cloned=new Set,deep=!0;break;case"RegExp":cloned=new RegExp(value.source,getRegExpFlags(value));break;case"Error":switch(name=value.name){case"AggregateError":cloned=getBuiltin("AggregateError")([]);break;case"EvalError":cloned=EvalError();break;case"RangeError":cloned=RangeError();break;case"ReferenceError":cloned=ReferenceError();break;case"SyntaxError":cloned=SyntaxError();break;case"TypeError":cloned=TypeError();break;case"URIError":cloned=URIError();break;case"CompileError":cloned=CompileError();break;case"LinkError":cloned=LinkError();break;case"RuntimeError":cloned=RuntimeError();break;default:cloned=Error()}deep=!0;break;case"DOMException":cloned=new DOMException(value.message,value.name),deep=!0;break;case"DataView":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"BigInt64Array":case"BigUint64Array":C=global[type],isObject(C)||throwUnpolyfillable(type),cloned=new C(structuredCloneInternal(value.buffer,map),value.byteOffset,"DataView"===type?value.byteLength:value.length);break;case"DOMQuad":try{cloned=new DOMQuad(structuredCloneInternal(value.p1,map),structuredCloneInternal(value.p2,map),structuredCloneInternal(value.p3,map),structuredCloneInternal(value.p4,map))}catch(error){nativeRestrictedStructuredClone?cloned=nativeRestrictedStructuredClone(value):throwUnpolyfillable(type)}break;case"FileList":if(dataTransfer=function(){var dataTransfer;try{dataTransfer=new global.DataTransfer}catch(error){try{dataTransfer=new global.ClipboardEvent("").clipboardData}catch(error2){}}return dataTransfer&&dataTransfer.items&&dataTransfer.files?dataTransfer:null}()){for(i=0,length=lengthOfArrayLike(value);i<length;i++)dataTransfer.items.add(structuredCloneInternal(value[i],map));cloned=dataTransfer.files}else nativeRestrictedStructuredClone?cloned=nativeRestrictedStructuredClone(value):throwUnpolyfillable(type);break;case"ImageData":try{cloned=new ImageData(structuredCloneInternal(value.data,map),value.width,value.height,{colorSpace:value.colorSpace})}catch(error){nativeRestrictedStructuredClone?cloned=nativeRestrictedStructuredClone(value):throwUnpolyfillable(type)}break;default:if(nativeRestrictedStructuredClone)cloned=nativeRestrictedStructuredClone(value);else switch(type){case"BigInt":cloned=Object(value.valueOf());break;case"Boolean":cloned=Object(thisBooleanValue(value));break;case"Number":cloned=Object(thisNumberValue(value));break;case"String":cloned=Object(thisStringValue(value));break;case"Date":cloned=new Date(thisTimeValue(value));break;case"ArrayBuffer":(C=global.DataView)||"function"==typeof value.slice||throwUnpolyfillable(type);try{if("function"!=typeof value.slice||value.resizable){length=value.byteLength,options="maxByteLength"in value?{maxByteLength:value.maxByteLength}:void 0,cloned=new ArrayBuffer(length,options),source=new C(value),target=new C(cloned);for(i=0;i<length;i++)target.setUint8(i,source.getUint8(i))}else cloned=value.slice(0)}catch(error){throw new DOMException("ArrayBuffer is detached",DATA_CLONE_ERROR)}break;case"SharedArrayBuffer":cloned=value;break;case"Blob":try{cloned=value.slice(0,value.size,value.type)}catch(error){throwUnpolyfillable(type)}break;case"DOMPoint":case"DOMPointReadOnly":C=global[type];try{cloned=C.fromPoint?C.fromPoint(value):new C(value.x,value.y,value.z,value.w)}catch(error){throwUnpolyfillable(type)}break;case"DOMRect":case"DOMRectReadOnly":C=global[type];try{cloned=C.fromRect?C.fromRect(value):new C(value.x,value.y,value.width,value.height)}catch(error){throwUnpolyfillable(type)}break;case"DOMMatrix":case"DOMMatrixReadOnly":C=global[type];try{cloned=C.fromMatrix?C.fromMatrix(value):new C(value)}catch(error){throwUnpolyfillable(type)}break;case"AudioData":case"VideoFrame":isCallable(value.clone)||throwUnpolyfillable(type);try{cloned=value.clone()}catch(error){throwUncloneable(type)}break;case"File":try{cloned=new File([value],value.name,value)}catch(error){throwUnpolyfillable(type)}break;case"CropTarget":case"CryptoKey":case"FileSystemDirectoryHandle":case"FileSystemFileHandle":case"FileSystemHandle":case"GPUCompilationInfo":case"GPUCompilationMessage":case"ImageBitmap":case"RTCCertificate":case"WebAssembly.Module":throwUnpolyfillable(type);default:throwUncloneable(type)}}if(mapSet(map,value,cloned),deep)switch(type){case"Array":case"Object":for(keys=objectKeys(value),i=0,length=lengthOfArrayLike(keys);i<length;i++)key=keys[i],createProperty(cloned,key,structuredCloneInternal(value[key],map));break;case"Map":value.forEach(function(v,k){mapSet(cloned,structuredCloneInternal(k,map),structuredCloneInternal(v,map))});break;case"Set":value.forEach(function(v){setAdd(cloned,structuredCloneInternal(v,map))});break;case"Error":createNonEnumerableProperty(cloned,"message",structuredCloneInternal(value.message,map)),hasOwn(value,"cause")&&createNonEnumerableProperty(cloned,"cause",structuredCloneInternal(value.cause,map)),"AggregateError"==name&&(cloned.errors=structuredCloneInternal(value.errors,map));case"DOMException":ERROR_STACK_INSTALLABLE&&createNonEnumerableProperty(cloned,"stack",structuredCloneInternal(value.stack,map))}return cloned}var structuredCloneImplementation,IS_PURE=require("../internals/is-pure"),$=require("../internals/export"),global=require("../internals/global"),getBuiltin=require("../internals/get-built-in"),uncurryThis=require("../internals/function-uncurry-this"),fails=require("../internals/fails"),uid=require("../internals/uid"),isCallable=require("../internals/is-callable"),isConstructor=require("../internals/is-constructor"),isNullOrUndefined=require("../internals/is-null-or-undefined"),isObject=require("../internals/is-object"),isSymbol=require("../internals/is-symbol"),iterate=require("../internals/iterate"),anObject=require("../internals/an-object"),classof=require("../internals/classof"),hasOwn=require("../internals/has-own-property"),createProperty=require("../internals/create-property"),createNonEnumerableProperty=require("../internals/create-non-enumerable-property"),lengthOfArrayLike=require("../internals/length-of-array-like"),validateArgumentsLength=require("../internals/validate-arguments-length"),getRegExpFlags=require("../internals/regexp-get-flags"),MapHelpers=require("../internals/map-helpers"),SetHelpers=require("../internals/set-helpers"),ERROR_STACK_INSTALLABLE=require("../internals/error-stack-installable"),PROPER_TRANSFER=require("../internals/structured-clone-proper-transfer"),Object=global.Object,Array=global.Array,Date=global.Date,Error=global.Error,EvalError=global.EvalError,RangeError=global.RangeError,ReferenceError=global.ReferenceError,SyntaxError=global.SyntaxError,TypeError=global.TypeError,URIError=global.URIError,PerformanceMark=global.PerformanceMark,require=global.WebAssembly,CompileError=require&&require.CompileError||Error,LinkError=require&&require.LinkError||Error,RuntimeError=require&&require.RuntimeError||Error,DOMException=getBuiltin("DOMException"),Map=MapHelpers.Map,mapHas=MapHelpers.has,mapGet=MapHelpers.get,mapSet=MapHelpers.set,Set=SetHelpers.Set,setAdd=SetHelpers.add,objectKeys=getBuiltin("Object","keys"),push=uncurryThis([].push),thisBooleanValue=uncurryThis((!0).valueOf),thisNumberValue=uncurryThis(1..valueOf),thisStringValue=uncurryThis("".valueOf),thisTimeValue=uncurryThis(Date.prototype.getTime),PERFORMANCE_MARK=uid("structuredClone"),DATA_CLONE_ERROR="DataCloneError",nativeStructuredClone=global.structuredClone,require=IS_PURE||!checkErrorsCloning(nativeStructuredClone,Error)||!checkErrorsCloning(nativeStructuredClone,DOMException)||(structuredCloneImplementation=nativeStructuredClone,!!fails(function(){var test=structuredCloneImplementation(new global.AggregateError([1],PERFORMANCE_MARK,{cause:3}));return"AggregateError"!=test.name||1!=test.errors[0]||test.message!=PERFORMANCE_MARK||3!=test.cause})),MapHelpers=!nativeStructuredClone&&checkBasicSemantic(function(value){return new PerformanceMark(PERFORMANCE_MARK,{detail:value}).detail}),nativeRestrictedStructuredClone=checkBasicSemantic(nativeStructuredClone)||MapHelpers;$({global:!0,enumerable:!0,sham:!PROPER_TRANSFER,forced:require},{structuredClone:function(value){var map,options=1<validateArgumentsLength(arguments.length,1)&&!isNullOrUndefined(arguments[1])?anObject(arguments[1]):void 0,options=options?options.transfer:void 0;return void 0!==options&&function(rawTransfer,map){if(!isObject(rawTransfer))throw TypeError("Transfer option cannot be converted to a sequence");var value,type,C,transferredArray,transferred,canvas,transfer=[],i=(iterate(rawTransfer,function(value){push(transfer,anObject(value))}),0),length=lengthOfArrayLike(transfer);if(PROPER_TRANSFER)for(transferredArray=nativeStructuredClone(transfer,{transfer:transfer});i<length;)mapSet(map,transfer[i],transferredArray[i++]);else for(;i<length;){if(value=transfer[i++],mapHas(map,value))throw new DOMException("Duplicate transferable",DATA_CLONE_ERROR);switch(type=classof(value)){case"ImageBitmap":C=global.OffscreenCanvas,isConstructor(C)||throwUnpolyfillable(type,"Transferring");try{(canvas=new C(value.width,value.height)).getContext("bitmaprenderer").transferFromImageBitmap(value),transferred=canvas.transferToImageBitmap()}catch(error){}break;case"AudioData":case"VideoFrame":isCallable(value.clone)&&isCallable(value.close)||throwUnpolyfillable(type,"Transferring");try{transferred=value.clone(),value.close()}catch(error){}break;case"ArrayBuffer":isCallable(value.transfer)||throwUnpolyfillable(type,"Transferring"),transferred=value.transfer();break;case"MediaSourceHandle":case"MessagePort":case"OffscreenCanvas":case"ReadableStream":case"TransformStream":case"WritableStream":throwUnpolyfillable(type,"Transferring")}if(void 0===transferred)throw new DOMException("This object cannot be transferred: "+type,DATA_CLONE_ERROR);mapSet(map,value,transferred)}}(options,map=new Map),structuredCloneInternal(value,map)}})},{"../internals/an-object":123,"../internals/classof":152,"../internals/create-non-enumerable-property":161,"../internals/create-property":163,"../internals/error-stack-installable":194,"../internals/export":196,"../internals/fails":197,"../internals/function-uncurry-this":209,"../internals/get-built-in":210,"../internals/global":216,"../internals/has-own-property":217,"../internals/is-callable":232,"../internals/is-constructor":233,"../internals/is-null-or-undefined":237,"../internals/is-object":238,"../internals/is-pure":239,"../internals/is-symbol":241,"../internals/iterate":242,"../internals/length-of-array-like":248,"../internals/map-helpers":250,"../internals/regexp-get-flags":295,"../internals/set-helpers":302,"../internals/structured-clone-proper-transfer":319,"../internals/uid":345,"../internals/validate-arguments-length":349}],629:[function(require,module,exports){require("../modules/web.set-interval"),require("../modules/web.set-timeout")},{"../modules/web.set-interval":626,"../modules/web.set-timeout":627}],630:[function(require,module,exports){"use strict";require("../modules/es.array.iterator");function safeGetBuiltIn(name){var descriptor;return DESCRIPTORS?(descriptor=getOwnPropertyDescriptor(global,name))&&descriptor.value:global[name]}function percentDecode(sequence){try{return decodeURIComponent(sequence)}catch(error){return sequence}}function deserialize(it){var result=replace(it,plus," "),bytes=4;try{return decodeURIComponent(result)}catch(error){for(;bytes;)result=replace(result,function(bytes){return sequences[bytes-1]||(sequences[bytes-1]=RegExp("((?:%[\\da-f]{2}){"+bytes+"})","gi"))}(bytes--),percentDecode);return result}}function replacer(match){return replacements[match]}function serialize(it){return replace(encodeURIComponent(it),find,replacer)}function URLSearchParamsState(init){this.entries=[],this.url=null,void 0!==init&&(isObject(init)?this.parseObject(init):this.parseQuery("string"==typeof init?"?"===charAt(init,0)?stringSlice(init,1):init:$toString(init)))}function URLSearchParamsConstructor(){anInstance(this,URLSearchParamsPrototype);var state=setInternalState(this,new URLSearchParamsState(0<arguments.length?arguments[0]:void 0));DESCRIPTORS||(this.length=state.entries.length)}var headersHas,headersSet,wrapRequestOptions,$=require("../internals/export"),global=require("../internals/global"),call=require("../internals/function-call"),uncurryThis=require("../internals/function-uncurry-this"),DESCRIPTORS=require("../internals/descriptors"),USE_NATIVE_URL=require("../internals/url-constructor-detection"),defineBuiltIn=require("../internals/define-built-in"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),defineBuiltIns=require("../internals/define-built-ins"),setToStringTag=require("../internals/set-to-string-tag"),createIteratorConstructor=require("../internals/iterator-create-constructor"),InternalStateModule=require("../internals/internal-state"),anInstance=require("../internals/an-instance"),isCallable=require("../internals/is-callable"),hasOwn=require("../internals/has-own-property"),bind=require("../internals/function-bind-context"),classof=require("../internals/classof"),anObject=require("../internals/an-object"),isObject=require("../internals/is-object"),$toString=require("../internals/to-string"),create=require("../internals/object-create"),createPropertyDescriptor=require("../internals/create-property-descriptor"),getIterator=require("../internals/get-iterator"),getIteratorMethod=require("../internals/get-iterator-method"),validateArgumentsLength=require("../internals/validate-arguments-length"),wellKnownSymbol=require("../internals/well-known-symbol"),arraySort=require("../internals/array-sort"),require=wellKnownSymbol("iterator"),setInternalState=InternalStateModule.set,getInternalParamsState=InternalStateModule.getterFor("URLSearchParams"),getInternalIteratorState=InternalStateModule.getterFor("URLSearchParamsIterator"),getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor,nativeFetch=safeGetBuiltIn("fetch"),NativeRequest=safeGetBuiltIn("Request"),Headers=safeGetBuiltIn("Headers"),RequestPrototype=NativeRequest&&NativeRequest.prototype,wellKnownSymbol=Headers&&Headers.prototype,RegExp=global.RegExp,TypeError=global.TypeError,decodeURIComponent=global.decodeURIComponent,encodeURIComponent=global.encodeURIComponent,charAt=uncurryThis("".charAt),join=uncurryThis([].join),push=uncurryThis([].push),replace=uncurryThis("".replace),shift=uncurryThis([].shift),splice=uncurryThis([].splice),split=uncurryThis("".split),stringSlice=uncurryThis("".slice),plus=/\+/g,sequences=Array(4),find=/[!'()~]|%20/g,replacements={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},URLSearchParamsIterator=createIteratorConstructor(function(params,kind){setInternalState(this,{type:"URLSearchParamsIterator",iterator:getIterator(getInternalParamsState(params).entries),kind:kind})},"Iterator",function(){var state=getInternalIteratorState(this),kind=state.kind,state=state.iterator.next(),entry=state.value;return state.done||(state.value="keys"===kind?entry.key:"values"===kind?entry.value:[entry.key,entry.value]),state},!0),URLSearchParamsPrototype=(URLSearchParamsState.prototype={type:"URLSearchParams",bindURL:function(url){this.url=url,this.update()},parseObject:function(object){var iterator,next,step,entryNext,first,second,iteratorMethod=getIteratorMethod(object);if(iteratorMethod)for(next=(iterator=getIterator(object,iteratorMethod)).next;!(step=call(next,iterator)).done;){if(entryNext=(step=getIterator(anObject(step.value))).next,(first=call(entryNext,step)).done||(second=call(entryNext,step)).done||!call(entryNext,step).done)throw TypeError("Expected sequence with length 2");push(this.entries,{key:$toString(first.value),value:$toString(second.value)})}else for(var key in object)hasOwn(object,key)&&push(this.entries,{key:key,value:$toString(object[key])})},parseQuery:function(query){if(query)for(var attribute,attributes=split(query,"&"),index=0;index<attributes.length;)(attribute=attributes[index++]).length&&(attribute=split(attribute,"="),push(this.entries,{key:deserialize(shift(attribute)),value:deserialize(join(attribute,"="))}))},serialize:function(){for(var entry,entries=this.entries,result=[],index=0;index<entries.length;)entry=entries[index++],push(result,serialize(entry.key)+"="+serialize(entry.value));return join(result,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}},URLSearchParamsConstructor.prototype);defineBuiltIns(URLSearchParamsPrototype,{append:function(name,value){validateArgumentsLength(arguments.length,2);var state=getInternalParamsState(this);push(state.entries,{key:$toString(name),value:$toString(value)}),DESCRIPTORS||this.length++,state.updateURL()},delete:function(name){validateArgumentsLength(arguments.length,1);for(var state=getInternalParamsState(this),entries=state.entries,key=$toString(name),index=0;index<entries.length;)entries[index].key===key?splice(entries,index,1):index++;DESCRIPTORS||(this.length=entries.length),state.updateURL()},get:function(name){validateArgumentsLength(arguments.length,1);for(var entries=getInternalParamsState(this).entries,key=$toString(name),index=0;index<entries.length;index++)if(entries[index].key===key)return entries[index].value;return null},getAll:function(name){validateArgumentsLength(arguments.length,1);for(var entries=getInternalParamsState(this).entries,key=$toString(name),result=[],index=0;index<entries.length;index++)entries[index].key===key&&push(result,entries[index].value);return result},has:function(name){validateArgumentsLength(arguments.length,1);for(var entries=getInternalParamsState(this).entries,key=$toString(name),index=0;index<entries.length;)if(entries[index++].key===key)return!0;return!1},set:function(name,value){validateArgumentsLength(arguments.length,1);for(var entry,state=getInternalParamsState(this),entries=state.entries,found=!1,key=$toString(name),val=$toString(value),index=0;index<entries.length;index++)(entry=entries[index]).key===key&&(found?splice(entries,index--,1):(found=!0,entry.value=val));found||push(entries,{key:key,value:val}),DESCRIPTORS||(this.length=entries.length),state.updateURL()},sort:function(){var state=getInternalParamsState(this);arraySort(state.entries,function(a,b){return a.key>b.key?1:-1}),state.updateURL()},forEach:function(callback){for(var entry,entries=getInternalParamsState(this).entries,boundFunction=bind(callback,1<arguments.length?arguments[1]:void 0),index=0;index<entries.length;)boundFunction((entry=entries[index++]).value,entry.key,this)},keys:function(){return new URLSearchParamsIterator(this,"keys")},values:function(){return new URLSearchParamsIterator(this,"values")},entries:function(){return new URLSearchParamsIterator(this,"entries")}},{enumerable:!0}),defineBuiltIn(URLSearchParamsPrototype,require,URLSearchParamsPrototype.entries,{name:"entries"}),defineBuiltIn(URLSearchParamsPrototype,"toString",function(){return getInternalParamsState(this).serialize()},{enumerable:!0}),DESCRIPTORS&&defineBuiltInAccessor(URLSearchParamsPrototype,"size",{get:function(){return getInternalParamsState(this).entries.length},configurable:!0,enumerable:!0}),setToStringTag(URLSearchParamsConstructor,"URLSearchParams"),$({global:!0,constructor:!0,forced:!USE_NATIVE_URL},{URLSearchParams:URLSearchParamsConstructor}),!USE_NATIVE_URL&&isCallable(Headers)&&(headersHas=uncurryThis(wellKnownSymbol.has),headersSet=uncurryThis(wellKnownSymbol.set),wrapRequestOptions=function(init){if(isObject(init)){var headers,body=init.body;if("URLSearchParams"===classof(body))return headers=init.headers?new Headers(init.headers):new Headers,headersHas(headers,"content-type")||headersSet(headers,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),create(init,{body:createPropertyDescriptor(0,$toString(body)),headers:createPropertyDescriptor(0,headers)})}return init},isCallable(nativeFetch)&&$({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(input){return nativeFetch(input,1<arguments.length?wrapRequestOptions(arguments[1]):{})}}),isCallable(NativeRequest))&&((RequestPrototype.constructor=InternalStateModule=function(input){return anInstance(this,RequestPrototype),new NativeRequest(input,1<arguments.length?wrapRequestOptions(arguments[1]):{})}).prototype=RequestPrototype,$({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:InternalStateModule})),module.exports={URLSearchParams:URLSearchParamsConstructor,getState:getInternalParamsState}},{"../internals/an-instance":122,"../internals/an-object":123,"../internals/array-sort":143,"../internals/classof":152,"../internals/create-property-descriptor":162,"../internals/define-built-in":167,"../internals/define-built-in-accessor":166,"../internals/define-built-ins":168,"../internals/descriptors":171,"../internals/export":196,"../internals/function-bind-context":202,"../internals/function-call":205,"../internals/function-uncurry-this":209,"../internals/get-iterator":212,"../internals/get-iterator-method":211,"../internals/global":216,"../internals/has-own-property":217,"../internals/internal-state":228,"../internals/is-callable":232,"../internals/is-object":238,"../internals/iterator-create-constructor":244,"../internals/object-create":265,"../internals/set-to-string-tag":304,"../internals/to-string":337,"../internals/url-constructor-detection":346,"../internals/validate-arguments-length":349,"../internals/well-known-symbol":353,"../modules/es.array.iterator":379}],631:[function(require,module,exports){require("../modules/web.url-search-params.constructor")},{"../modules/web.url-search-params.constructor":630}],632:[function(require,module,exports){"use strict";var DESCRIPTORS=require("../internals/descriptors"),uncurryThis=require("../internals/function-uncurry-this"),require=require("../internals/define-built-in-accessor"),URLSearchParamsPrototype=URLSearchParams.prototype,forEach=uncurryThis(URLSearchParamsPrototype.forEach);!DESCRIPTORS||"size"in URLSearchParamsPrototype||require(URLSearchParamsPrototype,"size",{get:function(){var count=0;return forEach(this,function(){count++}),count},configurable:!0,enumerable:!0})},{"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/function-uncurry-this":209}],633:[function(require,module,exports){var $=require("../internals/export"),getBuiltIn=require("../internals/get-built-in"),validateArgumentsLength=require("../internals/validate-arguments-length"),toString=require("../internals/to-string"),URL=getBuiltIn("URL");$({target:"URL",stat:!0},{canParse:function(url){var length=validateArgumentsLength(arguments.length,1),urlString=toString(url),length=length<2||void 0===arguments[1]?void 0:toString(arguments[1]);try{return!!new URL(urlString,length)}catch(error){return!1}}})},{"../internals/export":196,"../internals/get-built-in":210,"../internals/to-string":337,"../internals/validate-arguments-length":349}],634:[function(require,module,exports){"use strict";require("../modules/es.string.iterator");function serializeHost(host){var result,index,compress,ignore0;if("number"==typeof host){for(result=[],index=0;index<4;index++)unshift(result,host%256),host=floor(host/256);return join(result,".")}if("object"!=typeof host)return host;for(result="",compress=function(ipv6){for(var maxIndex=null,maxLength=1,currStart=null,currLength=0,index=0;index<8;index++)0!==ipv6[index]?(maxLength<currLength&&(maxIndex=currStart,maxLength=currLength),currStart=null,currLength=0):(null===currStart&&(currStart=index),++currLength);return maxLength<currLength&&(maxIndex=currStart,maxLength=currLength),maxIndex}(host),index=0;index<8;index++)ignore0&&0===host[index]||(ignore0=ignore0&&!1,compress===index?(result+=index?":":"::",ignore0=!0):(result+=numberToString(host[index],16),index<7&&(result+=":")));return"["+result+"]"}function percentEncode(chr,set){var code=codeAt(chr,0);return 32<code&&code<127&&!hasOwn(set,chr)?chr:encodeURIComponent(chr)}function isWindowsDriveLetter(string,normalized){return 2==string.length&&exec(ALPHA,charAt(string,0))&&(":"==(string=charAt(string,1))||!normalized&&"|"==string)}function startsWithWindowsDriveLetter(string){return 1<string.length&&isWindowsDriveLetter(stringSlice(string,0,2))&&(2==string.length||"/"===(string=charAt(string,2))||"\\"===string||"?"===string||"#"===string)}function URLState(url,isBase,base){var baseState,failure,url=$toString(url);if(isBase){if(failure=this.parse(url))throw TypeError(failure);this.searchParams=null}else{if(void 0!==base&&(baseState=new URLState(base,!0)),failure=this.parse(url,null,baseState))throw TypeError(failure);(isBase=getInternalSearchParamsState(new URLSearchParams)).bindURL(this),this.searchParams=isBase}}function accessorDescriptor(getter,setter){return{get:function(){return getInternalURLState(this)[getter]()},set:setter&&function(value){return getInternalURLState(this)[setter](value)},configurable:!0,enumerable:!0}}var EOF,$=require("../internals/export"),DESCRIPTORS=require("../internals/descriptors"),USE_NATIVE_URL=require("../internals/url-constructor-detection"),global=require("../internals/global"),bind=require("../internals/function-bind-context"),uncurryThis=require("../internals/function-uncurry-this"),defineBuiltIn=require("../internals/define-built-in"),defineBuiltInAccessor=require("../internals/define-built-in-accessor"),anInstance=require("../internals/an-instance"),hasOwn=require("../internals/has-own-property"),assign=require("../internals/object-assign"),arrayFrom=require("../internals/array-from"),arraySlice=require("../internals/array-slice-simple"),codeAt=require("../internals/string-multibyte").codeAt,toASCII=require("../internals/string-punycode-to-ascii"),$toString=require("../internals/to-string"),setToStringTag=require("../internals/set-to-string-tag"),validateArgumentsLength=require("../internals/validate-arguments-length"),URLSearchParamsModule=require("../modules/web.url-search-params.constructor"),require=require("../internals/internal-state"),setInternalState=require.set,getInternalURLState=require.getterFor("URL"),URLSearchParams=URLSearchParamsModule.URLSearchParams,getInternalSearchParamsState=URLSearchParamsModule.getState,require=global.URL,TypeError=global.TypeError,parseInt=global.parseInt,floor=Math.floor,pow=Math.pow,charAt=uncurryThis("".charAt),exec=uncurryThis(/./.exec),join=uncurryThis([].join),numberToString=uncurryThis(1..toString),pop=uncurryThis([].pop),push=uncurryThis([].push),replace=uncurryThis("".replace),shift=uncurryThis([].shift),split=uncurryThis("".split),stringSlice=uncurryThis("".slice),toLowerCase=uncurryThis("".toLowerCase),unshift=uncurryThis([].unshift),ALPHA=/[a-z]/i,ALPHANUMERIC=/[\d+-.a-z]/i,DIGIT=/\d/,HEX_START=/^0x/i,OCT=/^[0-7]+$/,DEC=/^\d+$/,HEX=/^[\da-f]+$/i,FORBIDDEN_HOST_CODE_POINT=/[\0\t\n\r #%/:<>?@[\\\]^|]/,FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT=/[\0\t\n\r #/:<>?@[\\\]^|]/,LEADING_C0_CONTROL_OR_SPACE=/^[\u0000-\u0020]+/,TRAILING_C0_CONTROL_OR_SPACE=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,TAB_AND_NEW_LINE=/[\t\n\r]/g,C0ControlPercentEncodeSet={},fragmentPercentEncodeSet=assign({},C0ControlPercentEncodeSet,{" ":1,'"':1,"<":1,">":1,"`":1}),pathPercentEncodeSet=assign({},fragmentPercentEncodeSet,{"#":1,"?":1,"{":1,"}":1}),userinfoPercentEncodeSet=assign({},pathPercentEncodeSet,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),specialSchemes={ftp:21,file:null,http:80,https:443,ws:80,wss:443},SCHEME_START={},SCHEME={},NO_SCHEME={},SPECIAL_RELATIVE_OR_AUTHORITY={},PATH_OR_AUTHORITY={},RELATIVE={},RELATIVE_SLASH={},SPECIAL_AUTHORITY_SLASHES={},SPECIAL_AUTHORITY_IGNORE_SLASHES={},AUTHORITY={},HOST={},HOSTNAME={},PORT={},FILE={},FILE_SLASH={},FILE_HOST={},PATH_START={},PATH={},CANNOT_BE_A_BASE_URL_PATH={},QUERY={},FRAGMENT={},URLConstructor=(URLState.prototype={type:"URL",parse:function(input,stateOverride,base){var codePoints,chr,failure,url=this,state=stateOverride||SCHEME_START,pointer=0,buffer="",seenAt=!1,seenBracket=!1,seenPasswordToken=!1;for(input=$toString(input),stateOverride||(url.scheme="",url.username="",url.password="",url.host=null,url.port=null,url.path=[],url.query=null,url.fragment=null,url.cannotBeABaseURL=!1,input=replace(input,LEADING_C0_CONTROL_OR_SPACE,""),input=replace(input,TRAILING_C0_CONTROL_OR_SPACE,"$1")),input=replace(input,TAB_AND_NEW_LINE,""),codePoints=arrayFrom(input);pointer<=codePoints.length;){switch(chr=codePoints[pointer],state){case SCHEME_START:if(!chr||!exec(ALPHA,chr)){if(stateOverride)return"Invalid scheme";state=NO_SCHEME;continue}buffer+=toLowerCase(chr),state=SCHEME;break;case SCHEME:if(chr&&(exec(ALPHANUMERIC,chr)||"+"==chr||"-"==chr||"."==chr))buffer+=toLowerCase(chr);else{if(":"!=chr){if(stateOverride)return"Invalid scheme";buffer="",state=NO_SCHEME,pointer=0;continue}if(stateOverride&&(url.isSpecial()!=hasOwn(specialSchemes,buffer)||"file"==buffer&&(url.includesCredentials()||null!==url.port)||"file"==url.scheme&&!url.host))return;if(url.scheme=buffer,stateOverride)return void(url.isSpecial()&&specialSchemes[url.scheme]==url.port&&(url.port=null));buffer="","file"==url.scheme?state=FILE:url.isSpecial()&&base&&base.scheme==url.scheme?state=SPECIAL_RELATIVE_OR_AUTHORITY:url.isSpecial()?state=SPECIAL_AUTHORITY_SLASHES:"/"==codePoints[pointer+1]?(state=PATH_OR_AUTHORITY,pointer++):(url.cannotBeABaseURL=!0,push(url.path,""),state=CANNOT_BE_A_BASE_URL_PATH)}break;case NO_SCHEME:if(!base||base.cannotBeABaseURL&&"#"!=chr)return"Invalid scheme";if(base.cannotBeABaseURL&&"#"==chr){url.scheme=base.scheme,url.path=arraySlice(base.path),url.query=base.query,url.fragment="",url.cannotBeABaseURL=!0,state=FRAGMENT;break}state="file"==base.scheme?FILE:RELATIVE;continue;case SPECIAL_RELATIVE_OR_AUTHORITY:if("/"!=chr||"/"!=codePoints[pointer+1]){state=RELATIVE;continue}state=SPECIAL_AUTHORITY_IGNORE_SLASHES,pointer++;break;case PATH_OR_AUTHORITY:if("/"==chr){state=AUTHORITY;break}state=PATH;continue;case RELATIVE:if(url.scheme=base.scheme,chr==EOF)url.username=base.username,url.password=base.password,url.host=base.host,url.port=base.port,url.path=arraySlice(base.path),url.query=base.query;else if("/"==chr||"\\"==chr&&url.isSpecial())state=RELATIVE_SLASH;else if("?"==chr)url.username=base.username,url.password=base.password,url.host=base.host,url.port=base.port,url.path=arraySlice(base.path),url.query="",state=QUERY;else{if("#"!=chr){url.username=base.username,url.password=base.password,url.host=base.host,url.port=base.port,url.path=arraySlice(base.path),url.path.length--,state=PATH;continue}url.username=base.username,url.password=base.password,url.host=base.host,url.port=base.port,url.path=arraySlice(base.path),url.query=base.query,url.fragment="",state=FRAGMENT}break;case RELATIVE_SLASH:if(!url.isSpecial()||"/"!=chr&&"\\"!=chr){if("/"!=chr){url.username=base.username,url.password=base.password,url.host=base.host,url.port=base.port,state=PATH;continue}state=AUTHORITY}else state=SPECIAL_AUTHORITY_IGNORE_SLASHES;break;case SPECIAL_AUTHORITY_SLASHES:if(state=SPECIAL_AUTHORITY_IGNORE_SLASHES,"/"!=chr||"/"!=charAt(buffer,pointer+1))continue;pointer++;break;case SPECIAL_AUTHORITY_IGNORE_SLASHES:if("/"==chr||"\\"==chr)break;state=AUTHORITY;continue;case AUTHORITY:if("@"==chr){seenAt&&(buffer="%40"+buffer);for(var seenAt=!0,bufferCodePoints=arrayFrom(buffer),i=0;i<bufferCodePoints.length;i++){var codePoint=bufferCodePoints[i];":"!=codePoint||seenPasswordToken?(codePoint=percentEncode(codePoint,userinfoPercentEncodeSet),seenPasswordToken?url.password+=codePoint:url.username+=codePoint):seenPasswordToken=!0}buffer=""}else if(chr==EOF||"/"==chr||"?"==chr||"#"==chr||"\\"==chr&&url.isSpecial()){if(seenAt&&""==buffer)return"Invalid authority";pointer-=arrayFrom(buffer).length+1,buffer="",state=HOST}else buffer+=chr;break;case HOST:case HOSTNAME:if(stateOverride&&"file"==url.scheme){state=FILE_HOST;continue}if(":"!=chr||seenBracket){if(chr==EOF||"/"==chr||"?"==chr||"#"==chr||"\\"==chr&&url.isSpecial()){if(url.isSpecial()&&""==buffer)return"Invalid host";if(stateOverride&&""==buffer&&(url.includesCredentials()||null!==url.port))return;if(failure=url.parseHost(buffer))return failure;if(buffer="",state=PATH_START,stateOverride)return;continue}"["==chr?seenBracket=!0:"]"==chr&&(seenBracket=!1),buffer+=chr}else{if(""==buffer)return"Invalid host";if(failure=url.parseHost(buffer))return failure;if(buffer="",state=PORT,stateOverride==HOSTNAME)return}break;case PORT:if(!exec(DIGIT,chr)){if(chr==EOF||"/"==chr||"?"==chr||"#"==chr||"\\"==chr&&url.isSpecial()||stateOverride){if(""!=buffer){var port=parseInt(buffer,10);if(65535<port)return"Invalid port";url.port=url.isSpecial()&&port===specialSchemes[url.scheme]?null:port,buffer=""}if(stateOverride)return;state=PATH_START;continue}return"Invalid port"}buffer+=chr;break;case FILE:if(url.scheme="file","/"==chr||"\\"==chr)state=FILE_SLASH;else{if(!base||"file"!=base.scheme){state=PATH;continue}if(chr==EOF)url.host=base.host,url.path=arraySlice(base.path),url.query=base.query;else if("?"==chr)url.host=base.host,url.path=arraySlice(base.path),url.query="",state=QUERY;else{if("#"!=chr){startsWithWindowsDriveLetter(join(arraySlice(codePoints,pointer),""))||(url.host=base.host,url.path=arraySlice(base.path),url.shortenPath()),state=PATH;continue}url.host=base.host,url.path=arraySlice(base.path),url.query=base.query,url.fragment="",state=FRAGMENT}}break;case FILE_SLASH:if("/"==chr||"\\"==chr){state=FILE_HOST;break}base&&"file"==base.scheme&&!startsWithWindowsDriveLetter(join(arraySlice(codePoints,pointer),""))&&(isWindowsDriveLetter(base.path[0],!0)?push(url.path,base.path[0]):url.host=base.host),state=PATH;continue;case FILE_HOST:if(chr==EOF||"/"==chr||"\\"==chr||"?"==chr||"#"==chr){if(!stateOverride&&isWindowsDriveLetter(buffer))state=PATH;else{if(""==buffer){if(url.host="",stateOverride)return}else{if(failure=url.parseHost(buffer))return failure;if("localhost"==url.host&&(url.host=""),stateOverride)return;buffer=""}state=PATH_START}continue}buffer+=chr;break;case PATH_START:if(url.isSpecial()){if(state=PATH,"/"!=chr&&"\\"!=chr)continue}else if(stateOverride||"?"!=chr)if(stateOverride||"#"!=chr){if(chr!=EOF&&(state=PATH,"/"!=chr))continue}else url.fragment="",state=FRAGMENT;else url.query="",state=QUERY;break;case PATH:if(chr==EOF||"/"==chr||"\\"==chr&&url.isSpecial()||!stateOverride&&("?"==chr||"#"==chr)){if(".."===(port=toLowerCase(port=buffer))||"%2e."===port||".%2e"===port||"%2e%2e"===port?(url.shortenPath(),"/"==chr||"\\"==chr&&url.isSpecial()||push(url.path,"")):!function(segment){return"."===segment||"%2e"===toLowerCase(segment)}(buffer)?("file"==url.scheme&&!url.path.length&&isWindowsDriveLetter(buffer)&&(url.host&&(url.host=""),buffer=charAt(buffer,0)+":"),push(url.path,buffer)):"/"==chr||"\\"==chr&&url.isSpecial()||push(url.path,""),buffer="","file"==url.scheme&&(chr==EOF||"?"==chr||"#"==chr))for(;1<url.path.length&&""===url.path[0];)shift(url.path);"?"==chr?(url.query="",state=QUERY):"#"==chr&&(url.fragment="",state=FRAGMENT)}else buffer+=percentEncode(chr,pathPercentEncodeSet);break;case CANNOT_BE_A_BASE_URL_PATH:"?"==chr?(url.query="",state=QUERY):"#"==chr?(url.fragment="",state=FRAGMENT):chr!=EOF&&(url.path[0]+=percentEncode(chr,C0ControlPercentEncodeSet));break;case QUERY:stateOverride||"#"!=chr?chr!=EOF&&("'"==chr&&url.isSpecial()?url.query+="%27":url.query+="#"==chr?"%23":percentEncode(chr,C0ControlPercentEncodeSet)):(url.fragment="",state=FRAGMENT);break;case FRAGMENT:chr!=EOF&&(url.fragment+=percentEncode(chr,fragmentPercentEncodeSet))}pointer++}},parseHost:function(input){var result,codePoints,index;if("["==charAt(input,0))return"]"==charAt(input,input.length-1)&&(result=function(input){function chr(){return charAt(input,pointer)}var value,length,numbersSeen,ipv4Piece,number,swaps,swap,address=[0,0,0,0,0,0,0,0],pieceIndex=0,compress=null,pointer=0;if(":"==chr()){if(":"!=charAt(input,1))return;pointer+=2,compress=++pieceIndex}for(;chr();){if(8==pieceIndex)return;if(":"==chr()){if(null!==compress)return;pointer++,compress=++pieceIndex}else{for(value=length=0;length<4&&exec(HEX,chr());)value=16*value+parseInt(chr(),16),pointer++,length++;if("."==chr()){if(0==length)return;if(pointer-=length,6<pieceIndex)return;for(numbersSeen=0;chr();){if(ipv4Piece=null,0<numbersSeen){if(!("."==chr()&&numbersSeen<4))return;pointer++}if(!exec(DIGIT,chr()))return;for(;exec(DIGIT,chr());){if(number=parseInt(chr(),10),null===ipv4Piece)ipv4Piece=number;else{if(0==ipv4Piece)return;ipv4Piece=10*ipv4Piece+number}if(255<ipv4Piece)return;pointer++}address[pieceIndex]=256*address[pieceIndex]+ipv4Piece,2!=++numbersSeen&&4!=numbersSeen||pieceIndex++}if(4!=numbersSeen)return;break}if(":"==chr()){if(pointer++,!chr())return}else if(chr())return;address[pieceIndex++]=value}}if(null!==compress)for(swaps=pieceIndex-compress,pieceIndex=7;0!=pieceIndex&&0<swaps;)swap=address[pieceIndex],address[pieceIndex--]=address[compress+swaps-1],address[compress+--swaps]=swap;else if(8!=pieceIndex)return;return address}(stringSlice(input,1,-1)))?void(this.host=result):"Invalid host";if(this.isSpecial())return input=toASCII(input),exec(FORBIDDEN_HOST_CODE_POINT,input)||null===(result=function(input){var partsLength,numbers,index,part,radix,number,ipv4,parts=split(input,".");if(parts.length&&""==parts[parts.length-1]&&parts.length--,4<(partsLength=parts.length))return input;for(numbers=[],index=0;index<partsLength;index++){if(""==(part=parts[index]))return input;if(radix=10,1<part.length&&"0"==charAt(part,0)&&(radix=exec(HEX_START,part)?16:8,part=stringSlice(part,8==radix?1:2)),""===part)number=0;else{if(!exec(10==radix?DEC:8==radix?OCT:HEX,part))return input;number=parseInt(part,radix)}push(numbers,number)}for(index=0;index<partsLength;index++)if(number=numbers[index],index==partsLength-1){if(number>=pow(256,5-partsLength))return null}else if(255<number)return null;for(ipv4=pop(numbers),index=0;index<numbers.length;index++)ipv4+=numbers[index]*pow(256,3-index);return ipv4}(input))?"Invalid host":void(this.host=result);if(exec(FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT,input))return"Invalid host";for(result="",codePoints=arrayFrom(input),index=0;index<codePoints.length;index++)result+=percentEncode(codePoints[index],C0ControlPercentEncodeSet);this.host=result},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return hasOwn(specialSchemes,this.scheme)},shortenPath:function(){var path=this.path,pathSize=path.length;!pathSize||"file"==this.scheme&&1==pathSize&&isWindowsDriveLetter(path[0],!0)||path.length--},serialize:function(){var url=this,scheme=url.scheme,username=url.username,password=url.password,host=url.host,port=url.port,path=url.path,query=url.query,fragment=url.fragment,output=scheme+":";return null!==host?(output+="//",url.includesCredentials()&&(output+=username+(password?":"+password:"")+"@"),output+=serializeHost(host),null!==port&&(output+=":"+port)):"file"==scheme&&(output+="//"),output+=url.cannotBeABaseURL?path[0]:path.length?"/"+join(path,"/"):"",null!==query&&(output+="?"+query),null!==fragment&&(output+="#"+fragment),output},setHref:function(href){href=this.parse(href);if(href)throw TypeError(href);this.searchParams.update()},getOrigin:function(){var scheme=this.scheme,port=this.port;if("blob"==scheme)try{return new URLConstructor(scheme.path[0]).origin}catch(error){return"null"}return"file"!=scheme&&this.isSpecial()?scheme+"://"+serializeHost(this.host)+(null!==port?":"+port:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(protocol){this.parse($toString(protocol)+":",SCHEME_START)},getUsername:function(){return this.username},setUsername:function(username){var codePoints=arrayFrom($toString(username));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<codePoints.length;i++)this.username+=percentEncode(codePoints[i],userinfoPercentEncodeSet)}},getPassword:function(){return this.password},setPassword:function(password){var codePoints=arrayFrom($toString(password));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<codePoints.length;i++)this.password+=percentEncode(codePoints[i],userinfoPercentEncodeSet)}},getHost:function(){var host=this.host,port=this.port;return null===host?"":null===port?serializeHost(host):serializeHost(host)+":"+port},setHost:function(host){this.cannotBeABaseURL||this.parse(host,HOST)},getHostname:function(){var host=this.host;return null===host?"":serializeHost(host)},setHostname:function(hostname){this.cannotBeABaseURL||this.parse(hostname,HOSTNAME)},getPort:function(){var port=this.port;return null===port?"":$toString(port)},setPort:function(port){this.cannotHaveUsernamePasswordPort()||(""==(port=$toString(port))?this.port=null:this.parse(port,PORT))},getPathname:function(){var path=this.path;return this.cannotBeABaseURL?path[0]:path.length?"/"+join(path,"/"):""},setPathname:function(pathname){this.cannotBeABaseURL||(this.path=[],this.parse(pathname,PATH_START))},getSearch:function(){var query=this.query;return query?"?"+query:""},setSearch:function(search){""==(search=$toString(search))?this.query=null:("?"==charAt(search,0)&&(search=stringSlice(search,1)),this.query="",this.parse(search,QUERY)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var fragment=this.fragment;return fragment?"#"+fragment:""},setHash:function(hash){""==(hash=$toString(hash))?this.fragment=null:("#"==charAt(hash,0)&&(hash=stringSlice(hash,1)),this.fragment="",this.parse(hash,FRAGMENT))},update:function(){this.query=this.searchParams.serialize()||null}},function(url){var that=anInstance(this,URLPrototype),base=1<validateArgumentsLength(arguments.length,1)?arguments[1]:void 0,url=setInternalState(that,new URLState(url,!1,base));DESCRIPTORS||(that.href=url.serialize(),that.origin=url.getOrigin(),that.protocol=url.getProtocol(),that.username=url.getUsername(),that.password=url.getPassword(),that.host=url.getHost(),that.hostname=url.getHostname(),that.port=url.getPort(),that.pathname=url.getPathname(),that.search=url.getSearch(),that.searchParams=url.getSearchParams(),that.hash=url.getHash())}),URLPrototype=URLConstructor.prototype;DESCRIPTORS&&(defineBuiltInAccessor(URLPrototype,"href",accessorDescriptor("serialize","setHref")),defineBuiltInAccessor(URLPrototype,"origin",accessorDescriptor("getOrigin")),defineBuiltInAccessor(URLPrototype,"protocol",accessorDescriptor("getProtocol","setProtocol")),defineBuiltInAccessor(URLPrototype,"username",accessorDescriptor("getUsername","setUsername")),defineBuiltInAccessor(URLPrototype,"password",accessorDescriptor("getPassword","setPassword")),defineBuiltInAccessor(URLPrototype,"host",accessorDescriptor("getHost","setHost")),defineBuiltInAccessor(URLPrototype,"hostname",accessorDescriptor("getHostname","setHostname")),defineBuiltInAccessor(URLPrototype,"port",accessorDescriptor("getPort","setPort")),defineBuiltInAccessor(URLPrototype,"pathname",accessorDescriptor("getPathname","setPathname")),defineBuiltInAccessor(URLPrototype,"search",accessorDescriptor("getSearch","setSearch")),defineBuiltInAccessor(URLPrototype,"searchParams",accessorDescriptor("getSearchParams")),defineBuiltInAccessor(URLPrototype,"hash",accessorDescriptor("getHash","setHash"))),defineBuiltIn(URLPrototype,"toJSON",function(){return getInternalURLState(this).serialize()},{enumerable:!0}),defineBuiltIn(URLPrototype,"toString",function(){return getInternalURLState(this).serialize()},{enumerable:!0}),require&&(URLSearchParamsModule=require.createObjectURL,global=require.revokeObjectURL,URLSearchParamsModule&&defineBuiltIn(URLConstructor,"createObjectURL",bind(URLSearchParamsModule,require)),global)&&defineBuiltIn(URLConstructor,"revokeObjectURL",bind(global,require)),setToStringTag(URLConstructor,"URL"),$({global:!0,constructor:!0,forced:!USE_NATIVE_URL,sham:!DESCRIPTORS},{URL:URLConstructor})},{"../internals/an-instance":122,"../internals/array-from":132,"../internals/array-slice-simple":141,"../internals/define-built-in":167,"../internals/define-built-in-accessor":166,"../internals/descriptors":171,"../internals/export":196,"../internals/function-bind-context":202,"../internals/function-uncurry-this":209,"../internals/global":216,"../internals/has-own-property":217,"../internals/internal-state":228,"../internals/object-assign":264,"../internals/set-to-string-tag":304,"../internals/string-multibyte":310,"../internals/string-punycode-to-ascii":313,"../internals/to-string":337,"../internals/url-constructor-detection":346,"../internals/validate-arguments-length":349,"../modules/es.string.iterator":528,"../modules/web.url-search-params.constructor":630}],635:[function(require,module,exports){require("../modules/web.url.constructor")},{"../modules/web.url.constructor":634}],636:[function(require,module,exports){"use strict";var $=require("../internals/export"),call=require("../internals/function-call");$({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return call(URL.prototype.toString,this)}})},{"../internals/export":196,"../internals/function-call":205}],637:[function(require,module,exports){require("../modules/es.symbol"),require("../modules/es.symbol.description"),require("../modules/es.symbol.async-iterator"),require("../modules/es.symbol.has-instance"),require("../modules/es.symbol.is-concat-spreadable"),require("../modules/es.symbol.iterator"),require("../modules/es.symbol.match"),require("../modules/es.symbol.match-all"),require("../modules/es.symbol.replace"),require("../modules/es.symbol.search"),require("../modules/es.symbol.species"),require("../modules/es.symbol.split"),require("../modules/es.symbol.to-primitive"),require("../modules/es.symbol.to-string-tag"),require("../modules/es.symbol.unscopables"),require("../modules/es.error.cause"),require("../modules/es.error.to-string"),require("../modules/es.aggregate-error"),require("../modules/es.aggregate-error.cause"),require("../modules/es.array.at"),require("../modules/es.array.concat"),require("../modules/es.array.copy-within"),require("../modules/es.array.every"),require("../modules/es.array.fill"),require("../modules/es.array.filter"),require("../modules/es.array.find"),require("../modules/es.array.find-index"),require("../modules/es.array.find-last"),require("../modules/es.array.find-last-index"),require("../modules/es.array.flat"),require("../modules/es.array.flat-map"),require("../modules/es.array.for-each"),require("../modules/es.array.from"),require("../modules/es.array.includes"),require("../modules/es.array.index-of"),require("../modules/es.array.is-array"),require("../modules/es.array.iterator"),require("../modules/es.array.join"),require("../modules/es.array.last-index-of"),require("../modules/es.array.map"),require("../modules/es.array.of"),require("../modules/es.array.push"),require("../modules/es.array.reduce"),require("../modules/es.array.reduce-right"),require("../modules/es.array.reverse"),require("../modules/es.array.slice"),require("../modules/es.array.some"),require("../modules/es.array.sort"),require("../modules/es.array.species"),require("../modules/es.array.splice"),require("../modules/es.array.to-reversed"),require("../modules/es.array.to-sorted"),require("../modules/es.array.to-spliced"),require("../modules/es.array.unscopables.flat"),require("../modules/es.array.unscopables.flat-map"),require("../modules/es.array.unshift"),require("../modules/es.array.with"),require("../modules/es.array-buffer.constructor"),require("../modules/es.array-buffer.is-view"),require("../modules/es.array-buffer.slice"),require("../modules/es.data-view"),require("../modules/es.date.get-year"),require("../modules/es.date.now"),require("../modules/es.date.set-year"),require("../modules/es.date.to-gmt-string"),require("../modules/es.date.to-iso-string"),require("../modules/es.date.to-json"),require("../modules/es.date.to-primitive"),require("../modules/es.date.to-string"),require("../modules/es.escape"),require("../modules/es.function.bind"),require("../modules/es.function.has-instance"),require("../modules/es.function.name"),require("../modules/es.global-this"),require("../modules/es.json.stringify"),require("../modules/es.json.to-string-tag"),require("../modules/es.map"),require("../modules/es.math.acosh"),require("../modules/es.math.asinh"),require("../modules/es.math.atanh"),require("../modules/es.math.cbrt"),require("../modules/es.math.clz32"),require("../modules/es.math.cosh"),require("../modules/es.math.expm1"),require("../modules/es.math.fround"),require("../modules/es.math.hypot"),require("../modules/es.math.imul"),require("../modules/es.math.log10"),require("../modules/es.math.log1p"),require("../modules/es.math.log2"),require("../modules/es.math.sign"),require("../modules/es.math.sinh"),require("../modules/es.math.tanh"),require("../modules/es.math.to-string-tag"),require("../modules/es.math.trunc"),require("../modules/es.number.constructor"),require("../modules/es.number.epsilon"),require("../modules/es.number.is-finite"),require("../modules/es.number.is-integer"),require("../modules/es.number.is-nan"),require("../modules/es.number.is-safe-integer"),require("../modules/es.number.max-safe-integer"),require("../modules/es.number.min-safe-integer"),require("../modules/es.number.parse-float"),require("../modules/es.number.parse-int"),require("../modules/es.number.to-exponential"),require("../modules/es.number.to-fixed"),require("../modules/es.number.to-precision"),require("../modules/es.object.assign"),require("../modules/es.object.create"),require("../modules/es.object.define-getter"),require("../modules/es.object.define-properties"),require("../modules/es.object.define-property"),require("../modules/es.object.define-setter"),require("../modules/es.object.entries"),require("../modules/es.object.freeze"),require("../modules/es.object.from-entries"),require("../modules/es.object.get-own-property-descriptor"),require("../modules/es.object.get-own-property-descriptors"),require("../modules/es.object.get-own-property-names"),require("../modules/es.object.get-prototype-of"),require("../modules/es.object.has-own"),require("../modules/es.object.is"),require("../modules/es.object.is-extensible"),require("../modules/es.object.is-frozen"),require("../modules/es.object.is-sealed"),require("../modules/es.object.keys"),require("../modules/es.object.lookup-getter"),require("../modules/es.object.lookup-setter"),require("../modules/es.object.prevent-extensions"),require("../modules/es.object.proto"),require("../modules/es.object.seal"),require("../modules/es.object.set-prototype-of"),require("../modules/es.object.to-string"),require("../modules/es.object.values"),require("../modules/es.parse-float"),require("../modules/es.parse-int"),require("../modules/es.promise"),require("../modules/es.promise.all-settled"),require("../modules/es.promise.any"),require("../modules/es.promise.finally"),require("../modules/es.reflect.apply"),require("../modules/es.reflect.construct"),require("../modules/es.reflect.define-property"),require("../modules/es.reflect.delete-property"),require("../modules/es.reflect.get"),require("../modules/es.reflect.get-own-property-descriptor"),require("../modules/es.reflect.get-prototype-of"),require("../modules/es.reflect.has"),require("../modules/es.reflect.is-extensible"),require("../modules/es.reflect.own-keys"),require("../modules/es.reflect.prevent-extensions"),require("../modules/es.reflect.set"),require("../modules/es.reflect.set-prototype-of"),require("../modules/es.reflect.to-string-tag"),require("../modules/es.regexp.constructor"),require("../modules/es.regexp.dot-all"),require("../modules/es.regexp.exec"),require("../modules/es.regexp.flags"),require("../modules/es.regexp.sticky"),require("../modules/es.regexp.test"),require("../modules/es.regexp.to-string"),require("../modules/es.set"),require("../modules/es.string.at-alternative"),require("../modules/es.string.code-point-at"),require("../modules/es.string.ends-with"),require("../modules/es.string.from-code-point"),require("../modules/es.string.includes"),require("../modules/es.string.iterator"),require("../modules/es.string.match"),require("../modules/es.string.match-all"),require("../modules/es.string.pad-end"),require("../modules/es.string.pad-start"),require("../modules/es.string.raw"),require("../modules/es.string.repeat"),require("../modules/es.string.replace"),require("../modules/es.string.replace-all"),require("../modules/es.string.search"),require("../modules/es.string.split"),require("../modules/es.string.starts-with"),require("../modules/es.string.substr"),require("../modules/es.string.trim"),require("../modules/es.string.trim-end"),require("../modules/es.string.trim-start"),require("../modules/es.string.anchor"),require("../modules/es.string.big"),require("../modules/es.string.blink"),require("../modules/es.string.bold"),require("../modules/es.string.fixed"),require("../modules/es.string.fontcolor"),require("../modules/es.string.fontsize"),require("../modules/es.string.italics"),require("../modules/es.string.link"),require("../modules/es.string.small"),require("../modules/es.string.strike"),require("../modules/es.string.sub"),require("../modules/es.string.sup"),require("../modules/es.typed-array.float32-array"),require("../modules/es.typed-array.float64-array"),require("../modules/es.typed-array.int8-array"),require("../modules/es.typed-array.int16-array"),require("../modules/es.typed-array.int32-array"),require("../modules/es.typed-array.uint8-array"),require("../modules/es.typed-array.uint8-clamped-array"),require("../modules/es.typed-array.uint16-array"),require("../modules/es.typed-array.uint32-array"),require("../modules/es.typed-array.at"),require("../modules/es.typed-array.copy-within"),require("../modules/es.typed-array.every"),require("../modules/es.typed-array.fill"),require("../modules/es.typed-array.filter"),require("../modules/es.typed-array.find"),require("../modules/es.typed-array.find-index"),require("../modules/es.typed-array.find-last"),require("../modules/es.typed-array.find-last-index"),require("../modules/es.typed-array.for-each"),require("../modules/es.typed-array.from"),require("../modules/es.typed-array.includes"),require("../modules/es.typed-array.index-of"),require("../modules/es.typed-array.iterator"),require("../modules/es.typed-array.join"),require("../modules/es.typed-array.last-index-of"),require("../modules/es.typed-array.map"),require("../modules/es.typed-array.of"),require("../modules/es.typed-array.reduce"),require("../modules/es.typed-array.reduce-right"),require("../modules/es.typed-array.reverse"),require("../modules/es.typed-array.set"),require("../modules/es.typed-array.slice"),require("../modules/es.typed-array.some"),require("../modules/es.typed-array.sort"),require("../modules/es.typed-array.subarray"),require("../modules/es.typed-array.to-locale-string"),require("../modules/es.typed-array.to-reversed"),require("../modules/es.typed-array.to-sorted"),require("../modules/es.typed-array.to-string"),require("../modules/es.typed-array.with"),require("../modules/es.unescape"),require("../modules/es.weak-map"),require("../modules/es.weak-set"),require("../modules/web.atob"),require("../modules/web.btoa"),require("../modules/web.dom-collections.for-each"),require("../modules/web.dom-collections.iterator"),require("../modules/web.dom-exception.constructor"),require("../modules/web.dom-exception.stack"),require("../modules/web.dom-exception.to-string-tag"),require("../modules/web.immediate"),require("../modules/web.queue-microtask"),require("../modules/web.self"),require("../modules/web.structured-clone"),require("../modules/web.timers"),require("../modules/web.url"),require("../modules/web.url.can-parse"),require("../modules/web.url.to-json"),require("../modules/web.url-search-params"),require("../modules/web.url-search-params.size"),module.exports=require("../internals/path")},{"../internals/path":284,"../modules/es.aggregate-error":358,"../modules/es.aggregate-error.cause":356,"../modules/es.array-buffer.constructor":359,"../modules/es.array-buffer.is-view":360,"../modules/es.array-buffer.slice":361,"../modules/es.array.at":362,"../modules/es.array.concat":363,"../modules/es.array.copy-within":364,"../modules/es.array.every":365,"../modules/es.array.fill":366,"../modules/es.array.filter":367,"../modules/es.array.find":371,"../modules/es.array.find-index":368,"../modules/es.array.find-last":370,"../modules/es.array.find-last-index":369,"../modules/es.array.flat":373,"../modules/es.array.flat-map":372,"../modules/es.array.for-each":374,"../modules/es.array.from":375,"../modules/es.array.includes":376,"../modules/es.array.index-of":377,"../modules/es.array.is-array":378,"../modules/es.array.iterator":379,"../modules/es.array.join":380,"../modules/es.array.last-index-of":381,"../modules/es.array.map":382,"../modules/es.array.of":383,"../modules/es.array.push":384,"../modules/es.array.reduce":386,"../modules/es.array.reduce-right":385,"../modules/es.array.reverse":387,"../modules/es.array.slice":388,"../modules/es.array.some":389,"../modules/es.array.sort":390,"../modules/es.array.species":391,"../modules/es.array.splice":392,"../modules/es.array.to-reversed":393,"../modules/es.array.to-sorted":394,"../modules/es.array.to-spliced":395,"../modules/es.array.unscopables.flat":397,"../modules/es.array.unscopables.flat-map":396,"../modules/es.array.unshift":398,"../modules/es.array.with":399,"../modules/es.data-view":401,"../modules/es.date.get-year":402,"../modules/es.date.now":403,"../modules/es.date.set-year":404,"../modules/es.date.to-gmt-string":405,"../modules/es.date.to-iso-string":406,"../modules/es.date.to-json":407,"../modules/es.date.to-primitive":408,"../modules/es.date.to-string":409,"../modules/es.error.cause":410,"../modules/es.error.to-string":411,"../modules/es.escape":412,"../modules/es.function.bind":413,"../modules/es.function.has-instance":414,"../modules/es.function.name":415,"../modules/es.global-this":416,"../modules/es.json.stringify":417,"../modules/es.json.to-string-tag":418,"../modules/es.map":420,"../modules/es.math.acosh":421,"../modules/es.math.asinh":422,"../modules/es.math.atanh":423,"../modules/es.math.cbrt":424,"../modules/es.math.clz32":425,"../modules/es.math.cosh":426,"../modules/es.math.expm1":427,"../modules/es.math.fround":428,"../modules/es.math.hypot":429,"../modules/es.math.imul":430,"../modules/es.math.log10":431,"../modules/es.math.log1p":432,"../modules/es.math.log2":433,"../modules/es.math.sign":434,"../modules/es.math.sinh":435,"../modules/es.math.tanh":436,"../modules/es.math.to-string-tag":437,"../modules/es.math.trunc":438,"../modules/es.number.constructor":439,"../modules/es.number.epsilon":440,"../modules/es.number.is-finite":441,"../modules/es.number.is-integer":442,"../modules/es.number.is-nan":443,"../modules/es.number.is-safe-integer":444,"../modules/es.number.max-safe-integer":445,"../modules/es.number.min-safe-integer":446,"../modules/es.number.parse-float":447,"../modules/es.number.parse-int":448,"../modules/es.number.to-exponential":449,"../modules/es.number.to-fixed":450,"../modules/es.number.to-precision":451,"../modules/es.object.assign":452,"../modules/es.object.create":453,"../modules/es.object.define-getter":454,"../modules/es.object.define-properties":455,"../modules/es.object.define-property":456,"../modules/es.object.define-setter":457,"../modules/es.object.entries":458,"../modules/es.object.freeze":459,"../modules/es.object.from-entries":460,"../modules/es.object.get-own-property-descriptor":461,"../modules/es.object.get-own-property-descriptors":462,"../modules/es.object.get-own-property-names":463,"../modules/es.object.get-prototype-of":465,"../modules/es.object.has-own":466,"../modules/es.object.is":470,"../modules/es.object.is-extensible":467,"../modules/es.object.is-frozen":468,"../modules/es.object.is-sealed":469,"../modules/es.object.keys":471,"../modules/es.object.lookup-getter":472,"../modules/es.object.lookup-setter":473,"../modules/es.object.prevent-extensions":474,"../modules/es.object.proto":475,"../modules/es.object.seal":476,"../modules/es.object.set-prototype-of":477,"../modules/es.object.to-string":478,"../modules/es.object.values":479,"../modules/es.parse-float":480,"../modules/es.parse-int":481,"../modules/es.promise":488,"../modules/es.promise.all-settled":482,"../modules/es.promise.any":484,"../modules/es.promise.finally":487,"../modules/es.reflect.apply":492,"../modules/es.reflect.construct":493,"../modules/es.reflect.define-property":494,"../modules/es.reflect.delete-property":495,"../modules/es.reflect.get":498,"../modules/es.reflect.get-own-property-descriptor":496,"../modules/es.reflect.get-prototype-of":497,"../modules/es.reflect.has":499,"../modules/es.reflect.is-extensible":500,"../modules/es.reflect.own-keys":501,"../modules/es.reflect.prevent-extensions":502,"../modules/es.reflect.set":504,"../modules/es.reflect.set-prototype-of":503,"../modules/es.reflect.to-string-tag":505,"../modules/es.regexp.constructor":506,"../modules/es.regexp.dot-all":507,"../modules/es.regexp.exec":508,"../modules/es.regexp.flags":509,"../modules/es.regexp.sticky":510,"../modules/es.regexp.test":511,"../modules/es.regexp.to-string":512,"../modules/es.set":514,"../modules/es.string.anchor":515,"../modules/es.string.at-alternative":516,"../modules/es.string.big":517,"../modules/es.string.blink":518,"../modules/es.string.bold":519,"../modules/es.string.code-point-at":520,"../modules/es.string.ends-with":521,"../modules/es.string.fixed":522,"../modules/es.string.fontcolor":523,"../modules/es.string.fontsize":524,"../modules/es.string.from-code-point":525,"../modules/es.string.includes":526,"../modules/es.string.italics":527,"../modules/es.string.iterator":528,"../modules/es.string.link":529,"../modules/es.string.match":531,"../modules/es.string.match-all":530,"../modules/es.string.pad-end":532,"../modules/es.string.pad-start":533,"../modules/es.string.raw":534,"../modules/es.string.repeat":535,"../modules/es.string.replace":537,"../modules/es.string.replace-all":536,"../modules/es.string.search":538,"../modules/es.string.small":539,"../modules/es.string.split":540,"../modules/es.string.starts-with":541,"../modules/es.string.strike":542,"../modules/es.string.sub":543,"../modules/es.string.substr":544,"../modules/es.string.sup":545,"../modules/es.string.trim":550,"../modules/es.string.trim-end":546,"../modules/es.string.trim-start":549,"../modules/es.symbol":558,"../modules/es.symbol.async-iterator":551,"../modules/es.symbol.description":553,"../modules/es.symbol.has-instance":555,"../modules/es.symbol.is-concat-spreadable":556,"../modules/es.symbol.iterator":557,"../modules/es.symbol.match":561,"../modules/es.symbol.match-all":560,"../modules/es.symbol.replace":562,"../modules/es.symbol.search":563,"../modules/es.symbol.species":564,"../modules/es.symbol.split":565,"../modules/es.symbol.to-primitive":566,"../modules/es.symbol.to-string-tag":567,"../modules/es.symbol.unscopables":568,"../modules/es.typed-array.at":569,"../modules/es.typed-array.copy-within":570,"../modules/es.typed-array.every":571,"../modules/es.typed-array.fill":572,"../modules/es.typed-array.filter":573,"../modules/es.typed-array.find":577,"../modules/es.typed-array.find-index":574,"../modules/es.typed-array.find-last":576,"../modules/es.typed-array.find-last-index":575,"../modules/es.typed-array.float32-array":578,"../modules/es.typed-array.float64-array":579,"../modules/es.typed-array.for-each":580,"../modules/es.typed-array.from":581,"../modules/es.typed-array.includes":582,"../modules/es.typed-array.index-of":583,"../modules/es.typed-array.int16-array":584,"../modules/es.typed-array.int32-array":585,"../modules/es.typed-array.int8-array":586,"../modules/es.typed-array.iterator":587,"../modules/es.typed-array.join":588,"../modules/es.typed-array.last-index-of":589,"../modules/es.typed-array.map":590,"../modules/es.typed-array.of":591,"../modules/es.typed-array.reduce":593,"../modules/es.typed-array.reduce-right":592,"../modules/es.typed-array.reverse":594,"../modules/es.typed-array.set":595,"../modules/es.typed-array.slice":596,"../modules/es.typed-array.some":597,"../modules/es.typed-array.sort":598,"../modules/es.typed-array.subarray":599,"../modules/es.typed-array.to-locale-string":600,"../modules/es.typed-array.to-reversed":601,"../modules/es.typed-array.to-sorted":602,"../modules/es.typed-array.to-string":603,"../modules/es.typed-array.uint16-array":604,"../modules/es.typed-array.uint32-array":605,"../modules/es.typed-array.uint8-array":606,"../modules/es.typed-array.uint8-clamped-array":607,"../modules/es.typed-array.with":608,"../modules/es.unescape":609,"../modules/es.weak-map":611,"../modules/es.weak-set":613,"../modules/web.atob":614,"../modules/web.btoa":615,"../modules/web.dom-collections.for-each":617,"../modules/web.dom-collections.iterator":618,"../modules/web.dom-exception.constructor":619,"../modules/web.dom-exception.stack":620,"../modules/web.dom-exception.to-string-tag":621,"../modules/web.immediate":622,"../modules/web.queue-microtask":623,"../modules/web.self":624,"../modules/web.structured-clone":628,"../modules/web.timers":629,"../modules/web.url":635,"../modules/web.url-search-params":631,"../modules/web.url-search-params.size":632,"../modules/web.url.can-parse":633,"../modules/web.url.to-json":636}],638:[function(require,module,exports){var objectKeys=require("object-keys"),isArguments=require("is-arguments"),is=require("object-is"),isRegex=require("is-regex"),flags=require("regexp.prototype.flags"),isDate=require("is-date-object"),getTime=Date.prototype.getTime;function deepEqual(actual,expected,options){options=options||{};return!(options.strict?!is(actual,expected):actual!==expected)||(!actual||!expected||"object"!=typeof actual&&"object"!=typeof expected?options.strict?is(actual,expected):actual==expected:function(a,b,opts){var i,key;if(typeof a!=typeof b)return!1;if(isUndefinedOrNull(a)||isUndefinedOrNull(b))return!1;if(a.prototype!==b.prototype)return!1;if(isArguments(a)!==isArguments(b))return!1;var aIsRegex=isRegex(a),bIsRegex=isRegex(b);if(aIsRegex!==bIsRegex)return!1;if(aIsRegex||bIsRegex)return a.source===b.source&&flags(a)===flags(b);if(isDate(a)&&isDate(b))return getTime.call(a)===getTime.call(b);aIsRegex=isBuffer(a),bIsRegex=isBuffer(b);if(aIsRegex!==bIsRegex)return!1;if(aIsRegex||bIsRegex){if(a.length!==b.length)return!1;for(i=0;i<a.length;i++)if(a[i]!==b[i])return!1}else{if(typeof a!=typeof b)return!1;try{var ka=objectKeys(a),kb=objectKeys(b)}catch(e){return!1}if(ka.length!==kb.length)return!1;for(ka.sort(),kb.sort(),i=ka.length-1;0<=i;i--)if(ka[i]!=kb[i])return!1;for(i=ka.length-1;0<=i;i--)if(key=ka[i],!deepEqual(a[key],b[key],opts))return!1}return!0}(actual,expected,options))}function isUndefinedOrNull(value){return null==value}function isBuffer(x){return!(!x||"object"!=typeof x||"number"!=typeof x.length||"function"!=typeof x.copy||"function"!=typeof x.slice||0<x.length&&"number"!=typeof x[0])}module.exports=deepEqual},{"is-arguments":657,"is-date-object":658,"is-regex":659,"object-is":1034,"object-keys":1038,"regexp.prototype.flags":1432}],639:[function(require,module,exports){"use strict";function defineProperties(object,map){var predicates=2<arguments.length?arguments[2]:{},props=keys(map);hasSymbols&&(props=concat.call(props,Object.getOwnPropertySymbols(map)));for(var i=0;i<props.length;i+=1)!function(object,name,value,predicate){if(name in object)if(!0===predicate){if(object[name]===value)return}else if(!isFunction(predicate)||!predicate())return;supportsDescriptors?origDefineProperty(object,name,{configurable:!0,enumerable:!1,value:value,writable:!0}):object[name]=value}(object,props[i],map[props[i]],predicates[props[i]])}var keys=require("object-keys"),hasSymbols="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),toStr=Object.prototype.toString,concat=Array.prototype.concat,origDefineProperty=Object.defineProperty,isFunction=function(fn){return"function"==typeof fn&&"[object Function]"===toStr.call(fn)},require=require("has-property-descriptors")(),supportsDescriptors=origDefineProperty&&require;defineProperties.supportsDescriptors=!!supportsDescriptors,module.exports=defineProperties},{"has-property-descriptors":646,"object-keys":1038}],640:[function(require,module,exports){!function(){"use strict";var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),ExecutionEnvironment={canUseDOM:canUseDOM,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:canUseDOM&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:canUseDOM&&!!window.screen};"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return ExecutionEnvironment}):void 0!==module&&module.exports?module.exports=ExecutionEnvironment:window.ExecutionEnvironment=ExecutionEnvironment}()},{}],641:[function(require,module,exports){"use strict";var slice=Array.prototype.slice,toStr=Object.prototype.toString;module.exports=function(that){var target=this;if("function"!=typeof target||"[object Function]"!==toStr.call(target))throw new TypeError("Function.prototype.bind called on incompatible "+target);for(var bound,Empty,args=slice.call(arguments,1),boundLength=Math.max(0,target.length-args.length),boundArgs=[],i=0;i<boundLength;i++)boundArgs.push("$"+i);return bound=Function("binder","return function ("+boundArgs.join(",")+"){ return binder.apply(this,arguments); }")(function(){var result;return this instanceof bound?(result=target.apply(this,args.concat(slice.call(arguments))),Object(result)===result?result:this):target.apply(that,args.concat(slice.call(arguments)))}),target.prototype&&((Empty=function(){}).prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound}},{}],642:[function(require,module,exports){"use strict";require=require("./implementation");module.exports=Function.prototype.bind||require},{"./implementation":641}],643:[function(require,module,exports){"use strict";function functionsHaveNames(){return"string"==typeof function(){}.name}var gOPD=Object.getOwnPropertyDescriptor;if(gOPD)try{gOPD([],"length")}catch(e){gOPD=null}functionsHaveNames.functionsHaveConfigurableNames=function(){var desc;return!!(functionsHaveNames()&&gOPD&&(desc=gOPD(function(){},"name"))&&desc.configurable)};var $bind=Function.prototype.bind;functionsHaveNames.boundFunctionsHaveNames=function(){return functionsHaveNames()&&"function"==typeof $bind&&""!==function(){}.bind().name},module.exports=functionsHaveNames},{}],644:[function(require,module,exports){"use strict";var $SyntaxError=SyntaxError,$Function=Function,$TypeError=TypeError,getEvalledConstructor=function(expressionSyntax){try{return $Function('"use strict"; return ('+expressionSyntax+").constructor;")()}catch(e){}},$gOPD=Object.getOwnPropertyDescriptor;if($gOPD)try{$gOPD({},"")}catch(e){$gOPD=null}function throwTypeError(){throw new $TypeError}var ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError,hasSymbols=require("has-symbols")(),getProto=Object.getPrototypeOf||function(x){return x.__proto__},needsEval={},TypedArray="undefined"==typeof Uint8Array?void 0:getProto(Uint8Array),INTRINSICS={"%AggregateError%":"undefined"==typeof AggregateError?void 0:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols?getProto([][Symbol.iterator]()):void 0,"%AsyncFromSyncIteratorPrototype%":void 0,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?void 0:Atomics,"%BigInt%":"undefined"==typeof BigInt?void 0:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?void 0:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?void 0:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?void 0:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?void 0:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?void 0:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?void 0:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?void 0:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?void 0:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols?getProto(getProto([][Symbol.iterator]())):void 0,"%JSON%":"object"==typeof JSON?JSON:void 0,"%Map%":"undefined"==typeof Map?void 0:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols?getProto((new Map)[Symbol.iterator]()):void 0,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?void 0:Promise,"%Proxy%":"undefined"==typeof Proxy?void 0:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?void 0:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?void 0:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols?getProto((new Set)[Symbol.iterator]()):void 0,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols?getProto(""[Symbol.iterator]()):void 0,"%Symbol%":hasSymbols?Symbol:void 0,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?void 0:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?void 0:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?void 0:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?void 0:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?void 0:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?void 0:WeakSet};try{null.error}catch(e){hasSymbols=getProto(getProto(e));INTRINSICS["%Error.prototype%"]=hasSymbols}function doEval(name){var value,fn;return"%AsyncFunction%"===name?value=getEvalledConstructor("async function () {}"):"%GeneratorFunction%"===name?value=getEvalledConstructor("function* () {}"):"%AsyncGeneratorFunction%"===name?value=getEvalledConstructor("async function* () {}"):"%AsyncGenerator%"===name?(fn=doEval("%AsyncGeneratorFunction%"))&&(value=fn.prototype):"%AsyncIteratorPrototype%"===name&&(fn=doEval("%AsyncGenerator%"))&&(value=getProto(fn.prototype)),INTRINSICS[name]=value}var LEGACY_ALIASES={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},ThrowTypeError=require("function-bind"),hasOwn=require("has"),$concat=ThrowTypeError.call(Function.call,Array.prototype.concat),$spliceApply=ThrowTypeError.call(Function.apply,Array.prototype.splice),$replace=ThrowTypeError.call(Function.call,String.prototype.replace),$strSlice=ThrowTypeError.call(Function.call,String.prototype.slice),$exec=ThrowTypeError.call(Function.call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g;module.exports=function(name,allowMissing){if("string"!=typeof name||0===name.length)throw new $TypeError("intrinsic name must be a non-empty string");if(1<arguments.length&&"boolean"!=typeof allowMissing)throw new $TypeError('"allowMissing" argument must be a boolean');if(null===$exec(/^%?[^%]*%?$/,name))throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var parts=function(string){var first=$strSlice(string,0,1),last=$strSlice(string,-1);if("%"===first&&"%"!==last)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===last&&"%"!==first)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var result=[];return $replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match}),result}(name),intrinsicBaseName=0<parts.length?parts[0]:"",intrinsic=function(name,allowMissing){var alias,intrinsicName=name;if(hasOwn(LEGACY_ALIASES,intrinsicName)&&(intrinsicName="%"+(alias=LEGACY_ALIASES[intrinsicName])[0]+"%"),hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(void 0!==(value=value===needsEval?doEval(intrinsicName):value)||allowMissing)return{alias:alias,name:intrinsicName,value:value};throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!")}throw new $SyntaxError("intrinsic "+name+" does not exist!")}("%"+intrinsicBaseName+"%",allowMissing),value=(intrinsic.name,intrinsic.value),skipFurtherCaching=!1,intrinsic=intrinsic.alias;intrinsic&&(intrinsicBaseName=intrinsic[0],$spliceApply(parts,$concat([0,1],intrinsic)));for(var i=1,isOwn=!0;i<parts.length;i+=1){var part=parts[i],first=$strSlice(part,0,1),last=$strSlice(part,-1);if(('"'===first||"'"===first||"`"===first||'"'===last||"'"===last||"`"===last)&&first!==last)throw new $SyntaxError("property names with quotes must have matching quotes");if("constructor"!==part&&isOwn||(skipFurtherCaching=!0),hasOwn(INTRINSICS,first="%"+(intrinsicBaseName+="."+part)+"%"))value=INTRINSICS[first];else if(null!=value){if(!(part in value)){if(allowMissing)return;throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.")}value=$gOPD&&i+1>=parts.length?(isOwn=!!(last=$gOPD(value,part)))&&"get"in last&&!("originalValue"in last.get)?last.get:value[part]:(isOwn=hasOwn(value,part),value[part]),isOwn&&!skipFurtherCaching&&(INTRINSICS[first]=value)}}return value}},{"function-bind":642,has:650,"has-symbols":647}],645:[function(require,module,exports){!function(global){!function(){"use strict";var key="__global_unique_id__";module.exports=function(){return global[key]=(global[key]||0)+1}}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],646:[function(require,module,exports){"use strict";function hasPropertyDescriptors(){if($defineProperty)try{return $defineProperty({},"a",{value:1}),!0}catch(e){}return!1}var $defineProperty=require("get-intrinsic")("%Object.defineProperty%",!0);hasPropertyDescriptors.hasArrayLengthDefineBug=function(){if(!hasPropertyDescriptors())return null;try{return 1!==$defineProperty([],"length",{value:1}).length}catch(e){return!0}},module.exports=hasPropertyDescriptors},{"get-intrinsic":644}],647:[function(require,module,exports){"use strict";var origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbolSham=require("./shams");module.exports=function(){return"function"==typeof origSymbol&&"function"==typeof Symbol&&"symbol"==typeof origSymbol("foo")&&"symbol"==typeof Symbol("bar")&&hasSymbolSham()}},{"./shams":648}],648:[function(require,module,exports){"use strict";module.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"!=typeof Symbol.iterator){var obj={},sym=Symbol("test"),symObj=Object(sym);if("string"==typeof sym)return!1;if("[object Symbol]"!==Object.prototype.toString.call(sym))return!1;if("[object Symbol]"!==Object.prototype.toString.call(symObj))return!1;for(sym in obj[sym]=42,obj)return!1;if("function"==typeof Object.keys&&0!==Object.keys(obj).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(obj).length)return!1;symObj=Object.getOwnPropertySymbols(obj);if(1!==symObj.length||symObj[0]!==sym)return!1;if(!Object.prototype.propertyIsEnumerable.call(obj,sym))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){symObj=Object.getOwnPropertyDescriptor(obj,sym);if(42!==symObj.value||!0!==symObj.enumerable)return!1}}return!0}},{}],649:[function(require,module,exports){"use strict";var hasSymbols=require("has-symbols/shams");module.exports=function(){return hasSymbols()&&!!Symbol.toStringTag}},{"has-symbols/shams":648}],650:[function(require,module,exports){"use strict";require=require("function-bind");module.exports=require.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":642}],651:[function(require,module,exports){"use strict";function _interopDefault(ex){return ex&&"object"==typeof ex&&"default"in ex?ex.default:ex}Object.defineProperty(exports,"__esModule",{value:!0});var resolvePathname=_interopDefault(require("resolve-pathname")),valueEqual=_interopDefault(require("value-equal")),warning=_interopDefault(require("tiny-warning")),invariant=_interopDefault(require("tiny-invariant"));function _extends(){return(_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var key,source=arguments[i];for(key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target}).apply(this,arguments)}function addLeadingSlash(path){return"/"===path.charAt(0)?path:"/"+path}function stripLeadingSlash(path){return"/"===path.charAt(0)?path.substr(1):path}function hasBasename(path,prefix){return 0===path.toLowerCase().indexOf(prefix.toLowerCase())&&-1!=="/?#".indexOf(path.charAt(prefix.length))}function stripBasename(path,prefix){return hasBasename(path,prefix)?path.substr(prefix.length):path}function stripTrailingSlash(path){return"/"===path.charAt(path.length-1)?path.slice(0,-1):path}function parsePath(path){var path=path||"/",search="",hash="",hashIndex=path.indexOf("#"),hashIndex=(-1!==hashIndex&&(hash=path.substr(hashIndex),path=path.substr(0,hashIndex)),path.indexOf("?"));return-1!==hashIndex&&(search=path.substr(hashIndex),path=path.substr(0,hashIndex)),{pathname:path,search:"?"===search?"":search,hash:"#"===hash?"":hash}}function createPath(location){var pathname=location.pathname,search=location.search,location=location.hash,pathname=pathname||"/";return search&&"?"!==search&&(pathname+="?"===search.charAt(0)?search:"?"+search),location&&"#"!==location&&(pathname+="#"===location.charAt(0)?location:"#"+location),pathname}function createLocation(path,state,key,currentLocation){var location;"string"==typeof path?(location=parsePath(path)).state=state:(void 0===(location=_extends({},path)).pathname&&(location.pathname=""),location.search?"?"!==location.search.charAt(0)&&(location.search="?"+location.search):location.search="",location.hash?"#"!==location.hash.charAt(0)&&(location.hash="#"+location.hash):location.hash="",void 0!==state&&void 0===location.state&&(location.state=state));try{location.pathname=decodeURI(location.pathname)}catch(e){throw e instanceof URIError?new URIError('Pathname "'+location.pathname+'" could not be decoded. This is likely caused by an invalid percent-encoding.'):e}return key&&(location.key=key),currentLocation?location.pathname?"/"!==location.pathname.charAt(0)&&(location.pathname=resolvePathname(location.pathname,currentLocation.pathname)):location.pathname=currentLocation.pathname:location.pathname||(location.pathname="/"),location}function createTransitionManager(){var prompt=null;var listeners=[];return{setPrompt:function(nextPrompt){return warning(null==prompt,"A history supports only one prompt at a time"),prompt=nextPrompt,function(){prompt===nextPrompt&&(prompt=null)}},confirmTransitionTo:function(location,action,getUserConfirmation,callback){null!=prompt?"string"==typeof(location="function"==typeof prompt?prompt(location,action):prompt)?"function"==typeof getUserConfirmation?getUserConfirmation(location,callback):(warning(!1,"A history needs a getUserConfirmation function in order to use a prompt message"),callback(!0)):callback(!1!==location):callback(!0)},appendListener:function(fn){var isActive=!0;function listener(){isActive&&fn.apply(void 0,arguments)}return listeners.push(listener),function(){isActive=!1,listeners=listeners.filter(function(item){return item!==listener})}},notifyListeners:function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];listeners.forEach(function(listener){return listener.apply(void 0,args)})}}}var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement);function getConfirmation(message,callback){callback(window.confirm(message))}function getHistoryState(){try{return window.history.state||{}}catch(e){return{}}}var HashPathCoders={hashbang:{encodePath:function(path){return"!"===path.charAt(0)?path:"!/"+stripLeadingSlash(path)},decodePath:function(path){return"!"===path.charAt(0)?path.substr(1):path}},noslash:{encodePath:stripLeadingSlash,decodePath:addLeadingSlash},slash:{encodePath:addLeadingSlash,decodePath:addLeadingSlash}};function stripHash(url){var hashIndex=url.indexOf("#");return-1===hashIndex?url:url.slice(0,hashIndex)}function getHashPath(){var href=window.location.href,hashIndex=href.indexOf("#");return-1===hashIndex?"":href.substring(hashIndex+1)}function replaceHashPath(path){window.location.replace(stripHash(window.location.href)+"#"+path)}function clamp(n,lowerBound,upperBound){return Math.min(Math.max(n,lowerBound),upperBound)}exports.createBrowserHistory=function(props){void 0===props&&(props={}),canUseDOM||invariant(!1,"Browser history needs a DOM");var globalHistory=window.history,canUseHistory=(-1===(ua=window.navigator.userAgent).indexOf("Android 2.")&&-1===ua.indexOf("Android 4.0")||-1===ua.indexOf("Mobile Safari")||-1!==ua.indexOf("Chrome")||-1!==ua.indexOf("Windows Phone"))&&window.history&&"pushState"in window.history,needsHashChangeListener=!(-1===window.navigator.userAgent.indexOf("Trident")),ua=props,_props$forceRefresh=ua.forceRefresh,forceRefresh=void 0!==_props$forceRefresh&&_props$forceRefresh,getUserConfirmation=void 0===(_props$forceRefresh=ua.getUserConfirmation)?getConfirmation:_props$forceRefresh,keyLength=void 0===(_props$forceRefresh=ua.keyLength)?6:_props$forceRefresh,basename=props.basename?stripTrailingSlash(addLeadingSlash(props.basename)):"";function getDOMLocation(historyState){var historyState=historyState||{},key=historyState.key,historyState=historyState.state,_window$location=window.location,_window$location=_window$location.pathname+_window$location.search+_window$location.hash;return warning(!basename||hasBasename(_window$location,basename),'You are attempting to use a basename on a page whose URL path does not begin with the basename. Expected path "'+_window$location+'" to begin with "'+basename+'".'),createLocation(_window$location=basename?stripBasename(_window$location,basename):_window$location,historyState,key)}function createKey(){return Math.random().toString(36).substr(2,keyLength)}var transitionManager=createTransitionManager();function setState(nextState){_extends(history,nextState),history.length=globalHistory.length,transitionManager.notifyListeners(history.location,history.action)}function handlePopState(event){!function(event){return void 0===event.state&&-1===navigator.userAgent.indexOf("CriOS")}(event)&&handlePop(getDOMLocation(event.state))}function handleHashChange(){handlePop(getDOMLocation(getHistoryState()))}var forceNextPop=!1;function handlePop(location){forceNextPop?(forceNextPop=!1,setState()):transitionManager.confirmTransitionTo(location,"POP",getUserConfirmation,function(ok){var toLocation;ok?setState({action:"POP",location:location}):(ok=location,toLocation=history.location,-1===(toLocation=allKeys.indexOf(toLocation.key))&&(toLocation=0),ok=allKeys.indexOf(ok.key),(toLocation-=ok=-1===ok?0:ok)&&(forceNextPop=!0,go(toLocation)))})}var allKeys=[(ua=getDOMLocation(getHistoryState())).key];function createHref(location){return basename+createPath(location)}function go(n){globalHistory.go(n)}var listenerCount=0;function checkDOMListeners(delta){1===(listenerCount+=delta)&&1===delta?(window.addEventListener("popstate",handlePopState),needsHashChangeListener&&window.addEventListener("hashchange",handleHashChange)):0===listenerCount&&(window.removeEventListener("popstate",handlePopState),needsHashChangeListener)&&window.removeEventListener("hashchange",handleHashChange)}var isBlocked=!1,history={length:globalHistory.length,action:"POP",location:ua,createHref:createHref,push:function(path,state){warning(!("object"==typeof path&&void 0!==path.state&&void 0!==state),"You should avoid providing a 2nd state argument to push when the 1st argument is a location-like object that already has state; it is ignored");var location=createLocation(path,state,createKey(),history.location);transitionManager.confirmTransitionTo(location,"PUSH",getUserConfirmation,function(ok){var state,key;ok&&(ok=createHref(location),key=location.key,state=location.state,canUseHistory?(globalHistory.pushState({key:key,state:state},null,ok),forceRefresh?window.location.href=ok:(key=allKeys.indexOf(history.location.key),(key=allKeys.slice(0,key+1)).push(location.key),allKeys=key,setState({action:"PUSH",location:location}))):(warning(void 0===state,"Browser history cannot push state in browsers that do not support HTML5 history"),window.location.href=ok))})},replace:function(path,state){warning(!("object"==typeof path&&void 0!==path.state&&void 0!==state),"You should avoid providing a 2nd state argument to replace when the 1st argument is a location-like object that already has state; it is ignored");var location=createLocation(path,state,createKey(),history.location);transitionManager.confirmTransitionTo(location,"REPLACE",getUserConfirmation,function(ok){var state,key;ok&&(ok=createHref(location),key=location.key,state=location.state,canUseHistory?(globalHistory.replaceState({key:key,state:state},null,ok),forceRefresh?window.location.replace(ok):(-1!==(key=allKeys.indexOf(history.location.key))&&(allKeys[key]=location.key),setState({action:"REPLACE",location:location}))):(warning(void 0===state,"Browser history cannot replace state in browsers that do not support HTML5 history"),window.location.replace(ok)))})},go:go,goBack:function(){go(-1)},goForward:function(){go(1)},block:function(prompt){var unblock=transitionManager.setPrompt(prompt=void 0===prompt?!1:prompt);return isBlocked||(checkDOMListeners(1),isBlocked=!0),function(){return isBlocked&&(isBlocked=!1,checkDOMListeners(-1)),unblock()}},listen:function(listener){var unlisten=transitionManager.appendListener(listener);return checkDOMListeners(1),function(){checkDOMListeners(-1),unlisten()}}};return history},exports.createHashHistory=function(props){void 0===props&&(props={}),canUseDOM||invariant(!1,"Hash history needs a DOM");var globalHistory=window.history,canGoWithoutReload=-1===window.navigator.userAgent.indexOf("Firefox"),_props$getUserConfirm=props.getUserConfirmation,getUserConfirmation=void 0===_props$getUserConfirm?getConfirmation:_props$getUserConfirm,_props=void 0===(_props$getUserConfirm=(_props=props).hashType)?"slash":_props$getUserConfirm,basename=props.basename?stripTrailingSlash(addLeadingSlash(props.basename)):"",encodePath=(_props$getUserConfirm=HashPathCoders[_props]).encodePath,decodePath=_props$getUserConfirm.decodePath;function getDOMLocation(){var path=decodePath(getHashPath());return warning(!basename||hasBasename(path,basename),'You are attempting to use a basename on a page whose URL path does not begin with the basename. Expected path "'+path+'" to begin with "'+basename+'".'),createLocation(path=basename?stripBasename(path,basename):path)}var transitionManager=createTransitionManager();function setState(nextState){_extends(history,nextState),history.length=globalHistory.length,transitionManager.notifyListeners(history.location,history.action)}var forceNextPop=!1,ignorePath=null;function handleHashChange(){var b,path=getHashPath(),encodedPath=encodePath(path);path!==encodedPath?replaceHashPath(encodedPath):(path=getDOMLocation(),encodedPath=history.location,!forceNextPop&&(b=path,(encodedPath=encodedPath).pathname===b.pathname)&&encodedPath.search===b.search&&encodedPath.hash===b.hash||ignorePath===createPath(path)||(ignorePath=null,function(location){forceNextPop?(forceNextPop=!1,setState()):transitionManager.confirmTransitionTo(location,"POP",getUserConfirmation,function(ok){var toLocation;ok?setState({action:"POP",location:location}):(ok=location,toLocation=history.location,-1===(toLocation=allPaths.lastIndexOf(createPath(toLocation)))&&(toLocation=0),ok=allPaths.lastIndexOf(createPath(ok)),(toLocation-=ok=-1===ok?0:ok)&&(forceNextPop=!0,go(toLocation)))})}(path)))}props=getHashPath(),_props=encodePath(props);props!==_props&&replaceHashPath(_props);var allPaths=[createPath(_props$getUserConfirm=getDOMLocation())];function go(n){warning(canGoWithoutReload,"Hash history go(n) causes a full page reload in this browser"),globalHistory.go(n)}var listenerCount=0;function checkDOMListeners(delta){1===(listenerCount+=delta)&&1===delta?window.addEventListener("hashchange",handleHashChange):0===listenerCount&&window.removeEventListener("hashchange",handleHashChange)}var isBlocked=!1,history={length:globalHistory.length,action:"POP",location:_props$getUserConfirm,createHref:function(location){var baseTag=document.querySelector("base"),href="";return(href=baseTag&&baseTag.getAttribute("href")?stripHash(window.location.href):href)+"#"+encodePath(basename+createPath(location))},push:function(path,state){warning(void 0===state,"Hash history cannot push state; it is ignored");var location=createLocation(path,void 0,void 0,history.location);transitionManager.confirmTransitionTo(location,"PUSH",getUserConfirmation,function(ok){var encodedPath;ok&&(ok=createPath(location),encodedPath=encodePath(basename+ok),getHashPath()!==encodedPath?(ignorePath=ok,function(path){window.location.hash=path}(encodedPath),encodedPath=allPaths.lastIndexOf(createPath(history.location)),(encodedPath=allPaths.slice(0,encodedPath+1)).push(ok),allPaths=encodedPath,setState({action:"PUSH",location:location})):(warning(!1,"Hash history cannot PUSH the same path; a new entry will not be added to the history stack"),setState()))})},replace:function(path,state){warning(void 0===state,"Hash history cannot replace state; it is ignored");var location=createLocation(path,void 0,void 0,history.location);transitionManager.confirmTransitionTo(location,"REPLACE",getUserConfirmation,function(ok){var encodedPath;ok&&(ok=createPath(location),encodedPath=encodePath(basename+ok),getHashPath()!==encodedPath&&(ignorePath=ok,replaceHashPath(encodedPath)),-1!==(encodedPath=allPaths.indexOf(createPath(history.location)))&&(allPaths[encodedPath]=ok),setState({action:"REPLACE",location:location}))})},go:go,goBack:function(){go(-1)},goForward:function(){go(1)},block:function(prompt){var unblock=transitionManager.setPrompt(prompt=void 0===prompt?!1:prompt);return isBlocked||(checkDOMListeners(1),isBlocked=!0),function(){return isBlocked&&(isBlocked=!1,checkDOMListeners(-1)),unblock()}},listen:function(listener){var unlisten=transitionManager.appendListener(listener);return checkDOMListeners(1),function(){checkDOMListeners(-1),unlisten()}}};return history},exports.createMemoryHistory=function(props){var getUserConfirmation=(props=props=void 0===props?{}:props).getUserConfirmation,_props$initialEntries=void 0===(_props$initialEntries=props.initialEntries)?["/"]:_props$initialEntries,_props$initialIndex=props.initialIndex,keyLength=void 0===(props=props.keyLength)?6:props,transitionManager=createTransitionManager();function setState(nextState){_extends(history,nextState),history.length=history.entries.length,transitionManager.notifyListeners(history.location,history.action)}function createKey(){return Math.random().toString(36).substr(2,keyLength)}function go(n){var nextIndex=clamp(history.index+n,0,history.entries.length-1),location=history.entries[nextIndex];transitionManager.confirmTransitionTo(location,"POP",getUserConfirmation,function(ok){ok?setState({action:"POP",location:location,index:nextIndex}):setState()})}props=clamp(void 0===_props$initialIndex?0:_props$initialIndex,0,_props$initialEntries.length-1);var history={length:(_props$initialIndex=_props$initialEntries.map(function(entry){return createLocation(entry,void 0,"string"!=typeof entry&&entry.key||createKey())})).length,action:"POP",location:_props$initialIndex[props],index:props,entries:_props$initialIndex,createHref:createPath,push:function(path,state){warning(!("object"==typeof path&&void 0!==path.state&&void 0!==state),"You should avoid providing a 2nd state argument to push when the 1st argument is a location-like object that already has state; it is ignored");var location=createLocation(path,state,createKey(),history.location);transitionManager.confirmTransitionTo(location,"PUSH",getUserConfirmation,function(ok){var nextEntries;ok&&(ok=history.index+1,(nextEntries=history.entries.slice(0)).length>ok?nextEntries.splice(ok,nextEntries.length-ok,location):nextEntries.push(location),setState({action:"PUSH",location:location,index:ok,entries:nextEntries}))})},replace:function(path,state){warning(!("object"==typeof path&&void 0!==path.state&&void 0!==state),"You should avoid providing a 2nd state argument to replace when the 1st argument is a location-like object that already has state; it is ignored");var location=createLocation(path,state,createKey(),history.location);transitionManager.confirmTransitionTo(location,"REPLACE",getUserConfirmation,function(ok){ok&&(history.entries[history.index]=location,setState({action:"REPLACE",location:location}))})},go:go,goBack:function(){go(-1)},goForward:function(){go(1)},canGo:function(n){return 0<=(n=history.index+n)&&n<history.entries.length},block:function(prompt){return transitionManager.setPrompt(prompt=void 0===prompt?!1:prompt)},listen:function(listener){return transitionManager.appendListener(listener)}};return history},exports.createLocation=createLocation,exports.locationsAreEqual=function(a,b){return a.pathname===b.pathname&&a.search===b.search&&a.hash===b.hash&&a.key===b.key&&valueEqual(a.state,b.state)},exports.parsePath=parsePath,exports.createPath=createPath},{"resolve-pathname":1437,"tiny-invariant":1696,"tiny-warning":1697,"value-equal":1701}],652:[function(require,module,exports){"use strict";function _interopDefault(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var resolvePathname=_interopDefault(require("resolve-pathname")),valueEqual=_interopDefault(require("value-equal")),invariant=(require("tiny-warning"),_interopDefault(require("tiny-invariant")));function _extends(){return(_extends=Object.assign||function(t){for(var n=1;n<arguments.length;n++){var a,e=arguments[n];for(a in e)Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a])}return t}).apply(this,arguments)}function addLeadingSlash(t){return"/"===t.charAt(0)?t:"/"+t}function stripLeadingSlash(t){return"/"===t.charAt(0)?t.substr(1):t}function stripBasename(t,n){return function(t,n){return 0===t.toLowerCase().indexOf(n.toLowerCase())&&-1!=="/?#".indexOf(t.charAt(n.length))}(t,n)?t.substr(n.length):t}function stripTrailingSlash(t){return"/"===t.charAt(t.length-1)?t.slice(0,-1):t}function parsePath(t){var t=t||"/",e="",a="",r=t.indexOf("#"),r=(-1!==r&&(a=t.substr(r),t=t.substr(0,r)),t.indexOf("?"));return-1!==r&&(e=t.substr(r),t=t.substr(0,r)),{pathname:t,search:"?"===e?"":e,hash:"#"===a?"":a}}function createPath(t){var n=t.pathname,e=t.search,t=t.hash,n=n||"/";return e&&"?"!==e&&(n+="?"===e.charAt(0)?e:"?"+e),t&&"#"!==t&&(n+="#"===t.charAt(0)?t:"#"+t),n}function createLocation(t,n,e,a){var r;"string"==typeof t?(r=parsePath(t)).state=n:(void 0===(r=_extends({},t)).pathname&&(r.pathname=""),r.search?"?"!==r.search.charAt(0)&&(r.search="?"+r.search):r.search="",r.hash?"#"!==r.hash.charAt(0)&&(r.hash="#"+r.hash):r.hash="",void 0!==n&&void 0===r.state&&(r.state=n));try{r.pathname=decodeURI(r.pathname)}catch(t){throw t instanceof URIError?new URIError('Pathname "'+r.pathname+'" could not be decoded. This is likely caused by an invalid percent-encoding.'):t}return e&&(r.key=e),a?r.pathname?"/"!==r.pathname.charAt(0)&&(r.pathname=resolvePathname(r.pathname,a.pathname)):r.pathname=a.pathname:r.pathname||(r.pathname="/"),r}function createTransitionManager(){var o=null,a=[];return{setPrompt:function(t){return o=t,function(){o===t&&(o=null)}},confirmTransitionTo:function(t,n,e,a){null!=o?"string"==typeof(t="function"==typeof o?o(t,n):o)?"function"==typeof e?e(t,a):a(!0):a(!1!==t):a(!0)},appendListener:function(t){var n=!0;function e(){n&&t.apply(void 0,arguments)}return a.push(e),function(){n=!1,a=a.filter(function(t){return t!==e})}},notifyListeners:function(){for(var t=arguments.length,n=new Array(t),e=0;e<t;e++)n[e]=arguments[e];a.forEach(function(t){return t.apply(void 0,n)})}}}var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement);function getConfirmation(t,n){n(window.confirm(t))}function getHistoryState(){try{return window.history.state||{}}catch(t){return{}}}var HashPathCoders={hashbang:{encodePath:function(t){return"!"===t.charAt(0)?t:"!/"+stripLeadingSlash(t)},decodePath:function(t){return"!"===t.charAt(0)?t.substr(1):t}},noslash:{encodePath:stripLeadingSlash,decodePath:addLeadingSlash},slash:{encodePath:addLeadingSlash,decodePath:addLeadingSlash}};function stripHash(t){var n=t.indexOf("#");return-1===n?t:t.slice(0,n)}function getHashPath(){var t=window.location.href,n=t.indexOf("#");return-1===n?"":t.substring(n+1)}function replaceHashPath(t){window.location.replace(stripHash(window.location.href)+"#"+t)}function clamp(t,n,e){return Math.min(Math.max(t,n),e)}exports.createBrowserHistory=function(t){void 0===t&&(t={}),canUseDOM||invariant(!1);var s=window.history,c=function(){var t=window.navigator.userAgent;return(-1===t.indexOf("Android 2.")&&-1===t.indexOf("Android 4.0")||-1===t.indexOf("Mobile Safari")||-1!==t.indexOf("Chrome")||-1!==t.indexOf("Windows Phone"))&&window.history&&"pushState"in window.history}(),n=!(-1===window.navigator.userAgent.indexOf("Trident")),e=t,a=e.forceRefresh,h=void 0!==a&&a,u=void 0===(a=e.getUserConfirmation)?getConfirmation:a,i=void 0===(a=e.keyLength)?6:a,f=t.basename?stripTrailingSlash(addLeadingSlash(t.basename)):"";function l(t){var t=t||{},e=t.key,t=t.state,r=window.location,r=r.pathname+r.search+r.hash;return createLocation(r=f?stripBasename(r,f):r,t,e)}function d(){return Math.random().toString(36).substr(2,i)}var v=createTransitionManager();function p(t){_extends(T,t),T.length=s.length,v.notifyListeners(T.location,T.action)}function g(t){!function(t){return void 0===t.state&&-1===navigator.userAgent.indexOf("CriOS")}(t)&&w(l(t.state))}function P(){w(l(getHistoryState()))}var m=!1;function w(n){m?(m=!1,p()):v.confirmTransitionTo(n,"POP",u,function(t){t?p({action:"POP",location:n}):function(t){var n=T.location,n=H.indexOf(n.key),t=(-1===n&&(n=0),H.indexOf(t.key)),n=n-(t=-1===t?0:t);n&&(m=!0,L(n))}(n)})}var H=[(e=l(getHistoryState())).key];function x(t){return f+createPath(t)}function L(t){s.go(t)}var O=0;function E(t){1===(O+=t)&&1===t?(window.addEventListener("popstate",g),n&&window.addEventListener("hashchange",P)):0===O&&(window.removeEventListener("popstate",g),n)&&window.removeEventListener("hashchange",P)}var S=!1,T={length:s.length,action:"POP",location:e,createHref:x,push:function(t,n){var i=createLocation(t,n,d(),T.location);v.confirmTransitionTo(i,"PUSH",u,function(t){var e,a;t&&(t=x(i),e=i.key,a=i.state,!c||(s.pushState({key:e,state:a},null,t),h)?window.location.href=t:(e=H.indexOf(T.location.key),(a=H.slice(0,e+1)).push(i.key),H=a,p({action:"PUSH",location:i})))})},replace:function(t,n){var o="REPLACE",i=createLocation(t,n,d(),T.location);v.confirmTransitionTo(i,o,u,function(t){var a,e;t&&(t=x(i),e=i.key,a=i.state,!c||(s.replaceState({key:e,state:a},null,t),h)?window.location.replace(t):(-1!==(e=H.indexOf(T.location.key))&&(H[e]=i.key),p({action:o,location:i})))})},go:L,goBack:function(){L(-1)},goForward:function(){L(1)},block:function(t){var n=v.setPrompt(t=void 0===t?!1:t);return S||(E(1),S=!0),function(){return S&&(S=!1,E(-1)),n()}},listen:function(t){var n=v.appendListener(t);return E(1),function(){E(-1),n()}}};return T},exports.createHashHistory=function(t){void 0===t&&(t={}),canUseDOM||invariant(!1);var n=window.history;window.navigator.userAgent.indexOf("Firefox");var i=void 0===(a=t.getUserConfirmation)?getConfirmation:a,a=void 0===(a=t.hashType)?"slash":a,s=t.basename?stripTrailingSlash(addLeadingSlash(t.basename)):"",h=(t=HashPathCoders[a]).encodePath,u=t.decodePath;function f(){var t=u(getHashPath());return createLocation(t=s?stripBasename(t,s):t)}var l=createTransitionManager();function d(t){_extends(E,t),E.length=n.length,l.notifyListeners(E.location,E.action)}var v=!1,p=null;function g(){var t=getHashPath(),n=h(t);t!==n?replaceHashPath(n):(t=f(),n=E.location,!v&&n.pathname===t.pathname&&n.search===t.search&&n.hash===t.hash||p===createPath(t)||(p=null,function(n){v?(v=!1,d()):l.confirmTransitionTo(n,"POP",i,function(t){t?d({action:"POP",location:n}):function(t){var n=E.location,n=y.lastIndexOf(createPath(n)),t=(-1===n&&(n=0),y.lastIndexOf(createPath(t))),n=n-(t=-1===t?0:t);n&&(v=!0,H(n))}(n)})}(t)))}a=getHashPath(),t=h(a);a!==t&&replaceHashPath(t);var y=[createPath(a=f())];function H(t){n.go(t)}var x=0;function L(t){1===(x+=t)&&1===t?window.addEventListener("hashchange",g):0===x&&window.removeEventListener("hashchange",g)}var O=!1,E={length:n.length,action:"POP",location:a,createHref:function(t){var n=document.querySelector("base"),e="";return(e=n&&n.getAttribute("href")?stripHash(window.location.href):e)+"#"+h(s+createPath(t))},push:function(t,n){var o=createLocation(t,void 0,void 0,E.location);l.confirmTransitionTo(o,"PUSH",i,function(t){var e;t&&(t=createPath(o),e=h(s+t),getHashPath()!==e?(p=t,function(t){window.location.hash=t}(e),e=y.lastIndexOf(createPath(E.location)),(e=y.slice(0,e+1)).push(t),y=e,d({action:"PUSH",location:o})):d())})},replace:function(t,n){var r="REPLACE",o=createLocation(t,void 0,void 0,E.location);l.confirmTransitionTo(o,r,i,function(t){var e;t&&(t=createPath(o),e=h(s+t),getHashPath()!==e&&(p=t,replaceHashPath(e)),-1!==(e=y.indexOf(createPath(E.location)))&&(y[e]=t),d({action:r,location:o}))})},go:H,goBack:function(){H(-1)},goForward:function(){H(1)},block:function(t){var n=l.setPrompt(t=void 0===t?!1:t);return O||(L(1),O=!0),function(){return O&&(O=!1,L(-1)),n()}},listen:function(t){var n=l.appendListener(t);return L(1),function(){L(-1),n()}}};return E},exports.createMemoryHistory=function(t){var r=(t=t=void 0===t?{}:t).getUserConfirmation,e=void 0===(e=t.initialEntries)?["/"]:e,o=void 0===(o=t.initialIndex)?0:o,c=void 0===(t=t.keyLength)?6:t,h=createTransitionManager();function u(t){_extends(g,t),g.length=g.entries.length,h.notifyListeners(g.location,g.action)}function f(){return Math.random().toString(36).substr(2,c)}function p(t){var n=clamp(g.index+t,0,g.entries.length-1),e=g.entries[n];h.confirmTransitionTo(e,"POP",r,function(t){t?u({action:"POP",location:e,index:n}):u()})}t=clamp(o,0,e.length-1);var g={length:(o=e.map(function(t){return createLocation(t,void 0,"string"!=typeof t&&t.key||f())})).length,action:"POP",location:o[t],index:t,entries:o,createHref:createPath,push:function(t,n){var a=createLocation(t,n,f(),g.location);h.confirmTransitionTo(a,"PUSH",r,function(t){var e;t&&(t=g.index+1,(e=g.entries.slice(0)).length>t?e.splice(t,e.length-t,a):e.push(a),u({action:"PUSH",location:a,index:t,entries:e}))})},replace:function(t,n){var e="REPLACE",a=createLocation(t,n,f(),g.location);h.confirmTransitionTo(a,e,r,function(t){t&&(g.entries[g.index]=a,u({action:e,location:a}))})},go:p,goBack:function(){p(-1)},goForward:function(){p(1)},canGo:function(t){t=g.index+t;return 0<=t&&t<g.entries.length},block:function(t){return h.setPrompt(t=void 0===t?!1:t)},listen:function(t){return h.appendListener(t)}};return g},exports.createLocation=createLocation,exports.locationsAreEqual=function(t,n){return t.pathname===n.pathname&&t.search===n.search&&t.hash===n.hash&&t.key===n.key&&valueEqual(t.state,n.state)},exports.parsePath=parsePath,exports.createPath=createPath},{"resolve-pathname":1437,"tiny-invariant":1696,"tiny-warning":1697,"value-equal":1701}],653:[function(require,module,exports){"use strict";module.exports=require("./cjs/history.min.js")},{"./cjs/history.js":651,"./cjs/history.min.js":652}],654:[function(require,module,exports){"use strict";var reactIs=require("react-is"),REACT_STATICS={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},KNOWN_STATICS={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},MEMO_STATICS={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},TYPE_STATICS={};function getStatics(component){return reactIs.isMemo(component)?MEMO_STATICS:TYPE_STATICS[component.$$typeof]||REACT_STATICS}TYPE_STATICS[reactIs.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},TYPE_STATICS[reactIs.Memo]=MEMO_STATICS;var defineProperty=Object.defineProperty,getOwnPropertyNames=Object.getOwnPropertyNames,getOwnPropertySymbols=Object.getOwnPropertySymbols,getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor,getPrototypeOf=Object.getPrototypeOf,objectPrototype=Object.prototype;module.exports=function hoistNonReactStatics(targetComponent,sourceComponent,blacklist){if("string"!=typeof sourceComponent){objectPrototype&&(inheritedComponent=getPrototypeOf(sourceComponent))&&inheritedComponent!==objectPrototype&&hoistNonReactStatics(targetComponent,inheritedComponent,blacklist);for(var inheritedComponent,keys=getOwnPropertyNames(sourceComponent),targetStatics=(getOwnPropertySymbols&&(keys=keys.concat(getOwnPropertySymbols(sourceComponent))),getStatics(targetComponent)),sourceStatics=getStatics(sourceComponent),i=0;i<keys.length;++i){var key=keys[i];if(!(KNOWN_STATICS[key]||blacklist&&blacklist[key]||sourceStatics&&sourceStatics[key]||targetStatics&&targetStatics[key])){var descriptor=getOwnPropertyDescriptor(sourceComponent,key);try{defineProperty(targetComponent,key,descriptor)}catch(e){}}}}return targetComponent}},{"react-is":1385}],655:[function(require,module,exports){var global,factory;global=this,factory=function(){"use strict";var extendStatics=function(d,b){return(extendStatics=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(d,b){d.__proto__=b}:function(d,b){for(var p in b)Object.prototype.hasOwnProperty.call(b,p)&&(d[p]=b[p])}))(d,b)};function __extends(d,b){if("function"!=typeof b&&null!==b)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function __(){this.constructor=d}extendStatics(d,b),d.prototype=null===b?Object.create(b):(__.prototype=b.prototype,new __)}var __assign=function(){return(__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t}).apply(this,arguments)};function __awaiter(thisArg,_arguments,P,generator){return new(P=P||Promise)(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):((value=result.value)instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){var op=[n,v];if(f)throw new TypeError("Generator is already executing.");for(;_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,(op=t?[2&op[0],t.value]:op)[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=0<(t=_.trys).length&&t[t.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3]))_.label=op[1];else if(6===op[0]&&_.label<t[1])_.label=t[1],t=op;else{if(!(t&&_.label<t[2])){t[2]&&_.ops.pop(),_.trys.pop();continue}_.label=t[2],_.ops.push(op)}}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}}}function __spreadArray(to,from,pack){if(pack||2===arguments.length)for(var ar,i=0,l=from.length;i<l;i++)!ar&&i in from||((ar=ar||Array.prototype.slice.call(from,0,i))[i]=from[i]);return to.concat(ar||from)}for(var Bounds=function(){function Bounds(left,top,width,height){this.left=left,this.top=top,this.width=width,this.height=height}return Bounds.prototype.add=function(x,y,w,h){return new Bounds(this.left+x,this.top+y,this.width+w,this.height+h)},Bounds.fromClientRect=function(context,clientRect){return new Bounds(clientRect.left+context.windowBounds.left,clientRect.top+context.windowBounds.top,clientRect.width,clientRect.height)},Bounds.fromDOMRectList=function(context,domRectList){domRectList=Array.from(domRectList).find(function(rect){return 0!==rect.width});return domRectList?new Bounds(domRectList.left+context.windowBounds.left,domRectList.top+context.windowBounds.top,domRectList.width,domRectList.height):Bounds.EMPTY},Bounds.EMPTY=new Bounds(0,0,0,0),Bounds}(),parseBounds=function(context,node){return Bounds.fromClientRect(context,node.getBoundingClientRect())},parseDocumentSize=function(document){var width,body=document.body,document=document.documentElement;if(body&&document)return width=Math.max(Math.max(body.scrollWidth,document.scrollWidth),Math.max(body.offsetWidth,document.offsetWidth),Math.max(body.clientWidth,document.clientWidth)),body=Math.max(Math.max(body.scrollHeight,document.scrollHeight),Math.max(body.offsetHeight,document.offsetHeight),Math.max(body.clientHeight,document.clientHeight)),new Bounds(0,0,width,body);throw new Error("Unable to get document size")},toCodePoints$1=function(str){for(var codePoints=[],i=0,length=str.length;i<length;){var extra,value=str.charCodeAt(i++);55296<=value&&value<=56319&&i<length?56320==(64512&(extra=str.charCodeAt(i++)))?codePoints.push(((1023&value)<<10)+(1023&extra)+65536):(codePoints.push(value),i--):codePoints.push(value)}return codePoints},fromCodePoint$1=function(){for(var codePoints=[],_i=0;_i<arguments.length;_i++)codePoints[_i]=arguments[_i];if(String.fromCodePoint)return String.fromCodePoint.apply(String,codePoints);var length=codePoints.length;if(!length)return"";for(var codeUnits=[],index=-1,result="";++index<length;){var codePoint=codePoints[index];codePoint<=65535?codeUnits.push(codePoint):codeUnits.push(55296+((codePoint-=65536)>>10),codePoint%1024+56320),(index+1===length||16384<codeUnits.length)&&(result+=String.fromCharCode.apply(String,codeUnits),codeUnits.length=0)}return result},chars$2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$2="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i$2=0;i$2<chars$2.length;i$2++)lookup$2[chars$2.charCodeAt(i$2)]=i$2;for(var chars$1$1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$1$1="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i$1$1=0;i$1$1<chars$1$1.length;i$1$1++)lookup$1$1[chars$1$1.charCodeAt(i$1$1)]=i$1$1;for(var slice16$1=function(view,start,end){return view.slice?view.slice(start,end):new Uint16Array(Array.prototype.slice.call(view,start,end))},Trie$1=function(){function Trie(initialValue,errorValue,highStart,highValueIndex,index,data){this.initialValue=initialValue,this.errorValue=errorValue,this.highStart=highStart,this.highValueIndex=highValueIndex,this.index=index,this.data=data}return Trie.prototype.get=function(codePoint){var ix;if(0<=codePoint){if(codePoint<55296||56319<codePoint&&codePoint<=65535)return ix=this.index[codePoint>>5],this.data[ix=(ix<<2)+(31&codePoint)];if(codePoint<=65535)return ix=this.index[2048+(codePoint-55296>>5)],this.data[ix=(ix<<2)+(31&codePoint)];if(codePoint<this.highStart)return ix=this.index[ix=2080+(codePoint>>11)],ix=this.index[ix+=codePoint>>5&63],this.data[ix=(ix<<2)+(31&codePoint)];if(codePoint<=1114111)return this.data[this.highValueIndex]}return this.errorValue},Trie}(),chars$3="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$3="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i$3=0;i$3<chars$3.length;i$3++)lookup$3[chars$3.charCodeAt(i$3)]=i$3;function isAdjacentWithSpaceIgnored(a,b,currentIndex,classTypes){var current=classTypes[currentIndex];if(Array.isArray(a)?-1!==a.indexOf(current):a===current)for(var i=currentIndex;i<=classTypes.length;){if((next=classTypes[++i])===b)return 1;if(10!==next)break}if(10===current)for(i=currentIndex;0<i;){var prev=classTypes[--i];if(Array.isArray(a)?-1!==a.indexOf(prev):a===prev)for(var next,n=currentIndex;n<=classTypes.length;){if((next=classTypes[++n])===b)return 1;if(10!==next)break}if(10!==prev)break}}function previousNonSpaceClassType(currentIndex,classTypes){for(var i=currentIndex;0<=i;){var type=classTypes[i];if(10!==type)return type;i--}return 0}function cssFormattedClasses(codePoints,options){var indicies=(_a=function(codePoints,lineBreak){void 0===lineBreak&&(lineBreak="strict");var types=[],indices=[],categories=[];return codePoints.forEach(function(codePoint,index){var classType=UnicodeTrie$1.get(codePoint);if(50<classType?(categories.push(!0),classType-=50):categories.push(!1),-1!==["normal","auto","loose"].indexOf(lineBreak)&&-1!==[8208,8211,12316,12448].indexOf(codePoint))return indices.push(index),types.push(16);if(4!==classType&&11!==classType)return indices.push(index),31===classType?types.push("strict"===lineBreak?21:37):42===classType||29===classType?types.push(30):43===classType?types.push(131072<=codePoint&&codePoint<=196605||196608<=codePoint&&codePoint<=262141?37:30):void types.push(classType);if(0!==index&&-1===LINE_BREAKS.indexOf(codePoint=types[index-1]))return indices.push(indices[index-1]),types.push(codePoint);return indices.push(index),types.push(30)}),[indices,types,categories]}(codePoints,(options=options||{lineBreak:"normal",wordBreak:"normal"}).lineBreak))[0],classTypes=_a[1],_a=_a[2],options=("break-all"!==options.wordBreak&&"break-word"!==options.wordBreak||(classTypes=classTypes.map(function(type){return-1!==[25,30,42].indexOf(type)?37:type})),"keep-all"===options.wordBreak?_a.map(function(letterNumber,i){return letterNumber&&19968<=codePoints[i]&&codePoints[i]<=40959}):void 0);return[indicies,classTypes,options]}function isDigit(codePoint){return ZERO<=codePoint&&codePoint<=57}function isHex(codePoint){return isDigit(codePoint)||65<=codePoint&&codePoint<=70||97<=codePoint&&codePoint<=102}function isWhiteSpace(codePoint){return 10===codePoint||9===codePoint||32===codePoint}function isNameStartCodePoint(codePoint){return isLetter(codePoint)||isNonASCIICodePoint(codePoint)||codePoint===LOW_LINE}function isNameCodePoint(codePoint){return isNameStartCodePoint(codePoint)||isDigit(codePoint)||45===codePoint}function isValidEscape(c1,c2){return 92===c1&&10!==c2}function isIdentifierStart(c1,c2,c3){return 45===c1?isNameStartCodePoint(c2)||92===c2&&10!==c3:!!isNameStartCodePoint(c1)||92===c1&&10!==c2}function isNumberStart(c1,c2,c3){return 43===c1||45===c1?!!isDigit(c2)||46===c2&&isDigit(c3):isDigit(46===c1?c2:c1)}function isStringToken(token){return 0===token.type}function isIdentWithValue(token,value){return isIdentToken(token)&&token.value===value}function nonWhiteSpace(token){return 31!==token.type}function nonFunctionArgSeparator(token){return 31!==token.type&&4!==token.type}function parseFunctionArgs(tokens){var args=[],arg=[];return tokens.forEach(function(token){if(4===token.type){if(0===arg.length)throw new Error("Error parsing function args, zero tokens for arg");args.push(arg),arg=[]}else 31!==token.type&&arg.push(token)}),arg.length&&args.push(arg),args}function parseLengthPercentageTuple(tokens){return 1<tokens.length?[tokens[0],tokens[1]]:[tokens[0]]}function isAngle(value){return 15===value.type&&(value.unit===DEG||value.unit===GRAD||value.unit===RAD||value.unit===TURN)}function parseNamedSide(tokens){switch(tokens.filter(isIdentToken).map(function(ident){return ident.value}).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[ZERO_LENGTH,ZERO_LENGTH];case"to top":case"bottom":return deg(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[ZERO_LENGTH,HUNDRED_PERCENT];case"to right":case"left":return deg(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[HUNDRED_PERCENT,HUNDRED_PERCENT];case"to bottom":case"top":return deg(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[HUNDRED_PERCENT,ZERO_LENGTH];case"to left":case"right":return deg(270)}return 0}function asString(color){var alpha=255&color,blue=255&color>>8,green=255&color>>16,color=255&color>>24;return alpha<255?"rgba("+color+","+green+","+blue+","+alpha/255+")":"rgb("+color+","+green+","+blue+")"}function getTokenColorValue(token,i){var max;return 17===token.type?token.number:16===token.type?(max=3===i?1:255,3===i?token.number/100*max:Math.round(token.number/100*max)):0}function rgb(_context,args){var r,g,_a;return 3===(args=args.filter(nonFunctionArgSeparator)).length?(r=(_a=args.map(getTokenColorValue))[0],g=_a[1],_a=_a[2],pack(r,g,_a,1)):4===args.length?(r=(args=args.map(getTokenColorValue))[0],g=args[1],_a=args[2],args=args[3],pack(r,g,_a,args)):0}var ea_OP=[9001,65288],UnicodeTrie$1=function(base64){var start,end,base64=function(base64){for(var encoded1,encoded2,encoded3,encoded4,bufferLength=.75*base64.length,len=base64.length,p=0,bufferLength=("="===base64[base64.length-1]&&(bufferLength--,"="===base64[base64.length-2])&&bufferLength--,new("undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?ArrayBuffer:Array)(bufferLength)),bytes=Array.isArray(bufferLength)?bufferLength:new Uint8Array(bufferLength),i=0;i<len;i+=4)encoded1=lookup$1$1[base64.charCodeAt(i)],encoded2=lookup$1$1[base64.charCodeAt(i+1)],encoded3=lookup$1$1[base64.charCodeAt(i+2)],encoded4=lookup$1$1[base64.charCodeAt(i+3)],bytes[p++]=encoded1<<2|encoded2>>4,bytes[p++]=(15&encoded2)<<4|encoded3>>2,bytes[p++]=(3&encoded3)<<6|63&encoded4;return bufferLength}(base64),view32=Array.isArray(base64)?function(buffer){for(var length=buffer.length,bytes=[],i=0;i<length;i+=4)bytes.push(buffer[i+3]<<24|buffer[i+2]<<16|buffer[i+1]<<8|buffer[i]);return bytes}(base64):new Uint32Array(base64),base64=Array.isArray(base64)?function(buffer){for(var length=buffer.length,bytes=[],i=0;i<length;i+=2)bytes.push(buffer[i+1]<<8|buffer[i]);return bytes}(base64):new Uint16Array(base64),index=slice16$1(base64,12,view32[4]/2),base64=2===view32[5]?slice16$1(base64,(24+view32[4])/2):(base64=view32,start=Math.ceil((24+view32[4])/4),base64.slice?base64.slice(start,end):new Uint32Array(Array.prototype.slice.call(base64,start,end)));return new Trie$1(view32[0],view32[1],view32[2],view32[3],index,base64)}("KwAAAAAAAAAACA4AUD0AADAgAAACAAAAAAAIABAAGABAAEgAUABYAGAAaABgAGgAYgBqAF8AZwBgAGgAcQB5AHUAfQCFAI0AlQCdAKIAqgCyALoAYABoAGAAaABgAGgAwgDKAGAAaADGAM4A0wDbAOEA6QDxAPkAAQEJAQ8BFwF1AH0AHAEkASwBNAE6AUIBQQFJAVEBWQFhAWgBcAF4ATAAgAGGAY4BlQGXAZ8BpwGvAbUBvQHFAc0B0wHbAeMB6wHxAfkBAQIJAvEBEQIZAiECKQIxAjgCQAJGAk4CVgJeAmQCbAJ0AnwCgQKJApECmQKgAqgCsAK4ArwCxAIwAMwC0wLbAjAA4wLrAvMC+AIAAwcDDwMwABcDHQMlAy0DNQN1AD0DQQNJA0kDSQNRA1EDVwNZA1kDdQB1AGEDdQBpA20DdQN1AHsDdQCBA4kDkQN1AHUAmQOhA3UAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AKYDrgN1AHUAtgO+A8YDzgPWAxcD3gPjA+sD8wN1AHUA+wMDBAkEdQANBBUEHQQlBCoEFwMyBDgEYABABBcDSARQBFgEYARoBDAAcAQzAXgEgASIBJAEdQCXBHUAnwSnBK4EtgS6BMIEyAR1AHUAdQB1AHUAdQCVANAEYABgAGAAYABgAGAAYABgANgEYADcBOQEYADsBPQE/AQEBQwFFAUcBSQFLAU0BWQEPAVEBUsFUwVbBWAAYgVgAGoFcgV6BYIFigWRBWAAmQWfBaYFYABgAGAAYABgAKoFYACxBbAFuQW6BcEFwQXHBcEFwQXPBdMF2wXjBeoF8gX6BQIGCgYSBhoGIgYqBjIGOgZgAD4GRgZMBmAAUwZaBmAAYABgAGAAYABgAGAAYABgAGAAYABgAGIGYABpBnAGYABgAGAAYABgAGAAYABgAGAAYAB4Bn8GhQZgAGAAYAB1AHcDFQSLBmAAYABgAJMGdQA9A3UAmwajBqsGqwaVALMGuwbDBjAAywbSBtIG1QbSBtIG0gbSBtIG0gbdBuMG6wbzBvsGAwcLBxMHAwcbByMHJwcsBywHMQcsB9IGOAdAB0gHTgfSBkgHVgfSBtIG0gbSBtIG0gbSBtIG0gbSBiwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdgAGAALAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdbB2MHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB2kH0gZwB64EdQB1AHUAdQB1AHUAdQB1AHUHfQdgAIUHjQd1AHUAlQedB2AAYAClB6sHYACzB7YHvgfGB3UAzgfWBzMB3gfmB1EB7gf1B/0HlQENAQUIDQh1ABUIHQglCBcDLQg1CD0IRQhNCEEDUwh1AHUAdQBbCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIcAh3CHoIMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIgggwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAALAcsBywHLAcsBywHLAcsBywHLAcsB4oILAcsB44I0gaWCJ4Ipgh1AHUAqgiyCHUAdQB1AHUAdQB1AHUAdQB1AHUAtwh8AXUAvwh1AMUIyQjRCNkI4AjoCHUAdQB1AO4I9gj+CAYJDgkTCS0HGwkjCYIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiAAIAAAAFAAYABgAGIAXwBgAHEAdQBFAJUAogCyAKAAYABgAEIA4ABGANMA4QDxAMEBDwE1AFwBLAE6AQEBUQF4QkhCmEKoQrhCgAHIQsAB0MLAAcABwAHAAeDC6ABoAHDCwMMAAcABwAHAAdDDGMMAAcAB6MM4wwjDWMNow3jDaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEjDqABWw6bDqABpg6gAaABoAHcDvwOPA+gAaABfA/8DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DpcPAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcAB9cPKwkyCToJMAB1AHUAdQBCCUoJTQl1AFUJXAljCWcJawkwADAAMAAwAHMJdQB2CX4JdQCECYoJjgmWCXUAngkwAGAAYABxAHUApgn3A64JtAl1ALkJdQDACTAAMAAwADAAdQB1AHUAdQB1AHUAdQB1AHUAowYNBMUIMAAwADAAMADICcsJ0wnZCRUE4QkwAOkJ8An4CTAAMAB1AAAKvwh1AAgKDwoXCh8KdQAwACcKLgp1ADYKqAmICT4KRgowADAAdQB1AE4KMAB1AFYKdQBeCnUAZQowADAAMAAwADAAMAAwADAAMAAVBHUAbQowADAAdQC5CXUKMAAwAHwBxAijBogEMgF9CoQKiASMCpQKmgqIBKIKqgquCogEDQG2Cr4KxgrLCjAAMADTCtsKCgHjCusK8Qr5CgELMAAwADAAMAB1AIsECQsRC3UANAEZCzAAMAAwADAAMAB1ACELKQswAHUANAExCzkLdQBBC0kLMABRC1kLMAAwADAAMAAwADAAdQBhCzAAMAAwAGAAYABpC3ELdwt/CzAAMACHC4sLkwubC58Lpwt1AK4Ltgt1APsDMAAwADAAMAAwADAAMAAwAL4LwwvLC9IL1wvdCzAAMADlC+kL8Qv5C/8LSQswADAAMAAwADAAMAAwADAAMAAHDDAAMAAwADAAMAAODBYMHgx1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1ACYMMAAwADAAdQB1AHUALgx1AHUAdQB1AHUAdQA2DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AD4MdQBGDHUAdQB1AHUAdQB1AEkMdQB1AHUAdQB1AFAMMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQBYDHUAdQB1AF8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUA+wMVBGcMMAAwAHwBbwx1AHcMfwyHDI8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAYABgAJcMMAAwADAAdQB1AJ8MlQClDDAAMACtDCwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB7UMLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AA0EMAC9DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAsBywHLAcsBywHLAcsBywHLQcwAMEMyAwsBywHLAcsBywHLAcsBywHLAcsBywHzAwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1ANQM2QzhDDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMABgAGAAYABgAGAAYABgAOkMYADxDGAA+AwADQYNYABhCWAAYAAODTAAMAAwADAAFg1gAGAAHg37AzAAMAAwADAAYABgACYNYAAsDTQNPA1gAEMNPg1LDWAAYABgAGAAYABgAGAAYABgAGAAUg1aDYsGVglhDV0NcQBnDW0NdQ15DWAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAlQCBDZUAiA2PDZcNMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAnw2nDTAAMAAwADAAMAAwAHUArw23DTAAMAAwADAAMAAwADAAMAAwADAAMAB1AL8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQDHDTAAYABgAM8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA1w11ANwNMAAwAD0B5A0wADAAMAAwADAAMADsDfQN/A0EDgwOFA4wABsOMAAwADAAMAAwADAAMAAwANIG0gbSBtIG0gbSBtIG0gYjDigOwQUuDsEFMw7SBjoO0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGQg5KDlIOVg7SBtIGXg5lDm0OdQ7SBtIGfQ6EDooOjQ6UDtIGmg6hDtIG0gaoDqwO0ga0DrwO0gZgAGAAYADEDmAAYAAkBtIGzA5gANIOYADaDokO0gbSBt8O5w7SBu8O0gb1DvwO0gZgAGAAxA7SBtIG0gbSBtIGYABgAGAAYAAED2AAsAUMD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHJA8sBywHLAcsBywHLAccDywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywPLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAc0D9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHPA/SBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gYUD0QPlQCVAJUAMAAwADAAMACVAJUAlQCVAJUAlQCVAEwPMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA//8EAAQABAAEAAQABAAEAAQABAANAAMAAQABAAIABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQACgATABcAHgAbABoAHgAXABYAEgAeABsAGAAPABgAHABLAEsASwBLAEsASwBLAEsASwBLABgAGAAeAB4AHgATAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYAGwASAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWAA0AEQAeAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAFAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJABYAGgAbABsAGwAeAB0AHQAeAE8AFwAeAA0AHgAeABoAGwBPAE8ADgBQAB0AHQAdAE8ATwAXAE8ATwBPABYAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAFAATwBAAE8ATwBPAEAATwBQAFAATwBQAB4AHgAeAB4AHgAeAB0AHQAdAB0AHgAdAB4ADgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgBQAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkACQAJAAkACQAJAAkABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAFAAHgAeAB4AKwArAFAAUABQAFAAGABQACsAKwArACsAHgAeAFAAHgBQAFAAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUAAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAYAA0AKwArAB4AHgAbACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAB4ABAAEAB4ABAAEABMABAArACsAKwArACsAKwArACsAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAKwArACsAKwBWAFYAVgBWAB4AHgArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AGgAaABoAGAAYAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQAEwAEACsAEwATAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABLAEsASwBLAEsASwBLAEsASwBLABoAGQAZAB4AUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABMAUAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABABQAFAABAAEAB4ABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUAAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAFAABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQAUABQAB4AHgAYABMAUAArACsABAAbABsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAFAABAAEAAQABAAEAFAABAAEAAQAUAAEAAQABAAEAAQAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArACsAHgArAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAUAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEAA0ADQBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUAArACsAKwBQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABABQACsAKwArACsAKwArACsAKwAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUAAaABoAUABQAFAAUABQAEwAHgAbAFAAHgAEACsAKwAEAAQABAArAFAAUABQAFAAUABQACsAKwArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQACsAUABQACsAKwAEACsABAAEAAQABAAEACsAKwArACsABAAEACsAKwAEAAQABAArACsAKwAEACsAKwArACsAKwArACsAUABQAFAAUAArAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLAAQABABQAFAAUAAEAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAArACsAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AGwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAKwArACsAKwArAAQABAAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAAQAUAArAFAAUABQAFAAUABQACsAKwArAFAAUABQACsAUABQAFAAUAArACsAKwBQAFAAKwBQACsAUABQACsAKwArAFAAUAArACsAKwBQAFAAUAArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAAQABAAEAAQABAArACsAKwAEAAQABAArAAQABAAEAAQAKwArAFAAKwArACsAKwArACsABAArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAHgAeAB4AHgAeAB4AGwAeACsAKwArACsAKwAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAUABQAFAAKwArACsAKwArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwAOAFAAUABQAFAAUABQAFAAHgBQAAQABAAEAA4AUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAKwArAAQAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAKwArACsAKwArACsAUAArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABABQAB4AKwArACsAKwBQAFAAUAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQABoAUABQAFAAUABQAFAAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQACsAUAArACsAUABQAFAAUABQAFAAUAArACsAKwAEACsAKwArACsABAAEAAQABAAEAAQAKwAEACsABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgAqACsAKwArACsAGwBcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAeAEsASwBLAEsASwBLAEsASwBLAEsADQANACsAKwArACsAKwBcAFwAKwBcACsAXABcAFwAXABcACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAXAArAFwAXABcAFwAXABcAFwAXABcAFwAKgBcAFwAKgAqACoAKgAqACoAKgAqACoAXAArACsAXABcAFwAXABcACsAXAArACoAKgAqACoAKgAqACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwBcAFwAXABcAFAADgAOAA4ADgAeAA4ADgAJAA4ADgANAAkAEwATABMAEwATAAkAHgATAB4AHgAeAAQABAAeAB4AHgAeAB4AHgBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQAFAADQAEAB4ABAAeAAQAFgARABYAEQAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAAQABAAEAAQADQAEAAQAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAA0ADQAeAB4AHgAeAB4AHgAEAB4AHgAeAB4AHgAeACsAHgAeAA4ADgANAA4AHgAeAB4AHgAeAAkACQArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgBcAEsASwBLAEsASwBLAEsASwBLAEsADQANAB4AHgAeAB4AXABcAFwAXABcAFwAKgAqACoAKgBcAFwAXABcACoAKgAqAFwAKgAqACoAXABcACoAKgAqACoAKgAqACoAXABcAFwAKgAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqAFwAKgBLAEsASwBLAEsASwBLAEsASwBLACoAKgAqACoAKgAqAFAAUABQAFAAUABQACsAUAArACsAKwArACsAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAKwBQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsABAAEAAQAHgANAB4AHgAeAB4AHgAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUAArACsADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWABEAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQANAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAANAA0AKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUAArAAQABAArACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqAA0ADQAVAFwADQAeAA0AGwBcACoAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwAeAB4AEwATAA0ADQAOAB4AEwATAB4ABAAEAAQACQArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAHgArACsAKwATABMASwBLAEsASwBLAEsASwBLAEsASwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAXABcAFwAXABcACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAXAArACsAKwAqACoAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsAHgAeAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKwAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKwArAAQASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACoAKgAqACoAKgAqACoAXAAqACoAKgAqACoAKgArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABABQAFAAUABQAFAAUABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwANAA0AHgANAA0ADQANAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwAeAB4AHgAeAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArAA0ADQANAA0ADQBLAEsASwBLAEsASwBLAEsASwBLACsAKwArAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUAAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAAQAUABQAFAAUABQAFAABABQAFAABAAEAAQAUAArACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQACsAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQACsAKwAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQACsAHgAeAB4AHgAeAB4AHgAOAB4AKwANAA0ADQANAA0ADQANAAkADQANAA0ACAAEAAsABAAEAA0ACQANAA0ADAAdAB0AHgAXABcAFgAXABcAFwAWABcAHQAdAB4AHgAUABQAFAANAAEAAQAEAAQABAAEAAQACQAaABoAGgAaABoAGgAaABoAHgAXABcAHQAVABUAHgAeAB4AHgAeAB4AGAAWABEAFQAVABUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ADQAeAA0ADQANAA0AHgANAA0ADQAHAB4AHgAeAB4AKwAEAAQABAAEAAQABAAEAAQABAAEAFAAUAArACsATwBQAFAAUABQAFAAHgAeAB4AFgARAE8AUABPAE8ATwBPAFAAUABQAFAAUAAeAB4AHgAWABEAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArABsAGwAbABsAGwAbABsAGgAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGgAbABsAGwAbABoAGwAbABoAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAHgAeAFAAGgAeAB0AHgBQAB4AGgAeAB4AHgAeAB4AHgAeAB4AHgBPAB4AUAAbAB4AHgBQAFAAUABQAFAAHgAeAB4AHQAdAB4AUAAeAFAAHgBQAB4AUABPAFAAUAAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgBQAFAAUABQAE8ATwBQAFAAUABQAFAATwBQAFAATwBQAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAUABQAFAATwBPAE8ATwBPAE8ATwBPAE8ATwBQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABPAB4AHgArACsAKwArAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHQAdAB4AHgAeAB0AHQAeAB4AHQAeAB4AHgAdAB4AHQAbABsAHgAdAB4AHgAeAB4AHQAeAB4AHQAdAB0AHQAeAB4AHQAeAB0AHgAdAB0AHQAdAB0AHQAeAB0AHgAeAB4AHgAeAB0AHQAdAB0AHgAeAB4AHgAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB0AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAdAB0AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAWABEAHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AHQAdAB0AHgAeAB0AHgAeAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlAB4AHQAdAB4AHgAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AJQAlAB0AHQAlAB4AJQAlACUAIAAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAdAB0AHQAeAB0AJQAdAB0AHgAdAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAdAB0AHQAdACUAHgAlACUAJQAdACUAJQAdAB0AHQAlACUAHQAdACUAHQAdACUAJQAlAB4AHQAeAB4AHgAeAB0AHQAlAB0AHQAdAB0AHQAdACUAJQAlACUAJQAdACUAJQAgACUAHQAdACUAJQAlACUAJQAlACUAJQAeAB4AHgAlACUAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AFwAXABcAFwAXABcAHgATABMAJQAeAB4AHgAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARABYAEQAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAeAB4AKwArACsAKwArABMADQANAA0AUAATAA0AUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUAANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAA0ADQANAA0ADQANAA0ADQAeAA0AFgANAB4AHgAXABcAHgAeABcAFwAWABEAFgARABYAEQAWABEADQANAA0ADQATAFAADQANAB4ADQANAB4AHgAeAB4AHgAMAAwADQANAA0AHgANAA0AFgANAA0ADQANAA0ADQANAA0AHgANAB4ADQANAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArAA0AEQARACUAJQBHAFcAVwAWABEAFgARABYAEQAWABEAFgARACUAJQAWABEAFgARABYAEQAWABEAFQAWABEAEQAlAFcAVwBXAFcAVwBXAFcAVwBXAAQABAAEAAQABAAEACUAVwBXAFcAVwA2ACUAJQBXAFcAVwBHAEcAJQAlACUAKwBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBRAFcAUQBXAFEAVwBXAFcAVwBXAFcAUQBXAFcAVwBXAFcAVwBRAFEAKwArAAQABAAVABUARwBHAFcAFQBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBRAFcAVwBXAFcAVwBXAFEAUQBXAFcAVwBXABUAUQBHAEcAVwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwAlACUAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACsAKwArACsAKwArACsAKwArACsAKwArAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBPAE8ATwBPAE8ATwBPAE8AJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADQATAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQAHgBQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAeAA0ADQANAA0ADQArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAAQAUABQAFAABABQAFAAUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAeAB4AHgAeAAQAKwArACsAUABQAFAAUABQAFAAHgAeABoAHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADgAOABMAEwArACsAKwArACsAKwArACsABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUAAeAB4AHgBQAA4AUABQAAQAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAB4AWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYACsAKwArAAQAHgAeAB4AHgAeAB4ADQANAA0AHgAeAB4AHgArAFAASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArAB4AHgBcAFwAXABcAFwAKgBcAFwAXABcAFwAXABcAFwAXABcAEsASwBLAEsASwBLAEsASwBLAEsAXABcAFwAXABcACsAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAFAAUABQAAQAUABQAFAAUABQAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAHgANAA0ADQBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAKgAqACoAXABcACoAKgBcAFwAXABcAFwAKgAqAFwAKgBcACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAA0ADQBQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQADQAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAVABVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBUAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVACsAKwArACsAKwArACsAKwArACsAKwArAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAKwArACsAKwBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAKwArACsAKwAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArACsAKwArAFYABABWAFYAVgBWAFYAVgBWAFYAVgBWAB4AVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgArAFYAVgBWAFYAVgArAFYAKwBWAFYAKwBWAFYAKwBWAFYAVgBWAFYAVgBWAFYAVgBWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAEQAWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAaAB4AKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAGAARABEAGAAYABMAEwAWABEAFAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACUAJQAlACUAJQAWABEAFgARABYAEQAWABEAFgARABYAEQAlACUAFgARACUAJQAlACUAJQAlACUAEQAlABEAKwAVABUAEwATACUAFgARABYAEQAWABEAJQAlACUAJQAlACUAJQAlACsAJQAbABoAJQArACsAKwArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAcAKwATACUAJQAbABoAJQAlABYAEQAlACUAEQAlABEAJQBXAFcAVwBXAFcAVwBXAFcAVwBXABUAFQAlACUAJQATACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXABYAJQARACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAWACUAEQAlABYAEQARABYAEQARABUAVwBRAFEAUQBRAFEAUQBRAFEAUQBRAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcARwArACsAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXACsAKwBXAFcAVwBXAFcAVwArACsAVwBXAFcAKwArACsAGgAbACUAJQAlABsAGwArAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAAQAB0AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsADQANAA0AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAA0AUABQAFAAUAArACsAKwArAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwBQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAUABQAFAAUABQAAQABAAEACsABAAEACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAKwBQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAA0ADQANAA0ADQANAA0ADQAeACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAArACsAKwArAFAAUABQAFAAUAANAA0ADQANAA0ADQAUACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsADQANAA0ADQANAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArAAQABAANACsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAB4AHgAeAB4AHgArACsAKwArACsAKwAEAAQABAAEAAQABAAEAA0ADQAeAB4AHgAeAB4AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsASwBLAEsASwBLAEsASwBLAEsASwANAA0ADQANAFAABAAEAFAAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAeAA4AUAArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAADQANAB4ADQAEAAQABAAEAB4ABAAEAEsASwBLAEsASwBLAEsASwBLAEsAUAAOAFAADQANAA0AKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAA0AHgANAA0AHgAEACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAA0AKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsABAAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAUAArACsAKwArACsAKwAEACsAKwArACsAKwBQAFAAUABQAFAABAAEACsAKwAEAAQABAAEAAQABAAEACsAKwArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABABQAFAAUABQAA0ADQANAA0AHgBLAEsASwBLAEsASwBLAEsASwBLAA0ADQArAB4ABABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUAAeAFAAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABAAEAAQADgANAA0AEwATAB4AHgAeAA0ADQANAA0ADQANAA0ADQANAA0ADQANAA0ADQANAFAAUABQAFAABAAEACsAKwAEAA0ADQAeAFAAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKwArACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBcAFwADQANAA0AKgBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQAKwAEAAQAKwArAAQABAAEAAQAUAAEAFAABAAEAA0ADQANACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABABQAA4AUAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAOAB4ADQANAA0ADQAOAB4ABAArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAA0ADQANAFAADgAOAA4ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAFAADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAOABMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAArACsAKwAEACsABAAEACsABAAEAAQABAAEAAQABABQAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAaABoAGgAaAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABIAEgAQwBDAEMAUABQAFAAUABDAFAAUABQAEgAQwBIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABDAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAJAAkACQAJAAkACQAJABYAEQArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwANAA0AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAANACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQANAB4AHgAeAB4AHgAeAFAAUABQAFAADQAeACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAA0AHgAeACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAARwBHABUARwAJACsAKwArACsAKwArACsAKwArACsAKwAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUQBRAFEAKwArACsAKwArACsAKwArACsAKwArACsAKwBRAFEAUQBRACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAHgAEAAQADQAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQABAAEAAQABAAeAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQAHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAKwArAFAAKwArAFAAUAArACsAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUAArAFAAUABQAFAAUABQAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAHgAeAFAAUABQAFAAUAArAFAAKwArACsAUABQAFAAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeACsAKwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4ABAAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAHgAeAA0ADQANAA0AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArAAQABAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwBQAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArABsAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAB4AHgAeAB4ABAAEAAQABAAEAAQABABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArABYAFgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAGgBQAFAAUAAaAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUAArACsAKwArACsAKwBQACsAKwArACsAUAArAFAAKwBQACsAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUAArAFAAKwBQACsAUAArAFAAUAArAFAAKwArAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAKwBQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AJQAlACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeACUAJQAlAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAlACUAJQAlACUAHgAlACUAJQAlACUAIAAgACAAJQAlACAAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACEAIQAhACEAIQAlACUAIAAgACUAJQAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAIAAlACUAJQAlACAAIAAgACUAIAAgACAAJQAlACUAJQAlACUAJQAgACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAlAB4AJQAeACUAJQAlACUAJQAgACUAJQAlACUAHgAlAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACAAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABcAFwAXABUAFQAVAB4AHgAeAB4AJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAgACUAJQAgACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAIAAgACUAJQAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACAAIAAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACAAIAAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAA=="),ALPHABETICS=[30,36],HARD_LINE_BREAKS=[1,2,3,5],SPACE$1=[10,8],PREFIX_POSTFIX=[27,26],LINE_BREAKS=HARD_LINE_BREAKS.concat(SPACE$1),KOREAN_SYLLABLE_BLOCK=[38,39,40,34,35],HYPHEN=[15,13],Break=function(){function Break(codePoints,lineBreak,start,end){this.codePoints=codePoints,this.required="!"===lineBreak,this.start=start,this.end=end}return Break.prototype.slice=function(){return fromCodePoint$1.apply(void 0,this.codePoints.slice(this.start,this.end))},Break}(),LineBreaker=function(str,options){var codePoints=toCodePoints$1(str),str=cssFormattedClasses(codePoints,options),indicies=str[0],classTypes=str[1],forbiddenBreakpoints=str[2],length=codePoints.length,lastEnd=0,nextIndex=0;return{next:function(){if(length<=nextIndex)return{done:!0,value:null};for(var value,lineBreak="×";nextIndex<length&&"×"===(lineBreak=function(codePoints,classTypes,indicies,index,forbiddenBreaks){if(0===indicies[index])return"×";index-=1;if(Array.isArray(forbiddenBreaks)&&!0===forbiddenBreaks[index])return"×";var forbiddenBreaks=index-1,afterIndex=1+index,current=classTypes[index],before=0<=forbiddenBreaks?classTypes[forbiddenBreaks]:0,next=classTypes[afterIndex];if(2===current&&3===next)return"×";if(-1!==HARD_LINE_BREAKS.indexOf(current))return"!";if(-1!==HARD_LINE_BREAKS.indexOf(next))return"×";if(-1!==SPACE$1.indexOf(next))return"×";if(8===previousNonSpaceClassType(index,classTypes))return"÷";if(11===UnicodeTrie$1.get(codePoints[index]))return"×";if((32===current||33===current)&&11===UnicodeTrie$1.get(codePoints[afterIndex]))return"×";if(7===current||7===next)return"×";if(9===current)return"×";if(-1===[10,13,15].indexOf(current)&&9===next)return"×";if(-1!==[17,18,19,24,28].indexOf(next))return"×";if(22===previousNonSpaceClassType(index,classTypes))return"×";if(isAdjacentWithSpaceIgnored(23,22,index,classTypes))return"×";if(isAdjacentWithSpaceIgnored([17,18],21,index,classTypes))return"×";if(isAdjacentWithSpaceIgnored(12,12,index,classTypes))return"×";if(10===current)return"÷";if(23===current||23===next)return"×";if(16===next||16===current)return"÷";if(-1!==[13,15,21].indexOf(next)||14===current)return"×";if(36===before&&-1!==HYPHEN.indexOf(current))return"×";if(28===current&&36===next)return"×";if(20===next)return"×";if(-1!==ALPHABETICS.indexOf(next)&&25===current||-1!==ALPHABETICS.indexOf(current)&&25===next)return"×";if(27===current&&-1!==[37,32,33].indexOf(next)||-1!==[37,32,33].indexOf(current)&&26===next)return"×";if(-1!==ALPHABETICS.indexOf(current)&&-1!==PREFIX_POSTFIX.indexOf(next)||-1!==PREFIX_POSTFIX.indexOf(current)&&-1!==ALPHABETICS.indexOf(next))return"×";if(-1!==[27,26].indexOf(current)&&(25===next||-1!==[22,15].indexOf(next)&&25===classTypes[1+afterIndex])||-1!==[22,15].indexOf(current)&&25===next||25===current&&-1!==[25,28,24].indexOf(next))return"×";if(-1!==[25,28,24,17,18].indexOf(next))for(var prevIndex=index;0<=prevIndex;){if(25===(type=classTypes[prevIndex]))return"×";if(-1===[28,24].indexOf(type))break;prevIndex--}if(-1!==[27,26].indexOf(next))for(var type,prevIndex=-1!==[17,18].indexOf(current)?forbiddenBreaks:index;0<=prevIndex;){if(25===(type=classTypes[prevIndex]))return"×";if(-1===[28,24].indexOf(type))break;prevIndex--}if(38===current&&-1!==[38,39,34,35].indexOf(next)||-1!==[39,34].indexOf(current)&&-1!==[39,40].indexOf(next)||-1!==[40,35].indexOf(current)&&40===next)return"×";if(-1!==KOREAN_SYLLABLE_BLOCK.indexOf(current)&&-1!==[20,26].indexOf(next)||-1!==KOREAN_SYLLABLE_BLOCK.indexOf(next)&&27===current)return"×";if(-1!==ALPHABETICS.indexOf(current)&&-1!==ALPHABETICS.indexOf(next))return"×";if(24===current&&-1!==ALPHABETICS.indexOf(next))return"×";if(-1!==ALPHABETICS.concat(25).indexOf(current)&&22===next&&-1===ea_OP.indexOf(codePoints[afterIndex])||-1!==ALPHABETICS.concat(25).indexOf(next)&&18===current)return"×";if(41===current&&41===next){for(var i=indicies[index],count=1;0<i&&41===classTypes[--i];)count++;if(count%2!=0)return"×"}return 32===current&&33===next?"×":"÷"}(codePoints,classTypes,indicies,++nextIndex,forbiddenBreakpoints)););return"×"!==lineBreak||nextIndex===length?(value=new Break(codePoints,lineBreak,lastEnd,nextIndex),lastEnd=nextIndex,{value:value,done:!1}):{done:!0,value:null}}}},LOW_LINE=95,ZERO=48,isLetter=function(codePoint){return function(codePoint){return 97<=codePoint&&codePoint<=122}(codePoint)||function(codePoint){return 65<=codePoint&&codePoint<=90}(codePoint)},isNonASCIICodePoint=function(codePoint){return 128<=codePoint},LEFT_PARENTHESIS_TOKEN={type:2},RIGHT_PARENTHESIS_TOKEN={type:3},COMMA_TOKEN={type:4},SUFFIX_MATCH_TOKEN={type:13},PREFIX_MATCH_TOKEN={type:8},COLUMN_TOKEN={type:21},DASH_MATCH_TOKEN={type:9},INCLUDE_MATCH_TOKEN={type:10},LEFT_CURLY_BRACKET_TOKEN={type:11},RIGHT_CURLY_BRACKET_TOKEN={type:12},SUBSTRING_MATCH_TOKEN={type:14},BAD_URL_TOKEN={type:23},BAD_STRING_TOKEN={type:1},CDO_TOKEN={type:25},CDC_TOKEN={type:24},COLON_TOKEN={type:26},SEMICOLON_TOKEN={type:27},LEFT_SQUARE_BRACKET_TOKEN={type:28},RIGHT_SQUARE_BRACKET_TOKEN={type:29},WHITESPACE_TOKEN={type:31},EOF_TOKEN={type:32},Tokenizer=function(){function Tokenizer(){this._value=[]}return Tokenizer.prototype.write=function(chunk){this._value=this._value.concat(toCodePoints$1(chunk))},Tokenizer.prototype.read=function(){for(var tokens=[],token=this.consumeToken();token!==EOF_TOKEN;)tokens.push(token),token=this.consumeToken();return tokens},Tokenizer.prototype.consumeToken=function(){var codePoint=this.consumeCodePoint();switch(codePoint){case 34:return this.consumeStringToken(34);case 35:var c1=this.peekCodePoint(0),c2=this.peekCodePoint(1),c3=this.peekCodePoint(2);if(isNameCodePoint(c1)||92===c2&&10!==c3)return c1=isIdentifierStart(c1,c2,c3)?2:1,{type:5,value:this.consumeName(),flags:c1};break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),SUFFIX_MATCH_TOKEN;break;case 39:return this.consumeStringToken(39);case 40:return LEFT_PARENTHESIS_TOKEN;case 41:return RIGHT_PARENTHESIS_TOKEN;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),SUBSTRING_MATCH_TOKEN;break;case 43:if(isNumberStart(codePoint,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(codePoint),this.consumeNumericToken();break;case 44:return COMMA_TOKEN;case 45:c2=codePoint,c3=this.peekCodePoint(0),c1=this.peekCodePoint(1);if(isNumberStart(c2,c3,c1))return this.reconsumeCodePoint(codePoint),this.consumeNumericToken();if(isIdentifierStart(c2,c3,c1))return this.reconsumeCodePoint(codePoint),this.consumeIdentLikeToken();if(45===c3&&62===c1)return this.consumeCodePoint(),this.consumeCodePoint(),CDC_TOKEN;break;case 46:if(isNumberStart(codePoint,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(codePoint),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var c=this.consumeCodePoint();if(42===c&&47===(c=this.consumeCodePoint()))return this.consumeToken();if(-1===c)return this.consumeToken()}break;case 58:return COLON_TOKEN;case 59:return SEMICOLON_TOKEN;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),CDO_TOKEN;break;case 64:c2=this.peekCodePoint(0),c3=this.peekCodePoint(1),c1=this.peekCodePoint(2);if(isIdentifierStart(c2,c3,c1))return{type:7,value:this.consumeName()};break;case 91:return LEFT_SQUARE_BRACKET_TOKEN;case 92:if(isValidEscape(codePoint,this.peekCodePoint(0)))return this.reconsumeCodePoint(codePoint),this.consumeIdentLikeToken();break;case 93:return RIGHT_SQUARE_BRACKET_TOKEN;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),PREFIX_MATCH_TOKEN;break;case 123:return LEFT_CURLY_BRACKET_TOKEN;case 125:return RIGHT_CURLY_BRACKET_TOKEN;case 117:case 85:c2=this.peekCodePoint(0),c3=this.peekCodePoint(1);return 43!==c2||!isHex(c3)&&63!==c3||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(codePoint),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),DASH_MATCH_TOKEN;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),COLUMN_TOKEN;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),INCLUDE_MATCH_TOKEN;break;case-1:return EOF_TOKEN}return isWhiteSpace(codePoint)?(this.consumeWhiteSpace(),WHITESPACE_TOKEN):isDigit(codePoint)?(this.reconsumeCodePoint(codePoint),this.consumeNumericToken()):isNameStartCodePoint(codePoint)?(this.reconsumeCodePoint(codePoint),this.consumeIdentLikeToken()):{type:6,value:fromCodePoint$1(codePoint)}},Tokenizer.prototype.consumeCodePoint=function(){var value=this._value.shift();return void 0===value?-1:value},Tokenizer.prototype.reconsumeCodePoint=function(codePoint){this._value.unshift(codePoint)},Tokenizer.prototype.peekCodePoint=function(delta){return delta>=this._value.length?-1:this._value[delta]},Tokenizer.prototype.consumeUnicodeRangeToken=function(){for(var digits=[],codePoint=this.consumeCodePoint();isHex(codePoint)&&digits.length<6;)digits.push(codePoint),codePoint=this.consumeCodePoint();for(var questionMarks=!1;63===codePoint&&digits.length<6;)digits.push(codePoint),codePoint=this.consumeCodePoint(),questionMarks=!0;if(questionMarks)return{type:30,start:parseInt(fromCodePoint$1.apply(void 0,digits.map(function(digit){return 63===digit?ZERO:digit})),16),end:parseInt(fromCodePoint$1.apply(void 0,digits.map(function(digit){return 63===digit?70:digit})),16)};var start=parseInt(fromCodePoint$1.apply(void 0,digits),16);if(45===this.peekCodePoint(0)&&isHex(this.peekCodePoint(1))){this.consumeCodePoint();for(var codePoint=this.consumeCodePoint(),endDigits=[];isHex(codePoint)&&endDigits.length<6;)endDigits.push(codePoint),codePoint=this.consumeCodePoint();return{type:30,start:start,end:parseInt(fromCodePoint$1.apply(void 0,endDigits),16)}}return{type:30,start:start,end:start}},Tokenizer.prototype.consumeIdentLikeToken=function(){var value=this.consumeName();return"url"===value.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:value}):{type:20,value:value}},Tokenizer.prototype.consumeUrlToken=function(){var value=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var next=this.peekCodePoint(0);if(39===next||34===next)return 0===(next=this.consumeStringToken(this.consumeCodePoint())).type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:next.value}):(this.consumeBadUrlRemnants(),BAD_URL_TOKEN);for(;;){var codePoint=this.consumeCodePoint();if(-1===codePoint||41===codePoint)return{type:22,value:fromCodePoint$1.apply(void 0,value)};if(isWhiteSpace(codePoint))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:fromCodePoint$1.apply(void 0,value)}):(this.consumeBadUrlRemnants(),BAD_URL_TOKEN);if(34===codePoint||39===codePoint||40===codePoint||function(codePoint){return 0<=codePoint&&codePoint<=8||11===codePoint||14<=codePoint&&codePoint<=31||127===codePoint}(codePoint))return this.consumeBadUrlRemnants(),BAD_URL_TOKEN;if(92===codePoint){if(!isValidEscape(codePoint,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),BAD_URL_TOKEN;value.push(this.consumeEscapedCodePoint())}else value.push(codePoint)}},Tokenizer.prototype.consumeWhiteSpace=function(){for(;isWhiteSpace(this.peekCodePoint(0));)this.consumeCodePoint()},Tokenizer.prototype.consumeBadUrlRemnants=function(){for(;;){var codePoint=this.consumeCodePoint();if(41===codePoint||-1===codePoint)return;isValidEscape(codePoint,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},Tokenizer.prototype.consumeStringSlice=function(count){for(var value="";0<count;){var amount=Math.min(5e4,count);value+=fromCodePoint$1.apply(void 0,this._value.splice(0,amount)),count-=amount}return this._value.shift(),value},Tokenizer.prototype.consumeStringToken=function(endingCodePoint){for(var value="",i=0;;){var next,codePoint=this._value[i];if(-1===codePoint||void 0===codePoint||codePoint===endingCodePoint)return{type:0,value:value+=this.consumeStringSlice(i)};if(10===codePoint)return this._value.splice(0,i),BAD_STRING_TOKEN;92===codePoint&&-1!==(next=this._value[i+1])&&void 0!==next&&(10===next?(value+=this.consumeStringSlice(i),i=-1,this._value.shift()):92===codePoint&&10!==next&&(value=(value+=this.consumeStringSlice(i))+fromCodePoint$1(this.consumeEscapedCodePoint()),i=-1)),i++}},Tokenizer.prototype.consumeNumber=function(){var repr=[],type=4;for(43!==(c1=this.peekCodePoint(0))&&45!==c1||repr.push(this.consumeCodePoint());isDigit(this.peekCodePoint(0));)repr.push(this.consumeCodePoint());var c1=this.peekCodePoint(0),c2=this.peekCodePoint(1);if(46===c1&&isDigit(c2))for(repr.push(this.consumeCodePoint(),this.consumeCodePoint()),type=8;isDigit(this.peekCodePoint(0));)repr.push(this.consumeCodePoint());c1=this.peekCodePoint(0);var c2=this.peekCodePoint(1),c3=this.peekCodePoint(2);if((69===c1||101===c1)&&((43===c2||45===c2)&&isDigit(c3)||isDigit(c2)))for(repr.push(this.consumeCodePoint(),this.consumeCodePoint()),type=8;isDigit(this.peekCodePoint(0));)repr.push(this.consumeCodePoint());return[function(codePoints){for(var c=0,sign=1,integers=(43!==codePoints[c]&&45!==codePoints[c]||(45===codePoints[c]&&(sign=-1),c++),[]);isDigit(codePoints[c]);)integers.push(codePoints[c++]);for(var int=integers.length?parseInt(fromCodePoint$1.apply(void 0,integers),10):0,fraction=(46===codePoints[c]&&c++,[]);isDigit(codePoints[c]);)fraction.push(codePoints[c++]);for(var fracd=fraction.length,frac=fracd?parseInt(fromCodePoint$1.apply(void 0,fraction),10):0,expsign=(69!==codePoints[c]&&101!==codePoints[c]||c++,1),exponent=(43!==codePoints[c]&&45!==codePoints[c]||(45===codePoints[c]&&(expsign=-1),c++),[]);isDigit(codePoints[c]);)exponent.push(codePoints[c++]);var exp=exponent.length?parseInt(fromCodePoint$1.apply(void 0,exponent),10):0;return sign*(int+frac*Math.pow(10,-fracd))*Math.pow(10,expsign*exp)}(repr),type]},Tokenizer.prototype.consumeNumericToken=function(){var _a=this.consumeNumber(),number=_a[0],_a=_a[1],c1=this.peekCodePoint(0),c2=this.peekCodePoint(1),c3=this.peekCodePoint(2);return isIdentifierStart(c1,c2,c3)?{type:15,number:number,flags:_a,unit:this.consumeName()}:37===c1?(this.consumeCodePoint(),{type:16,number:number,flags:_a}):{type:17,number:number,flags:_a}},Tokenizer.prototype.consumeEscapedCodePoint=function(){var codePoint=this.consumeCodePoint();if(isHex(codePoint)){for(var hex=fromCodePoint$1(codePoint);isHex(this.peekCodePoint(0))&&hex.length<6;)hex+=fromCodePoint$1(this.consumeCodePoint());isWhiteSpace(this.peekCodePoint(0))&&this.consumeCodePoint();var hexCodePoint=parseInt(hex,16);return 0===hexCodePoint||function(codePoint){return 55296<=codePoint&&codePoint<=57343}(hexCodePoint)||1114111<hexCodePoint?65533:hexCodePoint}return-1===codePoint?65533:codePoint},Tokenizer.prototype.consumeName=function(){for(var result="";;){var codePoint=this.consumeCodePoint();if(isNameCodePoint(codePoint))result+=fromCodePoint$1(codePoint);else{if(!isValidEscape(codePoint,this.peekCodePoint(0)))return this.reconsumeCodePoint(codePoint),result;result+=fromCodePoint$1(this.consumeEscapedCodePoint())}}},Tokenizer}(),Parser=function(){function Parser(tokens){this._tokens=tokens}return Parser.create=function(value){var tokenizer=new Tokenizer;return tokenizer.write(value),new Parser(tokenizer.read())},Parser.parseValue=function(value){return Parser.create(value).parseComponentValue()},Parser.parseValues=function(value){return Parser.create(value).parseComponentValues()},Parser.prototype.parseComponentValue=function(){for(var token=this.consumeToken();31===token.type;)token=this.consumeToken();if(32===token.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(token);for(var value=this.consumeComponentValue();31===(token=this.consumeToken()).type;);if(32===token.type)return value;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},Parser.prototype.parseComponentValues=function(){for(var values=[];;){var value=this.consumeComponentValue();if(32===value.type)return values;values.push(value),values.push()}},Parser.prototype.consumeComponentValue=function(){var token=this.consumeToken();switch(token.type){case 11:case 28:case 2:return this.consumeSimpleBlock(token.type);case 19:return this.consumeFunction(token)}return token},Parser.prototype.consumeSimpleBlock=function(type){for(var block={type:type,values:[]},token=this.consumeToken();;){if(32===token.type||isEndingTokenFor(token,type))return block;this.reconsumeToken(token),block.values.push(this.consumeComponentValue()),token=this.consumeToken()}},Parser.prototype.consumeFunction=function(functionToken){for(var cssFunction={name:functionToken.value,values:[],type:18};;){var token=this.consumeToken();if(32===token.type||3===token.type)return cssFunction;this.reconsumeToken(token),cssFunction.values.push(this.consumeComponentValue())}},Parser.prototype.consumeToken=function(){var token=this._tokens.shift();return void 0===token?EOF_TOKEN:token},Parser.prototype.reconsumeToken=function(token){this._tokens.unshift(token)},Parser}(),isDimensionToken=function(token){return 15===token.type},isIdentToken=function(token){return 20===token.type},isEndingTokenFor=function(token,type){return 11===type&&12===token.type||28===type&&29===token.type||2===type&&3===token.type},isLength=function(token){return 17===token.type||15===token.type},isLengthPercentage=function(token){return 16===token.type||isLength(token)},ZERO_LENGTH={type:17,number:0,flags:4},FIFTY_PERCENT={type:16,number:50,flags:4},HUNDRED_PERCENT={type:16,number:100,flags:4},getAbsoluteValueForTuple=function(tuple,width,height){var x=tuple[0],tuple=tuple[1];return[getAbsoluteValue(x,width),getAbsoluteValue(void 0!==tuple?tuple:x,height)]},getAbsoluteValue=function(token,parent){if(16===token.type)return token.number/100*parent;if(isDimensionToken(token))switch(token.unit){case"rem":case"em":return 16*token.number;default:return token.number}return token.number},DEG="deg",GRAD="grad",RAD="rad",TURN="turn",angle_parse=function(_context,value){if(15===value.type)switch(value.unit){case DEG:return Math.PI*value.number/180;case GRAD:return Math.PI/200*value.number;case RAD:return value.number;case TURN:return 2*Math.PI*value.number}throw new Error("Unsupported angle type")},deg=function(deg){return Math.PI*deg/180},color$1={name:"color",parse:function(context,value){if(18===value.type){var colorFunction=SUPPORTED_COLOR_FUNCTIONS[value.name];if(void 0===colorFunction)throw new Error('Attempting to parse an unsupported color function "'+value.name+'"');return colorFunction(context,value.values)}if(5===value.type){var r,g,b,a;if(3===value.value.length)return r=value.value.substring(0,1),g=value.value.substring(1,2),b=value.value.substring(2,3),pack(parseInt(r+r,16),parseInt(g+g,16),parseInt(b+b,16),1);if(4===value.value.length)return r=value.value.substring(0,1),g=value.value.substring(1,2),b=value.value.substring(2,3),a=value.value.substring(3,4),pack(parseInt(r+r,16),parseInt(g+g,16),parseInt(b+b,16),parseInt(a+a,16)/255);if(6===value.value.length)return r=value.value.substring(0,2),g=value.value.substring(2,4),b=value.value.substring(4,6),pack(parseInt(r,16),parseInt(g,16),parseInt(b,16),1);if(8===value.value.length)return r=value.value.substring(0,2),g=value.value.substring(2,4),b=value.value.substring(4,6),a=value.value.substring(6,8),pack(parseInt(r,16),parseInt(g,16),parseInt(b,16),parseInt(a,16)/255)}if(20===value.type){colorFunction=COLORS[value.value.toUpperCase()];if(void 0!==colorFunction)return colorFunction}return COLORS.TRANSPARENT}},pack=function(r,g,b,a){return(r<<24|g<<16|b<<8|Math.round(255*a)<<0)>>>0};function hue2rgb(t1,t2,hue){return hue<0&&(hue+=1),1<=hue&&--hue,hue<1/6?(t2-t1)*hue*6+t1:hue<.5?t2:hue<2/3?6*(t2-t1)*(2/3-hue)+t1:t1}function hsl(context,args){var g,hue=(args=args.filter(nonFunctionArgSeparator))[0],saturation=args[1],lightness=args[2],args=args[3],context=(17===hue.type?deg(hue.number):angle_parse(context,hue))/(2*Math.PI),hue=isLengthPercentage(saturation)?saturation.number/100:0,saturation=isLengthPercentage(lightness)?lightness.number/100:0,lightness=void 0!==args&&isLengthPercentage(args)?getAbsoluteValue(args,1):1;return 0==hue?pack(255*saturation,255*saturation,255*saturation,1):(hue=hue2rgb(saturation=2*saturation-(args=saturation<=.5?saturation*(1+hue):saturation+hue-saturation*hue),args,context+1/3),g=hue2rgb(saturation,args,context),saturation=hue2rgb(saturation,args,context-1/3),pack(255*hue,255*g,255*saturation,lightness))}function parseColor(context,value){return color$1.parse(context,Parser.create(value).parseComponentValue())}function parseColorStop(context,args){return context=color$1.parse(context,args[0]),(args=args[1])&&isLengthPercentage(args)?{color:context,stop:args}:{color:context,stop:null}}function processColorStops(stops,lineLength){for(var first=stops[0],last=stops[stops.length-1],processStops=(null===first.stop&&(first.stop=ZERO_LENGTH),null===last.stop&&(last.stop=HUNDRED_PERCENT),[]),previous=0,i=0;i<stops.length;i++){var stop_1=stops[i].stop;null!==stop_1?(stop_1=getAbsoluteValue(stop_1,lineLength),processStops.push(previous<stop_1?stop_1:previous),previous=stop_1):processStops.push(null)}for(var gapBegin=null,i=0;i<processStops.length;i++){var stop_2=processStops[i];if(null===stop_2)null===gapBegin&&(gapBegin=i);else if(null!==gapBegin){for(var gapLength=i-gapBegin,gapValue=(stop_2-processStops[gapBegin-1])/(1+gapLength),g=1;g<=gapLength;g++)processStops[gapBegin+g-1]=gapValue*g;gapBegin=null}}return stops.map(function(_a,i){return{color:_a.color,stop:Math.max(Math.min(1,processStops[i]/lineLength),0)}})}function prefixLinearGradient(context,tokens){var angle$1=deg(180),stops=[];return parseFunctionArgs(tokens).forEach(function(arg,i){if(0===i){i=arg[0];if(20===i.type&&-1!==["top","left","right","bottom"].indexOf(i.value))return void(angle$1=parseNamedSide(arg));if(isAngle(i))return void(angle$1=(angle_parse(context,i)+deg(270))%deg(360))}i=parseColorStop(context,arg);stops.push(i)}),{angle:angle$1,stops:stops,type:1}}function prefixRadialGradient(context,tokens){var shape=0,size=3,stops=[],position=[];return parseFunctionArgs(tokens).forEach(function(arg,i){var isColorStop=!0;0===i?isColorStop=arg.reduce(function(acc,token){if(isIdentToken(token))switch(token.value){case"center":return position.push(FIFTY_PERCENT),!1;case"top":case"left":return position.push(ZERO_LENGTH),!1;case"right":case"bottom":return position.push(HUNDRED_PERCENT),!1}else if(isLengthPercentage(token)||isLength(token))return position.push(token),!1;return acc},isColorStop):1===i&&(isColorStop=arg.reduce(function(acc,token){if(isIdentToken(token))switch(token.value){case"circle":return shape=0,!1;case"ellipse":return!(shape=1);case"contain":case"closest-side":return size=0,!1;case"farthest-side":return!(size=1);case"closest-corner":return!(size=2);case"cover":case"farthest-corner":return!(size=3)}else if(isLength(token)||isLengthPercentage(token))return(size=Array.isArray(size)?size:[]).push(token),!1;return acc},isColorStop)),isColorStop&&(i=parseColorStop(context,arg),stops.push(i))}),{size:size,shape:shape,stops:stops,position:position,type:2}}var SUPPORTED_COLOR_FUNCTIONS={hsl:hsl,hsla:hsl,rgb:rgb,rgba:rgb},COLORS={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},backgroundClip={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(_context,tokens){return tokens.map(function(token){if(isIdentToken(token))switch(token.value){case"padding-box":return 1;case"content-box":return 2}return 0})}},backgroundColor={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},getAngleFromCorner=function(corner,width,height){var centerX=width/2,centerY=height/2,width=getAbsoluteValue(corner[0],width)-centerX,centerX=centerY-getAbsoluteValue(corner[1],height);return(Math.atan2(centerX,width)+2*Math.PI)%(2*Math.PI)},distance=function(a,b){return Math.sqrt(a*a+b*b)},findCorner=function(width,height,x,y,closest){return[[0,0],[0,height],[width,0],[width,height]].reduce(function(stat,corner){var cx=corner[0],cy=corner[1],cx=distance(x-cx,y-cy);return(closest?cx<stat.optimumDistance:cx>stat.optimumDistance)?{optimumCorner:corner,optimumDistance:cx}:stat},{optimumDistance:closest?1/0:-1/0,optimumCorner:null}).optimumCorner},image_parse=function(context,value){if(22===value.type)return image_1={url:value.value,type:0},context.cache.addImage(value.value),image_1;if(18!==value.type)throw new Error("Unsupported image type "+value.type);var image_1=SUPPORTED_IMAGE_FUNCTIONS[value.name];if(void 0===image_1)throw new Error('Attempting to parse an unsupported image function "'+value.name+'"');return image_1(context,value.values)};for(var BACKGROUND_SIZE,LINE_BREAK,WORD_BREAK,SUPPORTED_IMAGE_FUNCTIONS={"linear-gradient":function(context,tokens){var angle$1=deg(180),stops=[];return parseFunctionArgs(tokens).forEach(function(arg,i){if(0===i){i=arg[0];if(20===i.type&&"to"===i.value)return void(angle$1=parseNamedSide(arg));if(isAngle(i))return void(angle$1=angle_parse(context,i))}i=parseColorStop(context,arg);stops.push(i)}),{angle:angle$1,stops:stops,type:1}},"-moz-linear-gradient":prefixLinearGradient,"-ms-linear-gradient":prefixLinearGradient,"-o-linear-gradient":prefixLinearGradient,"-webkit-linear-gradient":prefixLinearGradient,"radial-gradient":function(context,tokens){var shape=0,size=3,stops=[],position=[];return parseFunctionArgs(tokens).forEach(function(arg,i){var isAtPosition_1,isColorStop=!0;0===i&&(isAtPosition_1=!1,isColorStop=arg.reduce(function(acc,token){if(isAtPosition_1)if(isIdentToken(token))switch(token.value){case"center":return position.push(FIFTY_PERCENT),acc;case"top":case"left":return position.push(ZERO_LENGTH),acc;case"right":case"bottom":return position.push(HUNDRED_PERCENT),acc}else(isLengthPercentage(token)||isLength(token))&&position.push(token);else if(isIdentToken(token))switch(token.value){case"circle":return shape=0,!1;case"ellipse":return!(shape=1);case"at":return!(isAtPosition_1=!0);case"closest-side":return size=0,!1;case"cover":case"farthest-side":return!(size=1);case"contain":case"closest-corner":return!(size=2);case"farthest-corner":return!(size=3)}else if(isLength(token)||isLengthPercentage(token))return(size=Array.isArray(size)?size:[]).push(token),!1;return acc},isColorStop)),isColorStop&&(i=parseColorStop(context,arg),stops.push(i))}),{size:size,shape:shape,stops:stops,position:position,type:2}},"-moz-radial-gradient":prefixRadialGradient,"-ms-radial-gradient":prefixRadialGradient,"-o-radial-gradient":prefixRadialGradient,"-webkit-radial-gradient":prefixRadialGradient,"-webkit-gradient":function(context,tokens){var angle=deg(180),stops=[],type=1;return parseFunctionArgs(tokens).forEach(function(arg,i){var color,arg=arg[0];if(0===i){if(isIdentToken(arg)&&"linear"===arg.value)return void(type=1);if(isIdentToken(arg)&&"radial"===arg.value)return void(type=2)}18===arg.type&&("from"===arg.name?(color=color$1.parse(context,arg.values[0]),stops.push({stop:ZERO_LENGTH,color:color})):"to"===arg.name?(color=color$1.parse(context,arg.values[0]),stops.push({stop:HUNDRED_PERCENT,color:color})):"color-stop"===arg.name&&2===(i=arg.values.filter(nonFunctionArgSeparator)).length&&(color=color$1.parse(context,i[1]),17===(arg=i[0]).type)&&stops.push({stop:{type:16,number:100*arg.number,flags:arg.flags},color:color}))}),1===type?{angle:(angle+deg(180))%deg(360),stops:stops,type:type}:{size:3,shape:0,stops:stops,position:[],type:type}}},backgroundImage={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(context,tokens){var first;return 0===tokens.length||20===(first=tokens[0]).type&&"none"===first.value?[]:tokens.filter(function(value){return nonFunctionArgSeparator(value)&&function(value){return!(20===value.type&&"none"===value.value||18===value.type&&!SUPPORTED_IMAGE_FUNCTIONS[value.name])}(value)}).map(function(value){return image_parse(context,value)})}},backgroundOrigin={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(_context,tokens){return tokens.map(function(token){if(isIdentToken(token))switch(token.value){case"padding-box":return 1;case"content-box":return 2}return 0})}},backgroundPosition={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(_context,tokens){return parseFunctionArgs(tokens).map(function(values){return values.filter(isLengthPercentage)}).map(parseLengthPercentageTuple)}},backgroundRepeat={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(_context,tokens){return parseFunctionArgs(tokens).map(function(values){return values.filter(isIdentToken).map(function(token){return token.value}).join(" ")}).map(parseBackgroundRepeat)}},parseBackgroundRepeat=function(value){switch(value){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}},backgroundSize=(!function(BACKGROUND_SIZE){BACKGROUND_SIZE.AUTO="auto",BACKGROUND_SIZE.CONTAIN="contain",BACKGROUND_SIZE.COVER="cover"}(BACKGROUND_SIZE=BACKGROUND_SIZE||{}),{name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(_context,tokens){return parseFunctionArgs(tokens).map(function(values){return values.filter(isBackgroundSizeInfoToken)})}}),isBackgroundSizeInfoToken=function(value){return isIdentToken(value)||isLengthPercentage(value)},borderColorForSide=function(side){return{name:"border-"+side+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},borderTopColor=borderColorForSide("top"),borderRightColor=borderColorForSide("right"),borderBottomColor=borderColorForSide("bottom"),borderLeftColor=borderColorForSide("left"),borderColorForSide=function(side){return{name:"border-radius-"+side,initialValue:"0 0",prefix:!1,type:1,parse:function(_context,tokens){return parseLengthPercentageTuple(tokens.filter(isLengthPercentage))}}},borderTopLeftRadius=borderColorForSide("top-left"),borderTopRightRadius=borderColorForSide("top-right"),borderBottomRightRadius=borderColorForSide("bottom-right"),borderBottomLeftRadius=borderColorForSide("bottom-left"),borderColorForSide=function(side){return{name:"border-"+side+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(_context,style){switch(style){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},borderTopStyle=borderColorForSide("top"),borderRightStyle=borderColorForSide("right"),borderBottomStyle=borderColorForSide("bottom"),borderLeftStyle=borderColorForSide("left"),borderColorForSide=function(side){return{name:"border-"+side+"-width",initialValue:"0",type:0,prefix:!1,parse:function(_context,token){return isDimensionToken(token)?token.number:0}}},borderTopWidth=borderColorForSide("top"),borderRightWidth=borderColorForSide("right"),borderBottomWidth=borderColorForSide("bottom"),borderLeftWidth=borderColorForSide("left"),color={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},direction={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(_context,direction){return"rtl"!==direction?0:1}},display={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(_context,tokens){return tokens.filter(isIdentToken).reduce(function(bit,token){return bit|parseDisplayValue(token.value)},0)}},parseDisplayValue=function(display){switch(display){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},float={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(_context,float){switch(float){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},letterSpacing={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(_context,token){return!(20===token.type&&"normal"===token.value||17!==token.type&&15!==token.type)?token.number:0}},lineBreak=(!function(LINE_BREAK){LINE_BREAK.NORMAL="normal",LINE_BREAK.STRICT="strict"}(LINE_BREAK=LINE_BREAK||{}),{name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(_context,lineBreak){return"strict"!==lineBreak?LINE_BREAK.NORMAL:LINE_BREAK.STRICT}}),lineHeight={name:"line-height",initialValue:"normal",prefix:!1,type:4},computeLineHeight=function(token,fontSize){return isIdentToken(token)&&"normal"===token.value?1.2*fontSize:17===token.type?fontSize*token.number:isLengthPercentage(token)?getAbsoluteValue(token,fontSize):fontSize},listStyleImage={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(context,token){return 20===token.type&&"none"===token.value?null:image_parse(context,token)}},listStylePosition={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(_context,position){return"inside"!==position?1:0}},listStyleType={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(_context,type){switch(type){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},borderColorForSide=function(side){return{name:"margin-"+side,initialValue:"0",prefix:!1,type:4}},marginTop=borderColorForSide("top"),marginRight=borderColorForSide("right"),marginBottom=borderColorForSide("bottom"),marginLeft=borderColorForSide("left"),overflow={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(_context,tokens){return tokens.filter(isIdentToken).map(function(overflow){switch(overflow.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}})}},overflowWrap={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(_context,overflow){return"break-word"!==overflow?"normal":"break-word"}},borderColorForSide=function(side){return{name:"padding-"+side,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},paddingTop=borderColorForSide("top"),paddingRight=borderColorForSide("right"),paddingBottom=borderColorForSide("bottom"),paddingLeft=borderColorForSide("left"),textAlign={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(_context,textAlign){switch(textAlign){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},position={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(_context,position){switch(position){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},textShadow={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(context,tokens){return 1===tokens.length&&isIdentWithValue(tokens[0],"none")?[]:parseFunctionArgs(tokens).map(function(values){for(var shadow={color:COLORS.TRANSPARENT,offsetX:ZERO_LENGTH,offsetY:ZERO_LENGTH,blur:ZERO_LENGTH},c=0,i=0;i<values.length;i++){var token=values[i];isLength(token)?(0===c?shadow.offsetX=token:1===c?shadow.offsetY=token:shadow.blur=token,c++):shadow.color=color$1.parse(context,token)}return shadow})}},textTransform={name:"text-transform",initialValue:"none",prefix:!1,type:2,parse:function(_context,textTransform){switch(textTransform){case"uppercase":return 2;case"lowercase":return 1;case"capitalize":return 3}return 0}},transform$1={name:"transform",initialValue:"none",prefix:!0,type:0,parse:function(_context,token){if(20===token.type&&"none"===token.value)return null;if(18!==token.type)return null;var transformFunction=SUPPORTED_TRANSFORM_FUNCTIONS[token.name];if(void 0===transformFunction)throw new Error('Attempting to parse an unsupported transform function "'+token.name+'"');return transformFunction(token.values)}},SUPPORTED_TRANSFORM_FUNCTIONS={matrix:function(args){args=args.filter(function(arg){return 17===arg.type}).map(function(arg){return arg.number});return 6===args.length?args:null},matrix3d:function(args){var args=args.filter(function(arg){return 17===arg.type}).map(function(arg){return arg.number}),a1=args[0],b1=args[1],a2=(args[2],args[3],args[4]),b2=args[5],a4=(args[6],args[7],args[8],args[9],args[10],args[11],args[12]),b4=args[13];return args[14],args[15],16===args.length?[a1,b1,a2,b2,a4,b4]:null}},borderColorForSide={type:16,number:50,flags:4},DEFAULT=[borderColorForSide,borderColorForSide],transformOrigin={name:"transform-origin",initialValue:"50% 50%",prefix:!0,type:1,parse:function(_context,tokens){tokens=tokens.filter(isLengthPercentage);return 2!==tokens.length?DEFAULT:[tokens[0],tokens[1]]}},visibility={name:"visible",initialValue:"none",prefix:!1,type:2,parse:function(_context,visibility){switch(visibility){case"hidden":return 1;case"collapse":return 2;default:return 0}}},wordBreak=(!function(WORD_BREAK){WORD_BREAK.NORMAL="normal",WORD_BREAK.BREAK_ALL="break-all",WORD_BREAK.KEEP_ALL="keep-all"}(WORD_BREAK=WORD_BREAK||{}),{name:"word-break",initialValue:"normal",prefix:!1,type:2,parse:function(_context,wordBreak){switch(wordBreak){case"break-all":return WORD_BREAK.BREAK_ALL;case"keep-all":return WORD_BREAK.KEEP_ALL;default:return WORD_BREAK.NORMAL}}}),zIndex={name:"z-index",initialValue:"auto",prefix:!1,type:0,parse:function(_context,token){if(20===token.type)return{auto:!0,order:0};if(17===token.type)return{auto:!1,order:token.number};throw new Error("Invalid z-index number parsed")}},time_parse=function(_context,value){if(15===value.type)switch(value.unit.toLowerCase()){case"s":return 1e3*value.number;case"ms":return value.number}throw new Error("Unsupported time type")},opacity={name:"opacity",initialValue:"1",type:0,prefix:!1,parse:function(_context,token){return 17===token.type?token.number:1}},textDecorationColor={name:"text-decoration-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},textDecorationLine={name:"text-decoration-line",initialValue:"none",prefix:!1,type:1,parse:function(_context,tokens){return tokens.filter(isIdentToken).map(function(token){switch(token.value){case"underline":return 1;case"overline":return 2;case"line-through":return 3;case"none":return 4}return 0}).filter(function(line){return 0!==line})}},fontFamily={name:"font-family",initialValue:"",prefix:!1,type:1,parse:function(_context,tokens){var accumulator=[],results=[];return tokens.forEach(function(token){switch(token.type){case 20:case 0:accumulator.push(token.value);break;case 17:accumulator.push(token.number.toString());break;case 4:results.push(accumulator.join(" ")),accumulator.length=0}}),accumulator.length&&results.push(accumulator.join(" ")),results.map(function(result){return-1===result.indexOf(" ")?result:"'"+result+"'"})}},fontSize={name:"font-size",initialValue:"0",prefix:!1,type:3,format:"length"},fontWeight={name:"font-weight",initialValue:"normal",type:0,prefix:!1,parse:function(_context,token){return 17===token.type?token.number:!isIdentToken(token)||"bold"!==token.value?400:700}},fontVariant={name:"font-variant",initialValue:"none",type:1,prefix:!1,parse:function(_context,tokens){return tokens.filter(isIdentToken).map(function(token){return token.value})}},fontStyle={name:"font-style",initialValue:"normal",prefix:!1,type:2,parse:function(_context,overflow){switch(overflow){case"oblique":return"oblique";case"italic":return"italic";default:return"normal"}}},contains=function(bit,value){return 0!=(bit&value)},content={name:"content",initialValue:"none",type:1,prefix:!1,parse:function(_context,tokens){var first;return 0===tokens.length||20===(first=tokens[0]).type&&"none"===first.value?[]:tokens}},counterIncrement={name:"counter-increment",initialValue:"none",prefix:!0,type:1,parse:function(_context,tokens){if(0===tokens.length)return null;var first=tokens[0];if(20===first.type&&"none"===first.value)return null;for(var increments=[],filtered=tokens.filter(nonWhiteSpace),i=0;i<filtered.length;i++){var counter=filtered[i],next=filtered[i+1];20===counter.type&&(next=next&&17===next.type?next.number:1,increments.push({counter:counter.value,increment:next}))}return increments}},counterReset={name:"counter-reset",initialValue:"none",prefix:!0,type:1,parse:function(_context,tokens){if(0===tokens.length)return[];for(var resets=[],filtered=tokens.filter(nonWhiteSpace),i=0;i<filtered.length;i++){var counter=filtered[i],next=filtered[i+1];isIdentToken(counter)&&"none"!==counter.value&&(next=next&&17===next.type?next.number:0,resets.push({counter:counter.value,reset:next}))}return resets}},duration={name:"duration",initialValue:"0s",prefix:!1,type:1,parse:function(context,tokens){return tokens.filter(isDimensionToken).map(function(token){return time_parse(context,token)})}},quotes={name:"quotes",initialValue:"none",prefix:!0,type:1,parse:function(_context,tokens){if(0===tokens.length)return null;var first=tokens[0];if(20===first.type&&"none"===first.value)return null;var quotes=[],filtered=tokens.filter(isStringToken);if(filtered.length%2!=0)return null;for(var i=0;i<filtered.length;i+=2){var open_1=filtered[i].value,close_1=filtered[i+1].value;quotes.push({open:open_1,close:close_1})}return quotes}},getQuote=function(quotes,depth,open){return quotes&&(depth=quotes[Math.min(depth,quotes.length-1)])?open?depth.open:depth.close:""},boxShadow={name:"box-shadow",initialValue:"none",type:1,prefix:!1,parse:function(context,tokens){return 1===tokens.length&&isIdentWithValue(tokens[0],"none")?[]:parseFunctionArgs(tokens).map(function(values){for(var shadow={color:255,offsetX:ZERO_LENGTH,offsetY:ZERO_LENGTH,blur:ZERO_LENGTH,spread:ZERO_LENGTH,inset:!1},c=0,i=0;i<values.length;i++){var token=values[i];isIdentWithValue(token,"inset")?shadow.inset=!0:isLength(token)?(0===c?shadow.offsetX=token:1===c?shadow.offsetY=token:2===c?shadow.blur=token:shadow.spread=token,c++):shadow.color=color$1.parse(context,token)}return shadow})}},paintOrder={name:"paint-order",initialValue:"normal",prefix:!1,type:1,parse:function(_context,tokens){var layers=[];return tokens.filter(isIdentToken).forEach(function(token){switch(token.value){case"stroke":layers.push(1);break;case"fill":layers.push(0);break;case"markers":layers.push(2)}}),[0,1,2].forEach(function(value){-1===layers.indexOf(value)&&layers.push(value)}),layers}},webkitTextStrokeColor={name:"-webkit-text-stroke-color",initialValue:"currentcolor",prefix:!1,type:3,format:"color"},webkitTextStrokeWidth={name:"-webkit-text-stroke-width",initialValue:"0",type:0,prefix:!1,parse:function(_context,token){return isDimensionToken(token)?token.number:0}},CSSParsedDeclaration=function(){function CSSParsedDeclaration(context,declaration){this.animationDuration=parse(context,duration,declaration.animationDuration),this.backgroundClip=parse(context,backgroundClip,declaration.backgroundClip),this.backgroundColor=parse(context,backgroundColor,declaration.backgroundColor),this.backgroundImage=parse(context,backgroundImage,declaration.backgroundImage),this.backgroundOrigin=parse(context,backgroundOrigin,declaration.backgroundOrigin),this.backgroundPosition=parse(context,backgroundPosition,declaration.backgroundPosition),this.backgroundRepeat=parse(context,backgroundRepeat,declaration.backgroundRepeat),this.backgroundSize=parse(context,backgroundSize,declaration.backgroundSize),this.borderTopColor=parse(context,borderTopColor,declaration.borderTopColor),this.borderRightColor=parse(context,borderRightColor,declaration.borderRightColor),this.borderBottomColor=parse(context,borderBottomColor,declaration.borderBottomColor),this.borderLeftColor=parse(context,borderLeftColor,declaration.borderLeftColor),this.borderTopLeftRadius=parse(context,borderTopLeftRadius,declaration.borderTopLeftRadius),this.borderTopRightRadius=parse(context,borderTopRightRadius,declaration.borderTopRightRadius),this.borderBottomRightRadius=parse(context,borderBottomRightRadius,declaration.borderBottomRightRadius),this.borderBottomLeftRadius=parse(context,borderBottomLeftRadius,declaration.borderBottomLeftRadius),this.borderTopStyle=parse(context,borderTopStyle,declaration.borderTopStyle),this.borderRightStyle=parse(context,borderRightStyle,declaration.borderRightStyle),this.borderBottomStyle=parse(context,borderBottomStyle,declaration.borderBottomStyle),this.borderLeftStyle=parse(context,borderLeftStyle,declaration.borderLeftStyle),this.borderTopWidth=parse(context,borderTopWidth,declaration.borderTopWidth),this.borderRightWidth=parse(context,borderRightWidth,declaration.borderRightWidth),this.borderBottomWidth=parse(context,borderBottomWidth,declaration.borderBottomWidth),this.borderLeftWidth=parse(context,borderLeftWidth,declaration.borderLeftWidth),this.boxShadow=parse(context,boxShadow,declaration.boxShadow),this.color=parse(context,color,declaration.color),this.direction=parse(context,direction,declaration.direction),this.display=parse(context,display,declaration.display),this.float=parse(context,float,declaration.cssFloat),this.fontFamily=parse(context,fontFamily,declaration.fontFamily),this.fontSize=parse(context,fontSize,declaration.fontSize),this.fontStyle=parse(context,fontStyle,declaration.fontStyle),this.fontVariant=parse(context,fontVariant,declaration.fontVariant),this.fontWeight=parse(context,fontWeight,declaration.fontWeight),this.letterSpacing=parse(context,letterSpacing,declaration.letterSpacing),this.lineBreak=parse(context,lineBreak,declaration.lineBreak),this.lineHeight=parse(context,lineHeight,declaration.lineHeight),this.listStyleImage=parse(context,listStyleImage,declaration.listStyleImage),this.listStylePosition=parse(context,listStylePosition,declaration.listStylePosition),this.listStyleType=parse(context,listStyleType,declaration.listStyleType),this.marginTop=parse(context,marginTop,declaration.marginTop),this.marginRight=parse(context,marginRight,declaration.marginRight),this.marginBottom=parse(context,marginBottom,declaration.marginBottom),this.marginLeft=parse(context,marginLeft,declaration.marginLeft),this.opacity=parse(context,opacity,declaration.opacity);var overflowTuple=parse(context,overflow,declaration.overflow);this.overflowX=overflowTuple[0],this.overflowY=overflowTuple[1<overflowTuple.length?1:0],this.overflowWrap=parse(context,overflowWrap,declaration.overflowWrap),this.paddingTop=parse(context,paddingTop,declaration.paddingTop),this.paddingRight=parse(context,paddingRight,declaration.paddingRight),this.paddingBottom=parse(context,paddingBottom,declaration.paddingBottom),this.paddingLeft=parse(context,paddingLeft,declaration.paddingLeft),this.paintOrder=parse(context,paintOrder,declaration.paintOrder),this.position=parse(context,position,declaration.position),this.textAlign=parse(context,textAlign,declaration.textAlign),this.textDecorationColor=parse(context,textDecorationColor,null!=(overflowTuple=declaration.textDecorationColor)?overflowTuple:declaration.color),this.textDecorationLine=parse(context,textDecorationLine,null!=(overflowTuple=declaration.textDecorationLine)?overflowTuple:declaration.textDecoration),this.textShadow=parse(context,textShadow,declaration.textShadow),this.textTransform=parse(context,textTransform,declaration.textTransform),this.transform=parse(context,transform$1,declaration.transform),this.transformOrigin=parse(context,transformOrigin,declaration.transformOrigin),this.visibility=parse(context,visibility,declaration.visibility),this.webkitTextStrokeColor=parse(context,webkitTextStrokeColor,declaration.webkitTextStrokeColor),this.webkitTextStrokeWidth=parse(context,webkitTextStrokeWidth,declaration.webkitTextStrokeWidth),this.wordBreak=parse(context,wordBreak,declaration.wordBreak),this.zIndex=parse(context,zIndex,declaration.zIndex)}return CSSParsedDeclaration.prototype.isVisible=function(){return 0<this.display&&0<this.opacity&&0===this.visibility},CSSParsedDeclaration.prototype.isTransparent=function(){return 0==(255&this.backgroundColor)},CSSParsedDeclaration.prototype.isTransformed=function(){return null!==this.transform},CSSParsedDeclaration.prototype.isPositioned=function(){return 0!==this.position},CSSParsedDeclaration.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},CSSParsedDeclaration.prototype.isFloating=function(){return 0!==this.float},CSSParsedDeclaration.prototype.isInlineLevel=function(){return contains(this.display,4)||contains(this.display,33554432)||contains(this.display,268435456)||contains(this.display,536870912)||contains(this.display,67108864)||contains(this.display,134217728)},CSSParsedDeclaration}(),CSSParsedPseudoDeclaration=function(context,declaration){this.content=parse(context,content,declaration.content),this.quotes=parse(context,quotes,declaration.quotes)},CSSParsedCounterDeclaration=function(context,declaration){this.counterIncrement=parse(context,counterIncrement,declaration.counterIncrement),this.counterReset=parse(context,counterReset,declaration.counterReset)},parse=function(context,descriptor,style){var tokenizer=new Tokenizer,style=null!=style?style.toString():descriptor.initialValue,parser=(tokenizer.write(style),new Parser(tokenizer.read()));switch(descriptor.type){case 2:var token=parser.parseComponentValue();return descriptor.parse(context,isIdentToken(token)?token.value:descriptor.initialValue);case 0:return descriptor.parse(context,parser.parseComponentValue());case 1:return descriptor.parse(context,parser.parseComponentValues());case 4:return parser.parseComponentValue();case 3:switch(descriptor.format){case"angle":return angle_parse(context,parser.parseComponentValue());case"color":return color$1.parse(context,parser.parseComponentValue());case"image":return image_parse(context,parser.parseComponentValue());case"length":var length_1=parser.parseComponentValue();return isLength(length_1)?length_1:ZERO_LENGTH;case"length-percentage":length_1=parser.parseComponentValue();return isLengthPercentage(length_1)?length_1:ZERO_LENGTH;case"time":return time_parse(context,parser.parseComponentValue())}}},getElementDebugType=function(element){switch(element.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}},isDebugging=function(element,type){element=getElementDebugType(element);return 1===element||type===element},ElementContainer=function(context,element){this.context=context,this.textNodes=[],this.elements=[],this.flags=0,isDebugging(element,3),this.styles=new CSSParsedDeclaration(context,window.getComputedStyle(element,null)),isHTMLElementNode(element)&&(this.styles.animationDuration.some(function(duration){return 0<duration})&&(element.style.animationDuration="0s"),null!==this.styles.transform)&&(element.style.transform="none"),this.bounds=parseBounds(this.context,element),isDebugging(element,4)&&(this.flags|=16)},chars$1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$1="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i$1=0;i$1<chars$1.length;i$1++)lookup$1[chars$1.charCodeAt(i$1)]=i$1;for(var slice16=function(view,start,end){return view.slice?view.slice(start,end):new Uint16Array(Array.prototype.slice.call(view,start,end))},Trie=function(){function Trie(initialValue,errorValue,highStart,highValueIndex,index,data){this.initialValue=initialValue,this.errorValue=errorValue,this.highStart=highStart,this.highValueIndex=highValueIndex,this.index=index,this.data=data}return Trie.prototype.get=function(codePoint){var ix;if(0<=codePoint){if(codePoint<55296||56319<codePoint&&codePoint<=65535)return ix=this.index[codePoint>>5],this.data[ix=(ix<<2)+(31&codePoint)];if(codePoint<=65535)return ix=this.index[2048+(codePoint-55296>>5)],this.data[ix=(ix<<2)+(31&codePoint)];if(codePoint<this.highStart)return ix=this.index[ix=2080+(codePoint>>11)],ix=this.index[ix+=codePoint>>5&63],this.data[ix=(ix<<2)+(31&codePoint)];if(codePoint<=1114111)return this.data[this.highValueIndex]}return this.errorValue},Trie}(),chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i=0;i<chars.length;i++)lookup[chars.charCodeAt(i)]=i;function codePointToClass(codePoint){return UnicodeTrie.get(codePoint)}function isGreenPixel(data){return 0===data[0]&&255===data[1]&&0===data[2]&&255===data[3]}function createForeignObjectSVG(width,height,x,y,node){var xmlns="http://www.w3.org/2000/svg",svg=document.createElementNS(xmlns,"svg"),xmlns=document.createElementNS(xmlns,"foreignObject");return svg.setAttributeNS(null,"width",width.toString()),svg.setAttributeNS(null,"height",height.toString()),xmlns.setAttributeNS(null,"width","100%"),xmlns.setAttributeNS(null,"height","100%"),xmlns.setAttributeNS(null,"x",x.toString()),xmlns.setAttributeNS(null,"y",y.toString()),xmlns.setAttributeNS(null,"externalResourcesRequired","true"),svg.appendChild(xmlns),xmlns.appendChild(node),svg}function loadSerializedSVG$1(svg){return new Promise(function(resolve,reject){var img=new Image;img.onload=function(){return resolve(img)},img.onerror=reject,img.src="data:image/svg+xml;charset=utf-8,"+encodeURIComponent((new XMLSerializer).serializeToString(svg))})}function segmentWords(value,styles){var segmenter;return FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION?(segmenter=new Intl.Segmenter(void 0,{granularity:"word"}),Array.from(segmenter.segment(value)).map(function(segment){return segment.segment})):function(str,styles){var breaker=LineBreaker(str,{lineBreak:styles.lineBreak,wordBreak:styles.overflowWrap==="break-word"?"break-word":styles.wordBreak}),words=[],bk,_loop_1=function(){if(bk.value){var value=bk.value.slice();var codePoints=toCodePoints$1(value);var word_1="";codePoints.forEach(function(codePoint){if(wordSeparators.indexOf(codePoint)===-1)word_1+=fromCodePoint$1(codePoint);else{if(word_1.length)words.push(word_1);words.push(fromCodePoint$1(codePoint));word_1=""}});if(word_1.length)words.push(word_1)}};while(!(bk=breaker.next()).done)_loop_1();return words}(value,styles)}function isVideoElement(node){return"VIDEO"===node.tagName}function isStyleElement(node){return"STYLE"===node.tagName}function isCustomElement(node){return 0<node.tagName.indexOf("-")}function createAdditiveCounter(value,min,max,symbols,fallback,suffix){return value<min||max<value?createCounterText(value,fallback,0<suffix.length):symbols.integers.reduce(function(string,integer,index){for(;integer<=value;)value-=integer,string+=symbols.values[index];return string},"")+suffix}function createCounterStyleFromRange(value,codePointRangeStart,codePointRangeEnd,isNumeric,suffix){var codePointRangeLength=codePointRangeEnd-codePointRangeStart+1;return(value<0?"-":"")+(createCounterStyleWithSymbolResolver(Math.abs(value),codePointRangeLength,isNumeric,function(codePoint){return fromCodePoint$1(Math.floor(codePoint%codePointRangeLength)+codePointRangeStart)})+suffix)}function createCounterStyleFromSymbols(value,symbols,suffix){void 0===suffix&&(suffix=". ");var codePointRangeLength=symbols.length;return createCounterStyleWithSymbolResolver(Math.abs(value),codePointRangeLength,!1,function(codePoint){return symbols[Math.floor(codePoint%codePointRangeLength)]})+suffix}function createCJKCounter(value,numbers,multipliers,negativeSign,suffix,flags){if(value<-9999||9999<value)return createCounterText(value,4,0<suffix.length);var tmp=Math.abs(value),string=suffix;if(0===tmp)return numbers[0]+string;for(var digit=0;0<tmp&&digit<=4;digit++){var coefficient=tmp%10;0==coefficient&&contains(flags,CJK_ZEROS)&&""!==string?string=numbers[coefficient]+string:1<coefficient||1==coefficient&&0===digit||1==coefficient&&1===digit&&contains(flags,CJK_TEN_COEFFICIENTS)||1==coefficient&&1===digit&&contains(flags,CJK_TEN_HIGH_COEFFICIENTS)&&100<value||1==coefficient&&1<digit&&contains(flags,CJK_HUNDRED_COEFFICIENTS)?string=numbers[coefficient]+(0<digit?multipliers[digit-1]:"")+string:1==coefficient&&0<digit&&(string=multipliers[digit-1]+string),tmp=Math.floor(tmp/10)}return(value<0?negativeSign:"")+string}function imageReady(img){return new Promise(function(resolve){!img.complete&&img.src?(img.onload=resolve,img.onerror=resolve):resolve()})}function lerp(a,b,t){return new Vector(a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t)}function calculateBorderBoxPath(curves){return[curves.topLeftBorderBox,curves.topRightBorderBox,curves.bottomRightBorderBox,curves.bottomLeftBorderBox]}function calculatePaddingBoxPath(curves){return[curves.topLeftPaddingBox,curves.topRightPaddingBox,curves.bottomRightPaddingBox,curves.bottomLeftPaddingBox]}function equalPath(a,b){return a.length===b.length&&a.some(function(v,i){return v===b[i]})}function parsePathForBorder(curves,borderSide){switch(borderSide){case 0:return createPathFromCurves(curves.topLeftBorderBox,curves.topLeftPaddingBox,curves.topRightBorderBox,curves.topRightPaddingBox);case 1:return createPathFromCurves(curves.topRightBorderBox,curves.topRightPaddingBox,curves.bottomRightBorderBox,curves.bottomRightPaddingBox);case 2:return createPathFromCurves(curves.bottomRightBorderBox,curves.bottomRightPaddingBox,curves.bottomLeftBorderBox,curves.bottomLeftPaddingBox);default:return createPathFromCurves(curves.bottomLeftBorderBox,curves.bottomLeftPaddingBox,curves.topLeftBorderBox,curves.topLeftPaddingBox)}}function createStrokePathFromCurves(outer1,outer2){var path=[];return isBezierCurve(outer1)?path.push(outer1.subdivide(.5,!1)):path.push(outer1),isBezierCurve(outer2)?path.push(outer2.subdivide(.5,!0)):path.push(outer2),path}function createPathFromCurves(outer1,inner1,outer2,inner2){var path=[];return isBezierCurve(outer1)?path.push(outer1.subdivide(.5,!1)):path.push(outer1),isBezierCurve(outer2)?path.push(outer2.subdivide(.5,!0)):path.push(outer2),isBezierCurve(inner2)?path.push(inner2.subdivide(.5,!0).reverse()):path.push(inner2),isBezierCurve(inner1)?path.push(inner1.subdivide(.5,!1).reverse()):path.push(inner1),path}function paddingBox(element){var bounds=element.bounds,element=element.styles;return bounds.add(element.borderLeftWidth,element.borderTopWidth,-(element.borderRightWidth+element.borderLeftWidth),-(element.borderTopWidth+element.borderBottomWidth))}function contentBox(element){var styles=element.styles,element=element.bounds,paddingLeft=getAbsoluteValue(styles.paddingLeft,element.width),paddingRight=getAbsoluteValue(styles.paddingRight,element.width),paddingTop=getAbsoluteValue(styles.paddingTop,element.width),paddingBottom=getAbsoluteValue(styles.paddingBottom,element.width);return element.add(paddingLeft+styles.borderLeftWidth,paddingTop+styles.borderTopWidth,-(styles.borderRightWidth+styles.borderLeftWidth+paddingLeft+paddingRight),-(styles.borderTopWidth+styles.borderBottomWidth+paddingTop+paddingBottom))}function calculateBackgroundRendering(container,index,intrinsicSize){var backgroundPositioningArea=calculateBackgroundPositioningArea(getBackgroundValueForIndex(container.styles.backgroundOrigin,index),container),backgroundPaintingArea=calculateBackgroundPaintingArea(getBackgroundValueForIndex(container.styles.backgroundClip,index),container),sizeWidth=(intrinsicSize=calculateBackgroundSize(getBackgroundValueForIndex(container.styles.backgroundSize,index),intrinsicSize,backgroundPositioningArea))[0],sizeHeight=intrinsicSize[1],position=getAbsoluteValueForTuple(getBackgroundValueForIndex(container.styles.backgroundPosition,index),backgroundPositioningArea.width-sizeWidth,backgroundPositioningArea.height-sizeHeight);return[calculateBackgroundRepeatPath(getBackgroundValueForIndex(container.styles.backgroundRepeat,index),position,intrinsicSize,backgroundPositioningArea,backgroundPaintingArea),Math.round(backgroundPositioningArea.left+position[0]),Math.round(backgroundPositioningArea.top+position[1]),sizeWidth,sizeHeight]}function isAuto(token){return isIdentToken(token)&&token.value===BACKGROUND_SIZE.AUTO}function Renderer(context,options){this.context=context,this.options=options}var PseudoElementType,CORNER,UnicodeTrie=function(base64){var start,end,base64=function(base64){for(var encoded1,encoded2,encoded3,encoded4,bufferLength=.75*base64.length,len=base64.length,p=0,bufferLength=("="===base64[base64.length-1]&&(bufferLength--,"="===base64[base64.length-2])&&bufferLength--,new("undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?ArrayBuffer:Array)(bufferLength)),bytes=Array.isArray(bufferLength)?bufferLength:new Uint8Array(bufferLength),i=0;i<len;i+=4)encoded1=lookup$1[base64.charCodeAt(i)],encoded2=lookup$1[base64.charCodeAt(i+1)],encoded3=lookup$1[base64.charCodeAt(i+2)],encoded4=lookup$1[base64.charCodeAt(i+3)],bytes[p++]=encoded1<<2|encoded2>>4,bytes[p++]=(15&encoded2)<<4|encoded3>>2,bytes[p++]=(3&encoded3)<<6|63&encoded4;return bufferLength}(base64),view32=Array.isArray(base64)?function(buffer){for(var length=buffer.length,bytes=[],i=0;i<length;i+=4)bytes.push(buffer[i+3]<<24|buffer[i+2]<<16|buffer[i+1]<<8|buffer[i]);return bytes}(base64):new Uint32Array(base64),base64=Array.isArray(base64)?function(buffer){for(var length=buffer.length,bytes=[],i=0;i<length;i+=2)bytes.push(buffer[i+1]<<8|buffer[i]);return bytes}(base64):new Uint16Array(base64),index=slice16(base64,12,view32[4]/2),base64=2===view32[5]?slice16(base64,(24+view32[4])/2):(base64=view32,start=Math.ceil((24+view32[4])/4),base64.slice?base64.slice(start,end):new Uint32Array(Array.prototype.slice.call(base64,start,end)));return new Trie(view32[0],view32[1],view32[2],view32[3],index,base64)}("AAAAAAAAAAAAEA4AGBkAAFAaAAACAAAAAAAIABAAGAAwADgACAAQAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAgAEAAIABAAQABIAEQATAAIABAACAAQAAgAEAAIABAAVABcAAgAEAAIABAACAAQAGAAaABwAHgAgACIAI4AlgAIABAAmwCjAKgAsAC2AL4AvQDFAMoA0gBPAVYBWgEIAAgACACMANoAYgFkAWwBdAF8AX0BhQGNAZUBlgGeAaMBlQGWAasBswF8AbsBwwF0AcsBYwHTAQgA2wG/AOMBdAF8AekB8QF0AfkB+wHiAHQBfAEIAAMC5gQIAAsCEgIIAAgAFgIeAggAIgIpAggAMQI5AkACygEIAAgASAJQAlgCYAIIAAgACAAKBQoFCgUTBRMFGQUrBSsFCAAIAAgACAAIAAgACAAIAAgACABdAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABoAmgCrwGvAQgAbgJ2AggAHgEIAAgACADnAXsCCAAIAAgAgwIIAAgACAAIAAgACACKAggAkQKZAggAPADJAAgAoQKkAqwCsgK6AsICCADJAggA0AIIAAgACAAIANYC3gIIAAgACAAIAAgACABAAOYCCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAkASoB+QIEAAgACAA8AEMCCABCBQgACABJBVAFCAAIAAgACAAIAAgACAAIAAgACABTBVoFCAAIAFoFCABfBWUFCAAIAAgACAAIAAgAbQUIAAgACAAIAAgACABzBXsFfQWFBYoFigWKBZEFigWKBYoFmAWfBaYFrgWxBbkFCAAIAAgACAAIAAgACAAIAAgACAAIAMEFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAMgFCADQBQgACAAIAAgACAAIAAgACAAIAAgACAAIAO4CCAAIAAgAiQAIAAgACABAAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAD0AggACAD8AggACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIANYFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAMDvwAIAAgAJAIIAAgACAAIAAgACAAIAAgACwMTAwgACAB9BOsEGwMjAwgAKwMyAwsFYgE3A/MEPwMIAEUDTQNRAwgAWQOsAGEDCAAIAAgACAAIAAgACABpAzQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFIQUoBSwFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABtAwgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABMAEwACAAIAAgACAAIABgACAAIAAgACAC/AAgACAAyAQgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACAAIAAwAAgACAAIAAgACAAIAAgACAAIAAAARABIAAgACAAIABQASAAIAAgAIABwAEAAjgCIABsAqAC2AL0AigDQAtwC+IJIQqVAZUBWQqVAZUBlQGVAZUBlQGrC5UBlQGVAZUBlQGVAZUBlQGVAXsKlQGVAbAK6wsrDGUMpQzlDJUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAfAKAAuZA64AtwCJALoC6ADwAAgAuACgA/oEpgO6AqsD+AAIAAgAswMIAAgACAAIAIkAuwP5AfsBwwPLAwgACAAIAAgACADRA9kDCAAIAOED6QMIAAgACAAIAAgACADuA/YDCAAIAP4DyQAIAAgABgQIAAgAXQAOBAgACAAIAAgACAAIABMECAAIAAgACAAIAAgACAD8AAQBCAAIAAgAGgQiBCoECAExBAgAEAEIAAgACAAIAAgACAAIAAgACAAIAAgACAA4BAgACABABEYECAAIAAgATAQYAQgAVAQIAAgACAAIAAgACAAIAAgACAAIAFoECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAOQEIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAB+BAcACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAEABhgSMBAgACAAIAAgAlAQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAwAEAAQABAADAAMAAwADAAQABAAEAAQABAAEAAQABHATAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAdQMIAAgACAAIAAgACAAIAMkACAAIAAgAfQMIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACFA4kDCAAIAAgACAAIAOcBCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAIcDCAAIAAgACAAIAAgACAAIAAgACAAIAJEDCAAIAAgACADFAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABgBAgAZgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAbAQCBXIECAAIAHkECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABAAJwEQACjBKoEsgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAC6BMIECAAIAAgACAAIAAgACABmBAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAxwQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAGYECAAIAAgAzgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBd0FXwUIAOIF6gXxBYoF3gT5BQAGCAaKBYoFigWKBYoFigWKBYoFigWKBYoFigXWBIoFigWKBYoFigWKBYoFigWKBYsFEAaKBYoFigWKBYoFigWKBRQGCACKBYoFigWKBQgACAAIANEECAAIABgGigUgBggAJgYIAC4GMwaKBYoF0wQ3Bj4GigWKBYoFigWKBYoFigWKBYoFigWKBYoFigUIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWLBf///////wQABAAEAAQABAAEAAQABAAEAAQAAwAEAAQAAgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAQADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUAAAAFAAUAAAAFAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAQAAAAUABQAFAAUABQAFAAAAAAAFAAUAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAFAAUAAQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAAABwAHAAcAAAAHAAcABwAFAAEAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAcABwAFAAUAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQABAAAAAAAAAAAAAAAFAAUABQAFAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAHAAcAAAAHAAcAAAAAAAUABQAHAAUAAQAHAAEABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwABAAUABQAFAAUAAAAAAAAAAAAAAAEAAQABAAEAAQABAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABQANAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAABQAHAAUABQAFAAAAAAAAAAcABQAFAAUABQAFAAQABAAEAAQABAAEAAQABAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUAAAAFAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAUAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAcABwAFAAcABwAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUABwAHAAUABQAFAAUAAAAAAAcABwAAAAAABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAAAAAAAAAAABQAFAAAAAAAFAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAFAAUABQAFAAUAAAAFAAUABwAAAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABwAFAAUABQAFAAAAAAAHAAcAAAAAAAcABwAFAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAAAAAAAAAHAAcABwAAAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAUABQAFAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAHAAcABQAHAAcAAAAFAAcABwAAAAcABwAFAAUAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAFAAcABwAFAAUABQAAAAUAAAAHAAcABwAHAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAHAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUAAAAFAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAUAAAAFAAUAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABwAFAAUABQAFAAUABQAAAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABQAFAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAFAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAHAAUABQAFAAUABQAFAAUABwAHAAcABwAHAAcABwAHAAUABwAHAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABwAHAAcABwAFAAUABwAHAAcAAAAAAAAAAAAHAAcABQAHAAcABwAHAAcABwAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAUABQAFAAUABQAFAAUAAAAFAAAABQAAAAAABQAFAAUABQAFAAUABQAFAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAUABQAFAAUABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABwAFAAcABwAHAAcABwAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAUABQAFAAUABwAHAAUABQAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABQAFAAcABwAHAAUABwAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAcABQAFAAUABQAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAAAAAABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAAAAAAAAAFAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAUABQAHAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAFAAUABQAFAAcABwAFAAUABwAHAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAcABwAFAAUABwAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABQAAAAAABQAFAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAcABwAAAAAAAAAAAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAcABwAFAAcABwAAAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAFAAUABQAAAAUABQAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABwAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAHAAcABQAHAAUABQAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAAABwAHAAAAAAAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAFAAUABwAFAAcABwAFAAcABQAFAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAAAAAABwAHAAcABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAFAAcABwAFAAUABQAFAAUABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAUABQAFAAcABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABQAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAAAAAAFAAUABwAHAAcABwAFAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAHAAUABQAFAAUABQAFAAUABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAABQAAAAUABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAHAAcAAAAFAAUAAAAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABQAFAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAABQAFAAUABQAFAAUABQAAAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAFAAUABQAFAAUADgAOAA4ADgAOAA4ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAMAAwADAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAAAAAAAAAAAAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAAAAAAAAAAAAsADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwACwAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAADgAOAA4AAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAAAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4AAAAOAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAAAAAAAAAAAA4AAAAOAAAAAAAAAAAADgAOAA4AAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAA="),GraphemeBreaker=function(str){var codePoints=function(str){for(var codePoints=[],i=0,length=str.length;i<length;){var extra,value=str.charCodeAt(i++);55296<=value&&value<=56319&&i<length?56320==(64512&(extra=str.charCodeAt(i++)))?codePoints.push(((1023&value)<<10)+(1023&extra)+65536):(codePoints.push(value),i--):codePoints.push(value)}return codePoints}(str),length=codePoints.length,index=0,lastEnd=0,classTypes=codePoints.map(codePointToClass);return{next:function(){if(length<=index)return{done:!0,value:null};for(var value,graphemeBreak="×";index<length&&"×"===(graphemeBreak=function(classTypes,index){var prevIndex=index-2,prev=classTypes[prevIndex],current=classTypes[index-1],index=classTypes[index];if(2===current&&3===index)return"×";if(2!==current&&3!==current&&4!==current&&2!==index&&3!==index&&4!==index){if(8===current&&-1!==[8,9,11,12].indexOf(index))return"×";if(!(11!==current&&9!==current||9!==index&&10!==index))return"×";if((12===current||10===current)&&10===index)return"×";if(13===index||5===index)return"×";if(7===index)return"×";if(1===current)return"×";if(13===current&&14===index){for(;5===prev;)prev=classTypes[--prevIndex];if(14===prev)return"×"}if(15===current&&15===index){for(var countRI=0;15===prev;)countRI++,prev=classTypes[--prevIndex];if(countRI%2==0)return"×"}}return"÷"}(classTypes,++index)););return"×"!==graphemeBreak||index===length?(value=function(){for(var codePoints=[],_i=0;_i<arguments.length;_i++)codePoints[_i]=arguments[_i];if(String.fromCodePoint)return String.fromCodePoint.apply(String,codePoints);var length=codePoints.length;if(!length)return"";for(var codeUnits=[],index=-1,result="";++index<length;){var codePoint=codePoints[index];codePoint<=65535?codeUnits.push(codePoint):codeUnits.push(55296+((codePoint-=65536)>>10),codePoint%1024+56320),(index+1===length||16384<codeUnits.length)&&(result+=String.fromCharCode.apply(String,codeUnits),codeUnits.length=0)}return result}.apply(null,codePoints.slice(lastEnd,index)),lastEnd=index,{value:value,done:!1}):{done:!0,value:null}}}},FEATURES={get SUPPORT_RANGE_BOUNDS(){var value=function(document){if(document.createRange){var range=document.createRange();if(range.getBoundingClientRect){var testElement=document.createElement("boundtest"),range=(testElement.style.height="123px",testElement.style.display="block",document.body.appendChild(testElement),range.selectNode(testElement),range.getBoundingClientRect()),range=Math.round(range.height);if(document.body.removeChild(testElement),123===range)return!0}}return!1}(document);return Object.defineProperty(FEATURES,"SUPPORT_RANGE_BOUNDS",{value:value}),value},get SUPPORT_WORD_BREAKING(){var value=FEATURES.SUPPORT_RANGE_BOUNDS&&function(document){var testElement=document.createElement("boundtest"),range=(testElement.style.width="50px",testElement.style.display="block",testElement.style.fontSize="12px",testElement.style.letterSpacing="0px",testElement.style.wordSpacing="0px",document.body.appendChild(testElement),document.createRange()),node=(testElement.innerHTML="function"==typeof"".repeat?"&#128104;".repeat(10):"",testElement.firstChild),textList=toCodePoints$1(node.data).map(function(i){return fromCodePoint$1(i)}),offset=0,prev={},textList=textList.every(function(text,i){range.setStart(node,offset),range.setEnd(node,offset+text.length);var rect=range.getBoundingClientRect(),text=(offset+=text.length,rect.x>prev.x||rect.y>prev.y);return prev=rect,0===i||text});return document.body.removeChild(testElement),textList}(document);return Object.defineProperty(FEATURES,"SUPPORT_WORD_BREAKING",{value:value}),value},get SUPPORT_SVG_DRAWING(){var value=function(document){var img=new Image,document=document.createElement("canvas"),ctx=document.getContext("2d");if(!ctx)return!1;img.src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";try{ctx.drawImage(img,0,0),document.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(FEATURES,"SUPPORT_SVG_DRAWING",{value:value}),value},get SUPPORT_FOREIGNOBJECT_DRAWING(){var value="function"==typeof Array.from&&"function"==typeof window.fetch?function(document){var canvas=document.createElement("canvas"),ctx=(canvas.width=100,canvas.height=100,canvas.getContext("2d"));if(!ctx)return Promise.reject(!1);ctx.fillStyle="rgb(0, 255, 0)",ctx.fillRect(0,0,100,100);var img=new Image,greenImageSrc=canvas.toDataURL(),canvas=(img.src=greenImageSrc,createForeignObjectSVG(100,100,0,0,img));return ctx.fillStyle="red",ctx.fillRect(0,0,100,100),loadSerializedSVG$1(canvas).then(function(img){ctx.drawImage(img,0,0);var img=ctx.getImageData(0,0,100,100).data,node=(ctx.fillStyle="red",ctx.fillRect(0,0,100,100),document.createElement("div"));return node.style.backgroundImage="url("+greenImageSrc+")",node.style.height="100px",isGreenPixel(img)?loadSerializedSVG$1(createForeignObjectSVG(100,100,0,0,node)):Promise.reject(!1)}).then(function(img){return ctx.drawImage(img,0,0),isGreenPixel(ctx.getImageData(0,0,100,100).data)}).catch(function(){return!1})}(document):Promise.resolve(!1);return Object.defineProperty(FEATURES,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:value}),value},get SUPPORT_CORS_IMAGES(){var value=void 0!==(new Image).crossOrigin;return Object.defineProperty(FEATURES,"SUPPORT_CORS_IMAGES",{value:value}),value},get SUPPORT_RESPONSE_TYPE(){var value="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(FEATURES,"SUPPORT_RESPONSE_TYPE",{value:value}),value},get SUPPORT_CORS_XHR(){var value="withCredentials"in new XMLHttpRequest;return Object.defineProperty(FEATURES,"SUPPORT_CORS_XHR",{value:value}),value},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var value=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(FEATURES,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:value}),value}},TextBounds=function(text,bounds){this.text=text,this.bounds=bounds},getWrapperBounds=function(context,node){var ownerDocument=node.ownerDocument;if(ownerDocument){var ownerDocument=ownerDocument.createElement("html2canvaswrapper"),parentNode=(ownerDocument.appendChild(node.cloneNode(!0)),node.parentNode);if(parentNode)return parentNode.replaceChild(ownerDocument,node),node=parseBounds(context,ownerDocument),ownerDocument.firstChild&&parentNode.replaceChild(ownerDocument.firstChild,ownerDocument),node}return Bounds.EMPTY},createRange=function(node,offset,length){var ownerDocument=node.ownerDocument;if(ownerDocument)return(ownerDocument=ownerDocument.createRange()).setStart(node,offset),ownerDocument.setEnd(node,offset+length),ownerDocument;throw new Error("Node has no owner document")},segmentGraphemes=function(value){var segmenter;if(FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION)return segmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Array.from(segmenter.segment(value)).map(function(segment){return segment.segment});for(var bk,breaker=GraphemeBreaker(value),graphemes=[];!(bk=breaker.next()).done;)bk.value&&graphemes.push(bk.value.slice());return graphemes},breakText=function(value,styles){return 0!==styles.letterSpacing?segmentGraphemes(value):segmentWords(value,styles)},wordSeparators=[32,160,4961,65792,65793,4153,4241],TextContainer=function(context,node,styles){this.text=transform(node.data,styles.textTransform),this.textBounds=function(context,value,styles,node){var value=breakText(value,styles),textBounds=[],offset=0;return value.forEach(function(text){var clientRects,subOffset_1,subSegments;styles.textDecorationLine.length||0<text.trim().length?FEATURES.SUPPORT_RANGE_BOUNDS?1<(clientRects=createRange(node,offset,text.length).getClientRects()).length?(subSegments=segmentGraphemes(text),subOffset_1=0,subSegments.forEach(function(subSegment){textBounds.push(new TextBounds(subSegment,Bounds.fromDOMRectList(context,createRange(node,subOffset_1+offset,subSegment.length).getClientRects()))),subOffset_1+=subSegment.length})):textBounds.push(new TextBounds(text,Bounds.fromDOMRectList(context,clientRects))):(subSegments=node.splitText(text.length),textBounds.push(new TextBounds(text,getWrapperBounds(context,node))),node=subSegments):FEATURES.SUPPORT_RANGE_BOUNDS||(node=node.splitText(text.length)),offset+=text.length}),textBounds}(context,this.text,styles,node)},transform=function(text,transform){switch(transform){case 1:return text.toLowerCase();case 3:return text.replace(CAPITALIZE,capitalize);case 2:return text.toUpperCase();default:return text}},CAPITALIZE=/(^|\s|:|-|\(|\))([a-z])/g,capitalize=function(m,p1,p2){return 0<m.length?p1+p2.toUpperCase():m},ImageElementContainer=function(_super){function ImageElementContainer(context,img){context=_super.call(this,context,img)||this;return context.src=img.currentSrc||img.src,context.intrinsicWidth=img.naturalWidth,context.intrinsicHeight=img.naturalHeight,context.context.cache.addImage(context.src),context}return __extends(ImageElementContainer,_super),ImageElementContainer}(ElementContainer),CanvasElementContainer=function(_super){function CanvasElementContainer(context,canvas){context=_super.call(this,context,canvas)||this;return context.canvas=canvas,context.intrinsicWidth=canvas.width,context.intrinsicHeight=canvas.height,context}return __extends(CanvasElementContainer,_super),CanvasElementContainer}(ElementContainer),SVGElementContainer=function(_super){function SVGElementContainer(context,img){var _this=_super.call(this,context,img)||this,s=new XMLSerializer,context=parseBounds(context,img);return img.setAttribute("width",context.width+"px"),img.setAttribute("height",context.height+"px"),_this.svg="data:image/svg+xml,"+encodeURIComponent(s.serializeToString(img)),_this.intrinsicWidth=img.width.baseVal.value,_this.intrinsicHeight=img.height.baseVal.value,_this.context.cache.addImage(_this.svg),_this}return __extends(SVGElementContainer,_super),SVGElementContainer}(ElementContainer),LIElementContainer=function(_super){function LIElementContainer(context,element){context=_super.call(this,context,element)||this;return context.value=element.value,context}return __extends(LIElementContainer,_super),LIElementContainer}(ElementContainer),OLElementContainer=function(_super){function OLElementContainer(context,element){context=_super.call(this,context,element)||this;return context.start=element.start,context.reversed="boolean"==typeof element.reversed&&!0===element.reversed,context}return __extends(OLElementContainer,_super),OLElementContainer}(ElementContainer),CHECKBOX_BORDER_RADIUS=[{type:15,flags:0,unit:"px",number:3}],RADIO_BORDER_RADIUS=[{type:16,flags:0,number:50}],PASSWORD="password",InputElementContainer=function(_super){function InputElementContainer(context,input){var _this=_super.call(this,context,input)||this;switch(_this.type=input.type.toLowerCase(),_this.checked=input.checked,_this.value=0===(input=(context=input).type===PASSWORD?new Array(context.value.length+1).join("•"):context.value).length?context.placeholder||"":input,"checkbox"!==_this.type&&"radio"!==_this.type||(_this.styles.backgroundColor=3739148031,_this.styles.borderTopColor=_this.styles.borderRightColor=_this.styles.borderBottomColor=_this.styles.borderLeftColor=2779096575,_this.styles.borderTopWidth=_this.styles.borderRightWidth=_this.styles.borderBottomWidth=_this.styles.borderLeftWidth=1,_this.styles.borderTopStyle=_this.styles.borderRightStyle=_this.styles.borderBottomStyle=_this.styles.borderLeftStyle=1,_this.styles.backgroundClip=[0],_this.styles.backgroundOrigin=[0],_this.bounds=(context=_this.bounds).width>context.height?new Bounds(context.left+(context.width-context.height)/2,context.top,context.height,context.height):context.width<context.height?new Bounds(context.left,context.top+(context.height-context.width)/2,context.width,context.width):context),_this.type){case"checkbox":_this.styles.borderTopRightRadius=_this.styles.borderTopLeftRadius=_this.styles.borderBottomRightRadius=_this.styles.borderBottomLeftRadius=CHECKBOX_BORDER_RADIUS;break;case"radio":_this.styles.borderTopRightRadius=_this.styles.borderTopLeftRadius=_this.styles.borderBottomRightRadius=_this.styles.borderBottomLeftRadius=RADIO_BORDER_RADIUS}return _this}return __extends(InputElementContainer,_super),InputElementContainer}(ElementContainer),SelectElementContainer=function(_super){function SelectElementContainer(context,element){context=_super.call(this,context,element)||this,element=element.options[element.selectedIndex||0];return context.value=element&&element.text||"",context}return __extends(SelectElementContainer,_super),SelectElementContainer}(ElementContainer),TextareaElementContainer=function(_super){function TextareaElementContainer(context,element){context=_super.call(this,context,element)||this;return context.value=element.value,context}return __extends(TextareaElementContainer,_super),TextareaElementContainer}(ElementContainer),IFrameElementContainer=function(_super){function IFrameElementContainer(context,iframe){var documentBackgroundColor,bodyBackgroundColor,_this=_super.call(this,context,iframe)||this;_this.src=iframe.src,_this.width=parseInt(iframe.width,10)||0,_this.height=parseInt(iframe.height,10)||0,_this.backgroundColor=_this.styles.backgroundColor;try{iframe.contentWindow&&iframe.contentWindow.document&&iframe.contentWindow.document.documentElement&&(_this.tree=parseTree(context,iframe.contentWindow.document.documentElement),documentBackgroundColor=iframe.contentWindow.document.documentElement?parseColor(context,getComputedStyle(iframe.contentWindow.document.documentElement).backgroundColor):COLORS.TRANSPARENT,bodyBackgroundColor=iframe.contentWindow.document.body?parseColor(context,getComputedStyle(iframe.contentWindow.document.body).backgroundColor):COLORS.TRANSPARENT,_this.backgroundColor=0==(255&documentBackgroundColor)?0==(255&bodyBackgroundColor)?_this.styles.backgroundColor:bodyBackgroundColor:documentBackgroundColor)}catch(e){}return _this}return __extends(IFrameElementContainer,_super),IFrameElementContainer}(ElementContainer),LIST_OWNERS=["OL","UL","MENU"],parseNodeTree=function(context,node,parent,root){for(var childNode=node.firstChild;childNode;childNode=nextNode){var container,nextNode=childNode.nextSibling;isTextNode(childNode)&&0<childNode.data.trim().length?parent.textNodes.push(new TextContainer(context,childNode,parent.styles)):isElementNode(childNode)&&(isSlotElement(childNode)&&childNode.assignedNodes?childNode.assignedNodes().forEach(function(childNode){return parseNodeTree(context,childNode,parent,root)}):(container=createContainer(context,childNode)).styles.isVisible()&&(createsRealStackingContext(childNode,container,root)?container.flags|=4:createsStackingContext(container.styles)&&(container.flags|=2),-1!==LIST_OWNERS.indexOf(childNode.tagName)&&(container.flags|=8),parent.elements.push(container),childNode.slot,childNode.shadowRoot?parseNodeTree(context,childNode.shadowRoot,container,root):isTextareaElement(childNode)||isSVGElement(childNode)||isSelectElement(childNode)||parseNodeTree(context,childNode,container,root)))}},createContainer=function(context,element){return new(isImageElement(element)?ImageElementContainer:isCanvasElement(element)?CanvasElementContainer:isSVGElement(element)?SVGElementContainer:isLIElement(element)?LIElementContainer:isOLElement(element)?OLElementContainer:isInputElement(element)?InputElementContainer:isSelectElement(element)?SelectElementContainer:isTextareaElement(element)?TextareaElementContainer:isIFrameElement(element)?IFrameElementContainer:ElementContainer)(context,element)},parseTree=function(context,element){var container=createContainer(context,element);return container.flags|=4,parseNodeTree(context,element,container,container),container},createsRealStackingContext=function(node,container,root){return container.styles.isPositionedWithZIndex()||container.styles.opacity<1||container.styles.isTransformed()||isBodyElement(node)&&root.styles.isTransparent()},createsStackingContext=function(styles){return styles.isPositioned()||styles.isFloating()},isTextNode=function(node){return node.nodeType===Node.TEXT_NODE},isElementNode=function(node){return node.nodeType===Node.ELEMENT_NODE},isHTMLElementNode=function(node){return isElementNode(node)&&void 0!==node.style&&!isSVGElementNode(node)},isSVGElementNode=function(element){return"object"==typeof element.className},isLIElement=function(node){return"LI"===node.tagName},isOLElement=function(node){return"OL"===node.tagName},isInputElement=function(node){return"INPUT"===node.tagName},isHTMLElement=function(node){return"HTML"===node.tagName},isSVGElement=function(node){return"svg"===node.tagName},isBodyElement=function(node){return"BODY"===node.tagName},isCanvasElement=function(node){return"CANVAS"===node.tagName},isImageElement=function(node){return"IMG"===node.tagName},isIFrameElement=function(node){return"IFRAME"===node.tagName},isTextareaElement=function(node){return"TEXTAREA"===node.tagName},isSelectElement=function(node){return"SELECT"===node.tagName},isSlotElement=function(node){return"SLOT"===node.tagName},CounterState=function(){function CounterState(){this.counters={}}return CounterState.prototype.getCounterValue=function(name){name=this.counters[name];return name&&name.length?name[name.length-1]:1},CounterState.prototype.getCounterValues=function(name){name=this.counters[name];return name||[]},CounterState.prototype.pop=function(counters){var _this=this;counters.forEach(function(counter){return _this.counters[counter].pop()})},CounterState.prototype.parse=function(style){var _this=this,counterIncrement=style.counterIncrement,style=style.counterReset,canReset=!0,counterNames=(null!==counterIncrement&&counterIncrement.forEach(function(entry){var counter=_this.counters[entry.counter];counter&&0!==entry.increment&&(canReset=!1,counter.length||counter.push(1),counter[Math.max(0,counter.length-1)]+=entry.increment)}),[]);return canReset&&style.forEach(function(entry){var counter=_this.counters[entry.counter];counterNames.push(entry.counter),(counter=counter||(_this.counters[entry.counter]=[])).push(entry.reset)}),counterNames},CounterState}(),ROMAN_UPPER={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},ARMENIAN={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},HEBREW={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},GEORGIAN={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},createCounterStyleWithSymbolResolver=function(value,codePointRangeLength,isNumeric,resolver){for(var string="";isNumeric||value--,string=resolver(value)+string,codePointRangeLength<=(value/=codePointRangeLength)*codePointRangeLength;);return string},CJK_ZEROS=1,CJK_TEN_COEFFICIENTS=2,CJK_TEN_HIGH_COEFFICIENTS=4,CJK_HUNDRED_COEFFICIENTS=8,createCounterText=function(value,type,appendSuffix){var defaultSuffix=appendSuffix?". ":"",cjkSuffix=appendSuffix?"、":"",koreanSuffix=appendSuffix?", ":"",spaceSuffix=appendSuffix?" ":"";switch(type){case 0:return"•"+spaceSuffix;case 1:return"◦"+spaceSuffix;case 2:return"◾"+spaceSuffix;case 5:var string=createCounterStyleFromRange(value,48,57,!0,defaultSuffix);return string.length<4?"0"+string:string;case 4:return createCounterStyleFromSymbols(value,"〇一二三四五六七八九",cjkSuffix);case 6:return createAdditiveCounter(value,1,3999,ROMAN_UPPER,3,defaultSuffix).toLowerCase();case 7:return createAdditiveCounter(value,1,3999,ROMAN_UPPER,3,defaultSuffix);case 8:return createCounterStyleFromRange(value,945,969,!1,defaultSuffix);case 9:return createCounterStyleFromRange(value,97,122,!1,defaultSuffix);case 10:return createCounterStyleFromRange(value,65,90,!1,defaultSuffix);case 11:return createCounterStyleFromRange(value,1632,1641,!0,defaultSuffix);case 12:case 49:return createAdditiveCounter(value,1,9999,ARMENIAN,3,defaultSuffix);case 35:return createAdditiveCounter(value,1,9999,ARMENIAN,3,defaultSuffix).toLowerCase();case 13:return createCounterStyleFromRange(value,2534,2543,!0,defaultSuffix);case 14:case 30:return createCounterStyleFromRange(value,6112,6121,!0,defaultSuffix);case 15:return createCounterStyleFromSymbols(value,"子丑寅卯辰巳午未申酉戌亥",cjkSuffix);case 16:return createCounterStyleFromSymbols(value,"甲乙丙丁戊己庚辛壬癸",cjkSuffix);case 17:case 48:return createCJKCounter(value,"零一二三四五六七八九","十百千萬","負",cjkSuffix,CJK_TEN_COEFFICIENTS|CJK_TEN_HIGH_COEFFICIENTS|CJK_HUNDRED_COEFFICIENTS);case 47:return createCJKCounter(value,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",cjkSuffix,CJK_ZEROS|CJK_TEN_COEFFICIENTS|CJK_TEN_HIGH_COEFFICIENTS|CJK_HUNDRED_COEFFICIENTS);case 42:return createCJKCounter(value,"零一二三四五六七八九","十百千萬","负",cjkSuffix,CJK_TEN_COEFFICIENTS|CJK_TEN_HIGH_COEFFICIENTS|CJK_HUNDRED_COEFFICIENTS);case 41:return createCJKCounter(value,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",cjkSuffix,CJK_ZEROS|CJK_TEN_COEFFICIENTS|CJK_TEN_HIGH_COEFFICIENTS|CJK_HUNDRED_COEFFICIENTS);case 26:return createCJKCounter(value,"〇一二三四五六七八九","十百千万","マイナス",cjkSuffix,0);case 25:return createCJKCounter(value,"零壱弐参四伍六七八九","拾百千万","マイナス",cjkSuffix,CJK_ZEROS|CJK_TEN_COEFFICIENTS|CJK_TEN_HIGH_COEFFICIENTS);case 31:return createCJKCounter(value,"영일이삼사오육칠팔구","십백천만","마이너스",koreanSuffix,CJK_ZEROS|CJK_TEN_COEFFICIENTS|CJK_TEN_HIGH_COEFFICIENTS);case 33:return createCJKCounter(value,"零一二三四五六七八九","十百千萬","마이너스",koreanSuffix,0);case 32:return createCJKCounter(value,"零壹貳參四五六七八九","拾百千","마이너스",koreanSuffix,CJK_ZEROS|CJK_TEN_COEFFICIENTS|CJK_TEN_HIGH_COEFFICIENTS);case 18:return createCounterStyleFromRange(value,2406,2415,!0,defaultSuffix);case 20:return createAdditiveCounter(value,1,19999,GEORGIAN,3,defaultSuffix);case 21:return createCounterStyleFromRange(value,2790,2799,!0,defaultSuffix);case 22:return createCounterStyleFromRange(value,2662,2671,!0,defaultSuffix);case 22:return createAdditiveCounter(value,1,10999,HEBREW,3,defaultSuffix);case 23:return createCounterStyleFromSymbols(value,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return createCounterStyleFromSymbols(value,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return createCounterStyleFromRange(value,3302,3311,!0,defaultSuffix);case 28:return createCounterStyleFromSymbols(value,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",cjkSuffix);case 29:return createCounterStyleFromSymbols(value,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",cjkSuffix);case 34:return createCounterStyleFromRange(value,3792,3801,!0,defaultSuffix);case 37:return createCounterStyleFromRange(value,6160,6169,!0,defaultSuffix);case 38:return createCounterStyleFromRange(value,4160,4169,!0,defaultSuffix);case 39:return createCounterStyleFromRange(value,2918,2927,!0,defaultSuffix);case 40:return createCounterStyleFromRange(value,1776,1785,!0,defaultSuffix);case 43:return createCounterStyleFromRange(value,3046,3055,!0,defaultSuffix);case 44:return createCounterStyleFromRange(value,3174,3183,!0,defaultSuffix);case 45:return createCounterStyleFromRange(value,3664,3673,!0,defaultSuffix);case 46:return createCounterStyleFromRange(value,3872,3881,!0,defaultSuffix);default:return createCounterStyleFromRange(value,48,57,!0,defaultSuffix)}},DocumentCloner=function(){function DocumentCloner(context,element,options){if(this.context=context,this.options=options,this.scrolledElements=[],this.referenceElement=element,this.counters=new CounterState,this.quoteDepth=0,!element.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(element.ownerDocument.documentElement,!1)}return DocumentCloner.prototype.toIFrame=function(ownerDocument,windowSize){var scrollX,cloneWindow,documentClone,iframeLoad,_this=this,iframe=createIFrameContainer(ownerDocument,windowSize);return iframe.contentWindow?(scrollX=ownerDocument.defaultView.pageXOffset,ownerDocument=ownerDocument.defaultView.pageYOffset,cloneWindow=iframe.contentWindow,documentClone=cloneWindow.document,iframeLoad=iframeLoader(iframe).then(function(){return __awaiter(_this,void 0,void 0,function(){var onclone,referenceElement;return __generator(this,function(_a){switch(_a.label){case 0:return(this.scrolledElements.forEach(restoreNodeScroll),cloneWindow&&(cloneWindow.scrollTo(windowSize.left,windowSize.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||cloneWindow.scrollY===windowSize.top&&cloneWindow.scrollX===windowSize.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(cloneWindow.scrollX-windowSize.left,cloneWindow.scrollY-windowSize.top,0,0))),onclone=this.options.onclone,void 0===(referenceElement=this.clonedReferenceElement))?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:documentClone.fonts&&documentClone.fonts.ready?[4,documentClone.fonts.ready]:[3,2];case 1:_a.sent(),_a.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,imagesReady(documentClone)]:[3,4];case 3:_a.sent(),_a.label=4;case 4:return"function"==typeof onclone?[2,Promise.resolve().then(function(){return onclone(documentClone,referenceElement)}).then(function(){return iframe})]:[2,iframe]}})})}),documentClone.open(),documentClone.write(serializeDoctype(document.doctype)+"<html></html>"),restoreOwnerScroll(this.referenceElement.ownerDocument,scrollX,ownerDocument),documentClone.replaceChild(documentClone.adoptNode(this.documentElement),documentClone.documentElement),documentClone.close(),iframeLoad):Promise.reject("Unable to find iframe window")},DocumentCloner.prototype.createElementClone=function(node){var clone;return isDebugging(node,2),isCanvasElement(node)?this.createCanvasClone(node):isVideoElement(node)?this.createVideoClone(node):isStyleElement(node)?this.createStyleClone(node):(clone=node.cloneNode(!1),isImageElement(clone)&&(isImageElement(node)&&node.currentSrc&&node.currentSrc!==node.src&&(clone.src=node.currentSrc,clone.srcset=""),"lazy"===clone.loading)&&(clone.loading="eager"),isCustomElement(clone)?this.createCustomElementClone(clone):clone)},DocumentCloner.prototype.createCustomElementClone=function(node){var clone=document.createElement("html2canvascustomelement");return copyCSSStyles(node.style,clone),clone},DocumentCloner.prototype.createStyleClone=function(node){try{var css,style,sheet=node.sheet;if(sheet&&sheet.cssRules)return css=[].slice.call(sheet.cssRules,0).reduce(function(css,rule){return rule&&"string"==typeof rule.cssText?css+rule.cssText:css},""),(style=node.cloneNode(!1)).textContent=css,style}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return node.cloneNode(!1)},DocumentCloner.prototype.createCanvasClone=function(canvas){var _a;if(this.options.inlineImages&&canvas.ownerDocument){var img=canvas.ownerDocument.createElement("img");try{return img.src=canvas.toDataURL(),img}catch(e){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",canvas)}}img=canvas.cloneNode(!1);try{img.width=canvas.width,img.height=canvas.height;var gl,attribs,ctx=canvas.getContext("2d"),clonedCtx=img.getContext("2d");clonedCtx&&(!this.options.allowTaint&&ctx?clonedCtx.putImageData(ctx.getImageData(0,0,canvas.width,canvas.height),0,0):((gl=null!=(_a=canvas.getContext("webgl2"))?_a:canvas.getContext("webgl"))&&!1===(null==(attribs=gl.getContextAttributes())?void 0:attribs.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",canvas),clonedCtx.drawImage(canvas,0,0)))}catch(e){this.context.logger.info("Unable to clone canvas as it is tainted",canvas)}return img},DocumentCloner.prototype.createVideoClone=function(video){var canvas=video.ownerDocument.createElement("canvas"),ctx=(canvas.width=video.offsetWidth,canvas.height=video.offsetHeight,canvas.getContext("2d"));try{return ctx&&(ctx.drawImage(video,0,0,canvas.width,canvas.height),this.options.allowTaint||ctx.getImageData(0,0,canvas.width,canvas.height)),canvas}catch(e){this.context.logger.info("Unable to clone video as it is tainted",video)}ctx=video.ownerDocument.createElement("canvas");return ctx.width=video.offsetWidth,ctx.height=video.offsetHeight,ctx},DocumentCloner.prototype.appendChildNode=function(clone,child,copyStyles){isElementNode(child)&&("SCRIPT"===child.tagName||child.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(child))||this.options.copyStyles&&isElementNode(child)&&isStyleElement(child)||clone.appendChild(this.cloneNode(child,copyStyles))},DocumentCloner.prototype.cloneChildNodes=function(node,clone,copyStyles){for(var assignedNodes,_this=this,child=(node.shadowRoot||node).firstChild;child;child=child.nextSibling)isElementNode(child)&&isSlotElement(child)&&"function"==typeof child.assignedNodes?(assignedNodes=child.assignedNodes()).length&&assignedNodes.forEach(function(assignedNode){return _this.appendChildNode(clone,assignedNode,copyStyles)}):this.appendChildNode(clone,child,copyStyles)},DocumentCloner.prototype.cloneNode=function(node,copyStyles){var clone,style,window,counters,styleBefore;return isTextNode(node)?document.createTextNode(node.data):node.ownerDocument&&(window=node.ownerDocument.defaultView)&&isElementNode(node)&&(isHTMLElementNode(node)||isSVGElementNode(node))?((clone=this.createElementClone(node)).style.transitionProperty="none",style=window.getComputedStyle(node),styleBefore=window.getComputedStyle(node,":before"),window=window.getComputedStyle(node,":after"),this.referenceElement===node&&isHTMLElementNode(clone)&&(this.clonedReferenceElement=clone),isBodyElement(clone)&&createPseudoHideStyles(clone),counters=this.counters.parse(new CSSParsedCounterDeclaration(this.context,style)),styleBefore=this.resolvePseudoContent(node,clone,styleBefore,PseudoElementType.BEFORE),isCustomElement(node)&&(copyStyles=!0),isVideoElement(node)||this.cloneChildNodes(node,clone,copyStyles),styleBefore&&clone.insertBefore(styleBefore,clone.firstChild),(styleBefore=this.resolvePseudoContent(node,clone,window,PseudoElementType.AFTER))&&clone.appendChild(styleBefore),this.counters.pop(counters),(style&&(this.options.copyStyles||isSVGElementNode(node))&&!isIFrameElement(node)||copyStyles)&&copyCSSStyles(style,clone),0===node.scrollTop&&0===node.scrollLeft||this.scrolledElements.push([clone,node.scrollLeft,node.scrollTop]),(isTextareaElement(node)||isSelectElement(node))&&(isTextareaElement(clone)||isSelectElement(clone))&&(clone.value=node.value),clone):node.cloneNode(!1)},DocumentCloner.prototype.resolvePseudoContent=function(node,clone,style,pseudoElt){var _this=this;if(style){var declaration,anonymousReplacedElement,value=style.content,document=clone.ownerDocument;if(document&&value&&"none"!==value&&"-moz-alt-content"!==value&&"none"!==style.display)return this.counters.parse(new CSSParsedCounterDeclaration(this.context,style)),declaration=new CSSParsedPseudoDeclaration(this.context,style),anonymousReplacedElement=document.createElement("html2canvaspseudoelement"),copyCSSStyles(style,anonymousReplacedElement),declaration.content.forEach(function(token){if(0===token.type)anonymousReplacedElement.appendChild(document.createTextNode(token.value));else if(22===token.type){var img=document.createElement("img");img.src=token.value,img.style.opacity="1",anonymousReplacedElement.appendChild(img)}else if(18===token.type){var counterType,counterType_1,counter,counterStyle;"attr"===token.name?(img=token.values.filter(isIdentToken)).length&&anonymousReplacedElement.appendChild(document.createTextNode(node.getAttribute(img[0].value)||"")):"counter"===token.name?(counter=(img=token.values.filter(nonFunctionArgSeparator))[0],counterStyle=img[1],counter&&isIdentToken(counter)&&(img=_this.counters.getCounterValue(counter.value),counterType=counterStyle&&isIdentToken(counterStyle)?listStyleType.parse(_this.context,counterStyle.value):3,anonymousReplacedElement.appendChild(document.createTextNode(createCounterText(img,counterType,!1))))):"counters"===token.name&&(counter=(img=token.values.filter(nonFunctionArgSeparator))[0],counterType=img[1],counterStyle=img[2],counter)&&isIdentToken(counter)&&(img=_this.counters.getCounterValues(counter.value),counterType_1=counterStyle&&isIdentToken(counterStyle)?listStyleType.parse(_this.context,counterStyle.value):3,counter=counterType&&0===counterType.type?counterType.value:"",counterStyle=img.map(function(value){return createCounterText(value,counterType_1,!1)}).join(counter),anonymousReplacedElement.appendChild(document.createTextNode(counterStyle)))}else if(20===token.type)switch(token.value){case"open-quote":anonymousReplacedElement.appendChild(document.createTextNode(getQuote(declaration.quotes,_this.quoteDepth++,!0)));break;case"close-quote":anonymousReplacedElement.appendChild(document.createTextNode(getQuote(declaration.quotes,--_this.quoteDepth,!1)));break;default:anonymousReplacedElement.appendChild(document.createTextNode(token.value))}}),anonymousReplacedElement.className=PSEUDO_HIDE_ELEMENT_CLASS_BEFORE+" "+PSEUDO_HIDE_ELEMENT_CLASS_AFTER,value=pseudoElt===PseudoElementType.BEFORE?" "+PSEUDO_HIDE_ELEMENT_CLASS_BEFORE:" "+PSEUDO_HIDE_ELEMENT_CLASS_AFTER,isSVGElementNode(clone)?clone.className.baseValue+=value:clone.className+=value,anonymousReplacedElement}},DocumentCloner.destroy=function(container){return!!container.parentNode&&(container.parentNode.removeChild(container),!0)},DocumentCloner}(),createIFrameContainer=(!function(PseudoElementType){PseudoElementType[PseudoElementType.BEFORE=0]="BEFORE",PseudoElementType[PseudoElementType.AFTER=1]="AFTER"}(PseudoElementType=PseudoElementType||{}),function(ownerDocument,bounds){var cloneIframeContainer=ownerDocument.createElement("iframe");return cloneIframeContainer.className="html2canvas-container",cloneIframeContainer.style.visibility="hidden",cloneIframeContainer.style.position="fixed",cloneIframeContainer.style.left="-10000px",cloneIframeContainer.style.top="0px",cloneIframeContainer.style.border="0",cloneIframeContainer.width=bounds.width.toString(),cloneIframeContainer.height=bounds.height.toString(),cloneIframeContainer.scrolling="no",cloneIframeContainer.setAttribute("data-html2canvas-ignore","true"),ownerDocument.body.appendChild(cloneIframeContainer),cloneIframeContainer}),imagesReady=function(document){return Promise.all([].slice.call(document.images,0).map(imageReady))},iframeLoader=function(iframe){return new Promise(function(resolve,reject){var cloneWindow=iframe.contentWindow;if(!cloneWindow)return reject("No window assigned for iframe");var documentClone=cloneWindow.document;cloneWindow.onload=iframe.onload=function(){cloneWindow.onload=iframe.onload=null;var interval=setInterval(function(){0<documentClone.body.childNodes.length&&"complete"===documentClone.readyState&&(clearInterval(interval),resolve(iframe))},50)}})},ignoredStyleProperties=["all","d","content"],copyCSSStyles=function(style,target){for(var i=style.length-1;0<=i;i--){var property=style.item(i);-1===ignoredStyleProperties.indexOf(property)&&target.style.setProperty(property,style.getPropertyValue(property))}return target},serializeDoctype=function(doctype){var str="";return doctype&&(str+="<!DOCTYPE ",doctype.name&&(str+=doctype.name),doctype.internalSubset&&(str+=doctype.internalSubset),doctype.publicId&&(str+='"'+doctype.publicId+'"'),doctype.systemId&&(str+='"'+doctype.systemId+'"'),str+=">"),str},restoreOwnerScroll=function(ownerDocument,x,y){ownerDocument&&ownerDocument.defaultView&&(x!==ownerDocument.defaultView.pageXOffset||y!==ownerDocument.defaultView.pageYOffset)&&ownerDocument.defaultView.scrollTo(x,y)},restoreNodeScroll=function(_a){var element=_a[0],x=_a[1],_a=_a[2];element.scrollLeft=x,element.scrollTop=_a},PSEUDO_HIDE_ELEMENT_CLASS_BEFORE="___html2canvas___pseudoelement_before",PSEUDO_HIDE_ELEMENT_CLASS_AFTER="___html2canvas___pseudoelement_after",createPseudoHideStyles=function(body){createStyles(body,"."+PSEUDO_HIDE_ELEMENT_CLASS_BEFORE+':before{\n    content: "" !important;\n    display: none !important;\n}\n         .'+PSEUDO_HIDE_ELEMENT_CLASS_AFTER+':after{\n    content: "" !important;\n    display: none !important;\n}')},createStyles=function(body,styles){var document=body.ownerDocument;document&&((document=document.createElement("style")).textContent=styles,body.appendChild(document))},CacheStorage=function(){function CacheStorage(){}return CacheStorage.getOrigin=function(url){var link=CacheStorage._link;return link?(link.href=url,link.href=link.href,link.protocol+link.hostname+link.port):"about:blank"},CacheStorage.isSameOrigin=function(src){return CacheStorage.getOrigin(src)===CacheStorage._origin},CacheStorage.setContext=function(window){CacheStorage._link=window.document.createElement("a"),CacheStorage._origin=CacheStorage.getOrigin(window.location.href)},CacheStorage._origin="about:blank",CacheStorage}(),Cache=function(){function Cache(context,_options){this.context=context,this._options=_options,this._cache={}}return Cache.prototype.addImage=function(src){var result=Promise.resolve();return this.has(src)||(isBlobImage(src)||isRenderable(src))&&(this._cache[src]=this.loadImage(src)).catch(function(){}),result},Cache.prototype.match=function(src){return this._cache[src]},Cache.prototype.loadImage=function(key){return __awaiter(this,void 0,void 0,function(){var isSameOrigin,useCORS,useProxy,src,_this=this;return __generator(this,function(_a){switch(_a.label){case 0:return(isSameOrigin=CacheStorage.isSameOrigin(key),useCORS=!isInlineImage(key)&&!0===this._options.useCORS&&FEATURES.SUPPORT_CORS_IMAGES&&!isSameOrigin,useProxy=!isInlineImage(key)&&!isSameOrigin&&!isBlobImage(key)&&"string"==typeof this._options.proxy&&FEATURES.SUPPORT_CORS_XHR&&!useCORS,isSameOrigin||!1!==this._options.allowTaint||isInlineImage(key)||isBlobImage(key)||useProxy||useCORS)?(src=key,useProxy?[4,this.proxy(src)]:[3,2]):[2];case 1:src=_a.sent(),_a.label=2;case 2:return this.context.logger.debug("Added image "+key.substring(0,256)),[4,new Promise(function(resolve,reject){var img=new Image;img.onload=function(){return resolve(img)},img.onerror=reject,(isInlineBase64Image(src)||useCORS)&&(img.crossOrigin="anonymous"),img.src=src,!0===img.complete&&setTimeout(function(){return resolve(img)},500),0<_this._options.imageTimeout&&setTimeout(function(){return reject("Timed out ("+_this._options.imageTimeout+"ms) loading image")},_this._options.imageTimeout)})];case 3:return[2,_a.sent()]}})})},Cache.prototype.has=function(key){return void 0!==this._cache[key]},Cache.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},Cache.prototype.proxy=function(src){var key,_this=this,proxy=this._options.proxy;if(proxy)return key=src.substring(0,256),new Promise(function(resolve,reject){var timeout_1,responseType=FEATURES.SUPPORT_RESPONSE_TYPE?"blob":"text",xhr=new XMLHttpRequest,queryString=(xhr.onload=function(){var reader_1;200===xhr.status?"text"==responseType?resolve(xhr.response):((reader_1=new FileReader).addEventListener("load",function(){return resolve(reader_1.result)},!1),reader_1.addEventListener("error",function(e){return reject(e)},!1),reader_1.readAsDataURL(xhr.response)):reject("Failed to proxy resource "+key+" with status code "+xhr.status)},xhr.onerror=reject,-1<proxy.indexOf("?")?"&":"?");xhr.open("GET",proxy+queryString+"url="+encodeURIComponent(src)+"&responseType="+responseType),"text"!=responseType&&xhr instanceof XMLHttpRequest&&(xhr.responseType=responseType),_this._options.imageTimeout&&(timeout_1=_this._options.imageTimeout,xhr.timeout=timeout_1,xhr.ontimeout=function(){return reject("Timed out ("+timeout_1+"ms) proxying "+key)}),xhr.send()});throw new Error("No proxy defined")},Cache}(),INLINE_SVG=/^data:image\/svg\+xml/i,INLINE_BASE64=/^data:image\/.*;base64,/i,INLINE_IMG=/^data:image\/.*/i,isRenderable=function(src){return FEATURES.SUPPORT_SVG_DRAWING||!isSVG(src)},isInlineImage=function(src){return INLINE_IMG.test(src)},isInlineBase64Image=function(src){return INLINE_BASE64.test(src)},isBlobImage=function(src){return"blob"===src.substr(0,4)},isSVG=function(src){return"svg"===src.substr(-3).toLowerCase()||INLINE_SVG.test(src)},Vector=function(){function Vector(x,y){this.type=0,this.x=x,this.y=y}return Vector.prototype.add=function(deltaX,deltaY){return new Vector(this.x+deltaX,this.y+deltaY)},Vector}(),BezierCurve=function(){function BezierCurve(start,startControl,endControl,end){this.type=1,this.start=start,this.startControl=startControl,this.endControl=endControl,this.end=end}return BezierCurve.prototype.subdivide=function(t,firstHalf){var ab=lerp(this.start,this.startControl,t),bc=lerp(this.startControl,this.endControl,t),cd=lerp(this.endControl,this.end,t),abbc=lerp(ab,bc,t),bc=lerp(bc,cd,t),t=lerp(abbc,bc,t);return firstHalf?new BezierCurve(this.start,ab,abbc,t):new BezierCurve(t,bc,cd,this.end)},BezierCurve.prototype.add=function(deltaX,deltaY){return new BezierCurve(this.start.add(deltaX,deltaY),this.startControl.add(deltaX,deltaY),this.endControl.add(deltaX,deltaY),this.end.add(deltaX,deltaY))},BezierCurve.prototype.reverse=function(){return new BezierCurve(this.end,this.endControl,this.startControl,this.start)},BezierCurve}(),isBezierCurve=function(path){return 1===path.type},BoundCurves=function(element){var styles=element.styles,bounds=element.bounds,tlh=(_a=getAbsoluteValueForTuple(styles.borderTopLeftRadius,bounds.width,bounds.height))[0],_a=_a[1],trh=(_b=getAbsoluteValueForTuple(styles.borderTopRightRadius,bounds.width,bounds.height))[0],_b=_b[1],brh=(_c=getAbsoluteValueForTuple(styles.borderBottomRightRadius,bounds.width,bounds.height))[0],_c=_c[1],blh=(_d=getAbsoluteValueForTuple(styles.borderBottomLeftRadius,bounds.width,bounds.height))[0],_d=_d[1];(factors=[]).push((tlh+trh)/bounds.width),factors.push((blh+brh)/bounds.width),factors.push((_a+_d)/bounds.height),factors.push((_b+_c)/bounds.height);1<(factors=Math.max.apply(Math,factors))&&(tlh/=factors,_a/=factors,trh/=factors,_b/=factors,brh/=factors,_c/=factors,blh/=factors,_d/=factors);var factors=bounds.width-trh,rightHeight=bounds.height-_c,bottomWidth=bounds.width-brh,leftHeight=bounds.height-_d,borderTopWidth=styles.borderTopWidth,borderRightWidth=styles.borderRightWidth,borderBottomWidth=styles.borderBottomWidth,borderLeftWidth=styles.borderLeftWidth,paddingTop=getAbsoluteValue(styles.paddingTop,element.bounds.width),paddingRight=getAbsoluteValue(styles.paddingRight,element.bounds.width),paddingBottom=getAbsoluteValue(styles.paddingBottom,element.bounds.width),styles=getAbsoluteValue(styles.paddingLeft,element.bounds.width);this.topLeftBorderDoubleOuterBox=0<tlh||0<_a?getCurvePoints(bounds.left+borderLeftWidth/3,bounds.top+borderTopWidth/3,tlh-borderLeftWidth/3,_a-borderTopWidth/3,CORNER.TOP_LEFT):new Vector(bounds.left+borderLeftWidth/3,bounds.top+borderTopWidth/3),this.topRightBorderDoubleOuterBox=0<tlh||0<_a?getCurvePoints(bounds.left+factors,bounds.top+borderTopWidth/3,trh-borderRightWidth/3,_b-borderTopWidth/3,CORNER.TOP_RIGHT):new Vector(bounds.left+bounds.width-borderRightWidth/3,bounds.top+borderTopWidth/3),this.bottomRightBorderDoubleOuterBox=0<brh||0<_c?getCurvePoints(bounds.left+bottomWidth,bounds.top+rightHeight,brh-borderRightWidth/3,_c-borderBottomWidth/3,CORNER.BOTTOM_RIGHT):new Vector(bounds.left+bounds.width-borderRightWidth/3,bounds.top+bounds.height-borderBottomWidth/3),this.bottomLeftBorderDoubleOuterBox=0<blh||0<_d?getCurvePoints(bounds.left+borderLeftWidth/3,bounds.top+leftHeight,blh-borderLeftWidth/3,_d-borderBottomWidth/3,CORNER.BOTTOM_LEFT):new Vector(bounds.left+borderLeftWidth/3,bounds.top+bounds.height-borderBottomWidth/3),this.topLeftBorderDoubleInnerBox=0<tlh||0<_a?getCurvePoints(bounds.left+2*borderLeftWidth/3,bounds.top+2*borderTopWidth/3,tlh-2*borderLeftWidth/3,_a-2*borderTopWidth/3,CORNER.TOP_LEFT):new Vector(bounds.left+2*borderLeftWidth/3,bounds.top+2*borderTopWidth/3),this.topRightBorderDoubleInnerBox=0<tlh||0<_a?getCurvePoints(bounds.left+factors,bounds.top+2*borderTopWidth/3,trh-2*borderRightWidth/3,_b-2*borderTopWidth/3,CORNER.TOP_RIGHT):new Vector(bounds.left+bounds.width-2*borderRightWidth/3,bounds.top+2*borderTopWidth/3),this.bottomRightBorderDoubleInnerBox=0<brh||0<_c?getCurvePoints(bounds.left+bottomWidth,bounds.top+rightHeight,brh-2*borderRightWidth/3,_c-2*borderBottomWidth/3,CORNER.BOTTOM_RIGHT):new Vector(bounds.left+bounds.width-2*borderRightWidth/3,bounds.top+bounds.height-2*borderBottomWidth/3),this.bottomLeftBorderDoubleInnerBox=0<blh||0<_d?getCurvePoints(bounds.left+2*borderLeftWidth/3,bounds.top+leftHeight,blh-2*borderLeftWidth/3,_d-2*borderBottomWidth/3,CORNER.BOTTOM_LEFT):new Vector(bounds.left+2*borderLeftWidth/3,bounds.top+bounds.height-2*borderBottomWidth/3),this.topLeftBorderStroke=0<tlh||0<_a?getCurvePoints(bounds.left+borderLeftWidth/2,bounds.top+borderTopWidth/2,tlh-borderLeftWidth/2,_a-borderTopWidth/2,CORNER.TOP_LEFT):new Vector(bounds.left+borderLeftWidth/2,bounds.top+borderTopWidth/2),this.topRightBorderStroke=0<tlh||0<_a?getCurvePoints(bounds.left+factors,bounds.top+borderTopWidth/2,trh-borderRightWidth/2,_b-borderTopWidth/2,CORNER.TOP_RIGHT):new Vector(bounds.left+bounds.width-borderRightWidth/2,bounds.top+borderTopWidth/2),this.bottomRightBorderStroke=0<brh||0<_c?getCurvePoints(bounds.left+bottomWidth,bounds.top+rightHeight,brh-borderRightWidth/2,_c-borderBottomWidth/2,CORNER.BOTTOM_RIGHT):new Vector(bounds.left+bounds.width-borderRightWidth/2,bounds.top+bounds.height-borderBottomWidth/2),this.bottomLeftBorderStroke=0<blh||0<_d?getCurvePoints(bounds.left+borderLeftWidth/2,bounds.top+leftHeight,blh-borderLeftWidth/2,_d-borderBottomWidth/2,CORNER.BOTTOM_LEFT):new Vector(bounds.left+borderLeftWidth/2,bounds.top+bounds.height-borderBottomWidth/2),this.topLeftBorderBox=0<tlh||0<_a?getCurvePoints(bounds.left,bounds.top,tlh,_a,CORNER.TOP_LEFT):new Vector(bounds.left,bounds.top),this.topRightBorderBox=0<trh||0<_b?getCurvePoints(bounds.left+factors,bounds.top,trh,_b,CORNER.TOP_RIGHT):new Vector(bounds.left+bounds.width,bounds.top),this.bottomRightBorderBox=0<brh||0<_c?getCurvePoints(bounds.left+bottomWidth,bounds.top+rightHeight,brh,_c,CORNER.BOTTOM_RIGHT):new Vector(bounds.left+bounds.width,bounds.top+bounds.height),this.bottomLeftBorderBox=0<blh||0<_d?getCurvePoints(bounds.left,bounds.top+leftHeight,blh,_d,CORNER.BOTTOM_LEFT):new Vector(bounds.left,bounds.top+bounds.height),this.topLeftPaddingBox=0<tlh||0<_a?getCurvePoints(bounds.left+borderLeftWidth,bounds.top+borderTopWidth,Math.max(0,tlh-borderLeftWidth),Math.max(0,_a-borderTopWidth),CORNER.TOP_LEFT):new Vector(bounds.left+borderLeftWidth,bounds.top+borderTopWidth),this.topRightPaddingBox=0<trh||0<_b?getCurvePoints(bounds.left+Math.min(factors,bounds.width-borderRightWidth),bounds.top+borderTopWidth,factors>bounds.width+borderRightWidth?0:Math.max(0,trh-borderRightWidth),Math.max(0,_b-borderTopWidth),CORNER.TOP_RIGHT):new Vector(bounds.left+bounds.width-borderRightWidth,bounds.top+borderTopWidth),this.bottomRightPaddingBox=0<brh||0<_c?getCurvePoints(bounds.left+Math.min(bottomWidth,bounds.width-borderLeftWidth),bounds.top+Math.min(rightHeight,bounds.height-borderBottomWidth),Math.max(0,brh-borderRightWidth),Math.max(0,_c-borderBottomWidth),CORNER.BOTTOM_RIGHT):new Vector(bounds.left+bounds.width-borderRightWidth,bounds.top+bounds.height-borderBottomWidth),this.bottomLeftPaddingBox=0<blh||0<_d?getCurvePoints(bounds.left+borderLeftWidth,bounds.top+Math.min(leftHeight,bounds.height-borderBottomWidth),Math.max(0,blh-borderLeftWidth),Math.max(0,_d-borderBottomWidth),CORNER.BOTTOM_LEFT):new Vector(bounds.left+borderLeftWidth,bounds.top+bounds.height-borderBottomWidth),this.topLeftContentBox=0<tlh||0<_a?getCurvePoints(bounds.left+borderLeftWidth+styles,bounds.top+borderTopWidth+paddingTop,Math.max(0,tlh-(borderLeftWidth+styles)),Math.max(0,_a-(borderTopWidth+paddingTop)),CORNER.TOP_LEFT):new Vector(bounds.left+borderLeftWidth+styles,bounds.top+borderTopWidth+paddingTop),this.topRightContentBox=0<trh||0<_b?getCurvePoints(bounds.left+Math.min(factors,bounds.width+borderLeftWidth+styles),bounds.top+borderTopWidth+paddingTop,factors>bounds.width+borderLeftWidth+styles?0:trh-borderLeftWidth+styles,_b-(borderTopWidth+paddingTop),CORNER.TOP_RIGHT):new Vector(bounds.left+bounds.width-(borderRightWidth+paddingRight),bounds.top+borderTopWidth+paddingTop),this.bottomRightContentBox=0<brh||0<_c?getCurvePoints(bounds.left+Math.min(bottomWidth,bounds.width-(borderLeftWidth+styles)),bounds.top+Math.min(rightHeight,bounds.height+borderTopWidth+paddingTop),Math.max(0,brh-(borderRightWidth+paddingRight)),_c-(borderBottomWidth+paddingBottom),CORNER.BOTTOM_RIGHT):new Vector(bounds.left+bounds.width-(borderRightWidth+paddingRight),bounds.top+bounds.height-(borderBottomWidth+paddingBottom)),this.bottomLeftContentBox=0<blh||0<_d?getCurvePoints(bounds.left+borderLeftWidth+styles,bounds.top+leftHeight,Math.max(0,blh-(borderLeftWidth+styles)),_d-(borderBottomWidth+paddingBottom),CORNER.BOTTOM_LEFT):new Vector(bounds.left+borderLeftWidth+styles,bounds.top+bounds.height-(borderBottomWidth+paddingBottom))},getCurvePoints=(!function(CORNER){CORNER[CORNER.TOP_LEFT=0]="TOP_LEFT",CORNER[CORNER.TOP_RIGHT=1]="TOP_RIGHT",CORNER[CORNER.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",CORNER[CORNER.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(CORNER=CORNER||{}),function(x,y,r1,r2,position){var kappa=(Math.sqrt(2)-1)/3*4,ox=r1*kappa,oy=r2*kappa,xm=x+r1,ym=y+r2;switch(position){case CORNER.TOP_LEFT:return new BezierCurve(new Vector(x,ym),new Vector(x,ym-oy),new Vector(xm-ox,y),new Vector(xm,y));case CORNER.TOP_RIGHT:return new BezierCurve(new Vector(x,y),new Vector(x+ox,y),new Vector(xm,ym-oy),new Vector(xm,ym));case CORNER.BOTTOM_RIGHT:return new BezierCurve(new Vector(xm,y),new Vector(xm,y+oy),new Vector(x+ox,ym),new Vector(x,ym));default:CORNER.BOTTOM_LEFT;return new BezierCurve(new Vector(xm,ym),new Vector(xm-ox,ym),new Vector(x,y+oy),new Vector(x,y))}}),TransformEffect=function(offsetX,offsetY,matrix){this.offsetX=offsetX,this.offsetY=offsetY,this.matrix=matrix,this.type=0,this.target=6},ClipEffect=function(path,target){this.path=path,this.target=target,this.type=1},OpacityEffect=function(opacity){this.opacity=opacity,this.type=2,this.target=6},StackingContext=function(container){this.element=container,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},ElementPaint=function(){function ElementPaint(container,parent){var matrix;this.container=container,this.parent=parent,this.effects=[],this.curves=new BoundCurves(this.container),this.container.styles.opacity<1&&this.effects.push(new OpacityEffect(this.container.styles.opacity)),null!==this.container.styles.transform&&(container=this.container.bounds.left+this.container.styles.transformOrigin[0].number,parent=this.container.bounds.top+this.container.styles.transformOrigin[1].number,matrix=this.container.styles.transform,this.effects.push(new TransformEffect(container,parent,matrix))),0!==this.container.styles.overflowX&&(container=calculateBorderBoxPath(this.curves),parent=calculatePaddingBoxPath(this.curves),equalPath(container,parent)?this.effects.push(new ClipEffect(container,6)):(this.effects.push(new ClipEffect(container,2)),this.effects.push(new ClipEffect(parent,4))))}return ElementPaint.prototype.getEffects=function(target){for(var inFlow=-1===[2,3].indexOf(this.container.styles.position),parent=this.parent,effects=this.effects.slice(0);parent;){var borderBox,paddingBox,croplessEffects=parent.effects.filter(function(effect){return!(1===effect.type)});inFlow||0!==parent.container.styles.position||!parent.parent?(effects.unshift.apply(effects,croplessEffects),inFlow=-1===[2,3].indexOf(parent.container.styles.position),0!==parent.container.styles.overflowX&&(borderBox=calculateBorderBoxPath(parent.curves),paddingBox=calculatePaddingBoxPath(parent.curves),equalPath(borderBox,paddingBox)||effects.unshift(new ClipEffect(paddingBox,6)))):effects.unshift.apply(effects,croplessEffects),parent=parent.parent}return effects.filter(function(effect){return contains(effect.target,target)})},ElementPaint}(),parseStackTree=function(parent,stackingContext,realStackingContext,listItems){parent.container.elements.forEach(function(child){var stack,order_1,index_1,index_2,treatAsRealStackingContext=contains(child.flags,4),createsStackingContext=contains(child.flags,2),paintContainer=new ElementPaint(child,parent),listOwnerItems=(contains(child.styles.display,2048)&&listItems.push(paintContainer),contains(child.flags,8)?[]:listItems);treatAsRealStackingContext||createsStackingContext?(createsStackingContext=treatAsRealStackingContext||child.styles.isPositioned()?realStackingContext:stackingContext,stack=new StackingContext(paintContainer),child.styles.isPositioned()||child.styles.opacity<1||child.styles.isTransformed()?(order_1=child.styles.zIndex.order)<0?(index_1=0,createsStackingContext.negativeZIndex.some(function(current,i){return order_1>current.element.container.styles.zIndex.order?(index_1=i,!1):0<index_1}),createsStackingContext.negativeZIndex.splice(index_1,0,stack)):0<order_1?(index_2=0,createsStackingContext.positiveZIndex.some(function(current,i){return order_1>=current.element.container.styles.zIndex.order?(index_2=i+1,!1):0<index_2}),createsStackingContext.positiveZIndex.splice(index_2,0,stack)):createsStackingContext.zeroOrAutoZIndexOrTransformedOrOpacity.push(stack):(child.styles.isFloating()?createsStackingContext.nonPositionedFloats:createsStackingContext.nonPositionedInlineLevel).push(stack),parseStackTree(paintContainer,stack,treatAsRealStackingContext?stack:realStackingContext,listOwnerItems)):((child.styles.isInlineLevel()?stackingContext.inlineLevel:stackingContext.nonInlineLevel).push(paintContainer),parseStackTree(paintContainer,stackingContext,realStackingContext,listOwnerItems)),contains(child.flags,8)&&processListItems(child,listOwnerItems)})},processListItems=function(owner,elements){for(var numbering=owner instanceof OLElementContainer?owner.start:1,reversed=owner instanceof OLElementContainer&&owner.reversed,i=0;i<elements.length;i++){var item=elements[i];item.container instanceof LIElementContainer&&"number"==typeof item.container.value&&0!==item.container.value&&(numbering=item.container.value),item.listValue=createCounterText(numbering,item.container.styles.listStyleType,!0),numbering+=reversed?-1:1}},calculateBackgroundPositioningArea=function(backgroundOrigin,element){return 0===backgroundOrigin?element.bounds:(2===backgroundOrigin?contentBox:paddingBox)(element)},calculateBackgroundPaintingArea=function(backgroundClip,element){return 0===backgroundClip?element.bounds:(2===backgroundClip?contentBox:paddingBox)(element)},calculateBackgroundSize=function(size,_a,bounds){var intrinsicWidth=_a[0],intrinsicHeight=_a[1],_a=_a[2],first=size[0],size=size[1];if(!first)return[0,0];if(isLengthPercentage(first)&&size&&isLengthPercentage(size))return[getAbsoluteValue(first,bounds.width),getAbsoluteValue(size,bounds.height)];var hasIntrinsicProportion="number"==typeof _a;if(isIdentToken(first)&&(first.value===BACKGROUND_SIZE.CONTAIN||first.value===BACKGROUND_SIZE.COVER))return"number"==typeof _a?bounds.width/bounds.height<_a!=(first.value===BACKGROUND_SIZE.COVER)?[bounds.width,bounds.width/_a]:[bounds.height*_a,bounds.height]:[bounds.width,bounds.height];var hasIntrinsicWidth="number"==typeof intrinsicWidth,hasIntrinsicHeight="number"==typeof intrinsicHeight,hasIntrinsicDimensions=hasIntrinsicWidth||hasIntrinsicHeight;if(isAuto(first)&&(!size||isAuto(size)))return hasIntrinsicWidth&&hasIntrinsicHeight?[intrinsicWidth,intrinsicHeight]:hasIntrinsicProportion||hasIntrinsicDimensions?hasIntrinsicDimensions&&hasIntrinsicProportion?[hasIntrinsicWidth?intrinsicWidth:intrinsicHeight*_a,hasIntrinsicHeight?intrinsicHeight:intrinsicWidth/_a]:[hasIntrinsicWidth?intrinsicWidth:bounds.width,hasIntrinsicHeight?intrinsicHeight:bounds.height]:[bounds.width,bounds.height];if(hasIntrinsicProportion)return hasIntrinsicProportion=hasIntrinsicDimensions=0,isLengthPercentage(first)?hasIntrinsicDimensions=getAbsoluteValue(first,bounds.width):isLengthPercentage(size)&&(hasIntrinsicProportion=getAbsoluteValue(size,bounds.height)),isAuto(first)?hasIntrinsicDimensions=hasIntrinsicProportion*_a:size&&!isAuto(size)||(hasIntrinsicProportion=hasIntrinsicDimensions/_a),[hasIntrinsicDimensions,hasIntrinsicProportion];_a=null,hasIntrinsicDimensions=null;if(isLengthPercentage(first)?_a=getAbsoluteValue(first,bounds.width):size&&isLengthPercentage(size)&&(hasIntrinsicDimensions=getAbsoluteValue(size,bounds.height)),null!==(_a=null!==(hasIntrinsicDimensions=null===_a||size&&!isAuto(size)?hasIntrinsicDimensions:hasIntrinsicWidth&&hasIntrinsicHeight?_a/intrinsicWidth*intrinsicHeight:bounds.height)&&isAuto(first)?hasIntrinsicWidth&&hasIntrinsicHeight?hasIntrinsicDimensions/intrinsicHeight*intrinsicWidth:bounds.width:_a)&&null!==hasIntrinsicDimensions)return[_a,hasIntrinsicDimensions];throw new Error("Unable to calculate background-size for element")},getBackgroundValueForIndex=function(values,index){index=values[index];return void 0===index?values[0]:index},calculateBackgroundRepeatPath=function(repeat,_a,_b,backgroundPositioningArea,backgroundPaintingArea){var x=_a[0],y=_a[1],width=_b[0],height=_b[1];switch(repeat){case 2:return[new Vector(Math.round(backgroundPositioningArea.left),Math.round(backgroundPositioningArea.top+y)),new Vector(Math.round(backgroundPositioningArea.left+backgroundPositioningArea.width),Math.round(backgroundPositioningArea.top+y)),new Vector(Math.round(backgroundPositioningArea.left+backgroundPositioningArea.width),Math.round(height+backgroundPositioningArea.top+y)),new Vector(Math.round(backgroundPositioningArea.left),Math.round(height+backgroundPositioningArea.top+y))];case 3:return[new Vector(Math.round(backgroundPositioningArea.left+x),Math.round(backgroundPositioningArea.top)),new Vector(Math.round(backgroundPositioningArea.left+x+width),Math.round(backgroundPositioningArea.top)),new Vector(Math.round(backgroundPositioningArea.left+x+width),Math.round(backgroundPositioningArea.height+backgroundPositioningArea.top)),new Vector(Math.round(backgroundPositioningArea.left+x),Math.round(backgroundPositioningArea.height+backgroundPositioningArea.top))];case 1:return[new Vector(Math.round(backgroundPositioningArea.left+x),Math.round(backgroundPositioningArea.top+y)),new Vector(Math.round(backgroundPositioningArea.left+x+width),Math.round(backgroundPositioningArea.top+y)),new Vector(Math.round(backgroundPositioningArea.left+x+width),Math.round(backgroundPositioningArea.top+y+height)),new Vector(Math.round(backgroundPositioningArea.left+x),Math.round(backgroundPositioningArea.top+y+height))];default:return[new Vector(Math.round(backgroundPaintingArea.left),Math.round(backgroundPaintingArea.top)),new Vector(Math.round(backgroundPaintingArea.left+backgroundPaintingArea.width),Math.round(backgroundPaintingArea.top)),new Vector(Math.round(backgroundPaintingArea.left+backgroundPaintingArea.width),Math.round(backgroundPaintingArea.height+backgroundPaintingArea.top)),new Vector(Math.round(backgroundPaintingArea.left),Math.round(backgroundPaintingArea.height+backgroundPaintingArea.top))]}},FontMetrics=function(){function FontMetrics(document){this._data={},this._document=document}return FontMetrics.prototype.parseMetrics=function(fontFamily,fontSize){var container=this._document.createElement("div"),img=this._document.createElement("img"),span=this._document.createElement("span"),body=this._document.body,fontFamily=(container.style.visibility="hidden",container.style.fontFamily=fontFamily,container.style.fontSize=fontSize,container.style.margin="0",container.style.padding="0",container.style.whiteSpace="nowrap",body.appendChild(container),img.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",img.width=1,img.height=1,img.style.margin="0",img.style.padding="0",img.style.verticalAlign="baseline",span.style.fontFamily=fontFamily,span.style.fontSize=fontSize,span.style.margin="0",span.style.padding="0",span.appendChild(this._document.createTextNode("Hidden Text")),container.appendChild(span),container.appendChild(img),img.offsetTop-span.offsetTop+2),fontSize=(container.removeChild(span),container.appendChild(this._document.createTextNode("Hidden Text")),container.style.lineHeight="normal",img.style.verticalAlign="super",img.offsetTop-container.offsetTop+2);return body.removeChild(container),{baseline:fontFamily,middle:fontSize}},FontMetrics.prototype.getMetrics=function(fontFamily,fontSize){var key=fontFamily+" "+fontSize;return void 0===this._data[key]&&(this._data[key]=this.parseMetrics(fontFamily,fontSize)),this._data[key]},FontMetrics}(),CanvasRenderer=function(_super){function CanvasRenderer(context,options){context=_super.call(this,context,options)||this;return context._activeEffects=[],context.canvas=options.canvas||document.createElement("canvas"),context.ctx=context.canvas.getContext("2d"),options.canvas||(context.canvas.width=Math.floor(options.width*options.scale),context.canvas.height=Math.floor(options.height*options.scale),context.canvas.style.width=options.width+"px",context.canvas.style.height=options.height+"px"),context.fontMetrics=new FontMetrics(document),context.ctx.scale(context.options.scale,context.options.scale),context.ctx.translate(-options.x,-options.y),context.ctx.textBaseline="bottom",context._activeEffects=[],context.context.logger.debug("Canvas renderer initialized ("+options.width+"x"+options.height+") with scale "+options.scale),context}return __extends(CanvasRenderer,_super),CanvasRenderer.prototype.applyEffects=function(effects){for(var _this=this;this._activeEffects.length;)this.popEffect();effects.forEach(function(effect){return _this.applyEffect(effect)})},CanvasRenderer.prototype.applyEffect=function(effect){this.ctx.save(),2===effect.type&&(this.ctx.globalAlpha=effect.opacity),0===effect.type&&(this.ctx.translate(effect.offsetX,effect.offsetY),this.ctx.transform(effect.matrix[0],effect.matrix[1],effect.matrix[2],effect.matrix[3],effect.matrix[4],effect.matrix[5]),this.ctx.translate(-effect.offsetX,-effect.offsetY)),1===effect.type&&(this.path(effect.path),this.ctx.clip()),this._activeEffects.push(effect)},CanvasRenderer.prototype.popEffect=function(){this._activeEffects.pop(),this.ctx.restore()},CanvasRenderer.prototype.renderStack=function(stack){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return stack.element.container.styles.isVisible()?[4,this.renderStackContent(stack)]:[3,2];case 1:_a.sent(),_a.label=2;case 2:return[2]}})})},CanvasRenderer.prototype.renderNode=function(paint){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return(contains(paint.container.flags,16),paint.container.styles.isVisible())?[4,this.renderNodeBackgroundAndBorders(paint)]:[3,3];case 1:return _a.sent(),[4,this.renderNodeContent(paint)];case 2:_a.sent(),_a.label=3;case 3:return[2]}})})},CanvasRenderer.prototype.renderTextWithLetterSpacing=function(text,letterSpacing,baseline){var _this=this;0===letterSpacing?this.ctx.fillText(text.text,text.bounds.left,text.bounds.top+baseline):segmentGraphemes(text.text).reduce(function(left,letter){return _this.ctx.fillText(letter,left,text.bounds.top+baseline),left+_this.ctx.measureText(letter).width},text.bounds.left)},CanvasRenderer.prototype.createFontStyle=function(styles){var fontVariant=styles.fontVariant.filter(function(variant){return"normal"===variant||"small-caps"===variant}).join(""),fontFamily=fixIOSSystemFonts(styles.fontFamily).join(", "),fontSize=isDimensionToken(styles.fontSize)?""+styles.fontSize.number+styles.fontSize.unit:styles.fontSize.number+"px";return[[styles.fontStyle,fontVariant,styles.fontWeight,fontSize,fontFamily].join(" "),fontFamily,fontSize]},CanvasRenderer.prototype.renderTextNode=function(text,styles){return __awaiter(this,void 0,void 0,function(){var fontFamily,_a,font,baseline,middle,paintOrder,_this=this;return __generator(this,function(_c){return _a=this.createFontStyle(styles),font=_a[0],fontFamily=_a[1],_a=_a[2],this.ctx.font=font,this.ctx.direction=1===styles.direction?"rtl":"ltr",this.ctx.textAlign="left",this.ctx.textBaseline="alphabetic",font=this.fontMetrics.getMetrics(fontFamily,_a),baseline=font.baseline,middle=font.middle,paintOrder=styles.paintOrder,text.textBounds.forEach(function(text){paintOrder.forEach(function(paintOrderLayer){switch(paintOrderLayer){case 0:_this.ctx.fillStyle=asString(styles.color),_this.renderTextWithLetterSpacing(text,styles.letterSpacing,baseline);var textShadows=styles.textShadow;textShadows.length&&text.text.trim().length&&(textShadows.slice(0).reverse().forEach(function(textShadow){_this.ctx.shadowColor=asString(textShadow.color),_this.ctx.shadowOffsetX=textShadow.offsetX.number*_this.options.scale,_this.ctx.shadowOffsetY=textShadow.offsetY.number*_this.options.scale,_this.ctx.shadowBlur=textShadow.blur.number,_this.renderTextWithLetterSpacing(text,styles.letterSpacing,baseline)}),_this.ctx.shadowColor="",_this.ctx.shadowOffsetX=0,_this.ctx.shadowOffsetY=0,_this.ctx.shadowBlur=0),styles.textDecorationLine.length&&(_this.ctx.fillStyle=asString(styles.textDecorationColor||styles.color),styles.textDecorationLine.forEach(function(textDecorationLine){switch(textDecorationLine){case 1:_this.ctx.fillRect(text.bounds.left,Math.round(text.bounds.top+baseline),text.bounds.width,1);break;case 2:_this.ctx.fillRect(text.bounds.left,Math.round(text.bounds.top),text.bounds.width,1);break;case 3:_this.ctx.fillRect(text.bounds.left,Math.ceil(text.bounds.top+middle),text.bounds.width,1)}}));break;case 1:styles.webkitTextStrokeWidth&&text.text.trim().length&&(_this.ctx.strokeStyle=asString(styles.webkitTextStrokeColor),_this.ctx.lineWidth=styles.webkitTextStrokeWidth,_this.ctx.lineJoin=window.chrome?"miter":"round",_this.ctx.strokeText(text.text,text.bounds.left,text.bounds.top+baseline)),_this.ctx.strokeStyle="",_this.ctx.lineWidth=0,_this.ctx.lineJoin="miter"}})}),[2]})})},CanvasRenderer.prototype.renderReplacedElement=function(container,curves,image){var box;image&&0<container.intrinsicWidth&&0<container.intrinsicHeight&&(box=contentBox(container),curves=calculatePaddingBoxPath(curves),this.path(curves),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(image,0,0,container.intrinsicWidth,container.intrinsicHeight,box.left,box.top,box.width,box.height),this.ctx.restore())},CanvasRenderer.prototype.renderNodeContent=function(paint){return __awaiter(this,void 0,void 0,function(){var container,curves,styles,_i,_a,child,size,x,textBounds,image,fontSize,fontFamily,bounds;return __generator(this,function(_c){switch(_c.label){case 0:this.applyEffects(paint.getEffects(4)),container=paint.container,curves=paint.curves,styles=container.styles,_i=0,_a=container.textNodes,_c.label=1;case 1:return _i<_a.length?(child=_a[_i],[4,this.renderTextNode(child,styles)]):[3,4];case 2:_c.sent(),_c.label=3;case 3:return _i++,[3,1];case 4:if(!(container instanceof ImageElementContainer))return[3,8];_c.label=5;case 5:return _c.trys.push([5,7,,8]),[4,this.context.cache.match(container.src)];case 6:return image=_c.sent(),this.renderReplacedElement(container,curves,image),[3,8];case 7:return _c.sent(),this.context.logger.error("Error loading image "+container.src),[3,8];case 8:if(container instanceof CanvasElementContainer&&this.renderReplacedElement(container,curves,container.canvas),!(container instanceof SVGElementContainer))return[3,12];_c.label=9;case 9:return _c.trys.push([9,11,,12]),[4,this.context.cache.match(container.svg)];case 10:return image=_c.sent(),this.renderReplacedElement(container,curves,image),[3,12];case 11:return _c.sent(),this.context.logger.error("Error loading svg "+container.svg.substring(0,255)),[3,12];case 12:return container instanceof IFrameElementContainer&&container.tree?[4,new CanvasRenderer(this.context,{scale:this.options.scale,backgroundColor:container.backgroundColor,x:0,y:0,width:container.width,height:container.height}).render(container.tree)]:[3,14];case 13:child=_c.sent(),container.width&&container.height&&this.ctx.drawImage(child,0,0,container.width,container.height,container.bounds.left,container.bounds.top,container.bounds.width,container.bounds.height),_c.label=14;case 14:if(container instanceof InputElementContainer&&(size=Math.min(container.bounds.width,container.bounds.height),"checkbox"===container.type?container.checked&&(this.ctx.save(),this.path([new Vector(container.bounds.left+.39363*size,container.bounds.top+.79*size),new Vector(container.bounds.left+.16*size,container.bounds.top+.5549*size),new Vector(container.bounds.left+.27347*size,container.bounds.top+.44071*size),new Vector(container.bounds.left+.39694*size,container.bounds.top+.5649*size),new Vector(container.bounds.left+.72983*size,container.bounds.top+.23*size),new Vector(container.bounds.left+.84*size,container.bounds.top+.34085*size),new Vector(container.bounds.left+.39363*size,container.bounds.top+.79*size)]),this.ctx.fillStyle=asString(707406591),this.ctx.fill(),this.ctx.restore()):"radio"===container.type&&container.checked&&(this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(container.bounds.left+size/2,container.bounds.top+size/2,size/4,0,2*Math.PI,!0),this.ctx.fillStyle=asString(707406591),this.ctx.fill(),this.ctx.restore())),isTextInputElement(container)&&container.value.length){switch(size=this.createFontStyle(styles),fontFamily=size[0],fontSize=size[1],fontSize=this.fontMetrics.getMetrics(fontFamily,fontSize).baseline,this.ctx.font=fontFamily,this.ctx.fillStyle=asString(styles.color),this.ctx.textBaseline="alphabetic",this.ctx.textAlign=canvasTextAlign(container.styles.textAlign),bounds=contentBox(container),x=0,container.styles.textAlign){case 1:x+=bounds.width/2;break;case 2:x+=bounds.width}textBounds=bounds.add(x,0,0,-bounds.height/2+1),this.ctx.save(),this.path([new Vector(bounds.left,bounds.top),new Vector(bounds.left+bounds.width,bounds.top),new Vector(bounds.left+bounds.width,bounds.top+bounds.height),new Vector(bounds.left,bounds.top+bounds.height)]),this.ctx.clip(),this.renderTextWithLetterSpacing(new TextBounds(container.value,textBounds),styles.letterSpacing,fontSize),this.ctx.restore(),this.ctx.textBaseline="alphabetic",this.ctx.textAlign="left"}if(!contains(container.styles.display,2048))return[3,20];if(null===container.styles.listStyleImage)return[3,19];if(0!==(textBounds=container.styles.listStyleImage).type)return[3,18];image=void 0,fontSize=textBounds.url,_c.label=15;case 15:return _c.trys.push([15,17,,18]),[4,this.context.cache.match(fontSize)];case 16:return image=_c.sent(),this.ctx.drawImage(image,container.bounds.left-(image.width+10),container.bounds.top),[3,18];case 17:return _c.sent(),this.context.logger.error("Error loading list-style-image "+fontSize),[3,18];case 18:return[3,20];case 19:paint.listValue&&-1!==container.styles.listStyleType&&(fontFamily=this.createFontStyle(styles)[0],this.ctx.font=fontFamily,this.ctx.fillStyle=asString(styles.color),this.ctx.textBaseline="middle",this.ctx.textAlign="right",bounds=new Bounds(container.bounds.left,container.bounds.top+getAbsoluteValue(container.styles.paddingTop,container.bounds.width),container.bounds.width,computeLineHeight(styles.lineHeight,styles.fontSize.number)/2+1),this.renderTextWithLetterSpacing(new TextBounds(paint.listValue,bounds),styles.letterSpacing,computeLineHeight(styles.lineHeight,styles.fontSize.number)/2+2),this.ctx.textBaseline="bottom",this.ctx.textAlign="left"),_c.label=20;case 20:return[2]}})})},CanvasRenderer.prototype.renderStackContent=function(stack){return __awaiter(this,void 0,void 0,function(){var _i,_a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,child;return __generator(this,function(_p){switch(_p.label){case 0:return contains(stack.element.container.flags,16),[4,this.renderNodeBackgroundAndBorders(stack.element)];case 1:_p.sent(),_i=0,_a=stack.negativeZIndex,_p.label=2;case 2:return _i<_a.length?(child=_a[_i],[4,this.renderStack(child)]):[3,5];case 3:_p.sent(),_p.label=4;case 4:return _i++,[3,2];case 5:return[4,this.renderNodeContent(stack.element)];case 6:_p.sent(),_b=0,_c=stack.nonInlineLevel,_p.label=7;case 7:return _b<_c.length?(child=_c[_b],[4,this.renderNode(child)]):[3,10];case 8:_p.sent(),_p.label=9;case 9:return _b++,[3,7];case 10:_d=0,_e=stack.nonPositionedFloats,_p.label=11;case 11:return _d<_e.length?(child=_e[_d],[4,this.renderStack(child)]):[3,14];case 12:_p.sent(),_p.label=13;case 13:return _d++,[3,11];case 14:_f=0,_g=stack.nonPositionedInlineLevel,_p.label=15;case 15:return _f<_g.length?(child=_g[_f],[4,this.renderStack(child)]):[3,18];case 16:_p.sent(),_p.label=17;case 17:return _f++,[3,15];case 18:_h=0,_j=stack.inlineLevel,_p.label=19;case 19:return _h<_j.length?(child=_j[_h],[4,this.renderNode(child)]):[3,22];case 20:_p.sent(),_p.label=21;case 21:return _h++,[3,19];case 22:_k=0,_l=stack.zeroOrAutoZIndexOrTransformedOrOpacity,_p.label=23;case 23:return _k<_l.length?(child=_l[_k],[4,this.renderStack(child)]):[3,26];case 24:_p.sent(),_p.label=25;case 25:return _k++,[3,23];case 26:_m=0,_o=stack.positiveZIndex,_p.label=27;case 27:return _m<_o.length?(child=_o[_m],[4,this.renderStack(child)]):[3,30];case 28:_p.sent(),_p.label=29;case 29:return _m++,[3,27];case 30:return[2]}})})},CanvasRenderer.prototype.mask=function(paths){this.ctx.beginPath(),this.ctx.moveTo(0,0),this.ctx.lineTo(this.canvas.width,0),this.ctx.lineTo(this.canvas.width,this.canvas.height),this.ctx.lineTo(0,this.canvas.height),this.ctx.lineTo(0,0),this.formatPath(paths.slice(0).reverse()),this.ctx.closePath()},CanvasRenderer.prototype.path=function(paths){this.ctx.beginPath(),this.formatPath(paths),this.ctx.closePath()},CanvasRenderer.prototype.formatPath=function(paths){var _this=this;paths.forEach(function(point,index){var start=isBezierCurve(point)?point.start:point;0===index?_this.ctx.moveTo(start.x,start.y):_this.ctx.lineTo(start.x,start.y),isBezierCurve(point)&&_this.ctx.bezierCurveTo(point.startControl.x,point.startControl.y,point.endControl.x,point.endControl.y,point.end.x,point.end.y)})},CanvasRenderer.prototype.renderRepeat=function(path,pattern,offsetX,offsetY){this.path(path),this.ctx.fillStyle=pattern,this.ctx.translate(offsetX,offsetY),this.ctx.fill(),this.ctx.translate(-offsetX,-offsetY)},CanvasRenderer.prototype.resizeImage=function(image,width,height){var _a;return image.width===width&&image.height===height?image:((_a=(null!=(_a=this.canvas.ownerDocument)?_a:document).createElement("canvas")).width=Math.max(1,width),_a.height=Math.max(1,height),_a.getContext("2d").drawImage(image,0,0,image.width,image.height,0,0,width,height),_a)},CanvasRenderer.prototype.renderBackgroundImage=function(container){return __awaiter(this,void 0,void 0,function(){var index,_loop_1,this_1,_i,_a,backgroundImage;return __generator(this,function(_b){switch(_b.label){case 0:index=container.styles.backgroundImage.length-1,_loop_1=function(backgroundImage){var image,url,gradient_1,pattern,x0,path,y0,x1,width,_c,_d,x,y,lineLength,ctx,canvas,radialGradient_1,midX,midY,f,invF;return __generator(this,function(_h){switch(_h.label){case 0:if(0!==backgroundImage.type)return[3,5];image=void 0,url=backgroundImage.url,_h.label=1;case 1:return _h.trys.push([1,3,,4]),[4,this_1.context.cache.match(url)];case 2:return image=_h.sent(),[3,4];case 3:return _h.sent(),this_1.context.logger.error("Error loading background-image "+url),[3,4];case 4:return image&&(_c=calculateBackgroundRendering(container,index,[image.width,image.height,image.width/image.height]),path=_c[0],x=_c[1],y=_c[2],width=_c[3],_c=_c[4],pattern=this_1.ctx.createPattern(this_1.resizeImage(image,width,_c),"repeat"),this_1.renderRepeat(path,pattern,x,y)),[3,6];case 5:1===backgroundImage.type?(_d=calculateBackgroundRendering(container,index,[null,null,null]),path=_d[0],x=_d[1],y=_d[2],width=_d[3],_c=_d[4],_d=function(angle,width,height){var angle="number"==typeof angle?angle:getAngleFromCorner(angle,width,height),lineLength=Math.abs(width*Math.sin(angle))+Math.abs(height*Math.cos(angle)),width=width/2,height=height/2,halfLineLength=lineLength/2,yDiff=Math.sin(angle-Math.PI/2)*halfLineLength,angle=Math.cos(angle-Math.PI/2)*halfLineLength;return[lineLength,width-angle,width+angle,height-yDiff,height+yDiff]}(backgroundImage.angle,width,_c),lineLength=_d[0],x0=_d[1],x1=_d[2],y0=_d[3],_d=_d[4],(canvas=document.createElement("canvas")).width=width,canvas.height=_c,ctx=canvas.getContext("2d"),gradient_1=ctx.createLinearGradient(x0,y0,x1,_d),processColorStops(backgroundImage.stops,lineLength).forEach(function(colorStop){return gradient_1.addColorStop(colorStop.stop,asString(colorStop.color))}),ctx.fillStyle=gradient_1,ctx.fillRect(0,0,width,_c),0<width&&0<_c&&(pattern=this_1.ctx.createPattern(canvas,"repeat"),this_1.renderRepeat(path,pattern,x,y))):2===backgroundImage.type&&(x0=calculateBackgroundRendering(container,index,[null,null,null]),path=x0[0],y0=x0[1],x1=x0[2],width=x0[3],_c=x0[4],_d=0===backgroundImage.position.length?[FIFTY_PERCENT]:backgroundImage.position,x=getAbsoluteValue(_d[0],width),y=getAbsoluteValue(_d[_d.length-1],_c),ctx=(lineLength=function(gradient,x,y,width,height){var c,_b,cx,_a,rx=0,ry=0;switch(gradient.size){case 0:0===gradient.shape?rx=ry=Math.min(Math.abs(x),Math.abs(x-width),Math.abs(y),Math.abs(y-height)):1===gradient.shape&&(rx=Math.min(Math.abs(x),Math.abs(x-width)),ry=Math.min(Math.abs(y),Math.abs(y-height)));break;case 2:0===gradient.shape?rx=ry=Math.min(distance(x,y),distance(x,y-height),distance(x-width,y),distance(x-width,y-height)):1===gradient.shape&&(c=Math.min(Math.abs(y),Math.abs(y-height))/Math.min(Math.abs(x),Math.abs(x-width)),cx=(_a=findCorner(width,height,x,y,!0))[0],_a=_a[1],ry=c*(rx=distance(cx-x,(_a-y)/c)));break;case 1:0===gradient.shape?rx=ry=Math.max(Math.abs(x),Math.abs(x-width),Math.abs(y),Math.abs(y-height)):1===gradient.shape&&(rx=Math.max(Math.abs(x),Math.abs(x-width)),ry=Math.max(Math.abs(y),Math.abs(y-height)));break;case 3:0===gradient.shape?rx=ry=Math.max(distance(x,y),distance(x,y-height),distance(x-width,y),distance(x-width,y-height)):1===gradient.shape&&(c=Math.max(Math.abs(y),Math.abs(y-height))/Math.max(Math.abs(x),Math.abs(x-width)),cx=(_b=findCorner(width,height,x,y,!1))[0],_a=_b[1],ry=c*(rx=distance(cx-x,(_a-y)/c)))}return Array.isArray(gradient.size)&&(rx=getAbsoluteValue(gradient.size[0],width),ry=2===gradient.size.length?getAbsoluteValue(gradient.size[1],height):rx),[rx,ry]}(backgroundImage,x,y,width,_c))[0],canvas=lineLength[1],0<ctx)&&0<canvas&&(radialGradient_1=this_1.ctx.createRadialGradient(y0+x,x1+y,0,y0+x,x1+y,ctx),processColorStops(backgroundImage.stops,2*ctx).forEach(function(colorStop){return radialGradient_1.addColorStop(colorStop.stop,asString(colorStop.color))}),this_1.path(path),this_1.ctx.fillStyle=radialGradient_1,ctx!==canvas?(midX=container.bounds.left+.5*container.bounds.width,midY=container.bounds.top+.5*container.bounds.height,invF=1/(f=canvas/ctx),this_1.ctx.save(),this_1.ctx.translate(midX,midY),this_1.ctx.transform(1,0,0,f,0,0),this_1.ctx.translate(-midX,-midY),this_1.ctx.fillRect(y0,invF*(x1-midY)+midY,width,_c*invF),this_1.ctx.restore()):this_1.ctx.fill()),_h.label=6;case 6:return index--,[2]}})},this_1=this,_i=0,_a=container.styles.backgroundImage.slice(0).reverse(),_b.label=1;case 1:return _i<_a.length?(backgroundImage=_a[_i],[5,_loop_1(backgroundImage)]):[3,4];case 2:_b.sent(),_b.label=3;case 3:return _i++,[3,1];case 4:return[2]}})})},CanvasRenderer.prototype.renderSolidBorder=function(color,side,curvePoints){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return this.path(parsePathForBorder(curvePoints,side)),this.ctx.fillStyle=asString(color),this.ctx.fill(),[2]})})},CanvasRenderer.prototype.renderDoubleBorder=function(color,width,side,curvePoints){return __awaiter(this,void 0,void 0,function(){var outerPaths;return __generator(this,function(_a){switch(_a.label){case 0:return width<3?[4,this.renderSolidBorder(color,side,curvePoints)]:[3,2];case 1:return _a.sent(),[2];case 2:return outerPaths=function(curves,borderSide){switch(borderSide){case 0:return createPathFromCurves(curves.topLeftBorderBox,curves.topLeftBorderDoubleOuterBox,curves.topRightBorderBox,curves.topRightBorderDoubleOuterBox);case 1:return createPathFromCurves(curves.topRightBorderBox,curves.topRightBorderDoubleOuterBox,curves.bottomRightBorderBox,curves.bottomRightBorderDoubleOuterBox);case 2:return createPathFromCurves(curves.bottomRightBorderBox,curves.bottomRightBorderDoubleOuterBox,curves.bottomLeftBorderBox,curves.bottomLeftBorderDoubleOuterBox);default:return createPathFromCurves(curves.bottomLeftBorderBox,curves.bottomLeftBorderDoubleOuterBox,curves.topLeftBorderBox,curves.topLeftBorderDoubleOuterBox)}}(curvePoints,side),this.path(outerPaths),this.ctx.fillStyle=asString(color),this.ctx.fill(),outerPaths=function(curves,borderSide){switch(borderSide){case 0:return createPathFromCurves(curves.topLeftBorderDoubleInnerBox,curves.topLeftPaddingBox,curves.topRightBorderDoubleInnerBox,curves.topRightPaddingBox);case 1:return createPathFromCurves(curves.topRightBorderDoubleInnerBox,curves.topRightPaddingBox,curves.bottomRightBorderDoubleInnerBox,curves.bottomRightPaddingBox);case 2:return createPathFromCurves(curves.bottomRightBorderDoubleInnerBox,curves.bottomRightPaddingBox,curves.bottomLeftBorderDoubleInnerBox,curves.bottomLeftPaddingBox);default:return createPathFromCurves(curves.bottomLeftBorderDoubleInnerBox,curves.bottomLeftPaddingBox,curves.topLeftBorderDoubleInnerBox,curves.topLeftPaddingBox)}}(curvePoints,side),this.path(outerPaths),this.ctx.fill(),[2]}})})},CanvasRenderer.prototype.renderNodeBackgroundAndBorders=function(paint){return __awaiter(this,void 0,void 0,function(){var styles,hasBackground,borders,backgroundPaintingArea,side,_i,borders_1,border,_this=this;return __generator(this,function(_a){switch(_a.label){case 0:return(this.applyEffects(paint.getEffects(2)),styles=paint.container.styles,hasBackground=!(0==(255&styles.backgroundColor))||styles.backgroundImage.length,borders=[{style:styles.borderTopStyle,color:styles.borderTopColor,width:styles.borderTopWidth},{style:styles.borderRightStyle,color:styles.borderRightColor,width:styles.borderRightWidth},{style:styles.borderBottomStyle,color:styles.borderBottomColor,width:styles.borderBottomWidth},{style:styles.borderLeftStyle,color:styles.borderLeftColor,width:styles.borderLeftWidth}],backgroundPaintingArea=calculateBackgroundCurvedPaintingArea(getBackgroundValueForIndex(styles.backgroundClip,0),paint.curves),hasBackground||styles.boxShadow.length)?(this.ctx.save(),this.path(backgroundPaintingArea),this.ctx.clip(),0!=(255&styles.backgroundColor)&&(this.ctx.fillStyle=asString(styles.backgroundColor),this.ctx.fill()),[4,this.renderBackgroundImage(paint.container)]):[3,2];case 1:_a.sent(),this.ctx.restore(),styles.boxShadow.slice(0).reverse().forEach(function(shadow){_this.ctx.save();var deltaX,deltaY,deltaW,deltaH,borderBoxArea=calculateBorderBoxPath(paint.curves),maskOffset=shadow.inset?0:1e4,shadowPaintingArea=(deltaX=-maskOffset+(shadow.inset?1:-1)*shadow.spread.number,deltaY=(shadow.inset?1:-1)*shadow.spread.number,deltaW=shadow.spread.number*(shadow.inset?-2:2),deltaH=shadow.spread.number*(shadow.inset?-2:2),borderBoxArea.map(function(point,index){switch(index){case 0:return point.add(deltaX,deltaY);case 1:return point.add(deltaX+deltaW,deltaY);case 2:return point.add(deltaX+deltaW,deltaY+deltaH);case 3:return point.add(deltaX,deltaY+deltaH)}return point}));shadow.inset?(_this.path(borderBoxArea),_this.ctx.clip(),_this.mask(shadowPaintingArea)):(_this.mask(borderBoxArea),_this.ctx.clip(),_this.path(shadowPaintingArea)),_this.ctx.shadowOffsetX=shadow.offsetX.number+maskOffset,_this.ctx.shadowOffsetY=shadow.offsetY.number,_this.ctx.shadowColor=asString(shadow.color),_this.ctx.shadowBlur=shadow.blur.number,_this.ctx.fillStyle=shadow.inset?asString(shadow.color):"rgba(0,0,0,1)",_this.ctx.fill(),_this.ctx.restore()}),_a.label=2;case 2:_i=side=0,borders_1=borders,_a.label=3;case 3:return _i<borders_1.length?0!==(border=borders_1[_i]).style&&0!=(255&border.color)&&0<border.width?2!==border.style?[3,5]:[4,this.renderDashedDottedBorder(border.color,border.width,side,paint.curves,2)]:[3,11]:[3,13];case 4:return _a.sent(),[3,11];case 5:return 3!==border.style?[3,7]:[4,this.renderDashedDottedBorder(border.color,border.width,side,paint.curves,3)];case 6:return _a.sent(),[3,11];case 7:return 4!==border.style?[3,9]:[4,this.renderDoubleBorder(border.color,border.width,side,paint.curves)];case 8:return _a.sent(),[3,11];case 9:return[4,this.renderSolidBorder(border.color,side,paint.curves)];case 10:_a.sent(),_a.label=11;case 11:side++,_a.label=12;case 12:return _i++,[3,3];case 13:return[2]}})})},CanvasRenderer.prototype.renderDashedDottedBorder=function(color,width,side,curvePoints,style){return __awaiter(this,void 0,void 0,function(){var boxPaths,startX,endX,endY,strokePaths,useLineDash,multiplier,minSpace,startY,path1,path2;return __generator(this,function(_a){return this.ctx.save(),strokePaths=function(curves,borderSide){switch(borderSide){case 0:return createStrokePathFromCurves(curves.topLeftBorderStroke,curves.topRightBorderStroke);case 1:return createStrokePathFromCurves(curves.topRightBorderStroke,curves.bottomRightBorderStroke);case 2:return createStrokePathFromCurves(curves.bottomRightBorderStroke,curves.bottomLeftBorderStroke);default:return createStrokePathFromCurves(curves.bottomLeftBorderStroke,curves.topLeftBorderStroke)}}(curvePoints,side),boxPaths=parsePathForBorder(curvePoints,side),2===style&&(this.path(boxPaths),this.ctx.clip()),startY=(isBezierCurve(boxPaths[0])?(startX=boxPaths[0].start.x,boxPaths[0].start):(startX=boxPaths[0].x,boxPaths[0])).y,endY=(isBezierCurve(boxPaths[1])?(endX=boxPaths[1].end.x,boxPaths[1].end):(endX=boxPaths[1].x,boxPaths[1])).y,startY=0===side||2===side?Math.abs(startX-endX):Math.abs(startY-endY),this.ctx.beginPath(),3===style?this.formatPath(strokePaths):this.formatPath(boxPaths.slice(0,2)),endY=width<3?3*width:2*width,strokePaths=width<3?2*width:width,3===style&&(strokePaths=endY=width),useLineDash=!0,startY<=2*endY?useLineDash=!1:startY<=2*endY+strokePaths?(endY*=multiplier=startY/(2*endY+strokePaths),strokePaths*=multiplier):(multiplier=Math.floor((startY+strokePaths)/(endY+strokePaths)),minSpace=(startY-multiplier*endY)/(multiplier-1),strokePaths=(startY=(startY-(multiplier+1)*endY)/multiplier)<=0||Math.abs(strokePaths-minSpace)<Math.abs(strokePaths-startY)?minSpace:startY),useLineDash&&(3===style?this.ctx.setLineDash([0,endY+strokePaths]):this.ctx.setLineDash([endY,strokePaths])),3===style?(this.ctx.lineCap="round",this.ctx.lineWidth=width):this.ctx.lineWidth=2*width+1.1,this.ctx.strokeStyle=asString(color),this.ctx.stroke(),this.ctx.setLineDash([]),2===style&&(isBezierCurve(boxPaths[0])&&(path1=boxPaths[3],path2=boxPaths[0],this.ctx.beginPath(),this.formatPath([new Vector(path1.end.x,path1.end.y),new Vector(path2.start.x,path2.start.y)]),this.ctx.stroke()),isBezierCurve(boxPaths[1]))&&(path1=boxPaths[1],path2=boxPaths[2],this.ctx.beginPath(),this.formatPath([new Vector(path1.end.x,path1.end.y),new Vector(path2.start.x,path2.start.y)]),this.ctx.stroke()),this.ctx.restore(),[2]})})},CanvasRenderer.prototype.render=function(element){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return this.options.backgroundColor&&(this.ctx.fillStyle=asString(this.options.backgroundColor),this.ctx.fillRect(this.options.x,this.options.y,this.options.width,this.options.height)),container=new ElementPaint(container=element,null),root=new StackingContext(container),parseStackTree(container,root,root,listItems=[]),processListItems(container.container,listItems),[4,this.renderStack(root)];case 1:return _a.sent(),this.applyEffects([]),[2,this.canvas]}var container,root,listItems})})},CanvasRenderer}(Renderer),isTextInputElement=function(container){return container instanceof TextareaElementContainer||container instanceof SelectElementContainer||container instanceof InputElementContainer&&"radio"!==container.type&&"checkbox"!==container.type},calculateBackgroundCurvedPaintingArea=function(clip,curves){switch(clip){case 0:return calculateBorderBoxPath(curves);case 2:return function(curves){return[curves.topLeftContentBox,curves.topRightContentBox,curves.bottomRightContentBox,curves.bottomLeftContentBox]}(curves);default:return calculatePaddingBoxPath(curves)}},canvasTextAlign=function(textAlign){switch(textAlign){case 1:return"center";case 2:return"right";default:return"left"}},iOSBrokenFonts=["-apple-system","system-ui"],fixIOSSystemFonts=function(fontFamilies){return/iPhone OS 15_(0|1)/.test(window.navigator.userAgent)?fontFamilies.filter(function(fontFamily){return-1===iOSBrokenFonts.indexOf(fontFamily)}):fontFamilies},ForeignObjectRenderer=function(_super){function ForeignObjectRenderer(context,options){context=_super.call(this,context,options)||this;return context.canvas=options.canvas||document.createElement("canvas"),context.ctx=context.canvas.getContext("2d"),context.options=options,context.canvas.width=Math.floor(options.width*options.scale),context.canvas.height=Math.floor(options.height*options.scale),context.canvas.style.width=options.width+"px",context.canvas.style.height=options.height+"px",context.ctx.scale(context.options.scale,context.options.scale),context.ctx.translate(-options.x,-options.y),context.context.logger.debug("EXPERIMENTAL ForeignObject renderer initialized ("+options.width+"x"+options.height+" at "+options.x+","+options.y+") with scale "+options.scale),context}return __extends(ForeignObjectRenderer,_super),ForeignObjectRenderer.prototype.render=function(element){return __awaiter(this,void 0,void 0,function(){var svg;return __generator(this,function(_a){switch(_a.label){case 0:return svg=createForeignObjectSVG(this.options.width*this.options.scale,this.options.height*this.options.scale,this.options.scale,this.options.scale,element),[4,loadSerializedSVG(svg)];case 1:return svg=_a.sent(),this.options.backgroundColor&&(this.ctx.fillStyle=asString(this.options.backgroundColor),this.ctx.fillRect(0,0,this.options.width*this.options.scale,this.options.height*this.options.scale)),this.ctx.drawImage(svg,-this.options.x*this.options.scale,-this.options.y*this.options.scale),[2,this.canvas]}})})},ForeignObjectRenderer}(Renderer),loadSerializedSVG=function(svg){return new Promise(function(resolve,reject){var img=new Image;img.onload=function(){resolve(img)},img.onerror=reject,img.src="data:image/svg+xml;charset=utf-8,"+encodeURIComponent((new XMLSerializer).serializeToString(svg))})},Logger=function(){function Logger(_a){var id=_a.id,_a=_a.enabled;this.id=id,this.enabled=_a,this.start=Date.now()}return Logger.prototype.debug=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];this.enabled&&("undefined"!=typeof window&&window.console&&"function"==typeof console.debug?console.debug.apply(console,__spreadArray([this.id,this.getTime()+"ms"],args)):this.info.apply(this,args))},Logger.prototype.getTime=function(){return Date.now()-this.start},Logger.prototype.info=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];this.enabled&&"undefined"!=typeof window&&window.console&&"function"==typeof console.info&&console.info.apply(console,__spreadArray([this.id,this.getTime()+"ms"],args))},Logger.prototype.warn=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];this.enabled&&("undefined"!=typeof window&&window.console&&"function"==typeof console.warn?console.warn.apply(console,__spreadArray([this.id,this.getTime()+"ms"],args)):this.info.apply(this,args))},Logger.prototype.error=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];this.enabled&&("undefined"!=typeof window&&window.console&&"function"==typeof console.error?console.error.apply(console,__spreadArray([this.id,this.getTime()+"ms"],args)):this.info.apply(this,args))},Logger.instances={},Logger}(),Context=function(){function Context(options,windowBounds){this.windowBounds=windowBounds,this.instanceName="#"+Context.instanceCount++,this.logger=new Logger({id:this.instanceName,enabled:options.logging}),this.cache=null!=(windowBounds=options.cache)?windowBounds:new Cache(this,options)}return Context.instanceCount=1,Context}(),parseBackgroundColor=("undefined"!=typeof window&&CacheStorage.setContext(window),function(context,element,backgroundColorOverride){var ownerDocument=element.ownerDocument,documentBackgroundColor=ownerDocument.documentElement?parseColor(context,getComputedStyle(ownerDocument.documentElement).backgroundColor):COLORS.TRANSPARENT,bodyBackgroundColor=ownerDocument.body?parseColor(context,getComputedStyle(ownerDocument.body).backgroundColor):COLORS.TRANSPARENT,context="string"==typeof backgroundColorOverride?parseColor(context,backgroundColorOverride):null===backgroundColorOverride?COLORS.TRANSPARENT:4294967295;return element===ownerDocument.documentElement?0==(255&documentBackgroundColor)?0==(255&bodyBackgroundColor)?context:bodyBackgroundColor:documentBackgroundColor:context});return function(element,options){return function(element,opts){return __awaiter(void 0,void 0,void 0,function(){var ownerDocument,defaultView,resourceOptions,contextOptions,windowOptions,windowBounds,context,foreignObjectRendering,cloneOptions,documentCloner,clonedElement,container,_a,width,height,left,top,backgroundColor,renderOptions,canvas,renderer,root,renderer;var _b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t;return __generator(this,function(_u){switch(_u.label){case 0:if(!element||typeof element!=="object")return[2,Promise.reject("Invalid element provided as first argument")];ownerDocument=element.ownerDocument;if(!ownerDocument)throw new Error("Element is not attached to a Document");defaultView=ownerDocument.defaultView;if(!defaultView)throw new Error("Document is not attached to a Window");resourceOptions={allowTaint:(_b=opts.allowTaint)!==null&&_b!==void 0?_b:false,imageTimeout:(_c=opts.imageTimeout)!==null&&_c!==void 0?_c:15e3,proxy:opts.proxy,useCORS:(_d=opts.useCORS)!==null&&_d!==void 0?_d:false};contextOptions=__assign({logging:(_e=opts.logging)!==null&&_e!==void 0?_e:true,cache:opts.cache},resourceOptions);windowOptions={windowWidth:(_f=opts.windowWidth)!==null&&_f!==void 0?_f:defaultView.innerWidth,windowHeight:(_g=opts.windowHeight)!==null&&_g!==void 0?_g:defaultView.innerHeight,scrollX:(_h=opts.scrollX)!==null&&_h!==void 0?_h:defaultView.pageXOffset,scrollY:(_j=opts.scrollY)!==null&&_j!==void 0?_j:defaultView.pageYOffset};windowBounds=new Bounds(windowOptions.scrollX,windowOptions.scrollY,windowOptions.windowWidth,windowOptions.windowHeight);context=new Context(contextOptions,windowBounds);foreignObjectRendering=(_k=opts.foreignObjectRendering)!==null&&_k!==void 0?_k:false;cloneOptions={allowTaint:(_l=opts.allowTaint)!==null&&_l!==void 0?_l:false,onclone:opts.onclone,ignoreElements:opts.ignoreElements,inlineImages:foreignObjectRendering,copyStyles:foreignObjectRendering};context.logger.debug("Starting document clone with size "+windowBounds.width+"x"+windowBounds.height+" scrolled to "+-windowBounds.left+","+-windowBounds.top);documentCloner=new DocumentCloner(context,element,cloneOptions);clonedElement=documentCloner.clonedReferenceElement;if(!clonedElement)return[2,Promise.reject("Unable to find element in cloned iframe")];return[4,documentCloner.toIFrame(ownerDocument,windowBounds)];case 1:container=_u.sent();_a=isBodyElement(clonedElement)||isHTMLElement(clonedElement)?parseDocumentSize(clonedElement.ownerDocument):parseBounds(context,clonedElement),width=_a.width,height=_a.height,left=_a.left,top=_a.top;backgroundColor=parseBackgroundColor(context,clonedElement,opts.backgroundColor);renderOptions={canvas:opts.canvas,backgroundColor:backgroundColor,scale:(_o=(_m=opts.scale)!==null&&_m!==void 0?_m:defaultView.devicePixelRatio)!==null&&_o!==void 0?_o:1,x:((_p=opts.x)!==null&&_p!==void 0?_p:0)+left,y:((_q=opts.y)!==null&&_q!==void 0?_q:0)+top,width:(_r=opts.width)!==null&&_r!==void 0?_r:Math.ceil(width),height:(_s=opts.height)!==null&&_s!==void 0?_s:Math.ceil(height)};if(!foreignObjectRendering)return[3,3];context.logger.debug("Document cloned, using foreign object rendering");renderer=new ForeignObjectRenderer(context,renderOptions);return[4,renderer.render(clonedElement)];case 2:canvas=_u.sent();return[3,5];case 3:context.logger.debug("Document cloned, element located at "+left+","+top+" with size "+width+"x"+height+" using computed rendering");context.logger.debug("Starting DOM parsing");root=parseTree(context,clonedElement);if(backgroundColor===root.styles.backgroundColor)root.styles.backgroundColor=COLORS.TRANSPARENT;context.logger.debug("Starting renderer for element at "+renderOptions.x+","+renderOptions.y+" with size "+renderOptions.width+"x"+renderOptions.height);renderer=new CanvasRenderer(context,renderOptions);return[4,renderer.render(root)];case 4:canvas=_u.sent();_u.label=5;case 5:if((_t=opts.removeContainer)!==null&&_t!==void 0?_t:true)if(!DocumentCloner.destroy(container))context.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore");context.logger.debug("Finished rendering");return[2,canvas]}})})}(element,options=void 0===options?{}:options)}},"object"==typeof exports&&void 0!==module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):(global="undefined"!=typeof globalThis?globalThis:global||self).html2canvas=factory()},{}],656:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,nBytes=buffer[offset+i];for(i+=d,e=nBytes&(1<<-nBits)-1,nBytes>>=-nBits,nBits+=eLen;0<nBits;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;0<nBits;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(nBytes?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(nBytes?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,nBytes=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(isLE=Math.pow(2,-e))<1&&(e--,isLE*=2),2<=(value+=1<=e+eBias?rt/isLE:rt*Math.pow(2,1-eBias))*isLE&&(e++,isLE/=2),eMax<=e+eBias?(m=0,e=eMax):1<=e+eBias?(m=(value*isLE-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));8<=mLen;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<<mLen|m,eLen+=mLen;0<eLen;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*nBytes}},{}],657:[function(require,module,exports){"use strict";function isStandardArguments(value){return!(hasToStringTag&&value&&"object"==typeof value&&Symbol.toStringTag in value)&&"[object Arguments]"===$toString(value)}function isLegacyArguments(value){return!!isStandardArguments(value)||null!==value&&"object"==typeof value&&"number"==typeof value.length&&0<=value.length&&"[object Array]"!==$toString(value)&&"[object Function]"===$toString(value.callee)}var hasToStringTag=require("has-tostringtag/shams")(),$toString=require("call-bind/callBound")("Object.prototype.toString"),require=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments,module.exports=require?isStandardArguments:isLegacyArguments},{"call-bind/callBound":114,"has-tostringtag/shams":649}],658:[function(require,module,exports){"use strict";var getDay=Date.prototype.getDay,toStr=Object.prototype.toString,hasToStringTag=require("has-tostringtag/shams")();module.exports=function(value){return"object"==typeof value&&null!==value&&(hasToStringTag?function(value){try{return getDay.call(value),!0}catch(e){return!1}}(value):"[object Date]"===toStr.call(value))}},{"has-tostringtag/shams":649}],659:[function(require,module,exports){"use strict";var has,$exec,isRegexMarker,throwRegexMarker,badStringifier,callBound=require("call-bind/callBound"),require=require("has-tostringtag/shams")(),$toString=(require&&(has=callBound("Object.prototype.hasOwnProperty"),$exec=callBound("RegExp.prototype.exec"),isRegexMarker={},badStringifier={toString:throwRegexMarker=function(){throw isRegexMarker},valueOf:throwRegexMarker},"symbol"==typeof Symbol.toPrimitive)&&(badStringifier[Symbol.toPrimitive]=throwRegexMarker),callBound("Object.prototype.toString")),gOPD=Object.getOwnPropertyDescriptor;module.exports=require?function(value){if(!value||"object"!=typeof value)return!1;var descriptor=gOPD(value,"lastIndex");if(!(descriptor&&has(descriptor,"value")))return!1;try{$exec(value,badStringifier)}catch(e){return e===isRegexMarker}}:function(value){return!(!value||"object"!=typeof value&&"function"!=typeof value)&&"[object RegExp]"===$toString(value)}},{"call-bind/callBound":114,"has-tostringtag/shams":649}],660:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],661:[function(require,module,exports){!function(process){!function(){!function(exports,global){function renderDocument(t,e,n,r){return createWindowClone(t,t,n,r,e).then(function(i){log("Document cloned");var o="["+html2canvasNodeAttribute+"='true']",s=(t.querySelector(o).removeAttribute(html2canvasNodeAttribute),i.contentWindow),a=s.document.querySelector(o);return Promise.resolve("function"!=typeof e.onclone||e.onclone(s.document)).then(function(){return renderWindow(a,i,e,n,r)})})}function renderWindow(t,e,n,r,i){var o=e.contentWindow,s=new Support(o.document),a=new ImageLoader(n,s),c=getBounds(t),r="view"===n.type?r:documentWidth(o.document),i="view"===n.type?i:documentHeight(o.document),h=new CanvasRenderer(r,i,a,n,document);return new NodeParser(t,h,s,a,n).ready.then(function(){var r;return log("Finished rendering"),r="view"===n.type?crop(h.canvas,{width:h.canvas.width,height:h.canvas.height,top:0,left:0,x:0,y:0}):t===o.document.body||t===o.document.documentElement||null!=n.canvas?h.canvas:crop(h.canvas,{width:(null!=n.width?n:c).width,height:(null!=n.height?n:c).height,top:c.top,left:c.left,x:o.pageXOffset,y:o.pageYOffset}),cleanupContainer(e,n),r})}function cleanupContainer(t,e){e.removeContainer&&(t.parentNode.removeChild(t),log("Cleaned up container"))}function crop(t,e){var n=document.createElement("canvas"),r=Math.min(t.width-1,Math.max(0,e.left)),i=Math.min(t.width,Math.max(1,e.left+e.width)),o=Math.min(t.height-1,Math.max(0,e.top)),s=Math.min(t.height,Math.max(1,e.top+e.height));return n.width=e.width,n.height=e.height,log("Cropping canvas at:","left:",e.left,"top:",e.top,"width:",i-r,"height:",s-o),log("Resulting crop with width",e.width,"and height",e.height," with x",r,"and y",o),n.getContext("2d").drawImage(t,r,o,i-r,s-o,e.x,e.y,i-r,s-o),n}function documentWidth(t){return Math.max(Math.max(t.body.scrollWidth,t.documentElement.scrollWidth),Math.max(t.body.offsetWidth,t.documentElement.offsetWidth),Math.max(t.body.clientWidth,t.documentElement.clientWidth))}function documentHeight(t){return Math.max(Math.max(t.body.scrollHeight,t.documentElement.scrollHeight),Math.max(t.body.offsetHeight,t.documentElement.offsetHeight),Math.max(t.body.clientHeight,t.documentElement.clientHeight))}function smallImage(){return"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"}function createWindowClone(t,e,n,r,i){labelCanvasElements(t);var o=t.documentElement.cloneNode(!0),s=e.createElement("iframe");return s.className="html2canvas-container",s.style.visibility="hidden",s.style.position="fixed",s.style.left="-10000px",s.style.top="0px",s.style.border="0",s.width=n,s.height=r,s.scrolling="no",e.body.appendChild(s),new Promise(function(e){var n=s.contentWindow.document,r=(s.contentWindow.onload=s.onload=function(){var o=setInterval(function(){0<n.body.childNodes.length&&(cloneCanvasContents(t,n),clearInterval(o),"view"===i.type&&s.contentWindow.scrollTo(r,a),e(s))},50)},t.defaultView.pageXOffset),a=t.defaultView.pageYOffset;n.open(),n.write("<!DOCTYPE html><html></html>"),restoreOwnerScroll(t,r,a),n.replaceChild(!0===i.javascriptEnabled?n.adoptNode(o):removeScriptNodes(n.adoptNode(o)),n.documentElement),n.close()})}function restoreOwnerScroll(t,e,n){e===t.defaultView.pageXOffset&&n===t.defaultView.pageYOffset||t.defaultView.scrollTo(e,n)}function loadUrlDocument(t,e,n,r,i,o){return new Proxy(t,e,window.document).then(documentFromHTML(t)).then(function(t){return createWindowClone(t,n,r,i,o)})}function documentFromHTML(t){return function(e){var n,r=new DOMParser;try{n=r.parseFromString(e,"text/html")}catch(i){log("DOMParser not supported, falling back to createHTMLDocument"),n=document.implementation.createHTMLDocument("");try{n.open(),n.write(e),n.close()}catch(o){log("createHTMLDocument write not supported, falling back to document.body.innerHTML"),n.body.innerHTML=e}}r=n.querySelector("base");return r&&r.href.host||((e=n.createElement("base")).href=t,n.head.insertBefore(e,n.head.firstChild)),n}}function labelCanvasElements(t){[].slice.call(t.querySelectorAll("canvas"),0).forEach(function(t){t.setAttribute(html2canvasCanvasCloneAttribute,"canvas-"+html2canvasCanvasCloneIndex++)})}function cloneCanvasContents(t,e){[].slice.call(t.querySelectorAll("["+html2canvasCanvasCloneAttribute+"]"),0).forEach(function(t){try{var n=e.querySelector("["+html2canvasCanvasCloneAttribute+'="'+t.getAttribute(html2canvasCanvasCloneAttribute)+'"]');n&&(n.width=t.width,n.height=t.height,n.getContext("2d").putImageData(t.getContext("2d").getImageData(0,0,t.width,t.height),0,0))}catch(r){log("Unable to copy canvas content from",t,r)}t.removeAttribute(html2canvasCanvasCloneAttribute)})}function removeScriptNodes(t){return[].slice.call(t.childNodes,0).filter(isElementNode).forEach(function(e){"SCRIPT"===e.tagName?t.removeChild(e):removeScriptNodes(e)}),t}function isElementNode(t){return t.nodeType===Node.ELEMENT_NODE}function absoluteUrl(t){var e=document.createElement("a");return e.href=t,e.href=e.href,e}function DummyImageContainer(t){var e;log("DummyImageContainer for",this.src=t),this.promise&&this.image||(log("Initiating DummyImageContainer"),DummyImageContainer.prototype.image=new Image,e=this.image,DummyImageContainer.prototype.promise=new Promise(function(t,n){e.onload=t,e.onerror=n,e.src=smallImage(),!0===e.complete&&t(e)}))}function Font(t,e){var i=document.createElement("div"),o=document.createElement("img"),s=document.createElement("span"),a="Hidden Text";i.style.visibility="hidden",i.style.fontFamily=t,i.style.fontSize=e,i.style.margin=0,i.style.padding=0,document.body.appendChild(i),o.src=smallImage(),o.width=1,o.height=1,o.style.margin=0,o.style.padding=0,o.style.verticalAlign="baseline",s.style.fontFamily=t,s.style.fontSize=e,s.style.margin=0,s.style.padding=0,s.appendChild(document.createTextNode(a)),i.appendChild(s),i.appendChild(o),t=o.offsetTop-s.offsetTop+1,i.removeChild(s),i.appendChild(document.createTextNode(a)),i.style.lineHeight="normal",o.style.verticalAlign="super",e=o.offsetTop-i.offsetTop+1,document.body.removeChild(i),this.baseline=t,this.lineWidth=1,this.middle=e}function FontMetrics(){this.data={}}function FrameContainer(t,e,n){this.image=null,this.src=t;var r=this,i=getBounds(t);this.promise=(e?new Promise(function(e){"about:blank"===t.contentWindow.document.URL||null==t.contentWindow.document.documentElement?t.contentWindow.onload=t.onload=function(){e(t)}:e(t)}):this.proxyLoad(n.proxy,i,n)).then(function(t){return html2canvas(t.contentWindow.document.documentElement,{type:"view",width:t.width,height:t.height,proxy:n.proxy,javascriptEnabled:n.javascriptEnabled,removeContainer:n.removeContainer,allowTaint:n.allowTaint,imageTimeout:n.imageTimeout/2})}).then(function(t){return r.image=t})}function GradientContainer(t){this.src=t.value,this.colorStops=[],this.type=null,this.x0=.5,this.y0=.5,this.x1=.5,this.y1=.5,this.promise=Promise.resolve(!0)}function ImageContainer(t,e){this.src=t,this.image=new Image;var n=this;this.tainted=null,this.promise=new Promise(function(r,i){n.image.onload=r,n.image.onerror=i,e&&(n.image.crossOrigin="anonymous"),n.image.src=t,!0===n.image.complete&&r(n.image)})}function ImageLoader(t,e){this.link=null,this.options=t,this.support=e,this.origin=this.getOrigin(window.location.href)}function LinearGradientContainer(t){GradientContainer.apply(this,arguments),this.type=this.TYPES.LINEAR;var e=null===t.args[0].match(this.stepRegExp);e?t.args[0].split(" ").reverse().forEach(function(t){switch(t){case"left":this.x0=0,this.x1=1;break;case"top":this.y0=0,this.y1=1;break;case"right":this.x0=1,this.x1=0;break;case"bottom":this.y0=1,this.y1=0;break;case"to":var e=this.y0,n=this.x0;this.y0=this.y1,this.x0=this.x1,this.x1=n,this.y1=e}},this):(this.y0=0,this.y1=1),this.colorStops=t.args.slice(e?1:0).map(function(t){t=t.match(this.stepRegExp);return{color:t[1],stop:"%"===t[3]?t[2]/100:null}},this),null===this.colorStops[0].stop&&(this.colorStops[0].stop=0),null===this.colorStops[this.colorStops.length-1].stop&&(this.colorStops[this.colorStops.length-1].stop=1),this.colorStops.forEach(function(t,e){null===t.stop&&this.colorStops.slice(e).some(function(n,r){return null!==n.stop&&(t.stop=(n.stop-this.colorStops[e-1].stop)/(r+1)+this.colorStops[e-1].stop,!0)},this)},this)}function log(){window.html2canvas.logging&&window.console&&window.console.log&&Function.prototype.bind.call(window.console.log,window.console).apply(window.console,[Date.now()-window.html2canvas.start+"ms","html2canvas:"].concat([].slice.call(arguments,0)))}function NodeContainer(t,e){this.node=t,this.parent=e,this.stack=null,this.bounds=null,this.borders=null,this.clip=[],this.backgroundClip=[],this.offsetBounds=null,this.visible=null,this.computedStyles=null,this.styles={},this.backgroundImages=null,this.transformData=null,this.transformMatrix=null,this.isPseudoElement=!1,this.opacity=null}function selectionValue(t){t=t.options[t.selectedIndex||0];return t&&t.text||""}function parseMatrix(t){return t&&"matrix"===t[1]?t[2].split(",").map(function(t){return parseFloat(t.trim())}):void 0}function isPercentage(t){return-1!==t.toString().indexOf("%")}function parseBackgrounds(t){function d(){e&&((n='"'===n.substr(0,1)?n.substr(1,n.length-2):n)&&a.push(n),"-"===e.substr(0,1)&&0<(i=e.indexOf("-",1)+1)&&(r=e.substr(0,i),e=e.substr(i)),u.push({prefix:r,method:e.toLowerCase(),value:o,args:a,image:null})),a=[],e=r=n=o=""}var n,r,i,o,s,u=[],l=0,h=0,a=[],e=r=n=o="";return t.split("").forEach(function(t){if(!(0===l&&-1<" \r\n\t".indexOf(t))){switch(t){case'"':s?s===t&&(s=null):s=t;break;case"(":if(!s){if(0===l)return l=1,void(o+=t);h++}break;case")":if(!s&&1===l){if(0===h)return l=0,o+=t,void d();h--}break;case",":if(!s){if(0===l)return void d();if(1===l&&0===h&&!e.match(/^url$/i))return a.push(n),n="",void(o+=t)}}o+=t,0===l?e+=t:n+=t}}),d(),u}function removePx(t){return t.replace("px","")}function asFloat(t){return parseFloat(t)}function getBounds(t){var e,n;return t.getBoundingClientRect?(e=t.getBoundingClientRect(),n=null==t.offsetWidth?e.width:t.offsetWidth,{top:e.top,bottom:e.bottom||e.top+e.height,right:e.left+n,left:e.left,width:n,height:null==t.offsetHeight?e.height:t.offsetHeight}):{}}function offsetBounds(t){var e=t.offsetParent?offsetBounds(t.offsetParent):{top:0,left:0};return{top:t.offsetTop+e.top,bottom:t.offsetTop+t.offsetHeight+e.top,right:t.offsetLeft+e.left+t.offsetWidth,left:t.offsetLeft+e.left,width:t.offsetWidth,height:t.offsetHeight}}function NodeParser(t,e,n,r,i){log("Starting NodeParser"),this.renderer=e,this.options=i,this.range=null,this.support=n,this.renderQueue=[],this.stack=new StackingContext(!0,1,t.ownerDocument,null);var s,n=new NodeContainer(t,null);t===t.ownerDocument.documentElement&&(s=new NodeContainer(this.renderer.isTransparent(n.css("backgroundColor"))?t.ownerDocument.body:t.ownerDocument.documentElement,null),e.rectangle(0,0,e.width,e.height,s.css("backgroundColor"))),n.visibile=n.isElementVisible(),this.createPseudoHideStyles(t.ownerDocument),this.disableAnimations(t.ownerDocument),this.nodes=flatten([n].concat(this.getChildren(n)).filter(function(t){return t.visible=t.isElementVisible()}).map(this.getPseudoElements,this)),this.fontMetrics=new FontMetrics,log("Fetched nodes, total:",this.nodes.length),log("Calculate overflow clips"),this.calculateOverflowClips(),log("Start fetching images"),this.images=r.fetch(this.nodes.filter(isElement)),this.ready=this.images.ready.then(bind(function(){return log("Images loaded, starting parsing"),log("Creating stacking contexts"),this.createStackingContexts(),log("Sorting stacking contexts"),this.sortStackingContexts(this.stack),this.parse(this.stack),log("Render queue created with "+this.renderQueue.length+" items"),new Promise(bind(function(t){i.async?"function"==typeof i.async?i.async.call(this,this.renderQueue,t):0<this.renderQueue.length?(this.renderIndex=0,this.asyncRenderer(this.renderQueue,t)):t():(this.renderQueue.forEach(this.paint,this),t())},this))},this))}function hasParentClip(t){return t.parent&&t.parent.clip.length}function toCamelCase(t){return t.replace(/(\-[a-z])/g,function(t){return t.toUpperCase().replace("-","")})}function ClearTransform(){}function calculateBorders(t,e,n,r){return t.map(function(i,o){if(0<i.width){var s=e.left,a=e.top,c=e.width,u=e.height-t[2].width;switch(o){case 0:u=t[0].width,i.args=drawSide({c1:[s,a],c2:[s+c,a],c3:[s+c-t[1].width,a+u],c4:[s+t[3].width,a+u]},r[0],r[1],n.topLeftOuter,n.topLeftInner,n.topRightOuter,n.topRightInner);break;case 1:s=e.left+e.width-t[1].width,c=t[1].width,i.args=drawSide({c1:[s+c,a],c2:[s+c,a+u+t[2].width],c3:[s,a+u],c4:[s,a+t[0].width]},r[1],r[2],n.topRightOuter,n.topRightInner,n.bottomRightOuter,n.bottomRightInner);break;case 2:a=a+e.height-t[2].width,u=t[2].width,i.args=drawSide({c1:[s+c,a+u],c2:[s,a+u],c3:[s+t[3].width,a],c4:[s+c-t[3].width,a]},r[2],r[3],n.bottomRightOuter,n.bottomRightInner,n.bottomLeftOuter,n.bottomLeftInner);break;case 3:c=t[3].width,i.args=drawSide({c1:[s,a+u+t[2].width],c2:[s,a],c3:[s+c,a+t[0].width],c4:[s+c,a+u]},r[3],r[0],n.bottomLeftOuter,n.bottomLeftInner,n.topLeftOuter,n.topLeftInner)}}return i})}function getCurvePoints(t,e,n,r){var i=(Math.sqrt(2)-1)/3*4,o=n*i,i=r*i,n=t+n,r=e+r;return{topLeft:bezierCurve({x:t,y:r},{x:t,y:r-i},{x:n-o,y:e},{x:n,y:e}),topRight:bezierCurve({x:t,y:e},{x:t+o,y:e},{x:n,y:r-i},{x:n,y:r}),bottomRight:bezierCurve({x:n,y:e},{x:n,y:e+i},{x:t+o,y:r},{x:t,y:r}),bottomLeft:bezierCurve({x:n,y:r},{x:n-o,y:r},{x:t,y:e+i},{x:t,y:e})}}function calculateCurvePoints(t,e,n){var r=t.left,i=t.top,o=t.width,t=t.height,a=e[0][0],c=e[0][1],u=e[1][0],l=e[1][1],h=e[2][0],d=e[2][1],f=e[3][0],e=e[3][1],m=o-u,g=t-d,w=o-h,y=t-e;return{topLeftOuter:getCurvePoints(r,i,a,c).topLeft.subdivide(.5),topLeftInner:getCurvePoints(r+n[3].width,i+n[0].width,Math.max(0,a-n[3].width),Math.max(0,c-n[0].width)).topLeft.subdivide(.5),topRightOuter:getCurvePoints(r+m,i,u,l).topRight.subdivide(.5),topRightInner:getCurvePoints(r+Math.min(m,o+n[3].width),i+n[0].width,m>o+n[3].width?0:u-n[3].width,l-n[0].width).topRight.subdivide(.5),bottomRightOuter:getCurvePoints(r+w,i+g,h,d).bottomRight.subdivide(.5),bottomRightInner:getCurvePoints(r+Math.min(w,o-n[3].width),i+Math.min(g,t+n[0].width),Math.max(0,h-n[1].width),d-n[2].width).bottomRight.subdivide(.5),bottomLeftOuter:getCurvePoints(r,i+y,f,e).bottomLeft.subdivide(.5),bottomLeftInner:getCurvePoints(r+n[3].width,i+y,Math.max(0,f-n[3].width),e-n[2].width).bottomLeft.subdivide(.5)}}function bezierCurve(t,e,n,r){function i(t,e,n){return{x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}}return{start:t,startControl:e,endControl:n,end:r,subdivide:function(o){var s=i(t,e,o),a=i(e,n,o),c=i(n,r,o),u=i(s,a,o),a=i(a,c,o),o=i(u,a,o);return[bezierCurve(t,s,u,o),bezierCurve(o,a,c,r)]},curveTo:function(t){t.push(["bezierCurve",e.x,e.y,n.x,n.y,r.x,r.y])},curveToReversed:function(r){r.push(["bezierCurve",n.x,n.y,e.x,e.y,t.x,t.y])}}}function drawSide(t,e,n,r,i,o,s){var a=[];return 0<e[0]||0<e[1]?(a.push(["line",r[1].start.x,r[1].start.y]),r[1].curveTo(a)):a.push(["line",t.c1[0],t.c1[1]]),0<n[0]||0<n[1]?(a.push(["line",o[0].start.x,o[0].start.y]),o[0].curveTo(a),a.push(["line",s[0].end.x,s[0].end.y]),s[0].curveToReversed(a)):(a.push(["line",t.c2[0],t.c2[1]]),a.push(["line",t.c3[0],t.c3[1]])),0<e[0]||0<e[1]?(a.push(["line",i[1].end.x,i[1].end.y]),i[1].curveToReversed(a)):a.push(["line",t.c4[0],t.c4[1]]),a}function parseCorner(t,e,n,r,i,o,s){0<e[0]||0<e[1]?(t.push(["line",r[0].start.x,r[0].start.y]),r[0].curveTo(t),r[1].curveTo(t)):t.push(["line",o,s]),(0<n[0]||0<n[1])&&t.push(["line",i[0].start.x,i[0].start.y])}function negativeZIndex(t){return t.cssInt("zIndex")<0}function positiveZIndex(t){return 0<t.cssInt("zIndex")}function zIndex0(t){return 0===t.cssInt("zIndex")}function inlineLevel(t){return-1!==["inline","inline-block","inline-table"].indexOf(t.css("display"))}function isStackingContext(t){return t instanceof StackingContext}function hasText(t){return 0<t.node.data.trim().length}function noLetterSpacing(t){return/^(normal|none|0px)$/.test(t.parent.css("letterSpacing"))}function getBorderRadiusData(t){return["TopLeft","TopRight","BottomRight","BottomLeft"].map(function(e){e=t.css("border"+e+"Radius").split(" ");return e.length<=1&&(e[1]=e[0]),e.map(asInt)})}function renderableNode(t){return t.nodeType===Node.TEXT_NODE||t.nodeType===Node.ELEMENT_NODE}function isPositionedForStacking(t){var e=t.css("position");return"auto"!==(-1!==["absolute","relative","fixed"].indexOf(e)?t.css("zIndex"):"auto")}function isPositioned(t){return"static"!==t.css("position")}function isFloating(t){return"none"!==t.css("float")}function isInlineBlock(t){return-1!==["inline-block","inline-table"].indexOf(t.css("display"))}function not(t){var e=this;return function(){return!t.apply(e,arguments)}}function isElement(t){return t.node.nodeType===Node.ELEMENT_NODE}function isPseudoElement(t){return!0===t.isPseudoElement}function isTextNode(t){return t.node.nodeType===Node.TEXT_NODE}function zIndexSort(t){return function(e,n){return e.cssInt("zIndex")+t.indexOf(e)/t.length-(n.cssInt("zIndex")+t.indexOf(n)/t.length)}}function hasOpacity(t){return t.getOpacity()<1}function bind(t,e){return function(){return t.apply(e,arguments)}}function asInt(t){return parseInt(t,10)}function getWidth(t){return t.width}function nonIgnoredElement(t){return t.node.nodeType!==Node.ELEMENT_NODE||-1===["SCRIPT","HEAD","TITLE","OBJECT","BR","OPTION"].indexOf(t.node.nodeName)}function flatten(t){return[].concat.apply([],t)}function stripQuotes(t){var e=t.substr(0,1);return e===t.substr(t.length-1)&&e.match(/'|"/)?t.substr(1,t.length-2):t}function getWords(t){for(var e,n=[],r=0,i=!1;t.length;)isWordBoundary(t[r])===i?((e=t.splice(0,r)).length&&n.push(window.html2canvas.punycode.ucs2.encode(e)),i=!i,r=0):r++,r>=t.length&&(e=t.splice(0,r)).length&&n.push(window.html2canvas.punycode.ucs2.encode(e));return n}function isWordBoundary(t){return-1!==[32,13,10,9,45].indexOf(t)}function hasUnicode(t){return/[^\u0000-\u00ff]/.test(t)}function Proxy(t,e,n){var r=createCallback(supportsCORS),e=createProxyUrl(e,t,r);return supportsCORS?XHR(e):jsonp(n,e,r).then(function(t){return decode64(t.content)})}function ProxyURL(t,e,n){var r=createCallback(supportsCORSImage),e=createProxyUrl(e,t,r);return supportsCORSImage?Promise.resolve(e):jsonp(n,e,r).then(function(t){return"data:"+t.type+";base64,"+t.content})}function jsonp(t,e,n){return new Promise(function(r,i){function s(){delete window.html2canvas.proxy[n],t.body.removeChild(o)}var o=t.createElement("script");window.html2canvas.proxy[n]=function(t){s(),r(t)},o.src=e,o.onerror=function(t){s(),i(t)},t.body.appendChild(o)})}function createCallback(t){return t?"":"html2canvas_"+Date.now()+"_"+ ++proxyCount+"_"+Math.round(1e5*Math.random())}function createProxyUrl(t,e,n){return t+"?url="+encodeURIComponent(e)+(n.length?"&callback=html2canvas.proxy."+n:"")}function ProxyImageContainer(t,e){document.createElement("script");var n=document.createElement("a"),r=(n.href=t,t=n.href,this.src=t,this.image=new Image,this);this.promise=new Promise(function(n,i){r.image.crossOrigin="Anonymous",r.image.onload=n,r.image.onerror=i,new ProxyURL(t,e,document).then(function(t){r.image.src=t}).catch(i)})}function PseudoElementContainer(t,e,n){NodeContainer.call(this,t,e),this.isPseudoElement=!0,this.before=":before"===n}function Renderer(t,e,n,r,i){this.width=t,this.height=e,this.images=n,this.options=r,this.document=i}function StackingContext(t,e,n,r){NodeContainer.call(this,n,r),this.ownStacking=t,this.contexts=[],this.children=[],this.opacity=(this.parent?this.parent.stack.opacity:1)*e}function Support(t){this.rangeBounds=this.testRangeBounds(t),this.cors=this.testCORS(),this.svg=this.testSVG()}function SVGContainer(t){this.src=t,this.image=null;var e=this;this.promise=this.hasFabric().then(function(){return e.isInline(t)?Promise.resolve(e.inlineFormatting(t)):XHR(t)}).then(function(t){return new Promise(function(n){html2canvas.fabric.loadSVGFromString(t,e.createCanvas.call(e,n))})})}function decode64(t){for(var r,o,s,a,c,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=t.length,h="",e=0;e<l;e+=4)s=u.indexOf(t[e])<<2|(r=u.indexOf(t[e+1]))>>4,a=(15&r)<<4|(r=u.indexOf(t[e+2]))>>2,c=(3&r)<<6|(o=u.indexOf(t[e+3])),h+=64===r?String.fromCharCode(s):64===o||-1===o?String.fromCharCode(s,a):String.fromCharCode(s,a,c);return h}function SVGNodeContainer(t,e){this.src=t,this.image=null;var n=this;this.promise=e?new Promise(function(e,r){n.image=new Image,n.image.onload=e,n.image.onerror=r,n.image.src="data:image/svg+xml,"+(new XMLSerializer).serializeToString(t),!0===n.image.complete&&e(n.image)}):this.hasFabric().then(function(){return new Promise(function(e){html2canvas.fabric.parseSVGDocument(t,n.createCanvas.call(n,e))})})}function TextContainer(t,e){NodeContainer.call(this,t,e)}function capitalize(t,e,n){return 0<t.length?e+n.toUpperCase():void 0}function WebkitGradientContainer(t){GradientContainer.apply(this,arguments),this.type="linear"===t.args[0]?this.TYPES.LINEAR:this.TYPES.RADIAL}function XHR(t){return new Promise(function(e,n){var r=new XMLHttpRequest;r.open("GET",t),r.onload=function(){200===r.status?e(r.responseText):n(new Error(r.statusText))},r.onerror=function(){n(new Error("Network Error"))},r.send()})}function html2pdf(t,e,n){var i,o,r=e.canvas;if(!r)return alert("jsPDF canvas plugin not installed");(r.pdf=e).annotations={_nameMap:[],createAnnotation:function(t,n){var i=e.context2d._wrapX(n.left),o=e.context2d._wrapY(n.top),s=(e.context2d._page(n.top),t.indexOf("#")),s=0<=s?{name:t.substring(s+1)}:{url:t};e.link(i,o,n.right-n.left,n.bottom-n.top,s)},setName:function(t,n){var r=e.context2d._wrapX(n.left),i=e.context2d._wrapY(n.top),n=e.context2d._page(n.top);this._nameMap[t]={page:n,x:r,y:i}}},r.annotations=e.annotations,e.context2d._pageBreakAt=function(t){this.pageBreaks.push(t)},e.context2d._gotoPage=function(t){for(;e.internal.getNumberOfPages()<t;)e.addPage();e.setPage(t)},"string"==typeof t?(t=t.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,""),i=document.createElement("iframe"),document.body.appendChild(i),(o=null==(o=i.contentDocument)?i.contentWindow.document:o).open(),o.write(t),o.close(),html2canvas(o.body,{canvas:r,onrendered:function(){n&&(i&&i.parentElement.removeChild(i),n(e))}})):html2canvas(t,{canvas:r,onrendered:function(){n&&(i&&i.parentElement.removeChild(i),n(e))}})}global.true=exports;var jsPDF=function(t){"use strict";function e(e){var n={};this.subscribe=function(t,e,r){if("function"!=typeof e)return!1;n.hasOwnProperty(t)||(n[t]={});var i=Math.random().toString(35);return n[t][i]=[e,!!r],i},this.unsubscribe=function(t){for(var e in n)if(n[e][t])return delete n[e][t],!0;return!1},this.publish=function(r){if(n.hasOwnProperty(r)){var s,i=Array.prototype.slice.call(arguments,1),o=[];for(s in n[r]){var a=n[r][s];try{a[0].apply(e,i)}catch(c){t.console&&console.error("jsPDF PubSub Error",c.message,c)}a[1]&&o.push(s)}o.length&&o.forEach(this.unsubscribe)}}}function n(s,a,c,u){var l={};"object"==typeof s&&(s=(l=s).orientation,a=l.unit||a,c=l.format||c,u=l.compress||l.compressPdf||u),a=a||"mm",c=c||"a4",s=(""+(s||"P")).toLowerCase();function W(t){return t.toFixed(3)}function Z(){var e,r,i,u,l,c=t.adler32cs||n.adler32cs;for(b&&void 0===c&&(b=!1),e=1;e<=A;e++){if(X(),u=(m=N[e].width)*d,l=(g=N[e].height)*d,G("<</Type /Page"),G("/Parent 1 0 R"),G("/Resources 2 0 R"),G("/MediaBox [0 0 "+H(u)+" "+H(l)+"]"),G("/Contents "+(T+1)+" 0 R"),U.publish("putPage",{pageNumber:e,page:O[e]}),G(">>"),G("endobj"),r=O[e].join("\n"),X(),b){for(i=[],o=r.length;o--;)i[o]=r.charCodeAt(o);u=c.from(r),(l=new Deflater(6)).append(new Uint8Array(i)),r=l.flush(),(i=new Uint8Array(r.length+6)).set(new Uint8Array([120,156])),i.set(r,2),i.set(new Uint8Array([255&u,u>>8&255,u>>16&255,u>>24&255]),r.length+2),r=String.fromCharCode.apply(null,i),G("<</Length "+r.length+" /Filter [/FlateDecode]>>")}else G("<</Length "+r.length+">>");$(r),G("endobj")}q[1]=M,G("1 0 obj"),G("<</Type /Pages");for(var h="/Kids [",o=0;o<A;o++)h+=3+2*o+" 0 R ";G(h+"]"),G("/Count "+A),G(">>"),G("endobj")}function oe(t,e,n){P.hasOwnProperty(e)||(P[e]={}),P[e][n]=t}function se(t,e,n,r){var i="F"+(Object.keys(I).length+1).toString(10),t=I[i]={id:i,PostScriptName:t,fontName:e,fontStyle:n,encoding:r,metadata:{}};return oe(i,e,n),U.publish("addFont",t),i}function he(){for(var t in G("/Producer (jsPDF "+n.version+")"),j)j.hasOwnProperty(t)&&j[t]&&G("/"+t.substr(0,1).toUpperCase()+t.substr(1)+" ("+le(j[t])+")");var e=new Date,i=(r=e.getTimezoneOffset())<0?"+":"-",o=Math.floor(Math.abs(r/60)),r=Math.abs(r%60),i=[i,V(o),"'",V(r),"'"].join("");G(["/CreationDate (D:",e.getFullYear(),V(e.getMonth()+1),V(e.getDate()),V(e.getHours()),V(e.getMinutes()),V(e.getSeconds()),i,")"].join(""))}function me(){(function(t,e){var r,n="string"==typeof e&&e.toLowerCase();if("string"==typeof t&&(r=t.toLowerCase(),o.hasOwnProperty(r))&&(t=o[r][0]/d,e=o[r][1]/d),Array.isArray(t)&&(e=t[1],t=t[0]),n){switch(n.substr(0,1)){case"l":t<e&&(n="s");break;case"p":e<t&&(n="s")}"s"===n&&(f=t,t=e,e=f)}_=!0,O[++A]=[],N[A]={width:Number(t)||m,height:Number(e)||g},R[A]={},we(A)}).apply(this,arguments),G(H(S*d)+" w"),G(k),0!==L&&G(L+" J"),0!==F&&G(F+" j"),U.publish("addPage",{pageNumber:A})}function ye(t,e){var n;switch(t=void 0!==t?t:I[h].fontName,e=void 0!==e?e:I[h].fontStyle,t=void 0!==t?t.toLowerCase():t){case"sans-serif":case"verdana":case"arial":t="helvetica";break;case"fixed":case"monospace":case"terminal":t="courier";break;default:t="times"}try{n=P[t][e]}catch(r){}return n||null==(n=P.times[e])&&(n=P.times.normal),n}function be(t){var e="S";return"F"===t?e="f":"FD"===t||"DF"===t?e="B":"f"!==t&&"f*"!==t&&"B"!==t&&"B*"!==t||(e=t),e}function xe(){for(var t=ve(),e=t.length,n=new ArrayBuffer(e),r=new Uint8Array(n);e--;)r[e]=t.charCodeAt(e);return n}function ke(){return new Blob([xe()],{type:"application/pdf"})}(""+c).toLowerCase();var h,d,f,p,m,g,w,y,v,Ee,b=!!u&&"function"==typeof Uint8Array,x=l.textColor||"0 g",k=l.drawColor||"0 G",C=l.fontSize||16,E=l.lineHeight||1.15,S=l.lineWidth||.200025,T=2,_=!1,q=[],I={},P={},A=0,O=[],R=[],N=[],B=[],D=[],L=0,F=0,M=0,j={title:"",subject:"",author:"",keywords:"",creator:""},z={},U=new e(z),H=function(t){return t.toFixed(2)},V=function(t){return("0"+parseInt(t)).slice(-2)},G=function(t){(_?O[p]:(M+=t.length+1,B)).push(t)},X=function(){return q[++T]=M,G(T+" 0 obj"),T},$=function(t){G("stream"),G(t),G("endstream")},te=function(){for(var t in I)I.hasOwnProperty(t)&&function(t){t.objectNumber=X(),G("<</BaseFont/"+t.PostScriptName+"/Type/Font"),"string"==typeof t.encoding&&G("/Encoding/"+t.encoding),G("/Subtype/Type1>>"),G("endobj")}(I[t])},ne=function(){for(var t in G("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),G("/Font <<"),I)I.hasOwnProperty(t)&&G("/"+t+" "+I[t].objectNumber+" 0 R");G(">>"),G("/XObject <<"),U.publish("putXobjectDict"),G(">>")},le=function(t,e){return function(t,e){var n,r,a,c,u,l,i=(e=e||{}).sourceEncoding||"Unicode",s=e.outputEncoding;if((e.autoencode||s)&&I[h].metadata&&I[h].metadata[i]&&I[h].metadata[i].encoding&&(i=I[h].metadata[i].encoding,s="string"==typeof(s=!(s=!s&&I[h].encoding?I[h].encoding:s)&&i.codePages?i.codePages[0]:s)?i[s]:s)){for(c=!1,a=[],n=0,r=t.length;n<r;n++)u=s[t.charCodeAt(n)],a.push(u?String.fromCharCode(u):t[n]),a[n].charCodeAt(0)>>8&&(c=!0);t=a.join("")}for(n=t.length;void 0===c&&0!==n;)t.charCodeAt(n-1)>>8&&(c=!0),n--;if(!c)return t;for(a=e.noBOM?[]:[254,255],n=0,r=t.length;n<r;n++){if((l=(u=t.charCodeAt(n))>>8)>>8)throw new Error("Character at position "+n+" of string '"+t+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");a.push(l),a.push(u-(l<<8))}return String.fromCharCode.apply(void 0,a)}(t,e).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},we=function(t){0<t&&t<=A&&(m=N[p=t].width,g=N[t].height)},ve=function(){_=!1,T=2,B=[],q=[],D=[],G("%PDF-1.3"),Z(),function(){U.publish("putAdditionalObjects");for(var t=0;t<D.length;t++){var e=D[t];q[e.objId]=M,G(e.objId+" 0 obj"),G(e.content),G("endobj")}T+=D.length,U.publish("postPutAdditionalObjects")}(),te(),U.publish("putResources"),q[2]=M,G("2 0 obj"),G("<<"),ne(),G(">>"),G("endobj"),U.publish("postPutResources"),X(),G("<<"),he(),G(">>"),G("endobj"),X(),G("<<"),function(){switch(G("/Type /Catalog"),G("/Pages 1 0 R"),y=y||"fullwidth"){case"fullwidth":G("/OpenAction [3 0 R /FitH null]");break;case"fullheight":G("/OpenAction [3 0 R /FitV null]");break;case"fullpage":G("/OpenAction [3 0 R /Fit]");break;case"original":G("/OpenAction [3 0 R /XYZ null null 1]");break;default:var t=""+y;"number"==typeof(y="%"===t.substr(t.length-1)?parseInt(y)/100:y)&&G("/OpenAction [3 0 R /XYZ null null "+H(y)+"]")}switch(v=v||"continuous"){case"continuous":G("/PageLayout /OneColumn");break;case"single":G("/PageLayout /SinglePage");break;case"two":case"twoleft":G("/PageLayout /TwoColumnLeft");break;case"tworight":G("/PageLayout /TwoColumnRight")}w&&G("/PageMode /"+w),U.publish("putCatalog")}(),G(">>"),G("endobj");var t,e=M,n="0000000000";for(G("xref"),G("0 "+(T+1)),G(n+" 65535 f "),t=1;t<=T;t++){var i=q[t];G("function"==typeof i?(n+q[t]()).slice(-10)+" 00000 n ":(n+q[t]).slice(-10)+" 00000 n ")}return G("trailer"),G("<<"),G("/Size "+(T+1)),G("/Root "+T+" 0 R"),G("/Info "+(T-1)+" 0 R"),G(">>"),G("startxref"),G(e),G("%%EOF"),_=!0,B.join("\n")},Ce=function(e){return e.foo=function(){try{return e.apply(this,arguments)}catch(n){var r=n.stack||"",r="Error in function "+(r=~r.indexOf(" at ")?r.split(" at ")[1]:r).split("\n")[0].split("<")[0]+": "+n.message;if(!t.console)throw new Error(r);t.console.error(r,n),t.alert&&alert(r)}},(e.foo.bar=e).foo}(function(e,n){var r="dataur"===(""+e).substr(0,6)?"data:application/pdf;base64,"+btoa(ve()):0;switch(e){case void 0:return ve();case"save":if(navigator.getUserMedia&&(void 0===t.URL||void 0===t.URL.createObjectURL))return z.output("dataurlnewwindow");saveAs(ke(),n),"function"==typeof saveAs.unload&&t.setTimeout&&setTimeout(saveAs.unload,911);break;case"arraybuffer":return xe();case"blob":return ke();case"bloburi":case"bloburl":return t.URL&&t.URL.createObjectURL(ke())||void 0;case"datauristring":case"dataurlstring":return r;case"dataurlnewwindow":var i=t.open(r);if(i||"undefined"==typeof safari)return i;case"datauri":case"dataurl":return t.document.location.href=r;default:throw new Error('Output type "'+e+'" is not supported.')}});switch(a){case"pt":d=1;break;case"mm":d=72/25.4000508;break;case"cm":d=72/2.54000508;break;case"in":d=72;break;case"px":d=96/72;break;case"pc":case"em":d=12;break;case"ex":d=6;break;default:throw"Invalid unit: "+a}for(Ee in z.internal={pdfEscape:le,getStyle:be,getFont:function(){return I[ye.apply(z,arguments)]},getFontSize:function(){return C},getLineHeight:function(){return C*E},write:function(t){G(1===arguments.length?t:Array.prototype.join.call(arguments," "))},getCoordinateString:function(t){return H(t*d)},getVerticalCoordinateString:function(t){return H((g-t)*d)},collections:{},newObject:X,newAdditionalObject:function(){var t=2*O.length+1,t={objId:t+=D.length,content:""};return D.push(t),t},newObjectDeferred:function(){return q[++T]=function(){return M},T},newObjectDeferredBegin:function(t){q[t]=M},putStream:$,events:U,scaleFactor:d,pageSize:{get width(){return m},get height(){return g}},output:function(t,e){return Ce(t,e)},getNumberOfPages:function(){return O.length-1},pages:O,out:G,f2:H,getPageInfo:function(t){return{objId:2*(t-1)+3,pageNumber:t,pageContext:R[t]}},getCurrentPageInfo:function(){return{objId:2*(p-1)+3,pageNumber:p,pageContext:R[p]}}},z.addPage=function(){return me.apply(this,arguments),this},z.setPage=function(){return we.apply(this,arguments),this},z.insertPage=function(t){return this.addPage(),this.movePage(p,t),this},z.movePage=function(t,e){if(e<t){for(var n=O[t],r=N[t],i=R[t],o=t;e<o;o--)O[o]=O[o-1],N[o]=N[o-1],R[o]=R[o-1];O[e]=n,N[e]=r,R[e]=i,this.setPage(e)}else if(t<e){for(n=O[t],r=N[t],i=R[t],o=t;o<e;o++)O[o]=O[o+1],N[o]=N[o+1],R[o]=R[o+1];O[e]=n,N[e]=r,R[e]=i,this.setPage(e)}return this},z.deletePage=function(){return function(t){0<t&&t<=A&&(O.splice(t,1),N.splice(t,1),--A<p&&(p=A),this.setPage(p))}.apply(this,arguments),this},z.setDisplayMode=function(t,e,n){return y=t,v=e,w=n,this},z.text=function(t,e,n,r,o,s){function a(t){return t=t.split("\t").join(Array(l.TabLen||9).join(" ")),le(t,r)}"number"==typeof t&&(f=n,n=e,e=t,t=f),"string"==typeof t&&(t=t.match(/[\n\r]/)?t.split(/\r\n|\r|\n/g):[t]),"string"==typeof o&&(s=o,o=null),"string"==typeof r&&(s=r,r=null),"number"==typeof r&&(o=r,r=null);var u="",p="Td",o=(o&&(o*=Math.PI/180,m=Math.cos(o),o=Math.sin(o),u=[H(m),H(o),H(-1*o),H(m),""].join(" "),p="Tm"),"noBOM"in(r=r||{})||(r.noBOM=!0),"autoencode"in r||(r.autoencode=!0),""),m=this.internal.getCurrentPageInfo().pageContext;if(!0===r.stroke?!0!==m.lastTextWasStroke&&(o="1 Tr\n",m.lastTextWasStroke=!0):(m.lastTextWasStroke&&(o="0 Tr\n"),m.lastTextWasStroke=!1),void 0===this._runningPageHeight&&(this._runningPageHeight=0),"string"==typeof t)t=a(t);else{if(!(t instanceof Array))throw new Error('Type of text must be string or Array. "'+t+'" is not recognized.');for(var b=t.concat(),k=[],S=b.length;S--;)k.push(a(b.shift()));Math.ceil((g-n-this._runningPageHeight)*d/(C*E));if(s){var _,q,P=C*E,A=t.map(function(t){return this.getStringUnitWidth(t)*C/d},this),I=Math.max.apply(Math,A);if("center"===s)_=e-I/2,e-=A[0]/2;else{if("right"!==s)throw new Error('Unrecognized alignment option, use "center" or "right".');_=e-I,e-=A[0]}for(q=e,t=k[0]+") Tj\n",i=1,S=k.length;S>i;i++){var O=I-A[i];"center"===s&&(O/=2),t+=_-q+O+" -"+P+" Td ("+k[i],q=_+O,S-1>i&&(t+=") Tj\n")}}else t=k.join(") Tj\nT* (")}return m=H((g-n)*d),G("BT\n/"+h+" "+C+" Tf\n"+C*E+" TL\n"+o+x+"\n"+u+H(e*d)+" "+m+" "+p+"\n("+t+") Tj\nET"),this},z.lstext=function(t,e,n,r){for(var i=0,o=t.length;i<o;i++,e+=r)this.text(t[i],e,n)},z.line=function(t,e,n,r){return this.lines([[n-t,r-e]],t,e)},z.clip=function(){G("W"),G("S")},z.lines=function(t,e,n,r,i,o){var s,a,c,u,l,h,p,m,w,y,v;for("number"==typeof t&&(f=n,n=e,e=t,t=f),r=r||[1,1],G(W(e*d)+" "+W((g-n)*d)+" m "),s=r[0],a=r[1],u=t.length,y=e,v=n,c=0;c<u;c++)2===(l=t[c]).length?(y=l[0]*s+y,v=l[1]*a+v,G(W(y*d)+" "+W((g-v)*d)+" l")):(h=l[0]*s+y,p=l[1]*a+v,m=l[2]*s+y,w=l[3]*a+v,y=l[4]*s+y,v=l[5]*a+v,G(W(h*d)+" "+W((g-p)*d)+" "+W(m*d)+" "+W((g-w)*d)+" "+W(y*d)+" "+W((g-v)*d)+" c"));return o&&G(" h"),null!==i&&G(be(i)),this},z.rect=function(t,e,n,r,i){return be(i),G([H(t*d),H((g-e)*d),H(n*d),H(-r*d),"re"].join(" ")),null!==i&&G(be(i)),this},z.triangle=function(t,e,n,r,i,o,s){return this.lines([[n-t,r-e],[i-n,o-r],[t-i,e-o]],t,e,[1,1],s,!0),this},z.roundedRect=function(t,e,n,r,i,o,s){var a=4/3*(Math.SQRT2-1);return this.lines([[n-2*i,0],[i*a,0,i,o-o*a,i,o],[0,r-2*o],[0,o*a,-i*a,o,-i,o],[2*i-n,0],[-i*a,0,-i,-o*a,-i,-o],[0,2*o-r],[0,-o*a,i*a,-o,i,-o]],t+i,e,[1,1],s),this},z.ellipse=function(t,e,n,r,i){var o=4/3*(Math.SQRT2-1)*n,s=4/3*(Math.SQRT2-1)*r;return G([H((t+n)*d),H((g-e)*d),"m",H((t+n)*d),H((g-(e-s))*d),H((t+o)*d),H((g-(e-r))*d),H(t*d),H((g-(e-r))*d),"c"].join(" ")),G([H((t-o)*d),H((g-(e-r))*d),H((t-n)*d),H((g-(e-s))*d),H((t-n)*d),H((g-e)*d),"c"].join(" ")),G([H((t-n)*d),H((g-(e+s))*d),H((t-o)*d),H((g-(e+r))*d),H(t*d),H((g-(e+r))*d),"c"].join(" ")),G([H((t+o)*d),H((g-(e+r))*d),H((t+n)*d),H((g-(e+s))*d),H((t+n)*d),H((g-e)*d),"c"].join(" ")),null!==i&&G(be(i)),this},z.circle=function(t,e,n,r){return this.ellipse(t,e,n,n,r)},z.setProperties=function(t){for(var e in j)j.hasOwnProperty(e)&&t[e]&&(j[e]=t[e]);return this},z.setFontSize=function(t){return C=t,this},z.setFont=function(t,e){return h=ye(t,e),this},z.setFontStyle=z.setFontType=function(t){return h=ye(void 0,t),this},z.getFontList=function(){var t,e,n,r={};for(t in P)if(P.hasOwnProperty(t))for(e in r[t]=n=[],P[t])P[t].hasOwnProperty(e)&&n.push(e);return r},z.addFont=function(t,e,n){se(t,e,n,"StandardEncoding")},z.setLineWidth=function(t){return G((t*d).toFixed(2)+" w"),this},z.setDrawColor=function(t,e,n,r){t=void 0===e||void 0===r&&t===e===n?"string"==typeof t?t+" G":H(t/255)+" G":(void 0===r?"string"==typeof t?[t,e,n,"RG"]:[H(t/255),H(e/255),H(n/255),"RG"]:"string"==typeof t?[t,e,n,r,"K"]:[H(t),H(e),H(n),H(r),"K"]).join(" ");return G(t),this},z.setFillColor=function(t,e,n,r){var i;return void 0===e||void 0===r&&t===e===n?i="string"==typeof t?t+" g":H(t/255)+" g":void 0===r||"object"==typeof r?(i=("string"==typeof t?[t,e,n,"rg"]:[H(t/255),H(e/255),H(n/255),"rg"]).join(" "),r&&0===r.a&&(i=["255","255","255","rg"].join(" "))):i=("string"==typeof t?[t,e,n,r,"k"]:[H(t),H(e),H(n),H(r),"k"]).join(" "),G(i),this},z.setTextColor=function(t,e,n){var r;return"string"==typeof t&&/^#[0-9A-Fa-f]{6}$/.test(t)&&(t=(r=parseInt(t.substr(1),16))>>16&255,e=r>>8&255,n=255&r),x=0===t&&0===e&&0===n||void 0===e?W(t/255)+" g":[W(t/255),W(e/255),W(n/255),"rg"].join(" "),this},z.CapJoinStyles={0:0,butt:0,but:0,miter:0,1:1,round:1,rounded:1,circle:1,2:2,projecting:2,project:2,square:2,bevel:2},z.setLineCap=function(t){var e=this.CapJoinStyles[t];if(void 0===e)throw new Error("Line cap style of '"+t+"' is not recognized. See or extend .CapJoinStyles property for valid styles");return G((L=e)+" J"),this},z.setLineJoin=function(t){var e=this.CapJoinStyles[t];if(void 0===e)throw new Error("Line join style of '"+t+"' is not recognized. See or extend .CapJoinStyles property for valid styles");return G((F=e)+" j"),this},z.output=Ce,z.save=function(t){z.output("save",t)},n.API)n.API.hasOwnProperty(Ee)&&("events"===Ee&&n.API.events.length?function(t,e){for(var n,r,i=e.length-1;-1!==i;i--)n=e[i][0],r=e[i][1],t.subscribe.apply(t,[n].concat("function"==typeof r?[r]:r))}(U,n.API.events):z[Ee]=n.API[Ee]);return function(){for(var t="helvetica",e="times",n="courier",r="normal",i="bold",o="italic",s="bolditalic",c=[["Helvetica",t,r],["Helvetica-Bold",t,i],["Helvetica-Oblique",t,o],["Helvetica-BoldOblique",t,s],["Courier",n,r],["Courier-Bold",n,i],["Courier-Oblique",n,o],["Courier-BoldOblique",n,s],["Times-Roman",e,r],["Times-Bold",e,i],["Times-Italic",e,o],["Times-BoldItalic",e,s]],u=0,l=c.length;u<l;u++){var h=se(c[u][0],c[u][1],c[u][2],"StandardEncoding"),d=c[u][0].split("-");oe(h,d[0],d[1]||"")}U.publish("addFonts",{fonts:I,dictionary:P})}(),h="F1",me(c,s),U.publish("initialized"),z}var o={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};return n.API={events:[]},n.version="1.1.253-git 2015-09-10T13:05:bartvandeneijnden","function"==typeof define&&define.amd?define("jsPDF",function(){return n}):void 0!==module&&module.exports?module.exports=n:t.jsPDF=n,n}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this),saveAs=(!function(){"use strict";jsPDF.API.addHTML=function(t,e,n,r,i){if("undefined"==typeof html2canvas&&"undefined"==typeof rasterizeHTML)throw new Error("You need either https://github.com/niklasvh/html2canvas or https://github.com/cburgmer/rasterizeHTML.js");"number"!=typeof e&&(r=e,i=n),"function"==typeof r&&(i=r,r=null);var o=this.internal,s=o.scaleFactor,a=o.pageSize.width,c=o.pageSize.height;return(r=r||{}).onrendered=function(t){e=parseInt(e)||0,n=parseInt(n)||0;var f,o=r.dim||{},u=o.h||0,l=o.w||Math.min(a,t.width/s)-e,h="JPEG";r.format&&(h=r.format),t.height>c&&r.pagesplit?(o=function(){for(var r=0;;){var o=document.createElement("canvas");o.width=Math.min(a*s,t.width),o.height=Math.min(c*s,t.height-r);o.getContext("2d").drawImage(t,0,r,t.width,o.height,0,0,o.width,o.height);var d=[o,e,r?0:n,o.width/s,o.height/s,h,null,"SLOW"];if(this.addImage.apply(this,d),(r+=o.height)>=t.height)break;this.addPage()}i(l,r,null,d)}.bind(this),"CANVAS"===t.nodeName?((f=new Image).onload=o,f.src=t.toDataURL("image/png"),t=f):o()):(f=Math.random().toString(35),o=[t,e,n,l,u,h,f,"SLOW"],this.addImage.apply(this,o),i(l,u,f,o))}.bind(this),"undefined"==typeof html2canvas||r.rstz?"undefined"!=typeof rasterizeHTML?(o="drawDocument","string"==typeof t&&(o=/^http/.test(t)?"drawURL":"drawHTML"),r.width=r.width||a*s,rasterizeHTML[o](t,void 0,r).then(function(t){r.onrendered(t.image)},function(t){i(null,t)})):null:html2canvas(t,r)}}(),function(t){"use strict";function i(){var n,t=this.internal.collections[e+"images"];for(n in t)r.call(this,t[n])}function o(){var t,i,n=this.internal.collections[e+"images"],r=this.internal.write;for(i in n)t=n[i],r("/I"+t.i,t.n,"0","R")}function s(e){return(e=e&&"string"==typeof e?e.toUpperCase():e)in t.image_compression?e:t.image_compression.NONE}function a(){var t=this.internal.collections[e+"images"];return t||(this.internal.collections[e+"images"]=t={},this.internal.events.subscribe("putResources",i),this.internal.events.subscribe("putXobjectDict",o)),t}function l(e){return"string"==typeof e&&t.sHashCode(e)}function d(e){return"function"!=typeof t["process"+e.toUpperCase()]}function f(t){return"object"==typeof t&&1===t.nodeType}function m(t,e){var n;if(e)for(var r in e)if(t===e[r].alias){n=e[r];break}return n}function b(t,e){return t.subarray(e,e+5)}var e="addImage_",n=["jpeg","jpg","png"],r=function(t){var e=this.internal.newObject(),n=this.internal.write,i=this.internal.putStream;if(t.n=e,n("<</Type /XObject"),n("/Subtype /Image"),n("/Width "+t.w),n("/Height "+t.h),t.cs===this.color_spaces.INDEXED?n("/ColorSpace [/Indexed /DeviceRGB "+(t.pal.length/3-1)+" "+("smask"in t?e+2:e+1)+" 0 R]"):(n("/ColorSpace /"+t.cs),t.cs===this.color_spaces.DEVICE_CMYK&&n("/Decode [1 0 1 0 1 0 1 0]")),n("/BitsPerComponent "+t.bpc),"f"in t&&n("/Filter /"+t.f),"dp"in t&&n("/DecodeParms <<"+t.dp+">>"),"trns"in t&&t.trns.constructor==Array){for(var o="",s=0,a=t.trns.length;s<a;s++)o+=t.trns[s]+" "+t.trns[s]+" ";n("/Mask ["+o+"]")}"smask"in t&&n("/SMask "+(e+1)+" 0 R"),n("/Length "+t.data.length+">>"),i(t.data),n("endobj"),"smask"in t&&(e="/Predictor 15 /Colors 1 /BitsPerComponent "+t.bpc+" /Columns "+t.w,e={w:t.w,h:t.h,cs:"DeviceGray",bpc:t.bpc,dp:e,data:t.smask},"f"in t&&(e.f=t.f),r.call(this,e)),t.cs===this.color_spaces.INDEXED&&(this.internal.newObject(),n("<< /Length "+t.pal.length+">>"),i(this.arrayBufferToBinaryString(new Uint8Array(t.pal))),n("endobj"))};t.color_spaces={DEVICE_RGB:"DeviceRGB",DEVICE_GRAY:"DeviceGray",DEVICE_CMYK:"DeviceCMYK",CAL_GREY:"CalGray",CAL_RGB:"CalRGB",LAB:"Lab",ICC_BASED:"ICCBased",INDEXED:"Indexed",PATTERN:"Pattern",SEPERATION:"Seperation",DEVICE_N:"DeviceN"},t.decode={DCT_DECODE:"DCTDecode",FLATE_DECODE:"FlateDecode",LZW_DECODE:"LZWDecode",JPX_DECODE:"JPXDecode",JBIG2_DECODE:"JBIG2Decode",ASCII85_DECODE:"ASCII85Decode",ASCII_HEX_DECODE:"ASCIIHexDecode",RUN_LENGTH_DECODE:"RunLengthDecode",CCITT_FAX_DECODE:"CCITTFaxDecode"},t.image_compression={NONE:"NONE",FAST:"FAST",MEDIUM:"MEDIUM",SLOW:"SLOW"},t.sHashCode=function(t){return Array.prototype.reduce&&t.split("").reduce(function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t},0)},t.isString=function(t){return"string"==typeof t},t.extractInfoFromBase64DataURI=function(t){return/^data:([\w]+?\/([\w]+?));base64,(.+?)$/g.exec(t)},t.supportsArrayBuffer=function(){return"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array},t.isArrayBuffer=function(t){return!!this.supportsArrayBuffer()&&t instanceof ArrayBuffer},t.isArrayBufferView=function(t){return!!this.supportsArrayBuffer()&&"undefined"!=typeof Uint32Array&&(t instanceof Int8Array||t instanceof Uint8Array||"undefined"!=typeof Uint8ClampedArray&&t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array)},t.binaryStringToUint8Array=function(t){for(var e=t.length,n=new Uint8Array(e),r=0;r<e;r++)n[r]=t.charCodeAt(r);return n},t.arrayBufferToBinaryString=function(t){for(var e="",n=(t=this.isArrayBuffer(t)?new Uint8Array(t):t).byteLength,r=0;r<n;r++)e+=String.fromCharCode(t[r]);return e},t.arrayBufferToBase64=function(t){for(var o,s="",a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=new Uint8Array(t),t=c.byteLength,l=t%3,h=t-l,d=0;d<h;d+=3)s+=a[(16515072&(o=c[d]<<16|c[d+1]<<8|c[d+2]))>>18]+a[(258048&o)>>12]+a[(4032&o)>>6]+a[63&o];return 1==l?s+=a[(252&(o=c[h]))>>2]+a[(3&o)<<4]+"==":2==l&&(s+=a[(64512&(o=c[h]<<8|c[1+h]))>>10]+a[(1008&o)>>4]+a[(15&o)<<2]+"="),s},t.createImageInfo=function(t,e,n,r,i,o,s,a,c,u,l,h){a={alias:a,w:e,h:n,cs:r,bpc:i,i:s,data:t};return o&&(a.f=o),c&&(a.dp=c),u&&(a.trns=u),l&&(a.pal=l),h&&(a.smask=h),a},t.addImage=function(t,e,r,i,o,g,y,v,b){if("string"!=typeof e&&(x=g,g=o,o=i,i=r,r=e,e=x),"object"==typeof t&&!f(t)&&"imageData"in t&&(t=(x=t).imageData,e=x.format||e,r=x.x||r||0,i=x.y||i||0,o=x.w||o,g=x.h||g,y=x.alias||y,v=x.compression||v,b=x.rotation||x.angle||b),isNaN(r)||isNaN(i))throw console.error("jsPDF.addImage: Invalid coordinates",arguments),new Error("Invalid coordinates passed to jsPDF.addImage");var C,S,x=a.call(this);if(!(C=m(t,x))&&(f(t)&&(t=function(t,e,n){if("IMG"===t.nodeName&&t.hasAttribute("src")){var r=""+t.getAttribute("src");if(!n&&0===r.indexOf("data:image/"))return r;!e&&/\.png(?:[?#].*)?$/i.test(r)&&(e="png")}if("CANVAS"===t.nodeName)var i=t;else{(i=document.createElement("canvas")).width=t.clientWidth||t.width,i.height=t.clientHeight||t.height;var s,a,c,l,h,d,p,r=i.getContext("2d");if(!r)throw"addImage requires canvas to be supported by browser.";n?(p=Math.PI/180,"object"==typeof n&&(s=n.x,a=n.y,c=n.bg,n=n.angle),n=n*p,p=Math.abs(Math.cos(n)),l=Math.abs(Math.sin(n)),h=i.width,d=i.height,i.width=d*l+h*p,i.height=d*p+h*l,isNaN(s)&&(s=i.width/2),isNaN(a)&&(a=i.height/2),r.clearRect(0,0,i.width,i.height),r.fillStyle=c||"white",r.fillRect(0,0,i.width,i.height),r.save(),r.translate(s,a),r.rotate(n),r.drawImage(t,-h/2,-d/2),r.rotate(-n),r.translate(-s,-a),r.restore()):r.drawImage(t,0,0,i.width,i.height)}return i.toDataURL("png"==(""+e).toLowerCase()?"image/png":"image/jpeg")}(t,e,b)),function(t){return null==t}(y)&&(y=l(t)),!(C=m(y,x)))){if(this.isString(t)&&((b=this.extractInfoFromBase64DataURI(t))?(e=b[2],t=atob(b[3])):137===t.charCodeAt(0)&&80===t.charCodeAt(1)&&78===t.charCodeAt(2)&&71===t.charCodeAt(3)&&(e="png")),function(t){return-1===n.indexOf(t)}(e=(e||"JPEG").toLowerCase()))throw new Error("addImage currently only supports formats "+n+", not '"+e+"'");if(d(e))throw new Error("please ensure that the plugin for '"+e+"' support is added");if(this.supportsArrayBuffer()&&(S=t,t=this.binaryStringToUint8Array(t)),!(C=this["process"+e.toUpperCase()](t,function(t){var e=0;return e=t?Object.keys?Object.keys(t).length:function(t){var n,e=0;for(n in t)t.hasOwnProperty(n)&&e++;return e}(t):e}(x),y,s(v),S)))throw new Error("An unkwown error occurred whilst processing the image")}return function(t,e,n,r,i,o,s){var a=function(t,e,n){return t||e||(e=t=-96),t<0&&(t=-1*n.w*72/t/this.internal.scaleFactor),e<0&&(e=-1*n.h*72/e/this.internal.scaleFactor),[t=0===t?e*n.w/n.h:t,e=0===e?t*n.h/n.w:e]}.call(this,n,r,i),c=this.internal.getCoordinateString,u=this.internal.getVerticalCoordinateString;n=a[0],r=a[1],s[o]=i,this.internal.write("q",c(n),"0 0",c(r),c(t),u(e+r),"cm /I"+i.i,"Do Q")}.call(this,r,i,o,g,C,C.i,x),this};t.processJPEG=function(t,e,n,r,i){var o,s=this.color_spaces.DEVICE_RGB,a=this.decode.DCT_DECODE;return this.isString(t)?(o=function(t){var n;if(255===!t.charCodeAt(0)||216===!t.charCodeAt(1)||255===!t.charCodeAt(2)||224===!t.charCodeAt(3)||!t.charCodeAt(6)==="J".charCodeAt(0)||!t.charCodeAt(7)==="F".charCodeAt(0)||!t.charCodeAt(8)==="I".charCodeAt(0)||!t.charCodeAt(9)==="F".charCodeAt(0)||0===!t.charCodeAt(10))throw new Error("getJpegSize requires a binary string jpeg file");for(var i=256*t.charCodeAt(4)+t.charCodeAt(5),o=4,s=t.length;o<s;){if(o+=i,255!==t.charCodeAt(o))throw new Error("getJpegSize could not find the size of the image");if(192===t.charCodeAt(o+1)||193===t.charCodeAt(o+1)||194===t.charCodeAt(o+1)||195===t.charCodeAt(o+1)||196===t.charCodeAt(o+1)||197===t.charCodeAt(o+1)||198===t.charCodeAt(o+1)||199===t.charCodeAt(o+1))return n=256*t.charCodeAt(o+5)+t.charCodeAt(o+6),[256*t.charCodeAt(o+7)+t.charCodeAt(o+8),n,t.charCodeAt(o+9)];o+=2,i=256*t.charCodeAt(o)+t.charCodeAt(o+1)}}(t),this.createImageInfo(t,o[0],o[1],1==o[3]?this.color_spaces.DEVICE_GRAY:s,8,a,e,n)):(this.isArrayBuffer(t)&&(t=new Uint8Array(t)),this.isArrayBufferView(t)?(o=function(t){if(65496!=(t[0]<<8|t[1]))throw new Error("Supplied data is not a JPEG");for(var n,s=t.length,a=(t[4]<<8)+t[5],c=4;c<s;){if(a=((n=b(t,c+=a))[2]<<8)+n[3],(192===n[1]||194===n[1])&&255===n[0]&&7<a)return{width:((n=b(t,c+5))[2]<<8)+n[3],height:(n[0]<<8)+n[1],numcomponents:n[4]};c+=2}throw new Error("getJpegSizeFromBytes could not find the size of the image")}(t),t=i||this.arrayBufferToBinaryString(t),this.createImageInfo(t,o.width,o.height,1==o.numcomponents?this.color_spaces.DEVICE_GRAY:s,8,a,e,n)):null)},t.processJPG=function(){return this.processJPEG.apply(this,arguments)}}(jsPDF.API),function(t){"use strict";var e={annotations:[],f2:function(t){return t.toFixed(2)},notEmpty:function(t){return void 0!==t&&""!=t||void 0}};jsPDF.API.annotationPlugin=e,jsPDF.API.events.push(["addPage",function(t){this.annotationPlugin.annotations[t.pageNumber]=[]}]),t.events.push(["putPage",function(t){for(var n=this.annotationPlugin.annotations[t.pageNumber],r=!1,i=0;i<n.length&&!r;i++)switch((o=n[i]).type){case"link":if(e.notEmpty(o.options.url)||e.notEmpty(o.options.pageNumber)){r=!0;break}case"text":case"freetext":r=!0}if(0!=r){this.internal.write("/Annots [");for(var o,s=this.annotationPlugin.f2,a=this.internal.scaleFactor,c=this.internal.pageSize.height,u=this.internal.getPageInfo(t.pageNumber),i=0;i<n.length;i++)switch((o=n[i]).type){case"text":var l=this.internal.newAdditionalObject(),h=this.internal.newAdditionalObject(),d=o.title||"Note",y="<</Type /Annot /Subtype /Text "+(f="/Rect ["+s(o.bounds.x*a)+" "+s(c-(o.bounds.y+o.bounds.h)*a)+" "+s((o.bounds.x+o.bounds.w)*a)+" "+s((c-o.bounds.y)*a)+"] ")+"/Contents ("+o.contents+")",d=(y=(y+=" /Popup "+h.objId+" 0 R")+(" /P "+u.objId+" 0 R")+(" /T ("+d+") >>"),l.content=y,l.objId+" 0 R");y="<</Type /Annot /Subtype /Popup "+(f="/Rect ["+s((o.bounds.x+30)*a)+" "+s(c-(o.bounds.y+o.bounds.h)*a)+" "+s((o.bounds.x+o.bounds.w+30)*a)+" "+s((c-o.bounds.y)*a)+"] ")+" /Parent "+d,o.open&&(y+=" /Open true"),y+=" >>",h.content=y,this.internal.write(l.objId,"0 R",h.objId,"0 R");break;case"freetext":var f="/Rect ["+s(o.bounds.x*a)+" "+s((c-o.bounds.y)*a)+" "+s(o.bounds.x+o.bounds.w*a)+" "+s(c-(o.bounds.y+o.bounds.h)*a)+"] ",d=o.color||"#000000";y="<</Type /Annot /Subtype /FreeText "+f+"/Contents ("+o.contents+")",y=(y+=" /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#"+d+")")+" /Border [0 0 0]"+" >>",this.internal.write(y);break;case"link":o.options.name?(l=this.annotations._nameMap[o.options.name],o.options.pageNumber=l.page,o.options.top=l.y):o.options.top||(o.options.top=0);var f="/Rect ["+s(o.x*a)+" "+s((c-o.y)*a)+" "+s(o.x+o.w*a)+" "+s(c-(o.y+o.h)*a)+"] ",y="";if(o.options.url)y="<</Type /Annot /Subtype /Link "+f+"/Border [0 0 0] /A <</S /URI /URI ("+o.options.url+") >>";else if(o.options.pageNumber)switch(y="<</Type /Annot /Subtype /Link "+f+"/Border [0 0 0] /Dest ["+(t=this.internal.getPageInfo(o.options.pageNumber)).objId+" 0 R",o.options.magFactor=o.options.magFactor||"XYZ",o.options.magFactor){case"Fit":y+=" /Fit]";break;case"FitH":y+=" /FitH "+o.options.top+"]";break;case"FitV":o.options.left=o.options.left||0,y+=" /FitV "+o.options.left+"]";break;default:var v=s((c-o.options.top)*a);o.options.left=o.options.left||0,void 0===o.options.zoom&&(o.options.zoom=0),y+=" /XYZ "+o.options.left+" "+v+" "+o.options.zoom+"]"}""!=y&&(y+=" >>",this.internal.write(y))}this.internal.write("]")}}]),t.createAnnotation=function(t){switch(t.type){case"link":this.link(t.bounds.x,t.bounds.y,t.bounds.w,t.bounds.h,t);break;case"text":case"freetext":this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(t)}},t.link=function(t,e,n,r,i){this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({x:t,y:e,w:n,h:r,options:i,type:"link"})},t.link=function(t,e,n,r,i){this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({x:t,y:e,w:n,h:r,options:i,type:"link"})},t.textWithLink=function(t,e,n,r){var i=this.getTextWidth(t),o=this.internal.getLineHeight();return this.text(t,e,n),this.link(e,(n+=.2*o)-o,i,o,r),i},t.getTextWidth=function(t){var e=this.internal.getFontSize();return this.getStringUnitWidth(t)*e/this.internal.scaleFactor},t.getLineHeight=function(){return this.internal.getLineHeight()}}(jsPDF.API),function(){"use strict";jsPDF.API.autoPrint=function(){var t;return this.internal.events.subscribe("postPutResources",function(){t=this.internal.newObject(),this.internal.write("<< /S/Named /Type/Action /N/Print >>","endobj")}),this.internal.events.subscribe("putCatalog",function(){this.internal.write("/OpenAction "+t+" 0 R")}),this}}(),function(t){"use strict";t.events.push(["initialized",function(){this.canvas.pdf=this}]),t.canvas={getContext:function(){return this.pdf.context2d},style:{}},Object.defineProperty(t.canvas,"width",{get:function(){return this._width},set:function(t){this._width=t,this.getContext("2d").pageWrapX=t+1}}),Object.defineProperty(t.canvas,"height",{get:function(){return this._height},set:function(t){this._height=t,this.getContext("2d").pageWrapY=t+1}})}(jsPDF.API),function(t){"use strict";function u(t,e,n,r,i){a={x:t,y:e,w:n,h:r,ln:i}}function l(){return a}var e,n,r,i,a={x:void 0,y:void 0,w:void 0,h:void 0,ln:void 0},c=1,h={left:0,top:0,bottom:0};t.setHeaderFunction=function(t){i=t},t.getTextDimensions=function(t){e=this.internal.getFont().fontName,n=this.table_font_size||this.internal.getFontSize(),r=this.internal.getFont().fontStyle;var s=19.049976/25.4,o=document.createElement("font");o.id="jsPDFCell";try{o.style.fontStyle=r}catch(a){o.style.fontWeight=r}o.style.fontName=e,o.style.fontSize=n+"pt";try{o.textContent=t}catch(a){o.innerText=t}return document.body.appendChild(o),t={w:(o.offsetWidth+1)*s,h:(o.offsetHeight+1)*s},document.body.removeChild(o),t},t.cellAddPage=function(){var t=this.margins||h;this.addPage(),u(t.left,t.top,void 0,void 0),c+=1},t.cellInitialize=function(){a={x:void 0,y:void 0,w:void 0,h:void 0,ln:void 0},c=1},t.cell=function(t,e,n,r,i,a,c){var f,d=l();if(void 0!==d.ln&&(e=d.ln===a?(t=d.x+d.w,d.y):(f=this.margins||h,d.y+d.h+r+13>=this.internal.pageSize.height-f.bottom&&(this.cellAddPage(),this.printHeaders)&&this.tableHeaderRow&&this.printHeaderRow(a,!0),l().y+l().h)),void 0!==i[0])if(this.printingHeaderRow?this.rect(t,e,n,r,"FD"):this.rect(t,e,n,r),"right"===c){i instanceof Array||(i=[i]);for(var p=0;p<i.length;p++){var m=i[p],g=this.getStringUnitWidth(m)*this.internal.getFontSize();this.text(m,t+n-g-3,e+this.internal.getLineHeight()*(p+1))}}else this.text(i,t+3,e+this.internal.getLineHeight());return u(t,e,n,r,a),this},t.arrayMax=function(t,e){for(var i,o=t[0],n=0,r=t.length;n<r;n+=1)i=t[n],e?-1===e(o,i)&&(o=i):o<i&&(o=i);return o},t.table=function(e,n,r,i,o){if(!r)throw"No data for PDF table";var s,d,f,p,m,w,y,v=[],b=[],x={},k={},C=[],E=[],S=!1,T=!0,_=12,q=h;if(q.width=this.internal.pageSize.width,o&&(!0===o.autoSize&&(S=!0),!1===o.printHeaders&&(T=!1),o.fontSize&&(_=o.fontSize),o.margins)&&(q=o.margins),this.lnMod=0,a={x:void 0,y:void 0,w:void 0,h:void 0,ln:void 0},c=1,this.printHeaders=T,this.margins=q,this.setFontSize(_),this.table_font_size=_,null==i)v=Object.keys(r[0]);else if(i[0]&&"string"!=typeof i[0])for(var u=0,l=i.length;u<l;u+=1)s=i[u],v.push(s.name),b.push(s.prompt),k[s.name]=s.width*(19.049976/25.4);else v=i;if(S)for(y=function(t){return t[s]},u=0,l=v.length;u<l;u+=1){for(x[s=v[u]]=r.map(y),C.push(this.getTextDimensions(b[u]||s).w),m=0,d=(p=x[s]).length;m<d;m+=1)f=p[m],C.push(this.getTextDimensions(f).w);k[s]=t.arrayMax(C),C=[]}if(T){var P=this.calculateLineHeight(v,k,b.length?b:v);for(u=0,l=v.length;u<l;u+=1)s=v[u],E.push([e,n,k[s],P,String(b.length?b[u]:s)]);this.setTableHeaderRow(E),this.printHeaderRow(1,!1)}for(u=0,l=r.length;u<l;u+=1){var g=r[u];for(P=this.calculateLineHeight(v,k,g),m=0,w=v.length;m<w;m+=1)s=v[m],this.cell(e,n,k[s],P,g[s],u+2,s.align)}return this.lastCellPos=a,this.table_x=e,this.table_y=n,this},t.calculateLineHeight=function(t,e,n){for(var i=0,s=0;s<t.length;s++){n[r=t[s]]=this.splitTextToSize(String(n[r]),e[r]-3);var r=this.internal.getLineHeight()*n[r].length+3;i<r&&(i=r)}return i},t.setTableHeaderRow=function(t){this.tableHeaderRow=t},t.printHeaderRow=function(t,e){if(!this.tableHeaderRow)throw"Property tableHeaderRow does not exist.";this.printingHeaderRow=!0,void 0!==i&&(a=i(this,c),u(a[0],a[1],a[2],a[3],-1)),this.setFontStyle("bold");for(var n,a,l=[],o=0,s=this.tableHeaderRow.length;o<s;o+=1)this.setFillColor(200,200,200),n=this.tableHeaderRow[o],e&&(n[1]=this.margins&&this.margins.top||0,l.push(n)),n=[].concat(n),this.cell.apply(this,n.concat(t));0<l.length&&this.setTableHeaderRow(l),this.setFontStyle("normal"),this.printingHeaderRow=!1}}(jsPDF.API),function(t){"use strict";function e(){this.fillStyle="#000000",this.strokeStyle="#000000",this.font="12pt times",this.textBaseline="alphabetic",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this._translate={x:0,y:0},this.copy=function(t){this.fillStyle=t.fillStyle,this.strokeStyle=t.strokeStyle,this.font=t.font,this.lineWidth=t.lineWidth,this.lineJoin=t.lineJoin,this.lineCap=t.lineCap,this.textBaseline=t.textBaseline,this._fontSize=t._fontSize,this._translate={x:t._translate.x,y:t._translate.y}}}t.events.push(["initialized",function(){((this.context2d.pdf=this).context2d.internal.pdf=this).context2d.ctx=new e,this.context2d.ctxStack=[],this.context2d.path=[]}]),t.context2d={pageWrapXEnabled:!1,pageWrapYEnabled:!0,pageWrapX:9999999,pageWrapY:9999999,f2:function(t){return t.toFixed(2)},fillRect:function(t,e,n,r){t=this._wrapX(t),e=this._wrapY(e),this.pdf.rect(t,e,n,r,"f")},strokeRect:function(t,e,n,r){t=this._wrapX(t),e=this._wrapY(e),this.pdf.rect(t,e,n,r,"s")},clearRect:function(t,e,n,r){t=this._wrapX(t),e=this._wrapY(e),this.save(),this.setFillStyle("#ffffff"),this.pdf.rect(t,e,n,r,"f"),this.restore()},save:function(){this.ctx._fontSize=this.pdf.internal.getFontSize();var t=new e;t.copy(this.ctx),this.ctxStack.push(this.ctx),this.ctx=t},restore:function(){this.ctx=this.ctxStack.pop(),this.setFillStyle(this.ctx.fillStyle),this.setStrokeStyle(this.ctx.strokeStyle),this.setFont(this.ctx.font),this.pdf.setFontSize(this.ctx._fontSize),this.setLineCap(this.ctx.lineCap),this.setLineWidth(this.ctx.lineWidth),this.setLineJoin(this.ctx.lineJoin)},beginPath:function(){this.path=[]},closePath:function(){this.path.push({type:"close"})},setFillStyle:function(t){var e,n,r,i,o=this.internal.rxRgb.exec(t);null!=o?(e=parseInt(o[1]),n=parseInt(o[2]),r=parseInt(o[3])):null!=(o=this.internal.rxRgba.exec(t))?(e=parseInt(o[1]),n=parseInt(o[2]),r=parseInt(o[3]),i=parseInt(o[4])):("#"!=t.charAt(0)&&(t=(t=CssColors.colorNameToHex(t))||"#000000"),4===(this.ctx.fillStyle=t).length?(e=this.ctx.fillStyle.substring(1,2),e+=e,n=this.ctx.fillStyle.substring(2,3),n+=n,r=this.ctx.fillStyle.substring(3,4),r+=r):(e=this.ctx.fillStyle.substring(1,3),n=this.ctx.fillStyle.substring(3,5),r=this.ctx.fillStyle.substring(5,7)),e=parseInt(e,16),n=parseInt(n,16),r=parseInt(r,16)),this.pdf.setFillColor(e,n,r,{a:i}),this.pdf.setTextColor(e,n,r,{a:i})},setStrokeStyle:function(t){"#"!=t.charAt(0)&&(t=(t=CssColors.colorNameToHex(t))||"#000000"),this.ctx.strokeStyle=t;var t=this.ctx.strokeStyle.substring(1,3),t=parseInt(t,16),n=this.ctx.strokeStyle.substring(3,5),n=parseInt(n,16),r=this.ctx.strokeStyle.substring(5,7),r=parseInt(r,16);this.pdf.setDrawColor(t,n,r)},fillText:function(t,e,n){e=this._wrapX(e),n=this._wrapY(n),this.pdf.text(t,e,this._getBaseline(n))},strokeText:function(t,e,n){e=this._wrapX(e),n=this._wrapY(n),this.pdf.text(t,e,this._getBaseline(n),{stroke:!0})},setFont:function(t){var o,s,i,c,r,l,n;this.ctx.font=t,null!=(c=/\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+["']?(\w+)['"]?/.exec(t))?(n=c[1],c[2],r=c[3],i=c[4],o=c[5],s=c[6],i=Math.floor("px"!==o&&"em"===o?parseFloat(i)*this.pdf.getFontSize():parseFloat(i)),this.pdf.setFontSize(i),this.pdf.setFontStyle("bold"===r||"700"===r?"bold":"italic"===n?"italic":"normal"),this.pdf.setFont(r=s,l)):null!=(c=/(\d+)(pt|px|em)\s+(\w+)\s*(\w+)?/.exec(t))&&(n=c[1],c[2],r=c[3],l=(l=c[4])||"normal",n=Math.floor("em"===o?parseFloat(i)*this.pdf.getFontSize():parseFloat(n)),this.pdf.setFontSize(n),this.pdf.setFont(r,l))},setTextBaseline:function(t){this.ctx.textBaseline=t},getTextBaseline:function(){return this.ctx.textBaseline},setLineWidth:function(t){this.ctx.lineWidth=t,this.pdf.setLineWidth(t)},setLineCap:function(t){this.ctx.lineCap=t,this.pdf.setLineCap(t)},setLineJoin:function(t){this.ctx.lineJon=t,this.pdf.setLineJoin(t)},moveTo:function(t,e){t=this._wrapX(t),e=this._wrapY(e),this.path.push({type:"mt",x:t,y:e})},_wrapX:function(t){return this.pageWrapXEnabled?t%this.pageWrapX:t},_wrapY:function(t){return this.pageWrapYEnabled?(this._gotoPage(this._page(t)),(t-this.lastBreak)%this.pageWrapY):t},lastBreak:0,pageBreaks:[],_page:function(t){if(this.pageWrapYEnabled){for(var i,e=this.lastBreak=0,n=0,r=0;r<this.pageBreaks.length;r++)t>=this.pageBreaks[r]&&(e++,0===this.lastBreak&&n++,i=this.pageBreaks[r]-this.lastBreak,this.lastBreak=this.pageBreaks[r],n+=Math.floor(i/this.pageWrapY));return 0===this.lastBreak&&(n+=Math.floor(t/this.pageWrapY)+1),n+e}return this.pdf.internal.getCurrentPageInfo().pageNumber},_gotoPage:function(){},lineTo:function(t,e){t=this._wrapX(t),e=this._wrapY(e),this.path.push({type:"lt",x:t,y:e})},bezierCurveTo:function(t,e,n,r,i,o){t=this._wrapX(t),e=this._wrapY(e),n=this._wrapX(n),r=this._wrapY(r),i=this._wrapX(i),o=this._wrapY(o),this.path.push({type:"bct",x1:t,y1:e,x2:n,y2:r,x:i,y:o})},quadraticCurveTo:function(t,e,n,r){t=this._wrapX(t),e=this._wrapY(e),n=this._wrapX(n),r=this._wrapY(r),this.path.push({type:"qct",x1:t,y1:e,x:n,y:r})},arc:function(t,e,n,r,i,o){t=this._wrapX(t),e=this._wrapY(e),this.path.push({type:"arc",x:t,y:e,radius:n,startAngle:r,endAngle:i,anticlockwise:o})},drawImage:function(t,e,n,r,i,o,s,a,c){void 0!==o&&(e=o,n=s,r=a,i=c),e=this._wrapX(e),n=this._wrapY(n);o=/data:image\/(\w+).*/i.exec(t),s=null!=o?o[1]:"png";this.pdf.addImage(t,s,e,n,r,i)},stroke:function(){for(var e=[],n=!1,r=0;r<this.path.length;r++)switch((i=this.path[r]).type){case"mt":void 0!==(t=i)&&(this.pdf.lines(e,t.x,t.y,null,"s"),e=[]);break;case"lt":var o=[i.x-this.path[r-1].x,i.y-this.path[r-1].y];e.push(o);break;case"bct":o=[i.x1-this.path[r-1].x,i.y1-this.path[r-1].y,i.x2-this.path[r-1].x,i.y2-this.path[r-1].y,i.x-this.path[r-1].x,i.y-this.path[r-1].y];e.push(o);break;case"qct":var s=this.path[r-1].x+2/3*(i.x1-this.path[r-1].x),a=this.path[r-1].y+2/3*(i.y1-this.path[r-1].y),c=i.x+2/3*(i.x1-i.x),u=i.y+2/3*(i.y1-i.y),l=i.x,h=i.y,o=[s-this.path[r-1].x,a-this.path[r-1].y,c-this.path[r-1].x,u-this.path[r-1].y,l-this.path[r-1].x,h-this.path[r-1].y];e.push(o);break;case"close":n=!0}void 0!==t&&this.pdf.lines(e,t.x,t.y,null,"s",n);for(var i,t,d,r=0;r<this.path.length;r++)"arc"===(i=this.path[r]).type&&(t=360*i.startAngle/(2*Math.PI),d=360*i.endAngle/(2*Math.PI),this.internal.arc(i.x,i.y,i.radius,t,d,i.anticlockwise,"s"));this.path=[]},fill:function(){for(var e=[],n=0;n<this.path.length;n++)switch((r=this.path[n]).type){case"mt":void 0!==(t=r)&&(this.pdf.lines(e,t.x,t.y,null,"f"),e=[]);break;case"lt":var i=[r.x-this.path[n-1].x,r.y-this.path[n-1].y];e.push(i);break;case"bct":i=[r.x1-this.path[n-1].x,r.y1-this.path[n-1].y,r.x2-this.path[n-1].x,r.y2-this.path[n-1].y,r.x-this.path[n-1].x,r.y-this.path[n-1].y];e.push(i);break;case"qct":var o=this.path[n-1].x+2/3*(r.x1-this.path[n-1].x),s=this.path[n-1].y+2/3*(r.y1-this.path[n-1].y),a=r.x+2/3*(r.x1-r.x),c=r.y+2/3*(r.y1-r.y),u=r.x,l=r.y,i=[o-this.path[n-1].x,s-this.path[n-1].y,a-this.path[n-1].x,c-this.path[n-1].y,u-this.path[n-1].x,l-this.path[n-1].y];e.push(i)}void 0!==t&&this.pdf.lines(e,t.x,t.y,null,"f");for(var r,n=0;n<this.path.length;n++)switch((r=this.path[n]).type){case"arc":var t=360*r.startAngle/(2*Math.PI),h=360*r.endAngle/(2*Math.PI);this.internal.arc(r.x,r.y,r.radius,t,h,r.anticlockwise,"f");break;case"close":this.pdf.internal.out("h")}this.path=[]},clip:function(){},translate:function(t,e){this.ctx._translate={x:t,y:e}},measureText:function(t){var e=this.pdf;return{getWidth:function(){var n=e.internal.getFontSize();return e.getStringUnitWidth(t)*n/e.internal.scaleFactor},get width(){return this.getWidth(t)}}},_getBaseline:function(t){var e=parseInt(this.pdf.internal.getFontSize()),n=.25*e;switch(this.ctx.textBaseline){case"bottom":return t-n;case"top":return t+e;case"hanging":return t+e-n;case"middle":return t+e/2-n;case"ideographic":return t;default:return t}}};t=t.context2d;Object.defineProperty(t,"fillStyle",{set:function(t){this.setFillStyle(t)},get:function(){return this.ctx.fillStyle}}),Object.defineProperty(t,"textBaseline",{set:function(t){this.setTextBaseline(t)},get:function(){return this.getTextBaseline()}}),Object.defineProperty(t,"font",{set:function(t){this.setFont(t)},get:function(){return this.getFont()}}),t.internal={},t.internal.rxRgb=/rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/,t.internal.rxRgba=/rgba\s*\(\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)\s*\)/,t.internal.arc=function(t,e,n,r,i,o,s){for(var a=this.pdf.internal.scaleFactor,c=this.pdf.internal.pageSize.height,u=this.pdf.internal.f2,r=r*(Math.PI/180),i=i*(Math.PI/180),d=this.createArc(n,r,i,o),f=0;f<d.length;f++){var p=d[f];this.pdf.internal.out((0==f?[u((p.x1+t)*a),u((c-(p.y1+e))*a),"m",u((p.x2+t)*a),u((c-(p.y2+e))*a),u((p.x3+t)*a),u((c-(p.y3+e))*a),u((p.x4+t)*a),u((c-(p.y4+e))*a),"c"]:[u((p.x2+t)*a),u((c-(p.y2+e))*a),u((p.x3+t)*a),u((c-(p.y3+e))*a),u((p.x4+t)*a),u((c-(p.y4+e))*a),"c"]).join(" "))}null!==s&&this.pdf.internal.out(this.pdf.internal.getStyle(s))},t.internal.createArc=function(t,e,n,r){var o=2*Math.PI,s=e;(s<o||o<s)&&(s%=o);(n<o||o<n)&&(n%=o);for(var c=[],u=Math.PI/2,l=r?-1:1,h=e,d=Math.min(o,Math.abs(n-s));1e-5<d;){var f=h+l*Math.min(d,u);c.push(this.createSmallArc(t,h,f)),d-=Math.abs(f-h),h=f}return c},t.internal.createSmallArc=function(t,e,n){var r=(n-e)/2,i=t*Math.cos(r),o=t*Math.sin(r),s=i,a=-o,c=s*s+a*a,u=c+s*i+a*o,c=4/3*(Math.sqrt(2*c*u)-u)/(s*o-a*i),u=s-c*a,o=a+c*s,i=u,a=-o,c=r+e,s=Math.cos(c),r=Math.sin(c);return{x1:t*Math.cos(e),y1:t*Math.sin(e),x2:u*s-o*r,y2:u*r+o*s,x3:i*s-a*r,y3:i*r+a*s,x4:t*Math.cos(n),y4:t*Math.sin(n)}}}(jsPDF.API),function(t){var r,i,o,s,a,f,e=function(){function t(){}return function(e){return t.prototype=e,new t}}(),u=function(t){for(var o,a,n=0,r=t.length,e=void 0,i=!1,s=!1;!i&&n!==r;)(e=t[n]=t[n].trimLeft())&&(i=!0),n++;for(n=r-1;r&&!s&&-1!==n;)(e=t[n]=t[n].trimRight())&&(s=!0),n--;for(o=/\s+$/g,a=!0,n=0;n!==r;)"\u2028"!=t[n]&&(e=t[n].replace(/\s+/g," "),(e=a?e.trimLeft():e)&&(a=o.test(e)),t[n]=e),n++;return t},l=function(t,e,n,r){return this.pdf=t,this.x=e,this.y=n,this.settings=r,this.watchFunctions=[],this.init(),this},h=function(t){for(var e=void 0,i=t.split(","),n=i.shift();!e&&n;)e=r[n.trim().toLowerCase()],n=i.shift();return e},d=function(t){var r;return-1<(t=-1<(t="auto"===t?"0px":t).indexOf("em")&&!isNaN(Number(t.replace("em","")))?18.719*Number(t.replace("em",""))+"px":t).indexOf("pt")&&!isNaN(Number(t.replace("pt","")))&&(t=1.333*Number(t.replace("pt",""))+"px"),(r=f[t])||(void 0!==(r={"xx-small":9,"x-small":11,small:13,medium:16,large:19,"x-large":23,"xx-large":28,auto:0}[{css_line_height_string:t}])||(r=parseFloat(t))?f[t]=r/16:(r=t.match(/([\d\.]+)(px)/),f[t]=3===r.length?parseFloat(r[1])/16:1))},c=function(t){var n,t=function(t){var e=function(t){return document.defaultView&&document.defaultView.getComputedStyle?document.defaultView.getComputedStyle(t,null):t.currentStyle||t.style}(t);return function(t){return t=t.replace(/-\D/g,function(t){return t.charAt(1).toUpperCase()}),e[t]}}(t),e={};return e["font-family"]=h(t("font-family"))||"times",e["font-style"]=i[t("font-style")]||"normal",e["text-align"]=TextAlignMap[t("text-align")]||"left","bold"===(n=o[t("font-weight")]||"normal")&&(e["font-style"]="normal"===e["font-style"]?n:n+e["font-style"]),e["font-size"]=d(t("font-size"))||1,e["line-height"]=d(t("line-height"))||1,e.display="inline"===t("display")?"inline":"block",e["margin-top"]=(n="block"===e.display)&&d(t("margin-top"))||0,e["margin-bottom"]=n&&d(t("margin-bottom"))||0,e["padding-top"]=n&&d(t("padding-top"))||0,e["padding-bottom"]=n&&d(t("padding-bottom"))||0,e["margin-left"]=n&&d(t("margin-left"))||0,e["margin-right"]=n&&d(t("margin-right"))||0,e["padding-left"]=n&&d(t("padding-left"))||0,e["padding-right"]=n&&d(t("padding-right"))||0,e["page-break-before"]=t("page-break-before")||"auto",e.float=s[t("cssFloat")]||"none",e.clear=a[t("clear")]||"none",e.color=t("color"),e},p=function(t,e,n){var r,o=!1,i=void 0,s=void 0;if(r=n["#"+t.id])if("function"==typeof r)o=r(t,e);else for(i=0,s=r.length;!o&&i!==s;)o=r[i](t,e),i++;if(r=n[t.nodeName],!o&&r)if("function"==typeof r)o=r(t,e);else for(i=0,s=r.length;!o&&i!==s;)o=r[i](t,e),i++;return o},v=function(t,e){for(var o,s,a,l,n=[],r=[],i=0,h=t.rows[0].cells.length,u=t.clientWidth;i<h;)l=t.rows[0].cells[i],r[i]={name:l.textContent.toLowerCase().replace(/\s+/g,""),prompt:l.textContent.replace(/\r?\n/g,""),width:l.clientWidth/u*e.pdf.internal.pageSize.width},i++;for(i=1;i<t.rows.length;){for(a=t.rows[i],s={},o=0;o<a.cells.length;)s[r[o].name]=a.cells[o].textContent.replace(/\r?\n/g,""),o++;n.push(s),i++}return{rows:n,headers:r}},b={SCRIPT:1,STYLE:1,NOSCRIPT:1,OBJECT:1,EMBED:1,SELECT:1},x=1,n=function(t,r,i){var a,u,h,g,w,y,C,E,k,_,P,A,q,I,o,s=t.childNodes;for(o=void 0,(t="block"===(a=c(t)).display)&&(r.setBlockBoundary(),r.setBlockStyle(a)),u=0,h=s.length;u<h;)"object"==typeof(o=s[u])&&(r.executeWatchFunctions(o),1===o.nodeType&&"HEADER"===o.nodeName&&(w=o,y=r.pdf.margins_doc.top,r.pdf.internal.events.subscribe("addPage",function(){r.y=y,n(w,r,i),r.pdf.margins_doc.top=r.y+10,r.y+=10},!1)),8===o.nodeType&&"#comment"===o.nodeName?~o.textContent.indexOf("ADD_PAGE")&&(r.pdf.addPage(),r.y=r.pdf.margins_doc.top):1!==o.nodeType||b[o.nodeName]?3===o.nodeType?(k=o.nodeValue,o.nodeValue&&"LI"===o.parentNode.nodeName&&("OL"===o.parentNode.parentNode.nodeName?k=x+++". "+k:(C=a["font-size"],offsetX=(3-.75*C)*r.pdf.internal.scaleFactor,offsetY=.75*C*r.pdf.internal.scaleFactor,radius=1.74*C/r.pdf.internal.scaleFactor,g=function(t,e){this.pdf.circle(t+offsetX,e+offsetY,radius,"FD")})),o.ownerDocument.body.contains(o)&&r.addText(k,a)):"string"==typeof o&&r.addText(o,a):("IMG"===o.nodeName&&(C=o.getAttribute("src"),E=m[r.pdf.sHashCode(C)||C]),E?(r.pdf.internal.pageSize.height-r.pdf.margins_doc.bottom<r.y+o.height&&r.y>r.pdf.margins_doc.top&&(r.pdf.addPage(),r.y=r.pdf.margins_doc.top,r.executeWatchFunctions(o)),k=c(o),_=r.x,q=12/r.pdf.internal.scaleFactor,I=(k["margin-left"]+k["padding-left"])*q,P=(k["margin-right"]+k["padding-right"])*q,A=(k["margin-top"]+k["padding-top"])*q,q=(k["margin-bottom"]+k["padding-bottom"])*q,_+=void 0!==k.float&&"right"===k.float?r.settings.width-o.width-P:I,r.pdf.addImage(E,_,r.y+A,o.width,o.height),E=void 0,"right"===k.float||"left"===k.float?(r.watchFunctions.push(function(t,e,n,i){return r.y>=e?(r.x+=t,r.settings.width+=n,!0):!!(i&&1===i.nodeType&&!b[i.nodeName]&&r.x+i.width>r.pdf.margins_doc.left+r.pdf.margins_doc.width)&&(r.x+=t,r.y=e,r.settings.width+=n,!0)}.bind(this,"left"===k.float?-o.width-I-P:0,r.y+o.height+A+q,o.width)),r.watchFunctions.push(function(t,e,n){return!(r.y<t&&e===r.pdf.internal.getNumberOfPages())||1===n.nodeType&&"both"===c(n).clear&&(r.y=t,!0)}.bind(this,r.y+o.height,r.pdf.internal.getNumberOfPages())),r.settings.width-=o.width+I+P,"left"===k.float&&(r.x+=o.width+I+P)):r.y+=o.height+A+q):"TABLE"===o.nodeName?(_=v(o,r),r.y+=10,r.pdf.table(r.x,r.y,_.rows,_.headers,{autoSize:!1,printHeaders:!0,margins:r.pdf.margins_doc}),r.y=r.pdf.lastCellPos.y+r.pdf.lastCellPos.h+20):"OL"===o.nodeName||"UL"===o.nodeName?(x=1,p(o,r,i)||n(o,r,i),r.y+=10):"LI"===o.nodeName?(I=r.x,r.x+=20/r.pdf.internal.scaleFactor,r.y+=3,p(o,r,i)||n(o,r,i),r.x=I):"BR"===o.nodeName?(r.y+=a["font-size"]*r.pdf.internal.scaleFactor,r.addText("\u2028",e(a))):p(o,r,i)||n(o,r,i))),u++;return t?r.setBlockBoundary(g):void 0},m={},g=function(t,e,n,r){function i(){e.pdf.internal.events.publish("imagesLoaded"),r(s)}for(var s,a=t.getElementsByTagName("img"),c=a.length,u=0;c--;)!function(t,n,r){var o;t&&(o=new Image,s=++u,o.crossOrigin="",o.onerror=o.onload=function(){var s;o.complete&&(0===o.src.indexOf("data:image/")&&(o.width=n||o.width||0,o.height=r||o.height||0),o.width+o.height)&&(s=e.pdf.sHashCode(t)||t,m[s]=m[s]||o),--u||i()},o.src=t)}(a[c].getAttribute("src"),a[c].width,a[c].height);return u||i()},w=function(t,e,r){if(0<(i=t.getElementsByTagName("footer")).length){var i=i[0],t=e.pdf.internal.write,s=e.y,a=(e.pdf.internal.write=function(){},n(i,e,r),Math.ceil(e.y-s)+5);e.y=s,e.pdf.internal.write=t,e.pdf.margins_doc.bottom+=a;function c(t){var o=void 0!==t?t.pageNumber:1,t=e.y;e.y=e.pdf.internal.pageSize.height-e.pdf.margins_doc.bottom,e.pdf.margins_doc.bottom-=a;for(var c=i.getElementsByTagName("span"),u=0;u<c.length;++u)-1<(" "+c[u].className+" ").replace(/[\n\t]/g," ").indexOf(" pageCounter ")&&(c[u].innerHTML=o),-1<(" "+c[u].className+" ").replace(/[\n\t]/g," ").indexOf(" totalPages ")&&(c[u].innerHTML="###jsPDFVarTotalPages###");n(i,e,r),e.pdf.margins_doc.bottom+=a,e.y=t}for(var u=i.getElementsByTagName("span"),l=0;l<u.length;++l)-1<(" "+u[l].className+" ").replace(/[\n\t]/g," ").indexOf(" totalPages ")&&e.pdf.internal.events.subscribe("htmlRenderingFinished",e.pdf.putTotalPages.bind(e.pdf,"###jsPDFVarTotalPages###"),!0);e.pdf.internal.events.subscribe("addPage",c,!1),c(),b.FOOTER=1}},y=function(t,e,r,i,o,s){if(!e)return!1;"string"==typeof(e="string"==typeof e||e.parentNode?e:""+e.innerHTML)&&(e=function(t){var r="jsPDFhtmlText"+Date.now().toString()+(1e3*Math.random()).toFixed(0),n=document.createElement("div");return n.style.cssText="position: absolute !important;clip: rect(1px 1px 1px 1px); /* IE6, IE7 */clip: rect(1px, 1px, 1px, 1px);padding:0 !important;border:0 !important;height: 1px !important;width: 1px !important; top:auto;left:-100px;overflow: hidden;",n.innerHTML='<iframe style="height:1px;width:1px" name="'+r+'" />',document.body.appendChild(n),(n=window.frames[r]).document.open(),n.document.writeln(t),n.document.close(),n.document.body}(e.replace(/<\/?script[^>]*?>/gi,"")));var a,c=new l(t,r,i,o);return g.call(this,e,c,o.elementHandlers,function(t){w(e,c,o.elementHandlers),n(e,c,o.elementHandlers),c.pdf.internal.events.publish("htmlRenderingFinished"),a=c.dispose(),"function"==typeof s?s(a):t&&console.error("jsPDF Warning: rendering issues? provide a callback to fromHTML!")}),a||{x:c.x,y:c.y}};l.prototype.init=function(){return this.paragraph={text:[],style:[]},this.pdf.internal.write("q")},l.prototype.dispose=function(){return this.pdf.internal.write("Q"),{x:this.x,y:this.y,ready:!0}},l.prototype.executeWatchFunctions=function(t){var e=!1,n=[];if(0<this.watchFunctions.length){for(var r=0;r<this.watchFunctions.length;++r)!0===this.watchFunctions[r](t)?e=!0:n.push(this.watchFunctions[r]);this.watchFunctions=n}return e},l.prototype.splitFragmentsIntoLines=function(t,n){for(var d,c,o,f=this.pdf.internal.scaleFactor,a={},s=void 0,w=void 0,h=void 0,u=void 0,p=[],m=[p],r=0,g=this.settings.width;t.length;)if(c=t.shift(),w=n.shift(),c)if((s=a[(o=w["font-family"])+(d=w["font-style"])])||(s=this.pdf.internal.getFont(o,d).metadata.Unicode,a[o+d]=s),h={widths:s.widths,kerning:s.kerning,fontSize:12*w["font-size"],textIndent:r},o=this.pdf.getStringUnitWidth(c,h)*h.fontSize/f,"\u2028"==c)m.push(p=[]);else if(g<r+o){for(u=this.pdf.splitTextToSize(c,g,h),p.push([u.shift(),w]);u.length;)p=[[u.shift(),w]],m.push(p);r=this.pdf.getStringUnitWidth(p[0][0],h)*h.fontSize/f}else p.push([c,w]),r+=o;if(void 0!==w["text-align"]&&("center"===w["text-align"]||"right"===w["text-align"]||"justify"===w["text-align"]))for(var y=0;y<m.length;++y){var x,v=this.pdf.getStringUnitWidth(m[y][0][0],h)*h.fontSize/f,v=(0<y&&(m[y][0][1]=e(m[y][0][1])),g-v);"right"===w["text-align"]?m[y][0][1]["margin-left"]=v:"center"===w["text-align"]?m[y][0][1]["margin-left"]=v/2:"justify"===w["text-align"]&&(x=m[y][0][0].split(" ").length-1,m[y][0][1]["word-spacing"]=v/x,y===m.length-1)&&(m[y][0][1]["word-spacing"]=0)}return m},l.prototype.RenderTextFragment=function(t,e){this.pdf.internal.pageSize.height-this.pdf.margins_doc.bottom<this.y+this.pdf.internal.getFontSize()&&(this.pdf.internal.write("ET","Q"),this.pdf.addPage(),this.y=this.pdf.margins_doc.top,this.pdf.internal.write("q","BT 0 g",this.pdf.internal.getCoordinateString(this.x),this.pdf.internal.getVerticalCoordinateString(this.y),e.color,"Td"),i=Math.max(0,e["line-height"],e["font-size"]),this.pdf.internal.write(0,(-12*i).toFixed(2),"Td"));var i=this.pdf.internal.getFont(e["font-family"],e["font-style"]),o=this.getPdfColor(e.color);o!==this.lastTextColor&&(this.pdf.internal.write(o),this.lastTextColor=o),void 0!==e["word-spacing"]&&0<e["word-spacing"]&&this.pdf.internal.write(e["word-spacing"].toFixed(2),"Tw"),this.pdf.internal.write("/"+i.id,(12*e["font-size"]).toFixed(2),"Tf","("+this.pdf.internal.pdfEscape(t)+") Tj"),void 0!==e["word-spacing"]&&this.pdf.internal.write(0,"Tw")},l.prototype.getPdfColor=function(t){var n,r,i,s=/rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/.exec(t),t=(i=null!=s?(n=parseInt(s[1]),r=parseInt(s[2]),parseInt(s[3])):(n=(t="#"!=t.charAt(0)?(t=CssColors.colorNameToHex(t))||"#000000":t).substring(1,3),n=parseInt(n,16),r=t.substring(3,5),r=parseInt(r,16),i=t.substring(5,7),parseInt(i,16)),"string"==typeof n&&/^#[0-9A-Fa-f]{6}$/.test(n)&&(n=(s=parseInt(n.substr(1),16))>>16&255,r=s>>8&255,i=255&s),this.f3);return 0===n&&0===r&&0===i||void 0===r?t(n/255)+" g":[t(n/255),t(r/255),t(i/255),"rg"].join(" ")},l.prototype.f3=function(t){return t.toFixed(3)},l.prototype.renderParagraph=function(t){var r,o,s,a,c,l,h,g,i=u(this.paragraph.text),m=this.paragraph.style,e=this.paragraph.blockstyle;this.paragraph.priorblockstyle;if(this.paragraph={text:[],style:[],blockstyle:{},priorblockstyle:e},i.join("").trim()){c=this.splitFragmentsIntoLines(i,m),l=a=void 0,r=12/this.pdf.internal.scaleFactor,this.priorMarginBottom=this.priorMarginBottom||0,i=(Math.max((e["margin-top"]||0)-this.priorMarginBottom,0)+(e["padding-top"]||0))*r,m=((e["margin-bottom"]||0)+(e["padding-bottom"]||0))*r,this.priorMarginBottom=e["margin-bottom"]||0,"always"===e["page-break-before"]&&(this.pdf.addPage(),this.y=0,i=((e["margin-top"]||0)+(e["padding-top"]||0))*r),h=this.pdf.internal.write,s=o=void 0,this.y+=i,h("q","BT 0 g",this.pdf.internal.getCoordinateString(this.x),this.pdf.internal.getVerticalCoordinateString(this.y),"Td");for(var w=0;c.length;){for(o=l=0,s=(a=c.shift()).length;o!==s;)a[o][0].trim()&&(l=Math.max(l,a[o][1]["line-height"],a[o][1]["font-size"]),g=7*a[o][1]["font-size"]),o++;var b,x,y=0,v=(void 0!==a[0][1]["margin-left"]&&0<a[0][1]["margin-left"]&&(y=(wantedIndent=this.pdf.internal.getCoordinateString(a[0][1]["margin-left"]))-w,w=wantedIndent),Math.max(e["margin-left"]||0,0)*r);for(h(y+v,(-12*l).toFixed(2),"Td"),o=0,s=a.length;o!==s;)a[o][0]&&this.RenderTextFragment(a[o][0],a[o][1]),o++;this.y+=l*r,this.executeWatchFunctions(a[0][1])&&0<c.length&&(b=[],x=[],c.forEach(function(t){for(var e=0,n=t.length;e!==n;)t[e][0]&&(b.push(t[e][0]+" "),x.push(t[e][1])),++e}),c=this.splitFragmentsIntoLines(u(b),x),h("ET","Q"),h("q","BT 0 g",this.pdf.internal.getCoordinateString(this.x),this.pdf.internal.getVerticalCoordinateString(this.y),"Td"))}return t&&"function"==typeof t&&t.call(this,this.x-9,this.y-g/2),h("ET","Q"),this.y+=m}},l.prototype.setBlockBoundary=function(t){return this.renderParagraph(t)},l.prototype.setBlockStyle=function(t){return this.paragraph.blockstyle=t},l.prototype.addText=function(t,e){return this.paragraph.text.push(t),this.paragraph.style.push(e)},r={helvetica:"helvetica","sans-serif":"helvetica","times new roman":"times",serif:"times",times:"times",monospace:"courier",courier:"courier"},o={100:"normal",200:"normal",300:"normal",400:"normal",500:"bold",600:"bold",700:"bold",800:"bold",900:"bold",normal:"normal",bold:"bold",bolder:"bold",lighter:"normal"},i={normal:"normal",italic:"italic",oblique:"italic"},TextAlignMap={left:"left",right:"right",center:"center",justify:"justify"},s={none:"none",right:"right",left:"left"},a={none:"none",both:"both"},f={normal:1},t.fromHTML=function(t,e,n,r,i,o){"use strict";return this.margins_doc=o||{top:0,bottom:0},(r=r||{}).elementHandlers||(r.elementHandlers={}),y(this,t,isNaN(e)?4:e,isNaN(n)?4:n,r,i)}}(jsPDF.API),function(){"use strict";var e,n,r;jsPDF.API.addJS=function(t){return r=t,this.internal.events.subscribe("postPutResources",function(){e=this.internal.newObject(),this.internal.write("<< /Names [(EmbeddedJS) "+(e+1)+" 0 R] >>","endobj"),n=this.internal.newObject(),this.internal.write("<< /S /JavaScript /JS (",r,") >>","endobj")}),this.internal.events.subscribe("putCatalog",function(){void 0!==e&&void 0!==n&&this.internal.write("/Names <</JavaScript "+e+" 0 R>>")}),this}}(),function(t){"use strict";t.events.push(["postPutResources",function(){var t=this,e=/^(\d+) 0 obj$/;if(0<this.outline.root.children.length)for(var n=t.outline.render().split(/\r\n/),r=0;r<n.length;r++){var i=n[r],o=e.exec(i);null!=o&&(o=o[1],t.internal.newObjectDeferredBegin(o)),t.internal.write(i)}if(this.outline.createNamedDestinations){for(var a=this.internal.pages.length,c=[],r=0;r<a;r++){var u=t.internal.newObject(),u=(c.push(u),t.internal.getPageInfo(r+1));t.internal.write("<< /D["+u.objId+" 0 R /XYZ null null null]>> endobj")}var h=t.internal.newObject();t.internal.write("<< /Names [ ");for(r=0;r<c.length;r++)t.internal.write("(page_"+(r+1)+")"+c[r]+" 0 R");t.internal.write(" ] >>","endobj"),namesOid=t.internal.newObject(),t.internal.write("<< /Dests "+h+" 0 R"),t.internal.write(">>","endobj")}}]),t.events.push(["putCatalog",function(){var t=this;0<t.outline.root.children.length&&(t.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations)&&t.internal.write("/Names "+namesOid+" 0 R")}]),t.events.push(["initialized",function(){var t=this;t.outline={createNamedDestinations:!1,root:{children:[]}},t.outline.add=function(t,e,n){e={title:e,options:n,children:[]};return(t=null==t?this.root:t).children.push(e),e},t.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=t,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},t.outline.genIds_r=function(e){e.id=t.internal.newObjectDeferred();for(var n=0;n<e.children.length;n++)this.genIds_r(e.children[n])},t.outline.renderRoot=function(t){this.objStart(t),this.line("/Type /Outlines"),0<t.children.length&&(this.line("/First "+this.makeRef(t.children[0])),this.line("/Last "+this.makeRef(t.children[t.children.length-1]))),this.line("/Count "+this.count_r({count:0},t)),this.objEnd()},t.outline.renderItems=function(e){for(var n=0;n<e.children.length;n++){var r=e.children[n],i=(this.objStart(r),this.line("/Title "+this.makeString(r.title)),this.line("/Parent "+this.makeRef(e)),0<n&&this.line("/Prev "+this.makeRef(e.children[n-1])),n<e.children.length-1&&this.line("/Next "+this.makeRef(e.children[n+1])),0<r.children.length&&(this.line("/First "+this.makeRef(r.children[0])),this.line("/Last "+this.makeRef(r.children[r.children.length-1]))),this.count=this.count_r({count:0},r));0<i&&this.line("/Count "+i),r.options&&r.options.pageNumber&&(i=t.internal.getPageInfo(r.options.pageNumber),this.line("/Dest ["+i.objId+" 0 R /XYZ 0 "+this.ctx.pdf.internal.pageSize.height+" 0]")),this.objEnd()}for(n=0;n<e.children.length;n++){r=e.children[n];this.renderItems(r)}},t.outline.line=function(t){this.ctx.val+=t+"\r\n"},t.outline.makeRef=function(t){return t.id+" 0 R"},t.outline.makeString=function(e){return"("+t.internal.pdfEscape(e)+")"},t.outline.objStart=function(t){this.ctx.val+="\r\n"+t.id+" 0 obj\r\n<<\r\n"},t.outline.objEnd=function(){this.ctx.val+=">> \r\nendobj\r\n"},t.outline.count_r=function(t,e){for(var n=0;n<e.children.length;n++)t.count++,this.count_r(t,e.children[n]);return t.count}}])}(jsPDF.API),function(t){"use strict";function n(e){return e!==t.image_compression.NONE&&function(){var t="function"==typeof Deflater;if(t)return t;throw new Error("requires deflate.js for compression")}()}function i(e,n,r,i){var c=5,f=l;switch(i){case t.image_compression.FAST:c=3,f=u;break;case t.image_compression.MEDIUM:c=6,f=h;break;case t.image_compression.SLOW:c=9,f=d}e=a(e,n,r,f);var i=new Uint8Array(function(e){var n=8,r,i=Math.LOG2E*Math.log(32768)-8<<4|n,o=i<<8,s;return[i,255&(o=(o=o|Math.min(3,(e-1&255)>>1)<<6|0)+(31-o%31))&255]}()),n=function(t,e){for(var n,r=1,i=65535&r,o=r>>>16&65535,s=t.length,a=0;s>0;){n=s>e?e:s,s-=n;do{i+=t[a++],o+=i}while(--n);i%=65521,o%=65521}return(o<<16|i)>>>0}(e),e=(r=new Deflater(c)).append(e),r=r.flush(),v=i.length+e.length+r.length,b=new Uint8Array(v+4);return b.set(i),b.set(e,i.length),b.set(r,i.length+e.length),b[v++]=n>>>24&255,b[v++]=n>>>16&255,b[v++]=n>>>8&255,b[+v]=255&n,t.arrayBufferToBinaryString(b)}function a(t,e,n,r){for(var i,o,s,a=t.length/e,c=new Uint8Array(t.length+a),u=p(),l=0;l<a;l++){if(i=t.subarray(s=l*e,s+e),r)c.set(r(i,n,o),s+l);else{for(var h=0,d=u.length,f=[];h<d;h++)f[h]=u[h](i,n,o);var g=m(f.concat());c.set(f[g],s+l)}o=i}return c}function c(t){return(t=Array.apply([],t)).unshift(0),t}function u(t,e){var n,r=[],i=0,o=t.length;for(r[0]=1;i<o;i++)n=t[i-e]||0,r[i+1]=t[i]-n+256&255;return r}function l(t,e,n){var r,i=[],o=0,s=t.length;for(i[0]=2;o<s;o++)r=n&&n[o]||0,i[o+1]=t[o]-r+256&255;return i}function h(t,e,n){var r,i,o=[],s=0,a=t.length;for(o[0]=3;s<a;s++)r=t[s-e]||0,i=n&&n[s]||0,o[s+1]=t[s]+256-(r+i>>>1)&255;return o}function d(t,e,n){var i,o,r,a=[],c=0,u=t.length;for(a[0]=4;c<u;c++)r=t[c-e]||0,i=n&&n[c]||0,o=n&&n[c-e]||0,r=f(r,i,o),a[c+1]=t[c]-r+256&255;return a}var f=function(t,e,n){var r=t+e-n,i=Math.abs(r-t),o=Math.abs(r-e),r=Math.abs(r-n);return i<=o&&i<=r?t:o<=r?e:n},p=function(){return[c,u,l,h,d]},m=function(t){for(var e,n,r,i=0,o=t.length;i<o;)((e=function(t){for(var e=0,n=t.length,r=0;n>e;)r+=Math.abs(t[e++]);return r}(t[i].slice(1)))<n||!n)&&(n=e,r=i),i++;return r};t.processPNG=function(t,r,o,s){var a,u,l,h,d,f=this.color_spaces.DEVICE_RGB,p=this.decode.FLATE_DECODE,m=8;if(this.isArrayBuffer(t)&&(t=new Uint8Array(t)),this.isArrayBufferView(t)){if("function"!=typeof PNG||"function"!=typeof FlateStream)throw new Error("PNG support requires png.js and zlib.js");if(t=(a=new PNG(t)).imgData,m=a.bits,f=a.colorSpace,l=a.colors,-1!==[4,6].indexOf(a.colorType)){if(8===a.bits)for(var w,v=(y=new(32==a.pixelBitlength?Uint32Array:16==a.pixelBitlength?Uint16Array:Uint8Array)(a.decodePixels().buffer)).length,b=new Uint8Array(v*a.colors),x=new Uint8Array(v),k=a.pixelBitlength-a.bits,C=0,E=0;C<v;C++){for(g=y[C],w=0;w<k;)b[E++]=g>>>w&255,w+=a.bits;x[C]=g>>>w&255}if(16===a.bits){for(var g,v=(y=new Uint32Array(a.decodePixels().buffer)).length,b=new Uint8Array(v*(32/a.pixelBitlength)*a.colors),x=new Uint8Array(v*(32/a.pixelBitlength)),S=1<a.colors,C=0,E=0,T=0;C<v;)g=y[C++],b[E++]=g>>>0&255,S&&(b[E++]=g>>>16&255,g=y[C++],b[E++]=g>>>0&255),x[T++]=g>>>16&255;m=8}n(s)?(t=i(b,a.width*a.colors,a.colors,s),d=i(x,a.width,1,s)):(t=b,d=x,p=null)}if(3===a.colorType&&(f=this.color_spaces.INDEXED,h=a.palette,a.transparency.indexed)){for(var _=a.transparency.indexed,q=0,C=0,v=_.length;C<v;++C)q+=_[C];if((q/=255)===v-1&&-1!==_.indexOf(0))u=[_.indexOf(0)];else if(q!==v){for(var y=a.decodePixels(),x=new Uint8Array(y.length),C=0,v=y.length;C<v;C++)x[C]=_[y[C]];d=i(x,a.width,1)}}return s=p===this.decode.FLATE_DECODE?"/Predictor 15 /Colors "+l+" /BitsPerComponent "+m+" /Columns "+a.width:"/Colors "+l+" /BitsPerComponent "+m+" /Columns "+a.width,(this.isArrayBuffer(t)||this.isArrayBufferView(t))&&(t=this.arrayBufferToBinaryString(t)),(d&&this.isArrayBuffer(d)||this.isArrayBufferView(d))&&(d=this.arrayBufferToBinaryString(d)),this.createImageInfo(t,a.width,a.height,f,m,p,r,o,s,u,h,d)}throw new Error("Unsupported PNG image data, try using JPEG instead.")}}(jsPDF.API),function(t){"use strict";function n(t){for(var e=t.length,n=0;e;)n+=t[--e];return n}function o(t,o,s){var c,u,l,h,d,b,x,f=[],p=[f],m=(s=s||{}).textIndent||0,g=0,w=0,y=t.split(" "),v=e(" ",s)[0];for((d=-1===s.lineIndent?y[0].length+2:s.lineIndent||0)&&(b=Array(d).join(" "),x=[],y.map(function(t){1<(t=t.split(/\s*\n/)).length?x=x.concat(t.map(function(t,e){return(e&&t.length?"\n":"")+t})):x.push(t[0])}),y=x,d=r(b,s)),u=0,l=y.length;u<l;u++){var k=0,a=y[u];if(d&&"\n"==a[0]&&(a=a.substr(1),k=1),c=e(a,s),o<m+g+(w=n(c))||k){if(o<w){for(h=function(t,e,n,r){for(var i=[],o=0,s=t.length,a=0;o!==s&&a+e[o]<n;)a+=e[o],o++;i.push(t.slice(0,o));for(var c=o,a=0;o!==s;)a+e[o]>r&&(i.push(t.slice(c,o)),a=0,c=o),a+=e[o],o++;return c!==o&&i.push(t.slice(c,o)),i}(a,c,o-(m+g),o),f.push(h.shift()),f=[h.pop()];h.length;)p.push([h.shift()]);w=n(c.slice(a.length-f[0].length))}else f=[a];p.push(f),m=w+d}else f.push(a),m+=g+w;g=v}return p.map(d?function(t,e){return(e?b:"")+t.join(" ")}:function(t){return t.join(" ")})}var e=t.getCharWidthsArray=function(t,e){for(var i,o=(e=e||{}).widths||this.internal.getFont().metadata.Unicode.widths,s=o.fof||1,a=e.kerning||this.internal.getFont().metadata.Unicode.kerning,c=a.fof||1,u=0,l=o[0]||s,h=[],n=0,r=t.length;n<r;n++)i=t.charCodeAt(n),h.push((o[i]||l)/s+(a[i]&&a[i][u]||0)/c),u=i;return h},r=t.getStringUnitWidth=function(t,r){return n(e.call(this,t,r))};t.splitTextToSize=function(t,e,n){var i=(n=n||{}).fontSize||this.internal.getFontSize(),s=function(t){var i,e={0:1},n={};return t.widths&&t.kerning?{widths:t.widths,kerning:t.kerning}:(t=this.internal.getFont(t.fontName,t.fontStyle)).metadata[i="Unicode"]?{widths:t.metadata[i].widths||e,kerning:t.metadata[i].kerning||n}:{widths:e,kerning:n}}.call(this,n),r=Array.isArray(t)?t:t.split(/\r?\n/),a=+this.internal.scaleFactor*e/i;s.textIndent=n.textIndent?+n.textIndent*this.internal.scaleFactor/i:0,s.lineIndent=n.lineIndent;for(var l=[],c=0,u=r.length;c<u;c++)l=l.concat(o(r[c],a,s));return l}}(jsPDF.API),function(t){"use strict";function e(t){for(var n="klmnopqrstuvwxyz",r={},i=0;i<n.length;i++)r[n[i]]="0123456789abcdef"[i];for(var o,s,a,c,u,l={},h=1,d=l,f=[],p="",m="",g=t.length-1,i=1;i!=g;)u=t[i],i+=1,"'"==u?s=s?(c=s.join(""),o):[]:s?s.push(u):"{"==u?(f.push([d,c]),d={},c=o):"}"==u?((a=f.pop())[0][a[1]]=d,c=o,d=a[0]):"-"==u?h=-1:c===o?r.hasOwnProperty(u)?(p+=r[u],c=parseInt(p,16)*h,h=1,p=""):p+=u:r.hasOwnProperty(u)?(m+=r[u],d[c]=parseInt(m,16)*h,h=1,c=o,m=""):m+=u;return l}var n={codePages:["WinAnsiEncoding"],WinAnsiEncoding:e("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")},r={Unicode:{Courier:n,"Courier-Bold":n,"Courier-BoldOblique":n,"Courier-Oblique":n,Helvetica:n,"Helvetica-Bold":n,"Helvetica-BoldOblique":n,"Helvetica-Oblique":n,"Times-Roman":n,"Times-Bold":n,"Times-BoldItalic":n,"Times-Italic":n}},i={Unicode:{"Courier-Oblique":e("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-BoldItalic":e("{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"),"Helvetica-Bold":e("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),Courier:e("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Courier-BoldOblique":e("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-Bold":e("{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}"),Helvetica:e("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"),"Helvetica-BoldOblique":e("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),"Courier-Bold":e("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-Italic":e("{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}fv{17su5tu5qs}fw{17su5tu5qs}}}"),"Times-Roman":e("{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"),"Helvetica-Oblique":e("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}")}};t.events.push(["addFonts",function(t){var e,n,s,o,c="Unicode";for(n in t.fonts)t.fonts.hasOwnProperty(n)&&(e=t.fonts[n],o=i[c][e.PostScriptName],o&&(s=e.metadata[c]||(e.metadata[c]={}),s.widths=o.widths,s.kerning=o.kerning),o=r[c][e.PostScriptName],o)&&(s=e.metadata[c]||(e.metadata[c]={}),s.encoding=o,o.codePages)&&o.codePages.length&&(e.encoding=o.codePages[0])}])}(jsPDF.API),function(){"use strict";jsPDF.API.addSVG=function(t,e,n,r,i){if(e===u||n===u)throw new Error("addSVG needs values for 'x' and 'y'");var u=function(t){var n=t.createElement("iframe");return function(t,e){var n=e.createElement("style");n.type="text/css",n.styleSheet?n.styleSheet.cssText=t:n.appendChild(e.createTextNode(t)),e.getElementsByTagName("head")[0].appendChild(n)}(".jsPDF_sillysvg_iframe {display:none;position:absolute;}",t),n.name="childframe",n.setAttribute("width",0),n.setAttribute("height",0),n.setAttribute("frameborder","0"),n.setAttribute("scrolling","no"),n.setAttribute("seamless","seamless"),n.setAttribute("class","jsPDF_sillysvg_iframe"),t.body.appendChild(n),n}(document),t=function(t,e){return(e=(e.contentWindow||e.contentDocument).document).write(t),e.close(),e.getElementsByTagName("svg")[0]}(t,u),d=[1,1],u=parseFloat(t.getAttribute("width")),p=parseFloat(t.getAttribute("height"));u&&p&&(r&&i?d=[r/u,i/p]:r?d=[r/u,r/u]:i&&(d=[i/p,i/p]));for(var w,v=t.childNodes,m=0,g=v.length;m<g;m++)(w=v[m]).tagName&&"PATH"===w.tagName.toUpperCase()&&((w=function(t){for(var e=parseFloat(t[1]),n=parseFloat(t[2]),r=[],i=3,o=t.length;i<o;)"c"===t[i]?(r.push([parseFloat(t[i+1]),parseFloat(t[i+2]),parseFloat(t[i+3]),parseFloat(t[i+4]),parseFloat(t[i+5]),parseFloat(t[i+6])]),i+=7):"l"===t[i]?(r.push([parseFloat(t[i+1]),parseFloat(t[i+2])]),i+=3):i+=1;return[e,n,r]}(w.getAttribute("d").split(" ")))[0]=w[0]*d[0]+e,w[1]=w[1]*d[1]+n,this.lines.call(this,w[2],w[0],w[1],d));return this}}(),function(){"use strict";jsPDF.API.putTotalPages=function(t){for(var e=new RegExp(t,"g"),n=1;n<=this.internal.getNumberOfPages();n++)for(var r=0;r<this.internal.pages[n].length;r++)this.internal.pages[n][r]=this.internal.pages[n][r].replace(e,this.internal.getNumberOfPages());return this}}(),function(t){"use strict";if(t.URL=t.URL||t.webkitURL,t.Blob&&t.URL)try{return new Blob}catch(e){}var n=t.BlobBuilder||t.WebKitBlobBuilder||t.MozBlobBuilder||function(t){function e(t){return Object.prototype.toString.call(t).match(/^\[object\s(.*)\]$/)[1]}function n(){this.data=[]}function r(t,e,n){this.data=t,this.size=t.length,this.type=e,this.encoding=n}function a(t){this.code=this[this.name=t]}var i=n.prototype,o=r.prototype,s=t.FileReaderSync,c="NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR".split(" "),u=c.length,l=t.URL||t.webkitURL||t,h=l.createObjectURL,d=l.revokeObjectURL,f=l,p=t.btoa,m=t.atob,g=t.ArrayBuffer,w=t.Uint8Array,y=/^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/;for(r.fake=o.fake=!0;u--;)a.prototype[c[u]]=u+1;return(f=l.createObjectURL?f:t.URL=function(t){var n=document.createElementNS("http://www.w3.org/1999/xhtml","a");return n.href=t,"origin"in n||("data:"===n.protocol.toLowerCase()?n.origin=null:(t=t.match(y),n.origin=t&&t[1])),n}).createObjectURL=function(t){var n=t.type;return null===n&&(n="application/octet-stream"),t instanceof r?(n="data:"+n,"base64"===t.encoding?n+";base64,"+t.data:"URI"===t.encoding?n+","+decodeURIComponent(t.data):p?n+";base64,"+p(t.data):n+","+encodeURIComponent(t.data)):h?h.call(l,t):void 0},f.revokeObjectURL=function(t){"data:"!==t.substring(0,5)&&d&&d.call(l,t)},i.append=function(t){var n=this.data;if(w&&(t instanceof g||t instanceof w)){for(var i="",o=new w(t),c=0,u=o.length;c<u;c++)i+=String.fromCharCode(o[c]);n.push(i)}else if("Blob"===e(t)||"File"===e(t)){if(!s)throw new a("NOT_READABLE_ERR");var l=new s;n.push(l.readAsBinaryString(t))}else t instanceof r?"base64"===t.encoding&&m?n.push(m(t.data)):"URI"===t.encoding?n.push(decodeURIComponent(t.data)):"raw"===t.encoding&&n.push(t.data):("string"!=typeof t&&(t+=""),n.push(unescape(encodeURIComponent(t))))},i.getBlob=function(t){return arguments.length||(t=null),new r(this.data.join(""),t,"raw")},i.toString=function(){return"[object BlobBuilder]"},o.slice=function(t,e,n){var i=arguments.length;return i<3&&(n=null),new r(this.data.slice(t,1<i?e:this.data.length),n,this.encoding)},o.toString=function(){return"[object Blob]"},o.close=function(){this.size=0,delete this.data},n}(t),r=(t.Blob=function(t,e){var e=e&&e.type||"",i=new n;if(t)for(var o=0,s=t.length;o<s;o++)i.append(Uint8Array&&t[o]instanceof Uint8Array?t[o].buffer:t[o]);e=i.getBlob(e);return!e.slice&&e.webkitSlice&&(e.slice=e.webkitSlice),e},Object.getPrototypeOf||function(t){return t.__proto__});t.Blob.prototype=r(new t.Blob)}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content||this),saveAs||function(t){"use strict";var n,r,i,s,a,c,u,l,h,d,f,p,m,e;if("undefined"==typeof navigator||!/MSIE [1-9]\./.test(navigator.userAgent))return e=t.document,n=function(){return t.URL||t.webkitURL||t},r=e.createElementNS("http://www.w3.org/1999/xhtml","a"),i="download"in r,s=t.webkitRequestFileSystem,a=t.requestFileSystem||s||t.mozRequestFileSystem,c=function(e){(t.setImmediate||t.setTimeout)(function(){throw e},0)},u="application/octet-stream",l=0,h=500,d=function(e){function r(){"string"==typeof e?n().revokeObjectURL(e):e.remove()}t.chrome?r():setTimeout(r,h)},f=function(t,e,n){for(var r=(e=[].concat(e)).length;r--;){var i=t["on"+e[r]];if("function"==typeof i)try{i.call(t,n||t)}catch(o){c(o)}}},p=function(t){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(t.type)?new Blob(["\ufeff",t],{type:t.type}):t},e=(m=function(e,c,h){h||(e=p(e));function k(){!b&&m||(m=n().createObjectURL(e)),g?g.location.href=m:null==t.open(m,"_blank")&&"undefined"!=typeof safari&&(t.location.href=m),y.readyState=y.DONE,x(),d(m)}function C(t){return function(){return y.readyState!==y.DONE?t.apply(this,arguments):void 0}}var m,g,w,y=this,h=e.type,b=!1,x=function(){f(y,"writestart progress write writeend".split(" "))},E={create:!0,exclusive:!1};return y.readyState=y.INIT,c=c||"download",i?(m=n().createObjectURL(e),r.href=m,r.download=c,void setTimeout(function(){var t,e;t=r,e=new MouseEvent("click"),t.dispatchEvent(e),x(),d(m),y.readyState=y.DONE})):(t.chrome&&h&&h!==u&&(w=e.slice||e.webkitSlice,e=w.call(e,0,e.size,u),b=!0),s&&"download"!==c&&(c+=".download"),h!==u&&!s||(g=t),a?(l+=e.size,void a(t.TEMPORARY,l,C(function(t){t.root.getDirectory("saved",E,C(function(t){function n(){t.getFile(c,E,C(function(t){t.createWriter(C(function(n){n.onwriteend=function(e){g.location.href=t.toURL(),y.readyState=y.DONE,f(y,"writeend",e),d(t)},n.onerror=function(){var t=n.error;t.code!==t.ABORT_ERR&&k()},"writestart progress write abort".split(" ").forEach(function(t){n["on"+t]=y["on"+t]}),n.write(e),y.abort=function(){n.abort(),y.readyState=y.DONE},y.readyState=y.WRITING}),k)}),k)}t.getFile(c,{create:!1},C(function(t){t.remove(),n()}),C(function(t){(t.code===t.NOT_FOUND_ERR?n:k)()}))}),k)}),k)):void k())}).prototype,"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(t,e,n){return n||(t=p(t)),navigator.msSaveOrOpenBlob(t,e||"download")}:(e.abort=function(){var t=this;t.readyState=t.DONE,f(t,"abort")},e.readyState=e.INIT=0,e.WRITING=1,e.DONE=2,e.error=e.onwritestart=e.onprogress=e.onwrite=e.onabort=e.onerror=e.onwriteend=null,function(t,e,n){return new m(t,e,n)})}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content)),CssColors=(void 0!==module&&module.exports&&(module.exports.saveAs=saveAs),function(t,e){"object"==typeof module?module.exports=e():t.adler32cs=e()}(jsPDF,function(){function o(t,e){for(var n=65535&t,r=t>>>16,o=0,s=e.length;o<s;o++)r=(r+(n=(n+(255&e.charCodeAt(o)))%i))%i;return(r<<16|n)>>>0}function s(t,e){for(var n=65535&t,r=t>>>16,o=0,s=e.length;o<s;o++)r=(r+(n=(n+e[o])%i))%i;return(r<<16|n)>>>0}var t="function"==typeof ArrayBuffer&&"function"==typeof Uint8Array,e=null,n=function(){if(!t)return function(){return!1};try{var n=require("buffer");"function"==typeof n.Buffer&&(e=n.Buffer)}catch(r){}return function(t){return t instanceof ArrayBuffer||null!==e&&t instanceof e}}(),r=null!==e?function(t){return new e(t,"utf8").toString("binary")}:function(t){return unescape(encodeURIComponent(t))},i=65521,c=function(){function e(t){if(!(this instanceof e))throw new TypeError("Constructor cannot called be as a function.");if(!isFinite(t=null==t?1:+t))throw new Error("First arguments needs to be a finite number.");this.checksum=t>>>0}var i=e.prototype={};return(i.constructor=e).from=function(t){return t.prototype=i,t}(function(t){if(!(this instanceof e))throw new TypeError("Constructor cannot called be as a function.");if(null==t)throw new Error("First argument needs to be a string.");this.checksum=o(1,t.toString())}),e.fromUtf8=function(t){return t.prototype=i,t}(function(t){if(!(this instanceof e))throw new TypeError("Constructor cannot called be as a function.");if(null==t)throw new Error("First argument needs to be a string.");t=r(t.toString());this.checksum=o(1,t)}),t&&(e.fromBuffer=function(t){return t.prototype=i,t}(function(t){if(!(this instanceof e))throw new TypeError("Constructor cannot called be as a function.");if(n(t))return t=new Uint8Array(t),this.checksum=s(1,t);throw new Error("First argument needs to be ArrayBuffer.")})),i.update=function(t){if(null==t)throw new Error("First argument needs to be a string.");return t=t.toString(),this.checksum=o(this.checksum,t)},i.updateUtf8=function(t){if(null==t)throw new Error("First argument needs to be a string.");t=r(t.toString());return this.checksum=o(this.checksum,t)},t&&(i.updateBuffer=function(t){if(n(t))return t=new Uint8Array(t),this.checksum=s(this.checksum,t);throw new Error("First argument needs to be ArrayBuffer.")}),i.clone=function(){return new c(this.checksum)},e}();return t&&0,jsPDF}),{}),Deflater=(CssColors._colorsTable={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4","indianred ":"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},CssColors.colorNameToHex=function(t){return t=t.toLowerCase(),void 0!==this._colorsTable[t]&&this._colorsTable[t]},function(){function t(){function n(t,n,r){for(var o,a,c=[],u=0,i=1;i<=15;i++)c[i]=u=u+r[i-1]<<1;for(o=0;o<=n;o++)0!==(a=t[2*o+1])&&(t[2*o]=function(t,e){for(var n=0;n|=1&t,t>>>=1,n<<=1,0<--e;);return n>>>1}(c[a]++,a))}var r=this;r.build_tree=function(e){var i,o,s,a=r.dyn_tree,c=r.stat_desc.static_tree,u=r.stat_desc.elems,l=-1;for(e.heap_len=0,e.heap_max=573,i=0;i<u;i++)0!==a[2*i]?(e.heap[++e.heap_len]=l=i,e.depth[i]=0):a[2*i+1]=0;for(;e.heap_len<2;)a[2*(s=e.heap[++e.heap_len]=l<2?++l:0)]=1,e.depth[s]=0,e.opt_len--,c&&(e.static_len-=c[2*s+1]);for(r.max_code=l,i=Math.floor(e.heap_len/2);1<=i;i--)e.pqdownheap(a,i);for(s=u;i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],e.pqdownheap(a,1),o=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=o,a[2*s]=a[2*i]+a[2*o],e.depth[s]=Math.max(e.depth[i],e.depth[o])+1,a[2*i+1]=a[2*o+1]=s,e.heap[1]=s++,e.pqdownheap(a,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(t){for(var e,n,i,a,c,u=r.dyn_tree,l=r.stat_desc.static_tree,h=r.stat_desc.extra_bits,f=r.stat_desc.extra_base,p=r.stat_desc.max_length,m=0,o=0;o<=15;o++)t.bl_count[o]=0;for(u[2*t.heap[t.heap_max]+1]=0,e=t.heap_max+1;e<573;e++)p<(o=u[2*u[2*(n=t.heap[e])+1]+1]+1)&&(o=p,m++),u[2*n+1]=o,n>r.max_code||(t.bl_count[o]++,a=0,f<=n&&(a=h[n-f]),c=u[2*n],t.opt_len+=c*(o+a),l&&(t.static_len+=c*(l[2*n+1]+a)));if(0!==m){do{for(o=p-1;0===t.bl_count[o];)o--}while(t.bl_count[o]--,t.bl_count[o+1]+=2,t.bl_count[p]--,0<(m-=2));for(o=p;0!==o;o--)for(n=t.bl_count[o];0!==n;)(i=t.heap[--e])>r.max_code||(u[2*i+1]!=o&&(t.opt_len+=(o-u[2*i+1])*u[2*i],u[2*i+1]=o),n--)}}(e),n(a,r.max_code,e.bl_count)}}function e(t,e,n,r,i){var o=this;o.static_tree=t,o.extra_bits=e,o.extra_base=n,o.elems=r,o.max_length=i}function n(t,e,n,r,i){var o=this;o.good_length=t,o.max_lazy=e,o.nice_length=n,o.max_chain=r,o.func=i}function r(t,e,n,r){var i=t[2*e],t=t[2*n];return i<t||i==t&&r[e]<=r[n]}function i(){function i(){for(var t=0;t<286;t++)Ze[2*t]=0;for(t=0;t<30;t++)Ke[2*t]=0;for(t=0;t<19;t++)tn[2*t]=0;Ze[512]=1,en.opt_len=en.static_len=0,cn=ln=0}function s(t,e){var n,r,i=-1,o=t[1],s=0,a=7,c=4;for(0===o&&(a=138,c=3),t[2*(e+1)+1]=65535,n=0;n<=e;n++)r=o,o=t[2*(n+1)+1],++s<a&&r==o||(s<c?tn[2*r]+=s:0!==r?(r!=i&&tn[2*r]++,tn[32]++):s<=10?tn[34]++:tn[36]++,i=r,c=(s=0)===o?(a=138,3):r==o?(a=6,3):(a=7,4))}function u(){var e;for(s(Ze,nn.max_code),s(Ke,rn.max_code),on.build_tree(en),e=18;3<=e&&0===tn[2*t.bl_order[e]+1];e--);return en.opt_len+=3*(e+1)+5+5+4,e}function d(t){en.pending_buf[en.pending++]=t}function p(t){d(255&t),d(t>>>8&255)}function ne(t,e){var n;16-e<fn?(p(dn|=(n=t)<<fn&65535),dn=n>>>16-fn,fn+=e-16):(dn|=t<<fn&65535,fn+=e)}function re(t,e){t*=2;ne(65535&e[t],65535&e[1+t])}function ie(t,e){var n,r,i=-1,o=t[1],s=0,a=7,c=4;for(0===o&&(a=138,c=3),n=0;n<=e;n++)if(r=o,o=t[2*(n+1)+1],!(++s<a&&r==o)){if(s<c)for(;re(r,tn),0!=--s;);else 0!==r?(r!=i&&(re(r,tn),s--),re(16,tn),ne(s-3,2)):s<=10?(re(17,tn),ne(s-3,3)):(re(18,tn),ne(s-11,7));i=r,c=(s=0)===o?(a=138,3):r==o?(a=6,3):(a=7,4)}}function oe(e,n,r){var i;for(ne(e-257,5),ne(n-1,5),ne(r-4,4),i=0;i<r;i++)ne(tn[2*t.bl_order[i]+1],3);ie(Ze,e-1),ie(Ke,n-1)}function se(){16==fn?(p(dn),fn=dn=0):8<=fn&&(d(255&dn),dn>>>=8,fn-=8)}function ae(){ne(2,3),re(f,e.static_ltree),se(),1+hn+10-fn<9&&(ne(2,3),re(f,e.static_ltree),se()),hn=7}function ce(e,n){var r,o;if(en.pending_buf[un+2*cn]=e>>>8&255,en.pending_buf[un+2*cn+1]=255&e,en.pending_buf[sn+cn]=255&n,cn++,0===e?Ze[2*n]++:(ln++,e--,Ze[2*(t._length_code[n]+l+1)]++,Ke[2*t.d_code(e)]++),0==(8191&cn)&&2<Ye){for(r=8*cn,n=Ue-Fe,o=0;o<30;o++)r+=Ke[2*o]*(5+t.extra_dbits[o]);if(r>>>=3,ln<Math.floor(cn/2)&&r<Math.floor(n/2))return!0}return cn==an-1}function ue(e,n){var r,i,o,s,a=0;if(0!==cn)for(;r=en.pending_buf[un+2*a]<<8&65280|255&en.pending_buf[un+2*a+1],i=255&en.pending_buf[sn+a],a++,0==r?re(i,e):(re((o=t._length_code[i])+l+1,e),0!==(s=t.extra_lbits[o])&&ne(i-=t.base_length[o],s),re(o=t.d_code(--r),n),0!==(s=t.extra_dbits[o])&&ne(r-=t.base_dist[o],s)),a<cn;);re(f,e),hn=e[513]}function le(){8<fn?p(dn):0<fn&&d(255&dn),fn=dn=0}function de(t,e,n){ne(0+(n?1:0),3),function(t,e,n){le(),hn=8,n&&(p(e),p(~e)),en.pending_buf.set(Ie.subarray(t,t+e),en.pending),en.pending+=e}(t,e,!0)}function pe(t){(function(t,n,r){var o,s,a=0;0<Ye?(nn.build_tree(en),rn.build_tree(en),a=u(),o=en.opt_len+3+7>>>3,(s=en.static_len+3+7>>>3)<=o&&(o=s)):o=s=n+5,n+4<=o&&-1!=t?de(t,n,r):s==o?(ne(2+(r?1:0),3),ue(e.static_ltree,e.static_dtree)):(ne(4+(r?1:0),3),oe(nn.max_code+1,rn.max_code+1,a+1),ue(Ze,Ke)),i(),r&&le()})(0<=Fe?Fe:-1,Ue-Fe,t),Fe=Ue,xe.flush_pending()}function me(){var t,e,n,r;do{if(0===(r=Pe-We-Ue)&&0===Ue&&0===We)r=Te;else if(-1==r)r--;else if(Te+Te-ee<=Ue){for(Ie.set(Ie.subarray(Te,Te+Te),0),He-=Te,Ue-=Te,Fe-=Te,n=t=Ne;e=65535&Oe[--n],Oe[n]=Te<=e?e-Te:0,0!=--t;);for(n=t=Te;e=65535&Ae[--n],Ae[n]=Te<=e?e-Te:0,0!=--t;);r+=Te}if(0===xe.avail_in)return}while(t=xe.read_buf(Ie,Ue+We,r),3<=(We+=t)&&(Re=((Re=255&Ie[Ue])<<Le^255&Ie[Ue+1])&De),We<ee&&0!==xe.avail_in)}function we(t){var e,n,r=Ge,i=Ue,o=Ve,s=Te-ee<Ue?Ue-(Te-ee):0,a=$e,c=qe,u=Ue+258,l=Ie[i+o-1],h=Ie[i+o];Qe<=Ve&&(r>>=2),We<a&&(a=We);do{if(Ie[(e=t)+o]==h&&Ie[e+o-1]==l&&Ie[e]==Ie[i]&&Ie[++e]==Ie[i+1]){for(i+=2,e++;Ie[++i]==Ie[++e]&&Ie[++i]==Ie[++e]&&Ie[++i]==Ie[++e]&&Ie[++i]==Ie[++e]&&Ie[++i]==Ie[++e]&&Ie[++i]==Ie[++e]&&Ie[++i]==Ie[++e]&&Ie[++i]==Ie[++e]&&i<u;);if(n=258-(u-i),i=u-258,o<n){if(He=t,a<=(o=n))break;l=Ie[i+o-1],h=Ie[i+o]}}}while((t=65535&Ae[t&c])>s&&0!=--r);return o<=We?o:We}function be(t){return t.total_in=t.total_out=0,t.msg=null,en.pending=0,en.pending_out=0,ke=X,Se=0,nn.dyn_tree=Ze,nn.stat_desc=e.static_l_desc,rn.dyn_tree=Ke,rn.stat_desc=e.static_d_desc,on.dyn_tree=tn,on.stat_desc=e.static_bl_desc,fn=dn=0,hn=8,i(),function(){var t;for(Pe=2*Te,t=Oe[Ne-1]=0;t<Ne-1;t++)Oe[t]=0;Xe=M[Ye].max_lazy,Qe=M[Ye].good_length,$e=M[Ye].nice_length,Ge=M[Ye].max_chain,Me=Ve=2,Re=ze=We=Fe=Ue=0}(),0}var xe,ke,Ce,Se,Te,_e,qe,Ie,Pe,Ae,Oe,Re,Ne,Be,De,Le,Fe,Me,je,ze,Ue,He,We,Ve,Ge,Xe,Ye,Je,Qe,$e,Ze,Ke,tn,sn,an,cn,un,ln,hn,dn,fn,en=this,nn=new t,rn=new t,on=new t;en.depth=[],en.bl_count=[],en.heap=[],Ze=[],Ke=[],tn=[],en.pqdownheap=function(t,e){for(var n=en.heap,i=n[e],o=e<<1;o<=en.heap_len&&(o<en.heap_len&&r(t,n[o+1],n[o],en.depth)&&o++,!r(t,i,n[o],en.depth));)n[e]=n[o],e=o,o<<=1;n[e]=i},en.deflateInit=function(t,e,n,r,i,o){return r=r||8,i=i||8,o=o||0,t.msg=null,-1==e&&(e=6),i<1||9<i||8!=r||n<9||15<n||e<0||9<e||o<0||2<o?P:(t.dstate=en,qe=(Te=1<<(_e=n))-1,De=(Ne=1<<(Be=i+7))-1,Le=Math.floor((Be+3-1)/3),Ie=new Uint8Array(2*Te),Ae=[],Oe=[],an=1<<i+6,en.pending_buf=new Uint8Array(4*an),Ce=4*an,un=Math.floor(an/2),sn=3*an,Ye=e,Je=o,be(t))},en.deflateEnd=function(){return 42!=ke&&ke!=X&&ke!=Y?P:(en.pending_buf=null,Ie=Ae=Oe=null,en.dstate=null,ke==X?-3:0)},en.deflateParams=function(t,e,n){var r=0;return(e=-1==e?6:e)<0||9<e||n<0||2<n?P:(M[Ye].func!=M[e].func&&0!==t.total_in&&(r=t.deflate(1)),Ye!=e&&(Xe=M[Ye=e].max_lazy,Qe=M[Ye].good_length,$e=M[Ye].nice_length,Ge=M[Ye].max_chain),Je=n,r)},en.deflateSetDictionary=function(t,e,n){var r,i=n,o=0;if(!e||42!=ke)return P;if(!(i<3))for(Te-ee<i&&(o=n-(i=Te-ee)),Ie.set(e.subarray(o,o+i),0),Fe=Ue=i,Re=((Re=255&Ie[0])<<Le^255&Ie[1])&De,r=0;r<=i-3;r++)Re=(Re<<Le^255&Ie[r+2])&De,Ae[r&qe]=Oe[Re],Oe[Re]=r;return 0},en.deflate=function(t,e){var n,r,i,o,s;if(4<e||e<0)return P;if(!t.next_out||!t.next_in&&0!==t.avail_in||ke==Y&&4!=e)return t.msg=j[4],P;if(0===t.avail_out)return t.msg=j[7],O;if(xe=t,o=Se,Se=e,42==ke&&(r=8+(_e-8<<4)<<8,r|=(i=3<(i=(Ye-1&255)>>1)?3:i)<<6,0!==Ue&&(r|=32),ke=X,function(t){d(t>>8&255),d(255&t)}(r+=31-r%31)),0!==en.pending){if(xe.flush_pending(),0===xe.avail_out)return Se=-1,0}else if(0===xe.avail_in&&e<=o&&4!=e)return xe.msg=j[7],O;if(ke==Y&&0!==xe.avail_in)return t.msg=j[7],O;if(0!==xe.avail_in||0!==We||0!=e&&ke!=Y){switch(s=-1,M[Ye].func){case 0:s=function(t){var e,n=65535;for(Ce-5<n&&(n=Ce-5);;){if(We<=1){if(me(),0===We&&0==t)return 0;if(0===We)break}if(Ue+=We,e=Fe+n,((We=0)===Ue||e<=Ue)&&(We=Ue-e,Ue=e,pe(!1),0===xe.avail_out))return 0;if(Te-ee<=Ue-Fe&&(pe(!1),0===xe.avail_out))return 0}return pe(4==t),0===xe.avail_out?4==t?2:0:4==t?3:1}(e);break;case 1:s=function(t){for(var e,n=0;;){if(We<ee){if(me(),We<ee&&0==t)return 0;if(0===We)break}if(3<=We&&(Re=(Re<<Le^255&Ie[Ue+2])&De,n=65535&Oe[Re],Ae[Ue&qe]=Oe[Re],Oe[Re]=Ue),3<=(Me=0!==n&&(Ue-n&65535)<=Te-ee&&2!=Je?we(n):Me))if(e=ce(Ue-He,Me-3),We-=Me,Me<=Xe&&3<=We){for(Me--;Re=(Re<<Le^255&Ie[++Ue+2])&De,n=65535&Oe[Re],Ae[Ue&qe]=Oe[Re],Oe[Re]=Ue,0!=--Me;);Ue++}else Ue+=Me,Me=0,Re=((Re=255&Ie[Ue])<<Le^255&Ie[Ue+1])&De;else e=ce(0,255&Ie[Ue]),We--,Ue++;if(e&&(pe(!1),0===xe.avail_out))return 0}return pe(4==t),0===xe.avail_out?4==t?2:0:4==t?3:1}(e);break;case 2:s=function(t){for(var e,n,r=0;;){if(We<ee){if(me(),We<ee&&0==t)return 0;if(0===We)break}if(3<=We&&(Re=(Re<<Le^255&Ie[Ue+2])&De,r=65535&Oe[Re],Ae[Ue&qe]=Oe[Re],Oe[Re]=Ue),Ve=Me,je=He,Me=2,0!==r&&Ve<Xe&&(Ue-r&65535)<=Te-ee&&(Me=2!=Je?we(r):Me)<=5&&(1==Je||3==Me&&4096<Ue-He)&&(Me=2),3<=Ve&&Me<=Ve){for(n=Ue+We-3,e=ce(Ue-1-je,Ve-3),We-=Ve-1,Ve-=2;++Ue<=n&&(Re=(Re<<Le^255&Ie[Ue+2])&De,r=65535&Oe[Re],Ae[Ue&qe]=Oe[Re],Oe[Re]=Ue),0!=--Ve;);if(ze=0,Me=2,Ue++,e&&(pe(!1),0===xe.avail_out))return 0}else if(0!==ze){if((e=ce(0,255&Ie[Ue-1]))&&pe(!1),Ue++,We--,0===xe.avail_out)return 0}else ze=1,Ue++,We--}return 0!==ze&&(e=ce(0,255&Ie[Ue-1]),ze=0),pe(4==t),0===xe.avail_out?4==t?2:0:4==t?3:1}(e)}if(2!=s&&3!=s||(ke=Y),0==s||2==s)return 0===xe.avail_out&&(Se=-1),0;if(1==s){if(1==e)ae();else if(de(0,0,!1),3==e)for(n=0;n<Ne;n++)Oe[n]=0;if(xe.flush_pending(),0===xe.avail_out)return Se=-1,0}}return 4!=e?0:1}}function o(){var t=this;t.next_in_index=0,t.next_out_index=0,t.avail_in=0,t.total_in=0,t.avail_out=0,t.total_out=0}var l=256,f=256,P=-2,O=-5,R=[0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,0,0,16,17,18,18,19,19,20,20,20,20,21,21,21,21,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29],M=(t._length_code=[0,1,2,3,4,5,6,7,8,8,9,9,10,10,11,11,12,12,12,12,13,13,13,13,14,14,14,14,15,15,15,15,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28],t.base_length=[0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224,0],t.base_dist=[0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096,6144,8192,12288,16384,24576],t.d_code=function(t){return t<256?R[t]:R[256+(t>>>7)]},t.extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],t.extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],t.extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],t.bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],e.static_ltree=[12,8,140,8,76,8,204,8,44,8,172,8,108,8,236,8,28,8,156,8,92,8,220,8,60,8,188,8,124,8,252,8,2,8,130,8,66,8,194,8,34,8,162,8,98,8,226,8,18,8,146,8,82,8,210,8,50,8,178,8,114,8,242,8,10,8,138,8,74,8,202,8,42,8,170,8,106,8,234,8,26,8,154,8,90,8,218,8,58,8,186,8,122,8,250,8,6,8,134,8,70,8,198,8,38,8,166,8,102,8,230,8,22,8,150,8,86,8,214,8,54,8,182,8,118,8,246,8,14,8,142,8,78,8,206,8,46,8,174,8,110,8,238,8,30,8,158,8,94,8,222,8,62,8,190,8,126,8,254,8,1,8,129,8,65,8,193,8,33,8,161,8,97,8,225,8,17,8,145,8,81,8,209,8,49,8,177,8,113,8,241,8,9,8,137,8,73,8,201,8,41,8,169,8,105,8,233,8,25,8,153,8,89,8,217,8,57,8,185,8,121,8,249,8,5,8,133,8,69,8,197,8,37,8,165,8,101,8,229,8,21,8,149,8,85,8,213,8,53,8,181,8,117,8,245,8,13,8,141,8,77,8,205,8,45,8,173,8,109,8,237,8,29,8,157,8,93,8,221,8,61,8,189,8,125,8,253,8,19,9,275,9,147,9,403,9,83,9,339,9,211,9,467,9,51,9,307,9,179,9,435,9,115,9,371,9,243,9,499,9,11,9,267,9,139,9,395,9,75,9,331,9,203,9,459,9,43,9,299,9,171,9,427,9,107,9,363,9,235,9,491,9,27,9,283,9,155,9,411,9,91,9,347,9,219,9,475,9,59,9,315,9,187,9,443,9,123,9,379,9,251,9,507,9,7,9,263,9,135,9,391,9,71,9,327,9,199,9,455,9,39,9,295,9,167,9,423,9,103,9,359,9,231,9,487,9,23,9,279,9,151,9,407,9,87,9,343,9,215,9,471,9,55,9,311,9,183,9,439,9,119,9,375,9,247,9,503,9,15,9,271,9,143,9,399,9,79,9,335,9,207,9,463,9,47,9,303,9,175,9,431,9,111,9,367,9,239,9,495,9,31,9,287,9,159,9,415,9,95,9,351,9,223,9,479,9,63,9,319,9,191,9,447,9,127,9,383,9,255,9,511,9,0,7,64,7,32,7,96,7,16,7,80,7,48,7,112,7,8,7,72,7,40,7,104,7,24,7,88,7,56,7,120,7,4,7,68,7,36,7,100,7,20,7,84,7,52,7,116,7,3,8,131,8,67,8,195,8,35,8,163,8,99,8,227,8],e.static_dtree=[0,5,16,5,8,5,24,5,4,5,20,5,12,5,28,5,2,5,18,5,10,5,26,5,6,5,22,5,14,5,30,5,1,5,17,5,9,5,25,5,5,5,21,5,13,5,29,5,3,5,19,5,11,5,27,5,7,5,23,5],e.static_l_desc=new e(e.static_ltree,t.extra_lbits,257,286,15),e.static_d_desc=new e(e.static_dtree,t.extra_dbits,0,30,15),e.static_bl_desc=new e(null,t.extra_blbits,0,19,7),[new n(0,0,0,0,0),new n(4,4,8,4,1),new n(4,5,16,8,1),new n(4,6,32,32,1),new n(4,4,16,16,2),new n(8,16,32,32,2),new n(8,16,128,128,2),new n(8,32,128,256,2),new n(32,128,258,1024,2),new n(32,258,258,4096,2)]),j=["need dictionary","stream end","","","stream error","data error","","buffer error","",""],X=113,Y=666,ee=262;return o.prototype={deflateInit:function(t,e){var n=this;return n.dstate=new i,n.dstate.deflateInit(n,t,e=e||15)},deflate:function(t){var e=this;return e.dstate?e.dstate.deflate(e,t):P},deflateEnd:function(){var e,t=this;return t.dstate?(e=t.dstate.deflateEnd(),t.dstate=null,e):P},deflateParams:function(t,e){var n=this;return n.dstate?n.dstate.deflateParams(n,t,e):P},deflateSetDictionary:function(t,e){var n=this;return n.dstate?n.dstate.deflateSetDictionary(n,t,e):P},read_buf:function(t,e,n){var r=this,i=r.avail_in;return 0===(i=n<i?n:i)?0:(r.avail_in-=i,t.set(r.next_in.subarray(r.next_in_index,r.next_in_index+i),e),r.next_in_index+=i,r.total_in+=i,i)},flush_pending:function(){var t=this,e=t.dstate.pending;0!==(e=e>t.avail_out?t.avail_out:e)&&(t.next_out.set(t.dstate.pending_buf.subarray(t.dstate.pending_out,t.dstate.pending_out+e),t.next_out_index),t.next_out_index+=e,t.dstate.pending_out+=e,t.total_out+=e,t.avail_out-=e,t.dstate.pending-=e,0===t.dstate.pending)&&(t.dstate.pending_out=0)}},function(t){var n=new o,r=512,s=new Uint8Array(r);n.deflateInit(t=void 0===t?-1:t),n.next_out=s,this.append=function(t,e){var a,c=[],u=0,l=0,h=0;if(t.length){n.next_in_index=0,n.next_in=t,n.avail_in=t.length;do{if(n.next_out_index=0,n.avail_out=r,0!=n.deflate(0))throw"deflating: "+n.msg}while(n.next_out_index&&c.push(n.next_out_index==r?new Uint8Array(s):new Uint8Array(s.subarray(0,n.next_out_index))),h+=n.next_out_index,e&&0<n.next_in_index&&n.next_in_index!=u&&(e(n.next_in_index),u=n.next_in_index),0<n.avail_in||0===n.avail_out);return a=new Uint8Array(h),c.forEach(function(t){a.set(t,l),l+=t.length}),a}},this.flush=function(){var t,e,i=[],o=0,a=0;do{if(n.next_out_index=0,n.avail_out=r,1!=(t=n.deflate(4))&&0!=t)throw"deflating: "+n.msg}while(0<r-n.avail_out&&i.push(new Uint8Array(s.subarray(0,n.next_out_index))),a+=n.next_out_index,0<n.avail_in||0===n.avail_out);return n.deflateEnd(),e=new Uint8Array(a),i.forEach(function(t){e.set(t,o),o+=t.length}),e}}}()),html2canvasNodeAttribute=(!function(t,e,n,r,i,o,s){function c(t,n,r,i,o){var s=n.contentWindow,a=new Ne(s.document),c=new I(r,a),f=M(t),g=new Ue("view"===r.type?i:function(t){return Math.max(Math.max(t.body.scrollWidth,t.documentElement.scrollWidth),Math.max(t.body.offsetWidth,t.documentElement.offsetWidth),Math.max(t.body.clientWidth,t.documentElement.clientWidth))}(s.document),"view"===r.type?o:function(t){return Math.max(Math.max(t.body.scrollHeight,t.documentElement.scrollHeight),Math.max(t.body.offsetHeight,t.documentElement.offsetHeight),Math.max(t.body.clientHeight,t.documentElement.clientHeight))}(s.document),c,r,e);return new z(t,g,a,c,r).ready.then(function(){var e;return A("Finished rendering"),e="view"===r.type?l(g.canvas,{width:g.canvas.width,height:g.canvas.height,top:0,left:0,x:0,y:0}):t===s.document.body||t===s.document.documentElement||null!=r.canvas?g.canvas:l(g.canvas,{width:(null!=r.width?r:f).width,height:(null!=r.height?r:f).height,top:f.top,left:f.left,x:s.pageXOffset,y:s.pageYOffset}),function(t,e){e.removeContainer&&(t.parentNode.removeChild(t),A("Cleaned up container"))}(n,r),e})}function l(t,n){var r=e.createElement("canvas"),i=Math.min(t.width-1,Math.max(0,n.left)),o=Math.min(t.width,Math.max(1,n.left+n.width)),s=Math.min(t.height-1,Math.max(0,n.top)),a=Math.min(t.height,Math.max(1,n.top+n.height));return r.width=n.width,r.height=n.height,A("Cropping canvas at:","left:",n.left,"top:",n.top,"width:",o-i,"height:",a-s),A("Resulting crop with width",n.width,"and height",n.height," with x",i,"and y",s),r.getContext("2d").drawImage(t,i,s,o-i,a-s,n.x,n.y,o-i,a-s),r}function f(){return"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"}function p(t,e,n,r,i){!function(t){[].slice.call(t.querySelectorAll("canvas"),0).forEach(function(t){t.setAttribute(Ve,"canvas-"+Ge++)})}(t);var o=t.documentElement.cloneNode(!0),s=e.createElement("iframe");return s.className="html2canvas-container",s.style.visibility="hidden",s.style.position="fixed",s.style.left="-10000px",s.style.top="0px",s.style.border="0",s.width=n,s.height=r,s.scrolling="no",e.body.appendChild(s),new Promise(function(e){var n=s.contentWindow.document,r=(s.contentWindow.onload=s.onload=function(){var o=setInterval(function(){0<n.body.childNodes.length&&(function(t,e){[].slice.call(t.querySelectorAll("["+Ve+"]"),0).forEach(function(t){try{var n=e.querySelector("["+Ve+'="'+t.getAttribute(Ve)+'"]');n&&(n.width=t.width,n.height=t.height,n.getContext("2d").putImageData(t.getContext("2d").getImageData(0,0,t.width,t.height),0,0))}catch(r){A("Unable to copy canvas content from",t,r)}t.removeAttribute(Ve)})}(t,n),clearInterval(o),"view"===i.type&&s.contentWindow.scrollTo(r,a),e(s))},50)},t.defaultView.pageXOffset),a=t.defaultView.pageYOffset;n.open(),n.write("<!DOCTYPE html><html></html>"),function(t,e,n){e===t.defaultView.pageXOffset&&n===t.defaultView.pageYOffset||t.defaultView.scrollTo(e,n)}(t,r,a),n.replaceChild(!0===i.javascriptEnabled?n.adoptNode(o):function b(t){return[].slice.call(t.childNodes,0).filter(x).forEach(function(e){"SCRIPT"===e.tagName?t.removeChild(e):b(e)}),t}(n.adoptNode(o)),n.documentElement),n.close()})}function g(e,n,r,i,o,s){return new Se(e,n,t.document).then(w(e)).then(function(t){return p(t,r,i,o,s)})}function w(t){return function(n){var r,i=new DOMParser;try{r=i.parseFromString(n,"text/html")}catch(o){A("DOMParser not supported, falling back to createHTMLDocument"),r=e.implementation.createHTMLDocument("");try{r.open(),r.write(n),r.close()}catch(s){A("createHTMLDocument write not supported, falling back to document.body.innerHTML"),r.body.innerHTML=n}}i=r.querySelector("base");return i&&i.href.host||((n=r.createElement("base")).href=t,r.head.insertBefore(n,r.head.firstChild)),r}}function x(t){return t.nodeType===Node.ELEMENT_NODE}function C(t){var e;A("DummyImageContainer for",this.src=t),this.promise&&this.image||(A("Initiating DummyImageContainer"),C.prototype.image=new Image,e=this.image,C.prototype.promise=new Promise(function(t,n){e.onload=t,e.onerror=n,e.src=f(),!0===e.complete&&t(e)}))}function E(t,n){var o=e.createElement("div"),s=e.createElement("img"),a=e.createElement("span"),c="Hidden Text";o.style.visibility="hidden",o.style.fontFamily=t,o.style.fontSize=n,o.style.margin=0,o.style.padding=0,e.body.appendChild(o),s.src=f(),s.width=1,s.height=1,s.style.margin=0,s.style.padding=0,s.style.verticalAlign="baseline",a.style.fontFamily=t,a.style.fontSize=n,a.style.margin=0,a.style.padding=0,a.appendChild(e.createTextNode(c)),o.appendChild(a),o.appendChild(s),t=s.offsetTop-a.offsetTop+1,o.removeChild(a),o.appendChild(e.createTextNode(c)),o.style.lineHeight="normal",s.style.verticalAlign="super",n=s.offsetTop-o.offsetTop+1,e.body.removeChild(o),this.baseline=t,this.lineWidth=1,this.middle=n}function S(){this.data={}}function T(t,e,n){this.image=null,this.src=t;var r=this,i=M(t);this.promise=(e?new Promise(function(e){"about:blank"===t.contentWindow.document.URL||null==t.contentWindow.document.documentElement?t.contentWindow.onload=t.onload=function(){e(t)}:e(t)}):this.proxyLoad(n.proxy,i,n)).then(function(t){return html2canvas(t.contentWindow.document.documentElement,{type:"view",width:t.width,height:t.height,proxy:n.proxy,javascriptEnabled:n.javascriptEnabled,removeContainer:n.removeContainer,allowTaint:n.allowTaint,imageTimeout:n.imageTimeout/2})}).then(function(t){return r.image=t})}function _(t){this.src=t.value,this.colorStops=[],this.type=null,this.x0=.5,this.y0=.5,this.x1=.5,this.y1=.5,this.promise=Promise.resolve(!0)}function q(t,e){this.src=t,this.image=new Image;var n=this;this.tainted=null,this.promise=new Promise(function(r,i){n.image.onload=r,n.image.onerror=i,e&&(n.image.crossOrigin="anonymous"),n.image.src=t,!0===n.image.complete&&r(n.image)})}function I(e,n){this.link=null,this.options=e,this.support=n,this.origin=this.getOrigin(t.location.href)}function P(t){_.apply(this,arguments),this.type=this.TYPES.LINEAR;var e=null===t.args[0].match(this.stepRegExp);e?t.args[0].split(" ").reverse().forEach(function(t){switch(t){case"left":this.x0=0,this.x1=1;break;case"top":this.y0=0,this.y1=1;break;case"right":this.x0=1,this.x1=0;break;case"bottom":this.y0=1,this.y1=0;break;case"to":var e=this.y0,n=this.x0;this.y0=this.y1,this.x0=this.x1,this.x1=n,this.y1=e}},this):(this.y0=0,this.y1=1),this.colorStops=t.args.slice(e?1:0).map(function(t){t=t.match(this.stepRegExp);return{color:t[1],stop:"%"===t[3]?t[2]/100:null}},this),null===this.colorStops[0].stop&&(this.colorStops[0].stop=0),null===this.colorStops[this.colorStops.length-1].stop&&(this.colorStops[this.colorStops.length-1].stop=1),this.colorStops.forEach(function(t,e){null===t.stop&&this.colorStops.slice(e).some(function(n,r){return null!==n.stop&&(t.stop=(n.stop-this.colorStops[e-1].stop)/(r+1)+this.colorStops[e-1].stop,!0)},this)},this)}function A(){t.html2canvas.logging&&t.console&&t.console.log&&Function.prototype.bind.call(t.console.log,t.console).apply(t.console,[Date.now()-t.html2canvas.start+"ms","html2canvas:"].concat([].slice.call(arguments,0)))}function O(t,e){this.node=t,this.parent=e,this.stack=null,this.bounds=null,this.borders=null,this.clip=[],this.backgroundClip=[],this.offsetBounds=null,this.visible=null,this.computedStyles=null,this.styles={},this.backgroundImages=null,this.transformData=null,this.transformMatrix=null,this.isPseudoElement=!1,this.opacity=null}function B(t){return-1!==t.toString().indexOf("%")}function D(t){function d(){e&&((n='"'===n.substr(0,1)?n.substr(1,n.length-2):n)&&a.push(n),"-"===e.substr(0,1)&&0<(i=e.indexOf("-",1)+1)&&(r=e.substr(0,i),e=e.substr(i)),u.push({prefix:r,method:e.toLowerCase(),value:o,args:a,image:null})),a=[],e=r=n=o=""}var n,r,i,o,s,u=[],l=0,h=0,a=[],e=r=n=o="";return t.split("").forEach(function(t){if(!(0===l&&-1<" \r\n\t".indexOf(t))){switch(t){case'"':s?s===t&&(s=null):s=t;break;case"(":if(!s){if(0===l)return l=1,void(o+=t);h++}break;case")":if(!s&&1===l){if(0===h)return l=0,o+=t,void d();h--}break;case",":if(!s){if(0===l)return void d();if(1===l&&0===h&&!e.match(/^url$/i))return a.push(n),n="",void(o+=t)}}o+=t,0===l?e+=t:n+=t}}),d(),u}function L(t){return t.replace("px","")}function F(t){return parseFloat(t)}function M(t){var e,n;return t.getBoundingClientRect?(e=t.getBoundingClientRect(),n=null==t.offsetWidth?e.width:t.offsetWidth,{top:e.top,bottom:e.bottom||e.top+e.height,right:e.left+n,left:e.left,width:n,height:null==t.offsetHeight?e.height:t.offsetHeight}):{}}function j(t){var e=t.offsetParent?j(t.offsetParent):{top:0,left:0};return{top:t.offsetTop+e.top,bottom:t.offsetTop+t.offsetHeight+e.top,right:t.offsetLeft+e.left+t.offsetWidth,left:t.offsetLeft+e.left,width:t.offsetWidth,height:t.offsetHeight}}function z(t,e,n,r,i){A("Starting NodeParser"),this.renderer=e,this.options=i,this.range=null,this.support=n,this.renderQueue=[],this.stack=new Re(!0,1,t.ownerDocument,null);var s,n=new O(t,null);t===t.ownerDocument.documentElement&&(s=new O(this.renderer.isTransparent(n.css("backgroundColor"))?t.ownerDocument.body:t.ownerDocument.documentElement,null),e.rectangle(0,0,e.width,e.height,s.css("backgroundColor"))),n.visibile=n.isElementVisible(),this.createPseudoHideStyles(t.ownerDocument),this.disableAnimations(t.ownerDocument),this.nodes=be([n].concat(this.getChildren(n)).filter(function(t){return t.visible=t.isElementVisible()}).map(this.getPseudoElements,this)),this.fontMetrics=new S,A("Fetched nodes, total:",this.nodes.length),A("Calculate overflow clips"),this.calculateOverflowClips(),A("Start fetching images"),this.images=r.fetch(this.nodes.filter(he)),this.ready=this.images.ready.then(ge(function(){return A("Images loaded, starting parsing"),A("Creating stacking contexts"),this.createStackingContexts(),A("Sorting stacking contexts"),this.sortStackingContexts(this.stack),this.parse(this.stack),A("Render queue created with "+this.renderQueue.length+" items"),new Promise(ge(function(t){i.async?"function"==typeof i.async?i.async.call(this,this.renderQueue,t):0<this.renderQueue.length?(this.renderIndex=0,this.asyncRenderer(this.renderQueue,t)):t():(this.renderQueue.forEach(this.paint,this),t())},this))},this))}function U(t){return t.parent&&t.parent.clip.length}function W(){}function V(t,e,n,r){return t.map(function(i,o){if(0<i.width){var s=e.left,a=e.top,c=e.width,u=e.height-t[2].width;switch(o){case 0:u=t[0].width,i.args=J({c1:[s,a],c2:[s+c,a],c3:[s+c-t[1].width,a+u],c4:[s+t[3].width,a+u]},r[0],r[1],n.topLeftOuter,n.topLeftInner,n.topRightOuter,n.topRightInner);break;case 1:s=e.left+e.width-t[1].width,c=t[1].width,i.args=J({c1:[s+c,a],c2:[s+c,a+u+t[2].width],c3:[s,a+u],c4:[s,a+t[0].width]},r[1],r[2],n.topRightOuter,n.topRightInner,n.bottomRightOuter,n.bottomRightInner);break;case 2:a=a+e.height-t[2].width,u=t[2].width,i.args=J({c1:[s+c,a+u],c2:[s,a+u],c3:[s+t[3].width,a],c4:[s+c-t[3].width,a]},r[2],r[3],n.bottomRightOuter,n.bottomRightInner,n.bottomLeftOuter,n.bottomLeftInner);break;case 3:c=t[3].width,i.args=J({c1:[s,a+u+t[2].width],c2:[s,a],c3:[s+c,a+t[0].width],c4:[s+c,a+u]},r[3],r[0],n.bottomLeftOuter,n.bottomLeftInner,n.topLeftOuter,n.topLeftInner)}}return i})}function G(t,e,n,r){var i=(Math.sqrt(2)-1)/3*4,o=n*i,i=r*i,n=t+n,r=e+r;return{topLeft:Y({x:t,y:r},{x:t,y:r-i},{x:n-o,y:e},{x:n,y:e}),topRight:Y({x:t,y:e},{x:t+o,y:e},{x:n,y:r-i},{x:n,y:r}),bottomRight:Y({x:n,y:e},{x:n,y:e+i},{x:t+o,y:r},{x:t,y:r}),bottomLeft:Y({x:n,y:r},{x:n-o,y:r},{x:t,y:e+i},{x:t,y:e})}}function X(t,e,n){var r=t.left,i=t.top,o=t.width,t=t.height,a=e[0][0],c=e[0][1],u=e[1][0],l=e[1][1],h=e[2][0],d=e[2][1],f=e[3][0],e=e[3][1],m=o-u,g=t-d,w=o-h,y=t-e;return{topLeftOuter:G(r,i,a,c).topLeft.subdivide(.5),topLeftInner:G(r+n[3].width,i+n[0].width,Math.max(0,a-n[3].width),Math.max(0,c-n[0].width)).topLeft.subdivide(.5),topRightOuter:G(r+m,i,u,l).topRight.subdivide(.5),topRightInner:G(r+Math.min(m,o+n[3].width),i+n[0].width,m>o+n[3].width?0:u-n[3].width,l-n[0].width).topRight.subdivide(.5),bottomRightOuter:G(r+w,i+g,h,d).bottomRight.subdivide(.5),bottomRightInner:G(r+Math.min(w,o-n[3].width),i+Math.min(g,t+n[0].width),Math.max(0,h-n[1].width),d-n[2].width).bottomRight.subdivide(.5),bottomLeftOuter:G(r,i+y,f,e).bottomLeft.subdivide(.5),bottomLeftInner:G(r+n[3].width,i+y,Math.max(0,f-n[3].width),e-n[2].width).bottomLeft.subdivide(.5)}}function Y(t,e,n,r){function i(t,e,n){return{x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}}return{start:t,startControl:e,endControl:n,end:r,subdivide:function(o){var s=i(t,e,o),a=i(e,n,o),c=i(n,r,o),u=i(s,a,o),a=i(a,c,o),o=i(u,a,o);return[Y(t,s,u,o),Y(o,a,c,r)]},curveTo:function(t){t.push(["bezierCurve",e.x,e.y,n.x,n.y,r.x,r.y])},curveToReversed:function(r){r.push(["bezierCurve",n.x,n.y,e.x,e.y,t.x,t.y])}}}function J(t,e,n,r,i,o,s){var a=[];return 0<e[0]||0<e[1]?(a.push(["line",r[1].start.x,r[1].start.y]),r[1].curveTo(a)):a.push(["line",t.c1[0],t.c1[1]]),0<n[0]||0<n[1]?(a.push(["line",o[0].start.x,o[0].start.y]),o[0].curveTo(a),a.push(["line",s[0].end.x,s[0].end.y]),s[0].curveToReversed(a)):(a.push(["line",t.c2[0],t.c2[1]]),a.push(["line",t.c3[0],t.c3[1]])),0<e[0]||0<e[1]?(a.push(["line",i[1].end.x,i[1].end.y]),i[1].curveToReversed(a)):a.push(["line",t.c4[0],t.c4[1]]),a}function Q(t,e,n,r,i,o,s){0<e[0]||0<e[1]?(t.push(["line",r[0].start.x,r[0].start.y]),r[0].curveTo(t),r[1].curveTo(t)):t.push(["line",o,s]),(0<n[0]||0<n[1])&&t.push(["line",i[0].start.x,i[0].start.y])}function $(t){return t.cssInt("zIndex")<0}function Z(t){return 0<t.cssInt("zIndex")}function K(t){return 0===t.cssInt("zIndex")}function te(t){return-1!==["inline","inline-block","inline-table"].indexOf(t.css("display"))}function ee(t){return t instanceof Re}function ne(t){return 0<t.node.data.trim().length}function oe(t){return t.nodeType===Node.TEXT_NODE||t.nodeType===Node.ELEMENT_NODE}function ae(t){return"static"!==t.css("position")}function ce(t){return"none"!==t.css("float")}function le(t){var e=this;return function(){return!t.apply(e,arguments)}}function he(t){return t.node.nodeType===Node.ELEMENT_NODE}function de(t){return!0===t.isPseudoElement}function fe(t){return t.node.nodeType===Node.TEXT_NODE}function ge(t,e){return function(){return t.apply(e,arguments)}}function we(t){return parseInt(t,10)}function ye(t){return t.width}function ve(t){return t.node.nodeType!==Node.ELEMENT_NODE||-1===["SCRIPT","HEAD","TITLE","OBJECT","BR","OPTION"].indexOf(t.node.nodeName)}function be(t){return[].concat.apply([],t)}function Se(t,e,n){var r=qe(Ye),e=Ie(e,t,r);return Ye?ze(e):_e(n,e,r).then(function(t){return De(t.content)})}function Te(t,e,n){var r=qe(Je),e=Ie(e,t,r);return Je?Promise.resolve(e):_e(n,e,r).then(function(t){return"data:"+t.type+";base64,"+t.content})}function _e(e,n,r){return new Promise(function(i,o){function a(){delete t.html2canvas.proxy[r],e.body.removeChild(s)}var s=e.createElement("script");t.html2canvas.proxy[r]=function(t){a(),i(t)},s.src=n,s.onerror=function(t){a(),o(t)},e.body.appendChild(s)})}function qe(t){return t?"":"html2canvas_"+Date.now()+"_"+ ++Xe+"_"+Math.round(1e5*Math.random())}function Ie(t,e,n){return t+"?url="+encodeURIComponent(e)+(n.length?"&callback=html2canvas.proxy."+n:"")}function Pe(t,n){e.createElement("script");var r=e.createElement("a"),i=(r.href=t,t=r.href,this.src=t,this.image=new Image,this);this.promise=new Promise(function(r,o){i.image.crossOrigin="Anonymous",i.image.onload=r,i.image.onerror=o,new Te(t,n,e).then(function(t){i.image.src=t}).catch(o)})}function Ae(t,e,n){O.call(this,t,e),this.isPseudoElement=!0,this.before=":before"===n}function Oe(t,e,n,r,i){this.width=t,this.height=e,this.images=n,this.options=r,this.document=i}function Re(t,e,n,r){O.call(this,n,r),this.ownStacking=t,this.contexts=[],this.children=[],this.opacity=(this.parent?this.parent.stack.opacity:1)*e}function Ne(t){this.rangeBounds=this.testRangeBounds(t),this.cors=this.testCORS(),this.svg=this.testSVG()}function Be(t){this.src=t,this.image=null;var e=this;this.promise=this.hasFabric().then(function(){return e.isInline(t)?Promise.resolve(e.inlineFormatting(t)):ze(t)}).then(function(t){return new Promise(function(n){html2canvas.fabric.loadSVGFromString(t,e.createCanvas.call(e,n))})})}function De(t){for(var r,o,s,a,c,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=t.length,h="",e=0;e<l;e+=4)s=u.indexOf(t[e])<<2|(r=u.indexOf(t[e+1]))>>4,a=(15&r)<<4|(r=u.indexOf(t[e+2]))>>2,c=(3&r)<<6|(o=u.indexOf(t[e+3])),h+=64===r?String.fromCharCode(s):64===o||-1===o?String.fromCharCode(s,a):String.fromCharCode(s,a,c);return h}function Le(t,e){this.src=t,this.image=null;var n=this;this.promise=e?new Promise(function(e,r){n.image=new Image,n.image.onload=e,n.image.onerror=r,n.image.src="data:image/svg+xml,"+(new XMLSerializer).serializeToString(t),!0===n.image.complete&&e(n.image)}):this.hasFabric().then(function(){return new Promise(function(e){html2canvas.fabric.parseSVGDocument(t,n.createCanvas.call(n,e))})})}function Fe(t,e){O.call(this,t,e)}function Me(t,e,n){return 0<t.length?e+n.toUpperCase():void 0}function je(t){_.apply(this,arguments),this.type="linear"===t.args[0]?this.TYPES.LINEAR:this.TYPES.RADIAL}function ze(t){return new Promise(function(e,n){var r=new XMLHttpRequest;r.open("GET",t),r.onload=function(){200===r.status?e(r.responseText):n(new Error(r.statusText))},r.onerror=function(){n(new Error("Network Error"))},r.send()})}function Ue(t,e){Oe.apply(this,arguments),this.canvas=this.options.canvas||this.document.createElement("canvas"),this.options.canvas||(this.canvas.width=t,this.canvas.height=e),this.ctx=this.canvas.getContext("2d"),this.options.background&&this.rectangle(0,0,t,e,this.options.background),this.taintCtx=this.document.createElement("canvas").getContext("2d"),this.ctx.textBaseline="bottom",this.variables={},A("Initialized CanvasRenderer with size",t,"x",e)}function He(t){return 0<t.length}var We,Ve,Ge,Xe,Ye,Je;(function(){var n,r,s;!function(){var t={},e={};n=function(e,n,r){t[e]={deps:n,callback:r}},s=r=function(n){if(s._eak_seen=t,e[n])return e[n];if(e[n]={},!t[n])throw new Error("Could not find module "+n);for(var o,a=t[n],c=a.deps,a=a.callback,l=[],h=0,d=c.length;h<d;h++)l.push("exports"===c[h]?o={}:r(function(t){if("."!==t.charAt(0))return t;for(var e=t.split("/"),r=n.split("/").slice(0,-1),i=0,o=e.length;i<o;i++){var s=e[i];".."===s?r.pop():"."!==s&&r.push(s)}return r.join("/")}(c[h])));a=a.apply(this,l);return e[n]=o||a}}(),n("promise/all",["./utils","exports"],function(t,e){"use strict";var r=t.isArray,i=t.isFunction;e.all=function(t){if(r(t))return new this(function(e,n){function o(t,n){a[t]=n,0==--c&&e(a)}var s,a=[],c=t.length;0===c&&e([]);for(var u=0;u<t.length;u++)(s=t[u])&&i(s.then)?s.then(function(t){return function(e){o(t,e)}}(u),n):o(u,s)});throw new TypeError("You must pass an array to all.")}}),n("promise/asap",["exports"],function(n){"use strict";function a(){for(var t=0;t<f.length;t++){var e=f[t];(0,e[0])(e[1])}f=[]}var l=void 0!==t?t:{},h=l.MutationObserver||l.WebKitMutationObserver,d=void 0!==i?i:this,f=[],u=void 0!==process&&"[object process]"==={}.toString.call(process)?function(){process.nextTick(a)}:h?function(){var t=0,n=new h(a),r=e.createTextNode("");return n.observe(r,{characterData:!0}),function(){r.data=t=++t%2}}():function(){d.setTimeout(a,1)};n.asap=function(t,e){1===f.push([t,e])&&u()}}),n("promise/cast",["exports"],function(t){"use strict";t.cast=function(t){return t&&"object"==typeof t&&t.constructor===this?t:new this(function(e){e(t)})}}),n("promise/config",["exports"],function(t){"use strict";var n={instrument:!1};t.config=n,t.configure=function(t,e){return 2!==arguments.length?n[t]:void(n[t]=e)}}),n("promise/polyfill",["./promise","./utils","exports"],function(e,n,r){"use strict";var o=e.Promise,s=n.isFunction;r.polyfill=function(){"Promise"in t&&"cast"in t.Promise&&"resolve"in t.Promise&&"reject"in t.Promise&&"all"in t.Promise&&"race"in t.Promise&&function(){var e;return new t.Promise(function(t){e=t}),s(e)}()||(t.Promise=o)}}),n("promise/promise",["./config","./utils","./cast","./all","./race","./resolve","./reject","./asap","exports"],function(t,e,n,r,i,o,s,a,c){"use strict";function u(t){if(!k(t))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof u))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],function(t,e){function r(t){w(e,t)}try{t(function(t){m(e,t)},r)}catch(i){r(i)}}(t,this)}function h(t,e,n,r){var i,o,s,a,c=k(n);if(c)try{i=n(r),s=!0}catch(u){a=!0,o=u}else i=r,s=!0;p(e,i)||(c&&s?m(e,i):a?w(e,o):t===A?m(e,i):t===O&&w(e,i))}function f(t,e){for(var i=t._subscribers,o=t._detail,s=0;s<i.length;s+=3)h(e,i[s],i[s+e],o);t._subscribers=null}function p(t,e){var n,r=null;try{if(t===e)throw new TypeError("A promises callback cannot return that same promise.");if(x(e)&&(r=e.then,k(r)))return r.call(e,function(r){return!!n||(n=!0,void(e!==r?m:g)(t,r))},function(e){return!!n||(n=!0,void w(t,e))}),1}catch(i){return n||w(t,i),1}}function m(t,e){t!==e&&p(t,e)||g(t,e)}function g(t,e){t._state===I&&(t._state=P,t._detail=e,b.async(y,t))}function w(t,e){t._state===I&&(t._state=P,t._detail=e,b.async(v,t))}function y(t){f(t,t._state=A)}function v(t){f(t,t._state=O)}var b=t.config,x=(t.configure,e.objectOrFunction),k=e.isFunction,t=(e.now,n.cast),e=r.all,n=i.race,r=o.resolve,i=s.reject,o=a.asap,I=(b.async=o,void 0),P=0,A=1,O=2;u.prototype={constructor:u,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(t,e){var i,n=this,r=new this.constructor(function(){});return this._state?(i=arguments,b.async(function(){h(n._state,r,i[n._state-1],n._detail)})):function(t,e,n,r){var o=(t=t._subscribers).length;t[o]=e,t[o+A]=n,t[o+O]=r}(this,r,t,e),r},catch:function(t){return this.then(null,t)}},u.all=e,u.cast=t,u.race=n,u.resolve=r,u.reject=i,c.Promise=u}),n("promise/race",["./utils","exports"],function(t,e){"use strict";var r=t.isArray;e.race=function(t){if(r(t))return new this(function(e,n){for(var r,i=0;i<t.length;i++)(r=t[i])&&"function"==typeof r.then?r.then(e,n):e(r)});throw new TypeError("You must pass an array to race.")}}),n("promise/reject",["exports"],function(t){"use strict";t.reject=function(t){return new this(function(e,n){n(t)})}}),n("promise/resolve",["exports"],function(t){"use strict";t.resolve=function(t){return new this(function(e){e(t)})}}),n("promise/utils",["exports"],function(t){"use strict";function n(t){return"function"==typeof t}var i=Date.now||function(){return(new Date).getTime()};t.objectOrFunction=function(t){return n(t)||"object"==typeof t&&null!==t},t.isFunction=n,t.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},t.now=i}),r("promise/polyfill").polyfill()})(),"function"!=typeof Object.create||"function"!=typeof e.createElement("canvas").getContext?t.html2canvas=function(){return Promise.reject("No canvas support")}:(function(t){function e(t){throw RangeError(N[t])}function s(t,e){for(var n=t.length,r=[];n--;)r[n]=e(t[n]);return r}function a(t,e){var n=t.split("@"),r="",n=(1<n.length&&(r=n[0]+"@",t=n[1]),t.split(R));return r+s(n,e).join(".")}function c(t){for(var e,n,r=[],i=0,o=t.length;i<o;)55296<=(e=t.charCodeAt(i++))&&e<=56319&&i<o?56320==(64512&(n=t.charCodeAt(i++)))?r.push(((1023&e)<<10)+(1023&n)+65536):(r.push(e),i--):r.push(e);return r}function u(t){return s(t,function(t){var e="";return 65535<t&&(e+=L((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+L(t)}).join("")}function h(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,n){var r=0;for(t=n?D(t/_):t>>1,t+=D(t/e);B*S>>1<t;r+=C)t=D(t/B);return D(r+(B+1)*t/(t+T))}function f(t){var n,i,o,s,a,c,h,m=[],g=t.length,w=0,y=128,v=72,r=t.lastIndexOf("-");for(r<0&&(r=0),i=0;i<r;++i)128<=t.charCodeAt(i)&&e("not-basic"),m.push(t.charCodeAt(i));for(o=0<r?r+1:0;o<g;){for(s=w,a=1,c=C;g<=o&&e("invalid-input"),h=function(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:C}(t.charCodeAt(o++)),(C<=h||h>D((k-w)/a))&&e("overflow"),w+=h*a,!(h<(h=c<=v?1:v+S<=c?S:c-v));c+=C)a>D(k/(h=C-h))&&e("overflow"),a*=h;v=d(w-s,n=m.length+1,0==s),D(w/n)>k-y&&e("overflow"),y+=D(w/n),w%=n,m.splice(w++,0,y)}return u(m)}function p(t){for(var r,i,o,u,l,f,m,w,p,v,b=[],g=(t=c(t)).length,n=128,s=72,a=r=0;a<g;++a)(m=t[a])<128&&b.push(L(m));for(i=o=b.length,o&&b.push("-");i<g;){for(u=k,a=0;a<g;++a)n<=(m=t[a])&&m<u&&(u=m);for(u-n>D((k-r)/(w=i+1))&&e("overflow"),r+=(u-n)*w,n=u,a=0;a<g;++a)if((m=t[a])<n&&++r>k&&e("overflow"),m==n){for(l=r,f=C;!(l<(p=f<=s?1:s+S<=f?S:f-s));f+=C)b.push(L(h(p+(v=l-p)%(p=C-p),0))),l=D(v/p);b.push(L(h(l,0))),s=d(r,w,i==o),r=0,++i}++r,++n}return b.join("")}var w="object"==typeof r&&r&&!r.nodeType&&r,y="object"==typeof n&&n&&!n.nodeType&&n,v="object"==typeof i&&i;v.global!==v&&v.window!==v&&v.self!==v||(t=v);var x,k=2147483647,C=36,S=26,T=38,_=700,A=/^xn--/,O=/[^\x20-\x7E]/,R=/[\x2E\u3002\uFF0E\uFF61]/g,N={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},B=C-1,D=Math.floor,L=String.fromCharCode,b={version:"1.3.1",ucs2:{decode:c,encode:u},decode:f,encode:p,toASCII:function(t){return a(t,function(t){return O.test(t)?"xn--"+p(t):t})},toUnicode:function(t){return a(t,function(t){return A.test(t)?f(t.slice(4).toLowerCase()):t})}};if("function"==typeof o&&"object"==typeof o.amd&&o.amd)o("punycode",function(){return b});else if(w&&y)if(n.exports==w)y.exports=b;else for(x in b)b.hasOwnProperty(x)&&(w[x]=b[x]);else t.punycode=b}(this),We="data-html2canvas-node",Ve="data-html2canvas-canvas-clone",Ge=0,t.html2canvas=function(n,r){return(r=r||{}).logging&&(t.html2canvas.logging=!0,t.html2canvas.start=Date.now()),r.async=void 0===r.async||r.async,r.allowTaint=void 0!==r.allowTaint&&r.allowTaint,r.removeContainer=void 0===r.removeContainer||r.removeContainer,r.javascriptEnabled=void 0!==r.javascriptEnabled&&r.javascriptEnabled,r.imageTimeout=void 0===r.imageTimeout?1e4:r.imageTimeout,"string"==typeof n?"string"!=typeof r.proxy?Promise.reject("Proxy must be used when rendering url"):g(function(t){var n=e.createElement("a");return n.href=t,n.href=n.href,n}(n),r.proxy,e,t.innerWidth,t.innerHeight,r).then(function(e){return c(e.contentWindow.document.documentElement,e,r,t.innerWidth,t.innerHeight)}):((n=(n===s?[e.documentElement]:n.length?n:[n])[0]).setAttribute(We,"true"),function(t,e,n,r){return p(t,t,n,r,e).then(function(i){A("Document cloned");var o="["+We+"='true']",s=(t.querySelector(o).removeAttribute(We),i.contentWindow),a=s.document.querySelector(o);return Promise.resolve("function"!=typeof e.onclone||e.onclone(s.document)).then(function(){return c(a,i,e,n,r)})})}(n.ownerDocument,r,n.ownerDocument.defaultView.innerWidth,n.ownerDocument.defaultView.innerHeight).then(function(t){return"function"==typeof r.onrendered&&(A("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas"),r.onrendered(t)),t}))},t.html2canvas.punycode=this.punycode,t.html2canvas.proxy={},S.prototype.getMetrics=function(t,e){return this.data[t+"-"+e]===s&&(this.data[t+"-"+e]=new E(t,e)),this.data[t+"-"+e]},T.prototype.proxyLoad=function(t,e,n){var r=this.src;return g(r.src,t,r.ownerDocument,e.width,e.height,n)},_.prototype.TYPES={LINEAR:1,RADIAL:2},I.prototype.findImages=function(t){var e=[];return t.reduce(function(t,e){switch(e.node.nodeName){case"IMG":return t.concat([{args:[e.node.src],method:"url"}]);case"svg":case"IFRAME":return t.concat([{args:[e.node],method:e.node.nodeName}])}return t},[]).forEach(this.addImage(e,this.loadImage),this),e},I.prototype.findBackgroundImage=function(t,e){return e.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(t,this.loadImage),this),t},I.prototype.addImage=function(t,e){return function(n){n.args.forEach(function(r){this.imageExists(t,r)||(t.splice(0,0,e.call(this,n)),A("Added image #"+t.length,"string"==typeof r?r.substring(0,100):r))},this)}},I.prototype.hasImageBackground=function(t){return"none"!==t.method},I.prototype.loadImage=function(t){var e;return"url"===t.method?(e=t.args[0],!this.isSVG(e)||this.support.svg||this.options.allowTaint?e.match(/data:image\/.*;base64,/i)?new q(e.replace(/url\(['"]{0,}|['"]{0,}\)$/gi,""),!1):this.isSameOrigin(e)||!0===this.options.allowTaint||this.isSVG(e)?new q(e,!1):this.support.cors&&!this.options.allowTaint&&this.options.useCORS?new q(e,!0):this.options.proxy?new Pe(e,this.options.proxy):new C(e):new Be(e)):"linear-gradient"===t.method?new P(t):"gradient"===t.method?new je(t):"svg"===t.method?new Le(t.args[0],this.support.svg):"IFRAME"===t.method?new T(t.args[0],this.isSameOrigin(t.args[0].src),this.options):new C(t)},I.prototype.isSVG=function(t){return"svg"===t.substring(t.length-3).toLowerCase()||Be.prototype.isInline(t)},I.prototype.imageExists=function(t,e){return t.some(function(t){return t.src===e})},I.prototype.isSameOrigin=function(t){return this.getOrigin(t)===this.origin},I.prototype.getOrigin=function(t){var n=this.link||(this.link=e.createElement("a"));return n.href=t,n.href=n.href,n.protocol+n.hostname+n.port},I.prototype.getPromise=function(t){return this.timeout(t,this.options.imageTimeout).catch(function(){return new C(t.src).promise.then(function(e){t.image=e})})},I.prototype.get=function(t){var e=null;return this.images.some(function(n){return(e=n).src===t})?e:null},I.prototype.fetch=function(t){return this.images=t.reduce(ge(this.findBackgroundImage,this),this.findImages(t)),this.images.forEach(function(t,e){t.promise.then(function(){A("Succesfully loaded image #"+(e+1),t)},function(n){A("Failed loading image #"+(e+1),t,n)})}),this.ready=Promise.all(this.images.map(this.getPromise,this)),A("Finished searching images"),this},I.prototype.timeout=function(t,e){var n;return Promise.race([t.promise,new Promise(function(r,i){n=setTimeout(function(){A("Timed out loading image",t),i(t)},e)})]).then(function(t){return clearTimeout(n),t})},(P.prototype=Object.create(_.prototype)).stepRegExp=/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/,O.prototype.cloneTo=function(t){t.visible=this.visible,t.borders=this.borders,t.bounds=this.bounds,t.clip=this.clip,t.backgroundClip=this.backgroundClip,t.computedStyles=this.computedStyles,t.styles=this.styles,t.backgroundImages=this.backgroundImages,t.opacity=this.opacity},O.prototype.getOpacity=function(){return null===this.opacity?this.opacity=this.cssFloat("opacity"):this.opacity},O.prototype.assignStack=function(t){(this.stack=t).children.push(this)},O.prototype.isElementVisible=function(){return this.node.nodeType===Node.TEXT_NODE?this.parent.visible:"none"!==this.css("display")&&"hidden"!==this.css("visibility")&&!this.node.hasAttribute("data-html2canvas-ignore")&&("INPUT"!==this.node.nodeName||"hidden"!==this.node.getAttribute("type"))},O.prototype.css=function(t){return this.computedStyles||(this.computedStyles=this.isPseudoElement?this.parent.computedStyle(this.before?":before":":after"):this.computedStyle(null)),this.styles[t]||(this.styles[t]=this.computedStyles[t])},O.prototype.prefixedCss=function(t){var n=this.css(t);return n===s&&["webkit","moz","ms","o"].some(function(e){return(n=this.css(e+t.substr(0,1).toUpperCase()+t.substr(1)))!==s},this),n===s?null:n},O.prototype.computedStyle=function(t){return this.node.ownerDocument.defaultView.getComputedStyle(this.node,t)},O.prototype.cssInt=function(t){t=parseInt(this.css(t),10);return isNaN(t)?0:t},O.prototype.cssFloat=function(t){t=parseFloat(this.css(t));return isNaN(t)?0:t},O.prototype.fontWeight=function(){var t=this.css("fontWeight");switch(parseInt(t,10)){case 401:t="bold";break;case 400:t="normal"}return t},O.prototype.parseClip=function(){var t=this.css("clip").match(this.CLIP);return t?{top:parseInt(t[1],10),right:parseInt(t[2],10),bottom:parseInt(t[3],10),left:parseInt(t[4],10)}:null},O.prototype.parseBackgroundImages=function(){return this.backgroundImages||(this.backgroundImages=D(this.css("backgroundImage")))},O.prototype.cssList=function(t,e){t=(this.css(t)||"").split(",");return t=1===(t=(t=t[e||0]||t[0]||"auto").trim().split(" ")).length?[t[0],t[0]]:t},O.prototype.parseBackgroundSize=function(t,e,n){var r,a,n=this.cssList("backgroundSize",n);if(B(n[0]))r=t.width*parseFloat(n[0])/100;else{if(/contain|cover/.test(n[0]))return t.width/t.height<(a=e.width/e.height)^"contain"===n[0]?{width:t.height*a,height:t.height}:{width:t.width,height:t.width/a};r=parseInt(n[0],10)}return a="auto"===n[0]&&"auto"===n[1]?e.height:"auto"===n[1]?r/e.width*e.height:B(n[1])?t.height*parseFloat(n[1])/100:parseInt(n[1],10),{width:r="auto"===n[0]?a/e.height*e.width:r,height:a}},O.prototype.parseBackgroundPosition=function(t,e,n,r){var n=this.cssList("backgroundPosition",n),i=B(n[0])?(t.width-(r||e).width)*(parseFloat(n[0])/100):parseInt(n[0],10),t="auto"===n[1]?i/e.width*e.height:B(n[1])?(t.height-(r||e).height)*parseFloat(n[1])/100:parseInt(n[1],10);return{left:i="auto"===n[0]?t/e.height*e.width:i,top:t}},O.prototype.parseBackgroundRepeat=function(t){return this.cssList("backgroundRepeat",t)[0]},O.prototype.parseTextShadows=function(){var t=this.css("textShadow"),e=[];if(t&&"none"!==t)for(var n=t.match(this.TEXT_SHADOW_PROPERTY),r=0;n&&r<n.length;r++){var i=n[r].match(this.TEXT_SHADOW_VALUES);e.push({color:i[0],offsetX:i[1]?parseFloat(i[1].replace("px","")):0,offsetY:i[2]?parseFloat(i[2].replace("px","")):0,blur:i[3]?i[3].replace("px",""):0})}return e},O.prototype.parseTransform=function(){var t,e;return this.transformData||(this.hasTransform()?(t=this.parseBounds(),(e=this.prefixedCss("transformOrigin").split(" ").map(L).map(F))[0]+=t.left,e[1]+=t.top,this.transformData={origin:e,matrix:this.parseTransformMatrix()}):this.transformData={origin:[0,0],matrix:[1,0,0,1,0,0]}),this.transformData},O.prototype.parseTransformMatrix=function(){var t;return this.transformMatrix||(t=(t=this.prefixedCss("transform"))?function(t){return t&&"matrix"===t[1]?t[2].split(",").map(function(t){return parseFloat(t.trim())}):void 0}(t.match(this.MATRIX_PROPERTY)):null,this.transformMatrix=t||[1,0,0,1,0,0]),this.transformMatrix},O.prototype.parseBounds=function(){return this.bounds||(this.bounds=(this.hasTransform()?j:M)(this.node))},O.prototype.hasTransform=function(){return"1,0,0,1,0,0"!==this.parseTransformMatrix().join(",")||this.parent&&this.parent.hasTransform()},O.prototype.getValue=function(){var t=this.node.value||"";return 0===(t="SELECT"===this.node.tagName?function(t){return(t=t.options[t.selectedIndex||0])&&t.text||""}(this.node):t).length?this.node.placeholder||"":t},O.prototype.MATRIX_PROPERTY=/(matrix)\((.+)\)/,O.prototype.TEXT_SHADOW_PROPERTY=/((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g,O.prototype.TEXT_SHADOW_VALUES=/(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g,O.prototype.CLIP=/^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/,z.prototype.calculateOverflowClips=function(){this.nodes.forEach(function(t){var e,n;he(t)?(de(t)&&t.appendToDOM(),t.borders=this.parseBorders(t),e="hidden"===t.css("overflow")?[t.borders.clip]:[],(n=t.parseClip())&&-1!==["absolute","fixed"].indexOf(t.css("position"))&&e.push([["rect",t.bounds.left+n.left,t.bounds.top+n.top,n.right-n.left,n.bottom-n.top]]),t.clip=U(t)?t.parent.clip.concat(e):e,t.backgroundClip="hidden"!==t.css("overflow")?t.clip.concat([t.borders.clip]):t.clip,de(t)&&t.cleanDOM()):fe(t)&&(t.clip=U(t)?t.parent.clip:[]),de(t)||(t.bounds=null)},this)},z.prototype.asyncRenderer=function(t,e,n){n=n||Date.now(),this.paint(t[this.renderIndex++]),t.length===this.renderIndex?e():n+20>Date.now()?this.asyncRenderer(t,e,n):setTimeout(ge(function(){this.asyncRenderer(t,e)},this),0)},z.prototype.createPseudoHideStyles=function(t){this.createStyles(t,"."+Ae.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE+':before { content: "" !important; display: none !important; }.'+Ae.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER+':after { content: "" !important; display: none !important; }')},z.prototype.disableAnimations=function(t){this.createStyles(t,"* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; -webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}")},z.prototype.createStyles=function(t,e){var n=t.createElement("style");n.innerHTML=e,t.body.appendChild(n)},z.prototype.getPseudoElements=function(t){var n,e=[[t]];return t.node.nodeType===Node.ELEMENT_NODE&&(n=this.getPseudoElement(t,":before"),t=this.getPseudoElement(t,":after"),n&&e.push(n),t)&&e.push(t),be(e)},z.prototype.getPseudoElement=function(t,n){var r=t.computedStyle(n);if(!r||!r.content||"none"===r.content||"-moz-alt-content"===r.content||"none"===r.display)return null;for(var i=function(t){var e=t.substr(0,1);return e===t.substr(t.length-1)&&e.match(/'|"/)?t.substr(1,t.length-2):t}(r.content),o="url"===i.substr(0,3),s=e.createElement(o?"img":"html2canvaspseudoelement"),t=new Ae(s,t,n),c=r.length-1;0<=c;c--){var u=function(t){return t.replace(/(\-[a-z])/g,function(t){return t.toUpperCase().replace("-","")})}(r.item(c));s.style[u]=r[u]}return s.className=Ae.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE+" "+Ae.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER,o?(s.src=D(i)[0].args[0],[t]):(n=e.createTextNode(i),s.appendChild(n),[t,new Fe(n,t)])},z.prototype.getChildren=function(t){return be([].filter.call(t.node.childNodes,oe).map(function(e){var n=[new(e.nodeType===Node.TEXT_NODE?Fe:O)(e,t)].filter(ve);return e.nodeType===Node.ELEMENT_NODE&&n.length&&"TEXTAREA"!==e.tagName?n[0].isElementVisible()?n.concat(this.getChildren(n[0])):[]:n},this))},z.prototype.newStackingContext=function(t,e){var n=new Re(e,t.getOpacity(),t.node,t.parent);t.cloneTo(n),(e?n.getParentStack(this):n.parent.stack).contexts.push(n),t.stack=n},z.prototype.createStackingContexts=function(){this.nodes.forEach(function(t){he(t)&&(this.isRootElement(t)||t.getOpacity()<1||function(t){var e=t.css("position");return"auto"!==(-1!==["absolute","relative","fixed"].indexOf(e)?t.css("zIndex"):"auto")}(t)||this.isBodyWithTransparentRoot(t)||t.hasTransform())?this.newStackingContext(t,!0):he(t)&&(ae(t)&&K(t)||-1!==["inline-block","inline-table"].indexOf(t.css("display"))||ce(t))?this.newStackingContext(t,!1):t.assignStack(t.parent.stack)},this)},z.prototype.isBodyWithTransparentRoot=function(t){return"BODY"===t.node.nodeName&&this.renderer.isTransparent(t.parent.css("backgroundColor"))},z.prototype.isRootElement=function(t){return null===t.parent},z.prototype.sortStackingContexts=function(t){t.contexts.sort(function(t){return function(e,n){return e.cssInt("zIndex")+t.indexOf(e)/t.length-(n.cssInt("zIndex")+t.indexOf(n)/t.length)}}(t.contexts.slice(0))),t.contexts.forEach(this.sortStackingContexts,this)},z.prototype.parseTextBounds=function(t){return function(e,n,r){if("none"!==t.parent.css("textDecoration").substr(0,4)||0!==e.trim().length){if(this.support.rangeBounds&&!t.parent.hasTransform())return r=r.slice(0,n).join("").length,this.getRangeBounds(t.node,r,e.length);if(t.node&&"string"==typeof t.node.data)return n=t.node.splitText(e.length),r=this.getWrapperBounds(t.node,t.parent.hasTransform()),t.node=n,r}else this.support.rangeBounds&&!t.parent.hasTransform()||(t.node=t.node.splitText(e.length));return{}}},z.prototype.getWrapperBounds=function(t,e){var n=t.ownerDocument.createElement("html2canvaswrapper"),r=t.parentNode,i=t.cloneNode(!0),t=(n.appendChild(t.cloneNode(!0)),r.replaceChild(n,t),(e?j:M)(n));return r.replaceChild(i,n),t},z.prototype.getRangeBounds=function(t,e,n){var r=this.range||(this.range=t.ownerDocument.createRange());return r.setStart(t,e),r.setEnd(t,e+n),r.getBoundingClientRect()},z.prototype.parse=function(t){var e=t.contexts.filter($),n=t.children.filter(he),r=n.filter(le(ce)),i=r.filter(le(ae)).filter(le(te)),n=n.filter(le(ae)).filter(ce),s=r.filter(le(ae)).filter(te),r=t.contexts.concat(r.filter(ae)).filter(K),c=t.children.filter(fe).filter(ne),t=t.contexts.filter(Z);e.concat(i).concat(n).concat(s).concat(r).concat(c).concat(t).forEach(function(t){this.renderQueue.push(t),ee(t)&&(this.parse(t),this.renderQueue.push(new W))},this)},z.prototype.paint=function(t){try{t instanceof W?this.renderer.ctx.restore():fe(t)?(de(t.parent)&&t.parent.appendToDOM(),this.paintText(t),de(t.parent)&&t.parent.cleanDOM()):this.paintNode(t)}catch(e){A(e)}},z.prototype.paintNode=function(t){var e,r;ee(t)&&(this.renderer.setOpacity(t.opacity),this.renderer.ctx.save(),t.hasTransform())&&this.renderer.setTransform(t.parseTransform()),"INPUT"===t.node.nodeName&&"checkbox"===t.node.type?this.paintCheckbox(t):"INPUT"===t.node.nodeName&&"radio"===t.node.type?this.paintRadio(t):("always"===t.css("page-break-before")&&"function"==typeof(e=this.options.canvas.getContext("2d"))._pageBreakAt&&e._pageBreakAt(t.node.offsetTop),this.paintElement(t)),t.node.getAttribute&&null!==(e=null===(e=t.node.getAttribute("name"))?t.node.getAttribute("id"):e)&&(r=this.options.canvas.annotations)&&r.setName(e,t.bounds)},z.prototype.paintElement=function(t){var e=t.parseBounds();this.renderer.clip(t.backgroundClip,function(){this.renderer.renderBackground(t,e,t.borders.borders.map(ye))},this),this.renderer.clip(t.clip,function(){this.renderer.renderBorders(t.borders.borders)},this),this.renderer.clip(t.backgroundClip,function(){switch(t.node.nodeName){case"svg":case"IFRAME":var n=this.images.get(t.node);n?this.renderer.renderImage(t,e,t.borders,n):A("Error loading <"+t.node.nodeName+">",t.node);break;case"IMG":n=this.images.get(t.node.src);n?this.renderer.renderImage(t,e,t.borders,n):A("Error loading <img>",t.node.src);break;case"CANVAS":this.renderer.renderImage(t,e,t.borders,{image:t.node});break;case"SELECT":case"INPUT":case"TEXTAREA":this.paintFormValue(t)}},this)},z.prototype.paintCheckbox=function(t){var e=t.parseBounds(),n=Math.min(e.width,e.height),r={width:n-1,height:n-1,top:e.top,left:e.left},e=[3,3],o=[e,e,e,e],s=[1,1,1,1].map(function(t){return{color:"#A5A5A5",width:t}}),a=X(r,o,s);this.renderer.clip(t.backgroundClip,function(){this.renderer.rectangle(r.left+1,r.top+1,r.width-2,r.height-2,"#DEDEDE"),this.renderer.renderBorders(V(s,r,a,o)),t.node.checked&&(this.renderer.font("#424242","normal","normal","bold",n-3+"px","arial"),this.renderer.text("✔",r.left+n/6,r.top+n-1))},this)},z.prototype.paintRadio=function(t){var e=t.parseBounds(),n=Math.min(e.width,e.height)-2;this.renderer.clip(t.backgroundClip,function(){this.renderer.circleStroke(e.left+1,e.top+1,n,"#DEDEDE",1,"#A5A5A5"),t.node.checked&&this.renderer.circle(Math.ceil(e.left+n/4)+1,Math.ceil(e.top+n/4)+1,Math.floor(n/2),"#424242")},this)},z.prototype.paintFormValue=function(t){var e,n,i;0<t.getValue().length&&(e=t.node.ownerDocument,n=e.createElement("html2canvaswrapper"),["lineHeight","textAlign","fontFamily","fontWeight","fontSize","color","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","borderLeftStyle","borderTopStyle","borderLeftWidth","borderTopWidth","boxSizing","whiteSpace","wordWrap"].forEach(function(e){try{n.style[e]=t.css(e)}catch(r){A("html2canvas: Parse: Exception caught in renderFormValue: "+r.message)}}),i=t.parseBounds(),n.style.position="fixed",n.style.left=i.left+"px",n.style.top=i.top+"px",n.textContent=t.getValue(),e.body.appendChild(n),this.paintText(new Fe(n.firstChild,t)),e.body.removeChild(n))},z.prototype.paintText=function(e){e.applyTextTransform();var n=t.html2canvas.punycode.ucs2.decode(e.node.data),r=this.options.letterRendering&&!/^(normal|none|0px)$/.test(e.parent.css("letterSpacing"))||/[^\u0000-\u00ff]/.test(e.node.data)?n.map(function(e){return t.html2canvas.punycode.ucs2.encode([e])}):function(e){for(var n,r=[],i=0,o=!1;e.length;)-1!==[32,13,10,9,45].indexOf(e[i])===o?((n=e.splice(0,i)).length&&r.push(t.html2canvas.punycode.ucs2.encode(n)),o=!o,i=0):i++,i>=e.length&&(n=e.splice(0,i)).length&&r.push(t.html2canvas.punycode.ucs2.encode(n));return r}(n),n=e.parent.fontWeight(),o=e.parent.css("fontSize"),a=e.parent.css("fontFamily"),c=e.parent.parseTextShadows();this.renderer.font(e.parent.css("color"),e.parent.css("fontStyle"),e.parent.css("fontVariant"),n,o,a),c.length?this.renderer.fontShadow(c[0].color,c[0].offsetX,c[0].offsetY,c[0].blur):this.renderer.clearShadow(),this.renderer.clip(e.parent.clip,function(){r.map(this.parseTextBounds(e),this).forEach(function(t,n){t&&(t.left===s&&(t.left=0),t.bottom===s&&(t.bottom=0),this.renderer.text(r[n],t.left,t.bottom),this.renderTextDecoration(e.parent,t,this.fontMetrics.getMetrics(a,o)),0==n&&"LI"===e.parent.node.nodeName&&this.renderBullet(e,t),0==n)&&this.renderAnnotation(e.parent,t)},this)},this)},z.prototype.generateListNumber={listAlpha:function(t){for(var n="";n=String.fromCharCode(64+t%26)+n,26<26*(t/=26););return n},listRoman:function(t){var e,n=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"],r=[1e3,900,500,400,100,90,50,40,10,9,5,4,1],i="",o=n.length;if(t<=0||4e3<=t)return t;for(e=0;e<o;e+=1)for(;r[e]<=t;)t-=r[e],i+=n[e];return i}},z.prototype.listItemText=function(t,e){switch(t){case"decimal-leading-zero":text=1===e.toString().length?e="0"+e.toString():e.toString();break;case"upper-roman":text=this.generateListNumber.listRoman(e);break;case"lower-roman":text=this.generateListNumber.listRoman(e).toLowerCase();break;case"lower-alpha":text=this.generateListNumber.listAlpha(e).toLowerCase();break;case"upper-alpha":text=this.generateListNumber.listAlpha(e);break;default:text=e}return text},z.prototype.renderBullet=function(t,e){var n=t.parent.css("listStyleType");if("none"!==n){var r=e.top+(e.bottom-e.top)/2,i=this.renderer.canvas.getContext("2d"),o=i.measureText("M").width,s=o/4,a=.75*o,c=e.left-a;switch(n){case"decimal":case"decimal-leading-zero":case"upper-alpha":case"lower-alpha":case"upper-roman":case"lower-roman":var u=t.parent,l=u.parent,l=Array.prototype.slice.call(l.node.children).indexOf(u.node)+1,u=this.listItemText(n,l),l=e.left-a;l-=i.measureText(u+=".").width,i.fillText(u,l,e.bottom);break;case"square":var s=o/3;i.fillRect(c-=s,r-=s/2,s,s);break;case"circle":c-=s=o/6,i.beginPath(),i.arc(c,r,s,0,2*Math.PI),i.closePath(),i.stroke();break;default:c-=s=o/6,i.beginPath(),i.arc(c,r,s,0,2*Math.PI),i.closePath(),i.fill()}}},z.prototype.renderTextDecoration=function(t,e,n){switch(t.css("textDecoration").split(" ")[0]){case"underline":this.renderer.rectangle(e.left,Math.round(e.top+n.baseline+n.lineWidth),e.width,1,t.css("color"));break;case"overline":this.renderer.rectangle(e.left,Math.round(e.top),e.width,1,t.css("color"));break;case"line-through":this.renderer.rectangle(e.left,Math.ceil(e.top+n.middle+n.lineWidth),e.width,1,t.css("color"))}},z.prototype.renderAnnotation=function(t){var e,n;"A"===t.node.nodeName&&(e=t.node.getAttribute("href"))&&(n=this.options.canvas.annotations)&&n.createAnnotation(e,t.bounds)},z.prototype.parseBorders=function(t){var e=t.parseBounds(),n=function(t){return["TopLeft","TopRight","BottomRight","BottomLeft"].map(function(e){e=t.css("border"+e+"Radius").split(" ");return e.length<=1&&(e[1]=e[0]),e.map(we)})}(t),r=["Top","Right","Bottom","Left"].map(function(e){return{width:t.cssInt("border"+e+"Width"),color:t.css("border"+e+"Color"),args:null}}),i=X(e,n,r);return{clip:this.parseBackgroundClip(t,i,r,n,e),borders:V(r,e,i,n)}},z.prototype.parseBackgroundClip=function(t,e,n,r,i){var s=[];switch(t.css("backgroundClip")){case"content-box":case"padding-box":Q(s,r[0],r[1],e.topLeftInner,e.topRightInner,i.left+n[3].width,i.top+n[0].width),Q(s,r[1],r[2],e.topRightInner,e.bottomRightInner,i.left+i.width-n[1].width,i.top+n[0].width),Q(s,r[2],r[3],e.bottomRightInner,e.bottomLeftInner,i.left+i.width-n[1].width,i.top+i.height-n[2].width),Q(s,r[3],r[0],e.bottomLeftInner,e.topLeftInner,i.left+n[3].width,i.top+i.height-n[2].width);break;default:Q(s,r[0],r[1],e.topLeftOuter,e.topRightOuter,i.left,i.top),Q(s,r[1],r[2],e.topRightOuter,e.bottomRightOuter,i.left+i.width,i.top),Q(s,r[2],r[3],e.bottomRightOuter,e.bottomLeftOuter,i.left+i.width,i.top+i.height),Q(s,r[3],r[0],e.bottomLeftOuter,e.topLeftOuter,i.left,i.top+i.height)}return s},Xe=0,Ye="withCredentials"in new XMLHttpRequest,Je="crossOrigin"in new Image,Ae.prototype.cloneTo=function(t){Ae.prototype.cloneTo.call(this,t),t.isPseudoElement=!0,t.before=this.before},(Ae.prototype=Object.create(O.prototype)).appendToDOM=function(){this.before?this.parent.node.insertBefore(this.node,this.parent.node.firstChild):this.parent.node.appendChild(this.node),this.parent.node.className+=" "+this.getHideClass()},Ae.prototype.cleanDOM=function(){this.node.parentNode.removeChild(this.node),this.parent.node.className=this.parent.node.className.replace(this.getHideClass(),"")},Ae.prototype.getHideClass=function(){return this["PSEUDO_HIDE_ELEMENT_CLASS_"+(this.before?"BEFORE":"AFTER")]},Ae.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE="___html2canvas___pseudoelement_before",Ae.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER="___html2canvas___pseudoelement_after",Oe.prototype.renderImage=function(t,e,n,r){var i=t.cssInt("paddingLeft"),o=t.cssInt("paddingTop"),s=t.cssInt("paddingRight"),t=t.cssInt("paddingBottom"),n=n.borders,s=e.width-(n[1].width+n[3].width+i+s),t=e.height-(n[0].width+n[2].width+o+t);this.drawImage(r,0,0,r.image.width||s,r.image.height||t,e.left+i+n[3].width,e.top+o+n[0].width,s,t)},Oe.prototype.renderBackground=function(t,e,n){0<e.height&&0<e.width&&(this.renderBackgroundColor(t,e),this.renderBackgroundImage(t,e,n))},Oe.prototype.renderBackgroundColor=function(t,e){var n=t.css("backgroundColor");this.isTransparent(n)||this.rectangle(e.left,e.top,e.width,e.height,t.css("backgroundColor"))},Oe.prototype.renderBorders=function(t){t.forEach(this.renderBorder,this)},Oe.prototype.renderBorder=function(t){this.isTransparent(t.color)||null===t.args||this.drawShape(t.args,t.color)},Oe.prototype.renderBackgroundImage=function(t,e,n){t.parseBackgroundImages().reverse().forEach(function(r,i,o){switch(r.method){case"url":var s=this.images.get(r.args[0]);s?this.renderBackgroundRepeating(t,e,s,o.length-(i+1),n):A("Error loading background-image",r.args[0]);break;case"linear-gradient":case"gradient":s=this.images.get(r.value);s?this.renderBackgroundGradient(s,e,n):A("Error loading background-image",r.args[0]);break;case"none":break;default:A("Unknown background-image type",r.args[0])}},this)},Oe.prototype.renderBackgroundRepeating=function(t,e,n,r,i){var o=t.parseBackgroundSize(e,n.image,r),s=t.parseBackgroundPosition(e,n.image,r,o);switch(t.parseBackgroundRepeat(r)){case"repeat-x":case"repeat no-repeat":this.backgroundRepeatShape(n,s,o,e,e.left+i[3],e.top+s.top+i[0],99999,o.height,i);break;case"repeat-y":case"no-repeat repeat":this.backgroundRepeatShape(n,s,o,e,e.left+s.left+i[3],e.top+i[0],o.width,99999,i);break;case"no-repeat":this.backgroundRepeatShape(n,s,o,e,e.left+s.left+i[3],e.top+s.top+i[0],o.width,o.height,i);break;default:this.renderBackgroundRepeat(n,s,o,{top:e.top,left:e.left},i[3],i[0])}},Oe.prototype.isTransparent=function(t){return!t||"transparent"===t||"rgba(0, 0, 0, 0)"===t},(Re.prototype=Object.create(O.prototype)).getParentStack=function(t){var e=this.parent?this.parent.stack:null;return e?e.ownStacking?e:e.getParentStack(t):t.stack},Ne.prototype.testRangeBounds=function(t){var e,n,o=!1;return t.createRange&&(e=t.createRange()).getBoundingClientRect&&((n=t.createElement("boundtest")).style.height="123px",n.style.display="block",t.body.appendChild(n),e.selectNode(n),123===e.getBoundingClientRect().height&&(o=!0),t.body.removeChild(n)),o},Ne.prototype.testCORS=function(){return void 0!==(new Image).crossOrigin},Ne.prototype.testSVG=function(){var t=new Image,n=e.createElement("canvas"),r=n.getContext("2d");t.src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";try{r.drawImage(t,0,0),n.toDataURL()}catch(i){return!1}return!0},Be.prototype.hasFabric=function(){return html2canvas.fabric?Promise.resolve():Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg"))},Be.prototype.inlineFormatting=function(t){return/^data:image\/svg\+xml;base64,/.test(t)?this.decode64(this.removeContentType(t)):this.removeContentType(t)},Be.prototype.removeContentType=function(t){return t.replace(/^data:image\/svg\+xml(;base64)?,/,"")},Be.prototype.isInline=function(t){return/^data:image\/svg\+xml/i.test(t)},Be.prototype.createCanvas=function(t){var e=this;return function(n,r){var i=new html2canvas.fabric.StaticCanvas("c");e.image=i.lowerCanvasEl,i.setWidth(r.width).setHeight(r.height).add(html2canvas.fabric.util.groupSVGElements(n,r)).renderAll(),t(i.lowerCanvasEl)}},Be.prototype.decode64=function(e){return"function"==typeof t.atob?t.atob(e):De(e)},Le.prototype=Object.create(Be.prototype),(Fe.prototype=Object.create(O.prototype)).applyTextTransform=function(){this.node.data=this.transform(this.parent.css("textTransform"))},Fe.prototype.transform=function(t){var e=this.node.data;switch(t){case"lowercase":return e.toLowerCase();case"capitalize":return e.replace(/(^|\s|:|-|\(|\))([a-z])/g,Me);case"uppercase":return e.toUpperCase();default:return e}},je.prototype=Object.create(_.prototype),(Ue.prototype=Object.create(Oe.prototype)).setFillStyle=function(t){return this.ctx.fillStyle=t,this.ctx},Ue.prototype.rectangle=function(t,e,n,r,i){this.setFillStyle(i).fillRect(t,e,n,r)},Ue.prototype.circle=function(t,e,n,r){this.setFillStyle(r),this.ctx.beginPath(),this.ctx.arc(t+n/2,e+n/2,n/2,0,2*Math.PI,!0),this.ctx.closePath(),this.ctx.fill()},Ue.prototype.circleStroke=function(t,e,n,r,i,o){this.circle(t,e,n,r),this.ctx.strokeStyle=o,this.ctx.stroke()},Ue.prototype.drawShape=function(t,e){this.shape(t),this.setFillStyle(e).fill()},Ue.prototype.taints=function(t){if(null===t.tainted){this.taintCtx.drawImage(t.image,0,0);try{this.taintCtx.getImageData(0,0,1,1),t.tainted=!1}catch(n){this.taintCtx=e.createElement("canvas").getContext("2d"),t.tainted=!0}}return t.tainted},Ue.prototype.drawImage=function(t,e,n,r,i,o,s,a,c){this.taints(t)&&!this.options.allowTaint||this.ctx.drawImage(t.image,e,n,r,i,o,s,a,c)},Ue.prototype.clip=function(t,e,n){this.ctx.save(),t.filter(He).forEach(function(t){this.shape(t).clip()},this),e.call(n),this.ctx.restore()},Ue.prototype.shape=function(t){return this.ctx.beginPath(),t.forEach(function(t,e){("rect"===t[0]?this.ctx.rect:this.ctx[0===e?"moveTo":t[0]+"To"]).apply(this.ctx,t.slice(1))},this),this.ctx.closePath(),this.ctx},Ue.prototype.font=function(t,e,n,r,i,o){this.setFillStyle(t).font=[e,n,r,i,o].join(" ").split(",")[0]},Ue.prototype.fontShadow=function(t,e,n,r){this.setVariable("shadowColor",t).setVariable("shadowOffsetY",e).setVariable("shadowOffsetX",n).setVariable("shadowBlur",r)},Ue.prototype.clearShadow=function(){this.setVariable("shadowColor","rgba(0,0,0,0)")},Ue.prototype.setOpacity=function(t){this.ctx.globalAlpha=t},Ue.prototype.setTransform=function(t){this.ctx.translate(t.origin[0],t.origin[1]),this.ctx.transform.apply(this.ctx,t.matrix),this.ctx.translate(-t.origin[0],-t.origin[1])},Ue.prototype.setVariable=function(t,e){return this.variables[t]!==e&&(this.variables[t]=this.ctx[t]=e),this},Ue.prototype.text=function(t,e,n){this.ctx.fillText(t,e,n)},Ue.prototype.backgroundRepeatShape=function(t,e,n,r,i,o,s,a,c){s=[["line",Math.round(i),Math.round(o)],["line",Math.round(i+s),Math.round(o)],["line",Math.round(i+s),Math.round(a+o)],["line",Math.round(i),Math.round(a+o)]];this.clip([s],function(){this.renderBackgroundRepeat(t,e,n,r,c[3],c[0])},this)},Ue.prototype.renderBackgroundRepeat=function(t,e,n,r,i,o){i=Math.round(r.left+e.left+i),r=Math.round(r.top+e.top+o);this.setFillStyle(this.ctx.createPattern(this.resizeImage(t,n),"repeat")),this.ctx.translate(i,r),this.ctx.fill(),this.ctx.translate(-i,-r)},Ue.prototype.renderBackgroundGradient=function(t,e){var n;t instanceof P&&(n=this.ctx.createLinearGradient(e.left+e.width*t.x0,e.top+e.height*t.y0,e.left+e.width*t.x1,e.top+e.height*t.y1),t.colorStops.forEach(function(t){n.addColorStop(t.stop,t.color)}),this.rectangle(e.left,e.top,e.width,e.height,n))},Ue.prototype.resizeImage=function(t,n){var o,t=t.image;return t.width===n.width&&t.height===n.height?t:((o=e.createElement("canvas")).width=n.width,o.height=n.height,o.getContext("2d").drawImage(t,0,0,t.width,t.height,0,0,n.width,n.height),o)})}.call({},window,document),"data-html2canvas-node"),html2canvasCanvasCloneAttribute="data-html2canvas-canvas-clone",html2canvasCanvasCloneIndex=0,proxyCount=(window.html2canvas=function(t,e){return(e=e||{}).logging&&(window.html2canvas.logging=!0,window.html2canvas.start=Date.now()),e.async=void 0===e.async||e.async,e.allowTaint=void 0!==e.allowTaint&&e.allowTaint,e.removeContainer=void 0===e.removeContainer||e.removeContainer,e.javascriptEnabled=void 0!==e.javascriptEnabled&&e.javascriptEnabled,e.imageTimeout=void 0===e.imageTimeout?1e4:e.imageTimeout,"string"==typeof t?"string"!=typeof e.proxy?Promise.reject("Proxy must be used when rendering url"):loadUrlDocument(absoluteUrl(t),e.proxy,document,window.innerWidth,window.innerHeight,e).then(function(t){return renderWindow(t.contentWindow.document.documentElement,t,e,window.innerWidth,window.innerHeight)}):((t=(void 0===t?[document.documentElement]:t.length?t:[t])[0]).setAttribute(html2canvasNodeAttribute,"true"),renderDocument(t.ownerDocument,e,t.ownerDocument.defaultView.innerWidth,t.ownerDocument.defaultView.innerHeight).then(function(t){return"function"==typeof e.onrendered&&(log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas"),e.onrendered(t)),t}))},window.html2canvas.punycode=this.punycode,window.html2canvas.proxy={},"function"==typeof Object.create&&"function"==typeof document.createElement("canvas").getContext||(window.html2canvas=function(){return Promise.reject("No canvas support")}),FontMetrics.prototype.getMetrics=function(t,e){return void 0===this.data[t+"-"+e]&&(this.data[t+"-"+e]=new Font(t,e)),this.data[t+"-"+e]},FrameContainer.prototype.proxyLoad=function(t,e,n){var r=this.src;return loadUrlDocument(r.src,t,r.ownerDocument,e.width,e.height,n)},GradientContainer.prototype.TYPES={LINEAR:1,RADIAL:2},ImageLoader.prototype.findImages=function(t){var e=[];return t.reduce(function(t,e){switch(e.node.nodeName){case"IMG":return t.concat([{args:[e.node.src],method:"url"}]);case"svg":case"IFRAME":return t.concat([{args:[e.node],method:e.node.nodeName}])}return t},[]).forEach(this.addImage(e,this.loadImage),this),e},ImageLoader.prototype.findBackgroundImage=function(t,e){return e.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(t,this.loadImage),this),t},ImageLoader.prototype.addImage=function(t,e){return function(n){n.args.forEach(function(r){this.imageExists(t,r)||(t.splice(0,0,e.call(this,n)),log("Added image #"+t.length,"string"==typeof r?r.substring(0,100):r))},this)}},ImageLoader.prototype.hasImageBackground=function(t){return"none"!==t.method},ImageLoader.prototype.loadImage=function(t){var e;return"url"===t.method?(e=t.args[0],!this.isSVG(e)||this.support.svg||this.options.allowTaint?e.match(/data:image\/.*;base64,/i)?new ImageContainer(e.replace(/url\(['"]{0,}|['"]{0,}\)$/gi,""),!1):this.isSameOrigin(e)||!0===this.options.allowTaint||this.isSVG(e)?new ImageContainer(e,!1):this.support.cors&&!this.options.allowTaint&&this.options.useCORS?new ImageContainer(e,!0):this.options.proxy?new ProxyImageContainer(e,this.options.proxy):new DummyImageContainer(e):new SVGContainer(e)):"linear-gradient"===t.method?new LinearGradientContainer(t):"gradient"===t.method?new WebkitGradientContainer(t):"svg"===t.method?new SVGNodeContainer(t.args[0],this.support.svg):"IFRAME"===t.method?new FrameContainer(t.args[0],this.isSameOrigin(t.args[0].src),this.options):new DummyImageContainer(t)},ImageLoader.prototype.isSVG=function(t){return"svg"===t.substring(t.length-3).toLowerCase()||SVGContainer.prototype.isInline(t)},ImageLoader.prototype.imageExists=function(t,e){return t.some(function(t){return t.src===e})},ImageLoader.prototype.isSameOrigin=function(t){return this.getOrigin(t)===this.origin},ImageLoader.prototype.getOrigin=function(t){var e=this.link||(this.link=document.createElement("a"));return e.href=t,e.href=e.href,e.protocol+e.hostname+e.port},ImageLoader.prototype.getPromise=function(t){return this.timeout(t,this.options.imageTimeout).catch(function(){return new DummyImageContainer(t.src).promise.then(function(e){t.image=e})})},ImageLoader.prototype.get=function(t){var e=null;return this.images.some(function(n){return(e=n).src===t})?e:null},ImageLoader.prototype.fetch=function(t){return this.images=t.reduce(bind(this.findBackgroundImage,this),this.findImages(t)),this.images.forEach(function(t,e){t.promise.then(function(){log("Succesfully loaded image #"+(e+1),t)},function(n){log("Failed loading image #"+(e+1),t,n)})}),this.ready=Promise.all(this.images.map(this.getPromise,this)),log("Finished searching images"),this},ImageLoader.prototype.timeout=function(t,e){var n;return Promise.race([t.promise,new Promise(function(r,i){n=setTimeout(function(){log("Timed out loading image",t),i(t)},e)})]).then(function(t){return clearTimeout(n),t})},LinearGradientContainer.prototype=Object.create(GradientContainer.prototype),LinearGradientContainer.prototype.stepRegExp=/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/,NodeContainer.prototype.cloneTo=function(t){t.visible=this.visible,t.borders=this.borders,t.bounds=this.bounds,t.clip=this.clip,t.backgroundClip=this.backgroundClip,t.computedStyles=this.computedStyles,t.styles=this.styles,t.backgroundImages=this.backgroundImages,t.opacity=this.opacity},NodeContainer.prototype.getOpacity=function(){return null===this.opacity?this.opacity=this.cssFloat("opacity"):this.opacity},NodeContainer.prototype.assignStack=function(t){(this.stack=t).children.push(this)},NodeContainer.prototype.isElementVisible=function(){return this.node.nodeType===Node.TEXT_NODE?this.parent.visible:"none"!==this.css("display")&&"hidden"!==this.css("visibility")&&!this.node.hasAttribute("data-html2canvas-ignore")&&("INPUT"!==this.node.nodeName||"hidden"!==this.node.getAttribute("type"))},NodeContainer.prototype.css=function(t){return this.computedStyles||(this.computedStyles=this.isPseudoElement?this.parent.computedStyle(this.before?":before":":after"):this.computedStyle(null)),this.styles[t]||(this.styles[t]=this.computedStyles[t])},NodeContainer.prototype.prefixedCss=function(t){var n=this.css(t);return void 0===n&&["webkit","moz","ms","o"].some(function(e){return void 0!==(n=this.css(e+t.substr(0,1).toUpperCase()+t.substr(1)))},this),void 0===n?null:n},NodeContainer.prototype.computedStyle=function(t){return this.node.ownerDocument.defaultView.getComputedStyle(this.node,t)},NodeContainer.prototype.cssInt=function(t){t=parseInt(this.css(t),10);return isNaN(t)?0:t},NodeContainer.prototype.cssFloat=function(t){t=parseFloat(this.css(t));return isNaN(t)?0:t},NodeContainer.prototype.fontWeight=function(){var t=this.css("fontWeight");switch(parseInt(t,10)){case 401:t="bold";break;case 400:t="normal"}return t},NodeContainer.prototype.parseClip=function(){var t=this.css("clip").match(this.CLIP);return t?{top:parseInt(t[1],10),right:parseInt(t[2],10),bottom:parseInt(t[3],10),left:parseInt(t[4],10)}:null},NodeContainer.prototype.parseBackgroundImages=function(){return this.backgroundImages||(this.backgroundImages=parseBackgrounds(this.css("backgroundImage")))},NodeContainer.prototype.cssList=function(t,e){t=(this.css(t)||"").split(",");return t=1===(t=(t=t[e||0]||t[0]||"auto").trim().split(" ")).length?[t[0],t[0]]:t},NodeContainer.prototype.parseBackgroundSize=function(t,e,n){var r,a,n=this.cssList("backgroundSize",n);if(isPercentage(n[0]))r=t.width*parseFloat(n[0])/100;else{if(/contain|cover/.test(n[0]))return t.width/t.height<(a=e.width/e.height)^"contain"===n[0]?{width:t.height*a,height:t.height}:{width:t.width,height:t.width/a};r=parseInt(n[0],10)}return a="auto"===n[0]&&"auto"===n[1]?e.height:"auto"===n[1]?r/e.width*e.height:isPercentage(n[1])?t.height*parseFloat(n[1])/100:parseInt(n[1],10),{width:r="auto"===n[0]?a/e.height*e.width:r,height:a}},NodeContainer.prototype.parseBackgroundPosition=function(t,e,n,r){var n=this.cssList("backgroundPosition",n),i=isPercentage(n[0])?(t.width-(r||e).width)*(parseFloat(n[0])/100):parseInt(n[0],10),t="auto"===n[1]?i/e.width*e.height:isPercentage(n[1])?(t.height-(r||e).height)*parseFloat(n[1])/100:parseInt(n[1],10);return{left:i="auto"===n[0]?t/e.height*e.width:i,top:t}},NodeContainer.prototype.parseBackgroundRepeat=function(t){return this.cssList("backgroundRepeat",t)[0]},NodeContainer.prototype.parseTextShadows=function(){var t=this.css("textShadow"),e=[];if(t&&"none"!==t)for(var n=t.match(this.TEXT_SHADOW_PROPERTY),r=0;n&&r<n.length;r++){var i=n[r].match(this.TEXT_SHADOW_VALUES);e.push({color:i[0],offsetX:i[1]?parseFloat(i[1].replace("px","")):0,offsetY:i[2]?parseFloat(i[2].replace("px","")):0,blur:i[3]?i[3].replace("px",""):0})}return e},NodeContainer.prototype.parseTransform=function(){var t,e;return this.transformData||(this.hasTransform()?(t=this.parseBounds(),(e=this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat))[0]+=t.left,e[1]+=t.top,this.transformData={origin:e,matrix:this.parseTransformMatrix()}):this.transformData={origin:[0,0],matrix:[1,0,0,1,0,0]}),this.transformData},NodeContainer.prototype.parseTransformMatrix=function(){var t;return this.transformMatrix||(t=(t=this.prefixedCss("transform"))?parseMatrix(t.match(this.MATRIX_PROPERTY)):null,this.transformMatrix=t||[1,0,0,1,0,0]),this.transformMatrix},NodeContainer.prototype.parseBounds=function(){return this.bounds||(this.bounds=(this.hasTransform()?offsetBounds:getBounds)(this.node))},NodeContainer.prototype.hasTransform=function(){return"1,0,0,1,0,0"!==this.parseTransformMatrix().join(",")||this.parent&&this.parent.hasTransform()},NodeContainer.prototype.getValue=function(){var t=this.node.value||"";return 0===(t="SELECT"===this.node.tagName?selectionValue(this.node):t).length?this.node.placeholder||"":t},NodeContainer.prototype.MATRIX_PROPERTY=/(matrix)\((.+)\)/,NodeContainer.prototype.TEXT_SHADOW_PROPERTY=/((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g,NodeContainer.prototype.TEXT_SHADOW_VALUES=/(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g,NodeContainer.prototype.CLIP=/^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/,NodeParser.prototype.calculateOverflowClips=function(){this.nodes.forEach(function(t){var e,n;isElement(t)?(isPseudoElement(t)&&t.appendToDOM(),t.borders=this.parseBorders(t),e="hidden"===t.css("overflow")?[t.borders.clip]:[],(n=t.parseClip())&&-1!==["absolute","fixed"].indexOf(t.css("position"))&&e.push([["rect",t.bounds.left+n.left,t.bounds.top+n.top,n.right-n.left,n.bottom-n.top]]),t.clip=hasParentClip(t)?t.parent.clip.concat(e):e,t.backgroundClip="hidden"!==t.css("overflow")?t.clip.concat([t.borders.clip]):t.clip,isPseudoElement(t)&&t.cleanDOM()):isTextNode(t)&&(t.clip=hasParentClip(t)?t.parent.clip:[]),isPseudoElement(t)||(t.bounds=null)},this)},NodeParser.prototype.asyncRenderer=function(t,e,n){n=n||Date.now(),this.paint(t[this.renderIndex++]),t.length===this.renderIndex?e():n+20>Date.now()?this.asyncRenderer(t,e,n):setTimeout(bind(function(){this.asyncRenderer(t,e)},this),0)},NodeParser.prototype.createPseudoHideStyles=function(t){this.createStyles(t,"."+PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE+':before { content: "" !important; display: none !important; }.'+PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER+':after { content: "" !important; display: none !important; }')},NodeParser.prototype.disableAnimations=function(t){this.createStyles(t,"* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; -webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}")},NodeParser.prototype.createStyles=function(t,e){var n=t.createElement("style");n.innerHTML=e,t.body.appendChild(n)},NodeParser.prototype.getPseudoElements=function(t){var n,e=[[t]];return t.node.nodeType===Node.ELEMENT_NODE&&(n=this.getPseudoElement(t,":before"),t=this.getPseudoElement(t,":after"),n&&e.push(n),t)&&e.push(t),flatten(e)},NodeParser.prototype.getPseudoElement=function(t,e){var n=t.computedStyle(e);if(!n||!n.content||"none"===n.content||"-moz-alt-content"===n.content||"none"===n.display)return null;for(var r=stripQuotes(n.content),i="url"===r.substr(0,3),o=document.createElement(i?"img":"html2canvaspseudoelement"),t=new PseudoElementContainer(o,t,e),a=n.length-1;0<=a;a--){var c=toCamelCase(n.item(a));o.style[c]=n[c]}return o.className=PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE+" "+PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER,i?(o.src=parseBackgrounds(r)[0].args[0],[t]):(e=document.createTextNode(r),o.appendChild(e),[t,new TextContainer(e,t)])},NodeParser.prototype.getChildren=function(t){return flatten([].filter.call(t.node.childNodes,renderableNode).map(function(e){var n=[new(e.nodeType===Node.TEXT_NODE?TextContainer:NodeContainer)(e,t)].filter(nonIgnoredElement);return e.nodeType===Node.ELEMENT_NODE&&n.length&&"TEXTAREA"!==e.tagName?n[0].isElementVisible()?n.concat(this.getChildren(n[0])):[]:n},this))},NodeParser.prototype.newStackingContext=function(t,e){var n=new StackingContext(e,t.getOpacity(),t.node,t.parent);t.cloneTo(n),(e?n.getParentStack(this):n.parent.stack).contexts.push(n),t.stack=n},NodeParser.prototype.createStackingContexts=function(){this.nodes.forEach(function(t){isElement(t)&&(this.isRootElement(t)||hasOpacity(t)||isPositionedForStacking(t)||this.isBodyWithTransparentRoot(t)||t.hasTransform())?this.newStackingContext(t,!0):isElement(t)&&(isPositioned(t)&&zIndex0(t)||isInlineBlock(t)||isFloating(t))?this.newStackingContext(t,!1):t.assignStack(t.parent.stack)},this)},NodeParser.prototype.isBodyWithTransparentRoot=function(t){return"BODY"===t.node.nodeName&&this.renderer.isTransparent(t.parent.css("backgroundColor"))},NodeParser.prototype.isRootElement=function(t){return null===t.parent},NodeParser.prototype.sortStackingContexts=function(t){t.contexts.sort(zIndexSort(t.contexts.slice(0))),t.contexts.forEach(this.sortStackingContexts,this)},NodeParser.prototype.parseTextBounds=function(t){return function(e,n,r){if("none"!==t.parent.css("textDecoration").substr(0,4)||0!==e.trim().length){if(this.support.rangeBounds&&!t.parent.hasTransform())return r=r.slice(0,n).join("").length,this.getRangeBounds(t.node,r,e.length);if(t.node&&"string"==typeof t.node.data)return n=t.node.splitText(e.length),r=this.getWrapperBounds(t.node,t.parent.hasTransform()),t.node=n,r}else this.support.rangeBounds&&!t.parent.hasTransform()||(t.node=t.node.splitText(e.length));return{}}},NodeParser.prototype.getWrapperBounds=function(t,e){var n=t.ownerDocument.createElement("html2canvaswrapper"),r=t.parentNode,i=t.cloneNode(!0),t=(n.appendChild(t.cloneNode(!0)),r.replaceChild(n,t),(e?offsetBounds:getBounds)(n));return r.replaceChild(i,n),t},NodeParser.prototype.getRangeBounds=function(t,e,n){var r=this.range||(this.range=t.ownerDocument.createRange());return r.setStart(t,e),r.setEnd(t,e+n),r.getBoundingClientRect()},NodeParser.prototype.parse=function(t){var e=t.contexts.filter(negativeZIndex),n=t.children.filter(isElement),r=n.filter(not(isFloating)),i=r.filter(not(isPositioned)).filter(not(inlineLevel)),n=n.filter(not(isPositioned)).filter(isFloating),s=r.filter(not(isPositioned)).filter(inlineLevel),r=t.contexts.concat(r.filter(isPositioned)).filter(zIndex0),c=t.children.filter(isTextNode).filter(hasText),t=t.contexts.filter(positiveZIndex);e.concat(i).concat(n).concat(s).concat(r).concat(c).concat(t).forEach(function(t){this.renderQueue.push(t),isStackingContext(t)&&(this.parse(t),this.renderQueue.push(new ClearTransform))},this)},NodeParser.prototype.paint=function(t){try{t instanceof ClearTransform?this.renderer.ctx.restore():isTextNode(t)?(isPseudoElement(t.parent)&&t.parent.appendToDOM(),this.paintText(t),isPseudoElement(t.parent)&&t.parent.cleanDOM()):this.paintNode(t)}catch(e){log(e)}},NodeParser.prototype.paintNode=function(t){isStackingContext(t)&&(this.renderer.setOpacity(t.opacity),this.renderer.ctx.save(),t.hasTransform())&&this.renderer.setTransform(t.parseTransform()),"INPUT"===t.node.nodeName&&"checkbox"===t.node.type?this.paintCheckbox(t):"INPUT"===t.node.nodeName&&"radio"===t.node.type?this.paintRadio(t):this.paintElement(t)},NodeParser.prototype.paintElement=function(t){var e=t.parseBounds();this.renderer.clip(t.backgroundClip,function(){this.renderer.renderBackground(t,e,t.borders.borders.map(getWidth))},this),this.renderer.clip(t.clip,function(){this.renderer.renderBorders(t.borders.borders)},this),this.renderer.clip(t.backgroundClip,function(){switch(t.node.nodeName){case"svg":case"IFRAME":var n=this.images.get(t.node);n?this.renderer.renderImage(t,e,t.borders,n):log("Error loading <"+t.node.nodeName+">",t.node);break;case"IMG":n=this.images.get(t.node.src);n?this.renderer.renderImage(t,e,t.borders,n):log("Error loading <img>",t.node.src);break;case"CANVAS":this.renderer.renderImage(t,e,t.borders,{image:t.node});break;case"SELECT":case"INPUT":case"TEXTAREA":this.paintFormValue(t)}},this)},NodeParser.prototype.paintCheckbox=function(t){var e=t.parseBounds(),n=Math.min(e.width,e.height),r={width:n-1,height:n-1,top:e.top,left:e.left},e=[3,3],o=[e,e,e,e],s=[1,1,1,1].map(function(t){return{color:"#A5A5A5",width:t}}),a=calculateCurvePoints(r,o,s);this.renderer.clip(t.backgroundClip,function(){this.renderer.rectangle(r.left+1,r.top+1,r.width-2,r.height-2,"#DEDEDE"),this.renderer.renderBorders(calculateBorders(s,r,a,o)),t.node.checked&&(this.renderer.font("#424242","normal","normal","bold",n-3+"px","arial"),this.renderer.text("✔",r.left+n/6,r.top+n-1))},this)},NodeParser.prototype.paintRadio=function(t){var e=t.parseBounds(),n=Math.min(e.width,e.height)-2;this.renderer.clip(t.backgroundClip,function(){this.renderer.circleStroke(e.left+1,e.top+1,n,"#DEDEDE",1,"#A5A5A5"),t.node.checked&&this.renderer.circle(Math.ceil(e.left+n/4)+1,Math.ceil(e.top+n/4)+1,Math.floor(n/2),"#424242")},this)},NodeParser.prototype.paintFormValue=function(t){var e,n,i;0<t.getValue().length&&(e=t.node.ownerDocument,n=e.createElement("html2canvaswrapper"),["lineHeight","textAlign","fontFamily","fontWeight","fontSize","color","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","borderLeftStyle","borderTopStyle","borderLeftWidth","borderTopWidth","boxSizing","whiteSpace","wordWrap","list-style-type"].forEach(function(e){try{n.style[e]=t.css(e)}catch(r){log("html2canvas: Parse: Exception caught in renderFormValue: "+r.message)}}),i=t.parseBounds(),n.style.position="fixed",n.style.left=i.left+"px",n.style.top=i.top+"px",n.textContent=t.getValue(),e.body.appendChild(n),this.paintText(new TextContainer(n.firstChild,t)),e.body.removeChild(n))},NodeParser.prototype.paintText=function(t){t.applyTextTransform();var e=window.html2canvas.punycode.ucs2.decode(t.node.data),n=this.options.letterRendering&&!noLetterSpacing(t)||hasUnicode(t.node.data)?e.map(function(t){return window.html2canvas.punycode.ucs2.encode([t])}):getWords(e),e=t.parent.fontWeight(),i=t.parent.css("fontSize"),o=t.parent.css("fontFamily"),s=t.parent.parseTextShadows();this.renderer.font(t.parent.css("color"),t.parent.css("fontStyle"),t.parent.css("fontVariant"),e,i,o),s.length?this.renderer.fontShadow(s[0].color,s[0].offsetX,s[0].offsetY,s[0].blur):this.renderer.clearShadow(),this.renderer.clip(t.parent.clip,function(){n.map(this.parseTextBounds(t),this).forEach(function(e,r){e&&(this.renderer.text(n[r],e.left,e.bottom),this.renderTextDecoration(t.parent,e,this.fontMetrics.getMetrics(o,i)))},this)},this)},NodeParser.prototype.renderTextDecoration=function(t,e,n){switch(t.css("textDecoration").split(" ")[0]){case"underline":this.renderer.rectangle(e.left,Math.round(e.top+n.baseline+n.lineWidth),e.width,1,t.css("color"));break;case"overline":this.renderer.rectangle(e.left,Math.round(e.top),e.width,1,t.css("color"));break;case"line-through":this.renderer.rectangle(e.left,Math.ceil(e.top+n.middle+n.lineWidth),e.width,1,t.css("color"))}},NodeParser.prototype.parseBorders=function(t){var e=t.parseBounds(),n=getBorderRadiusData(t),r=["Top","Right","Bottom","Left"].map(function(e){return{width:t.cssInt("border"+e+"Width"),color:t.css("border"+e+"Color"),args:null}}),i=calculateCurvePoints(e,n,r);return{clip:this.parseBackgroundClip(t,i,r,n,e),borders:calculateBorders(r,e,i,n)}},NodeParser.prototype.parseBackgroundClip=function(t,e,n,r,i){var s=[];switch(t.css("backgroundClip")){case"content-box":case"padding-box":parseCorner(s,r[0],r[1],e.topLeftInner,e.topRightInner,i.left+n[3].width,i.top+n[0].width),parseCorner(s,r[1],r[2],e.topRightInner,e.bottomRightInner,i.left+i.width-n[1].width,i.top+n[0].width),parseCorner(s,r[2],r[3],e.bottomRightInner,e.bottomLeftInner,i.left+i.width-n[1].width,i.top+i.height-n[2].width),parseCorner(s,r[3],r[0],e.bottomLeftInner,e.topLeftInner,i.left+n[3].width,i.top+i.height-n[2].width);break;default:parseCorner(s,r[0],r[1],e.topLeftOuter,e.topRightOuter,i.left,i.top),parseCorner(s,r[1],r[2],e.topRightOuter,e.bottomRightOuter,i.left+i.width,i.top),parseCorner(s,r[2],r[3],e.bottomRightOuter,e.bottomLeftOuter,i.left+i.width,i.top+i.height),parseCorner(s,r[3],r[0],e.bottomLeftOuter,e.topLeftOuter,i.left,i.top+i.height)}return s},function(){var t,e,r,i,o;i={},o={},r=e=function(t){if(r._eak_seen=i,o[t])return o[t];if(o[t]={},!i[t])throw new Error("Could not find module "+t);for(var s,a=i[t],c=a.deps,a=a.callback,l=[],h=0,d=c.length;h<d;h++)l.push("exports"===c[h]?s={}:e(function(e){if("."!==e.charAt(0))return e;for(var n=e.split("/"),r=t.split("/").slice(0,-1),i=0,o=n.length;i<o;i++){var s=n[i];".."===s?r.pop():"."!==s&&r.push(s)}return r.join("/")}(c[h])));a=a.apply(this,l);return o[t]=s||a},(t=function(t,e,n){i[t]={deps:e,callback:n}})("promise/all",["./utils","exports"],function(t,e){"use strict";var r=t.isArray,i=t.isFunction;e.all=function(t){if(r(t))return new this(function(e,n){function o(t,n){a[t]=n,0==--c&&e(a)}var s,a=[],c=t.length;0===c&&e([]);for(var u=0;u<t.length;u++)(s=t[u])&&i(s.then)?s.then(function(t){return function(e){o(t,e)}}(u),n):o(u,s)});throw new TypeError("You must pass an array to all.")}}),t("promise/asap",["exports"],function(t){"use strict";function i(){for(var t=0;t<l.length;t++){var e=l[t];(0,e[0])(e[1])}l=[]}var a="undefined"!=typeof window?window:{},c=a.MutationObserver||a.WebKitMutationObserver,u=void 0!==global?global:this,l=[],s=void 0!==process&&"[object process]"==={}.toString.call(process)?function(){process.nextTick(i)}:c?function(){var t=0,e=new c(i),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}():function(){u.setTimeout(i,1)};t.asap=function(t,e){1===l.push([t,e])&&s()}}),t("promise/cast",["exports"],function(t){"use strict";t.cast=function(t){return t&&"object"==typeof t&&t.constructor===this?t:new this(function(e){e(t)})}}),t("promise/config",["exports"],function(t){"use strict";var n={instrument:!1};t.config=n,t.configure=function(t,e){return 2!==arguments.length?n[t]:void(n[t]=e)}}),t("promise/polyfill",["./promise","./utils","exports"],function(t,e,n){"use strict";var i=t.Promise,o=e.isFunction;n.polyfill=function(){"Promise"in window&&"cast"in window.Promise&&"resolve"in window.Promise&&"reject"in window.Promise&&"all"in window.Promise&&"race"in window.Promise&&function(){var t;return new window.Promise(function(e){t=e}),o(t)}()||(window.Promise=i)}}),t("promise/promise",["./config","./utils","./cast","./all","./race","./resolve","./reject","./asap","exports"],function(t,e,n,r,i,o,s,a,c){"use strict";function u(t){if(!k(t))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof u))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],function(t,e){function r(t){w(e,t)}try{t(function(t){m(e,t)},r)}catch(i){r(i)}}(t,this)}function h(t,e,n,r){var i,o,s,a,c=k(n);if(c)try{i=n(r),s=!0}catch(u){a=!0,o=u}else i=r,s=!0;p(e,i)||(c&&s?m(e,i):a?w(e,o):t===A?m(e,i):t===O&&w(e,i))}function f(t,e){for(var i=t._subscribers,o=t._detail,s=0;s<i.length;s+=3)h(e,i[s],i[s+e],o);t._subscribers=null}function p(t,e){var n,r=null;try{if(t===e)throw new TypeError("A promises callback cannot return that same promise.");if(x(e)&&(r=e.then,k(r)))return r.call(e,function(r){return!!n||(n=!0,void(e!==r?m:g)(t,r))},function(e){return!!n||(n=!0,void w(t,e))}),1}catch(i){return n||w(t,i),1}}function m(t,e){t!==e&&p(t,e)||g(t,e)}function g(t,e){t._state===I&&(t._state=P,t._detail=e,b.async(y,t))}function w(t,e){t._state===I&&(t._state=P,t._detail=e,b.async(v,t))}function y(t){f(t,t._state=A)}function v(t){f(t,t._state=O)}var b=t.config,x=(t.configure,e.objectOrFunction),k=e.isFunction,t=(e.now,n.cast),e=r.all,n=i.race,r=o.resolve,i=s.reject,o=a.asap,I=(b.async=o,void 0),P=0,A=1,O=2;u.prototype={constructor:u,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(t,e){var i,n=this,r=new this.constructor(function(){});return this._state?(i=arguments,b.async(function(){h(n._state,r,i[n._state-1],n._detail)})):function(t,e,n,r){var o=(t=t._subscribers).length;t[o]=e,t[o+A]=n,t[o+O]=r}(this,r,t,e),r},catch:function(t){return this.then(null,t)}},u.all=e,u.cast=t,u.race=n,u.resolve=r,u.reject=i,c.Promise=u}),t("promise/race",["./utils","exports"],function(t,e){"use strict";var r=t.isArray;e.race=function(t){if(r(t))return new this(function(e,n){for(var r,i=0;i<t.length;i++)(r=t[i])&&"function"==typeof r.then?r.then(e,n):e(r)});throw new TypeError("You must pass an array to race.")}}),t("promise/reject",["exports"],function(t){"use strict";t.reject=function(t){return new this(function(e,n){n(t)})}}),t("promise/resolve",["exports"],function(t){"use strict";t.resolve=function(t){return new this(function(e){e(t)})}}),t("promise/utils",["exports"],function(t){"use strict";function n(t){return"function"==typeof t}var i=Date.now||function(){return(new Date).getTime()};t.objectOrFunction=function(t){return n(t)||"object"==typeof t&&null!==t},t.isFunction=n,t.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},t.now=i}),e("promise/polyfill").polyfill()}(),0),supportsCORS="withCredentials"in new XMLHttpRequest,supportsCORSImage="crossOrigin"in new Image,DecodeStream=(PseudoElementContainer.prototype.cloneTo=function(t){PseudoElementContainer.prototype.cloneTo.call(this,t),t.isPseudoElement=!0,t.before=this.before},PseudoElementContainer.prototype=Object.create(NodeContainer.prototype),PseudoElementContainer.prototype.appendToDOM=function(){this.before?this.parent.node.insertBefore(this.node,this.parent.node.firstChild):this.parent.node.appendChild(this.node),this.parent.node.className+=" "+this.getHideClass()},PseudoElementContainer.prototype.cleanDOM=function(){this.node.parentNode.removeChild(this.node),this.parent.node.className=this.parent.node.className.replace(this.getHideClass(),"")},PseudoElementContainer.prototype.getHideClass=function(){return this["PSEUDO_HIDE_ELEMENT_CLASS_"+(this.before?"BEFORE":"AFTER")]},PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE="___html2canvas___pseudoelement_before",PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER="___html2canvas___pseudoelement_after",Renderer.prototype.renderImage=function(t,e,n,r){var i=t.cssInt("paddingLeft"),o=t.cssInt("paddingTop"),s=t.cssInt("paddingRight"),t=t.cssInt("paddingBottom"),n=n.borders,s=e.width-(n[1].width+n[3].width+i+s),t=e.height-(n[0].width+n[2].width+o+t);this.drawImage(r,0,0,r.image.width||s,r.image.height||t,e.left+i+n[3].width,e.top+o+n[0].width,s,t)},Renderer.prototype.renderBackground=function(t,e,n){0<e.height&&0<e.width&&(this.renderBackgroundColor(t,e),this.renderBackgroundImage(t,e,n))},Renderer.prototype.renderBackgroundColor=function(t,e){var n=t.css("backgroundColor");this.isTransparent(n)||this.rectangle(e.left,e.top,e.width,e.height,t.css("backgroundColor"))},Renderer.prototype.renderBorders=function(t){t.forEach(this.renderBorder,this)},Renderer.prototype.renderBorder=function(t){this.isTransparent(t.color)||null===t.args||this.drawShape(t.args,t.color)},Renderer.prototype.renderBackgroundImage=function(t,e,n){t.parseBackgroundImages().reverse().forEach(function(r,i,o){switch(r.method){case"url":var s=this.images.get(r.args[0]);s?this.renderBackgroundRepeating(t,e,s,o.length-(i+1),n):log("Error loading background-image",r.args[0]);break;case"linear-gradient":case"gradient":s=this.images.get(r.value);s?this.renderBackgroundGradient(s,e,n):log("Error loading background-image",r.args[0]);break;case"none":break;default:log("Unknown background-image type",r.args[0])}},this)},Renderer.prototype.renderBackgroundRepeating=function(t,e,n,r,i){var o=t.parseBackgroundSize(e,n.image,r),s=t.parseBackgroundPosition(e,n.image,r,o);switch(t.parseBackgroundRepeat(r)){case"repeat-x":case"repeat no-repeat":this.backgroundRepeatShape(n,s,o,e,e.left+i[3],e.top+s.top+i[0],99999,o.height,i);break;case"repeat-y":case"no-repeat repeat":this.backgroundRepeatShape(n,s,o,e,e.left+s.left+i[3],e.top+i[0],o.width,99999,i);break;case"no-repeat":this.backgroundRepeatShape(n,s,o,e,e.left+s.left+i[3],e.top+s.top+i[0],o.width,o.height,i);break;default:this.renderBackgroundRepeat(n,s,o,{top:e.top,left:e.left},i[3],i[0])}},Renderer.prototype.isTransparent=function(t){return!t||"transparent"===t||"rgba(0, 0, 0, 0)"===t},StackingContext.prototype=Object.create(NodeContainer.prototype),StackingContext.prototype.getParentStack=function(t){var e=this.parent?this.parent.stack:null;return e?e.ownStacking?e:e.getParentStack(t):t.stack},Support.prototype.testRangeBounds=function(t){var e,n,o=!1;return t.createRange&&(e=t.createRange()).getBoundingClientRect&&((n=t.createElement("boundtest")).style.height="123px",n.style.display="block",t.body.appendChild(n),e.selectNode(n),123===e.getBoundingClientRect().height&&(o=!0),t.body.removeChild(n)),o},Support.prototype.testCORS=function(){return void 0!==(new Image).crossOrigin},Support.prototype.testSVG=function(){var t=new Image,e=document.createElement("canvas"),n=e.getContext("2d");t.src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";try{n.drawImage(t,0,0),e.toDataURL()}catch(r){return!1}return!0},SVGContainer.prototype.hasFabric=function(){return html2canvas.fabric?Promise.resolve():Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg"))},SVGContainer.prototype.inlineFormatting=function(t){return/^data:image\/svg\+xml;base64,/.test(t)?this.decode64(this.removeContentType(t)):this.removeContentType(t)},SVGContainer.prototype.removeContentType=function(t){return t.replace(/^data:image\/svg\+xml(;base64)?,/,"")},SVGContainer.prototype.isInline=function(t){return/^data:image\/svg\+xml/i.test(t)},SVGContainer.prototype.createCanvas=function(t){var e=this;return function(n,r){var i=new html2canvas.fabric.StaticCanvas("c");e.image=i.lowerCanvasEl,i.setWidth(r.width).setHeight(r.height).add(html2canvas.fabric.util.groupSVGElements(n,r)).renderAll(),t(i.lowerCanvasEl)}},SVGContainer.prototype.decode64=function(t){return"function"==typeof window.atob?window.atob(t):decode64(t)},SVGNodeContainer.prototype=Object.create(SVGContainer.prototype),TextContainer.prototype=Object.create(NodeContainer.prototype),TextContainer.prototype.applyTextTransform=function(){this.node.data=this.transform(this.parent.css("textTransform"))},TextContainer.prototype.transform=function(t){var e=this.node.data;switch(t){case"lowercase":return e.toLowerCase();case"capitalize":return e.replace(/(^|\s|:|-|\(|\))([a-z])/g,capitalize);case"uppercase":return e.toUpperCase();default:return e}},WebkitGradientContainer.prototype=Object.create(GradientContainer.prototype),function(t){var e=function(){function e(t){var e,n,r,s,i,l,h,o,f,p,u;for(this.data=t,this.pos=8,this.palette=[],this.imgData=[],this.transparency={},this.animation=null,this.text={},s=null;;){switch(e=this.readUInt32(),l=function(){var t,e=[];for(t=0;t<4;++t)e.push(String.fromCharCode(this.data[this.pos++]));return e}.call(this).join("")){case"IHDR":this.width=this.readUInt32(),this.height=this.readUInt32(),this.bits=this.data[this.pos++],this.colorType=this.data[this.pos++],this.compressionMethod=this.data[this.pos++],this.filterMethod=this.data[this.pos++],this.interlaceMethod=this.data[this.pos++];break;case"acTL":this.animation={numFrames:this.readUInt32(),numPlays:this.readUInt32()||1/0,frames:[]};break;case"PLTE":this.palette=this.read(e);break;case"fcTL":s&&this.animation.frames.push(s),this.pos+=4,s={width:this.readUInt32(),height:this.readUInt32(),xOffset:this.readUInt32(),yOffset:this.readUInt32()},o=this.readUInt16(),i=this.readUInt16()||100,s.delay=1e3*o/i,s.disposeOp=this.data[this.pos++],s.blendOp=this.data[this.pos++],s.data=[];break;case"IDAT":case"fdAT":for("fdAT"===l&&(this.pos+=4,e-=4),t=(null!=s?s.data:void 0)||this.imgData,f=0;0<=e?f<e:e<f;0<=e?++f:--f)t.push(this.data[this.pos++]);break;case"tRNS":switch(this.transparency={},this.colorType){case 3:if(r=this.palette.length/3,this.transparency.indexed=this.read(e),this.transparency.indexed.length>r)throw new Error("More transparent colors than palette size");if(0<(h=r-this.transparency.indexed.length))for(p=0;0<=h?p<h:h<p;0<=h?++p:--p)this.transparency.indexed.push(255);break;case 0:this.transparency.grayscale=this.read(e)[0];break;case 2:this.transparency.rgb=this.read(e)}break;case"tEXt":i=(o=this.read(e)).indexOf(0),u=String.fromCharCode.apply(String,o.slice(0,i)),this.text[u]=String.fromCharCode.apply(String,o.slice(i+1));break;case"IEND":return s&&this.animation.frames.push(s),this.colors=function(){switch(this.colorType){case 0:case 3:case 4:return 1;case 2:case 6:return 3}}.call(this),this.hasAlphaChannel=4===(u=this.colorType)||6===u,n=this.colors+(this.hasAlphaChannel?1:0),this.pixelBitlength=this.bits*n,this.colorSpace=function(){switch(this.colors){case 1:return"DeviceGray";case 3:return"DeviceRGB"}}.call(this),void(this.imgData=new Uint8Array(this.imgData));default:this.pos+=e}if(this.pos+=4,this.pos>this.data.length)throw new Error("Incomplete or corrupt PNG file")}}var a,c,u;e.load=function(t,n,r){var i;return"function"==typeof n&&(r=n),(i=new XMLHttpRequest).open("GET",t,!0),i.responseType="arraybuffer",i.onload=function(){var o=new e(new Uint8Array(i.response||i.mozResponseArrayBuffer));return"function"==typeof(null!=n?n.getContext:void 0)&&o.render(n),"function"==typeof r?r(o):void 0},i.send(null)},e.prototype.read=function(t){var n,r=[];for(n=0;0<=t?n<t:t<n;0<=t?++n:--n)r.push(this.data[this.pos++]);return r},e.prototype.readUInt32=function(){return this.data[this.pos++]<<24|this.data[this.pos++]<<16|this.data[this.pos++]<<8|this.data[this.pos++]},e.prototype.readUInt16=function(){return this.data[this.pos++]<<8|this.data[this.pos++]},e.prototype.decodePixels=function(t){var e,n,r,i,o,s,c,l,a,d,f,p,m,g,w,y,v,b,x,k,C;if(0===(t=null==t?this.imgData:t).length)return new Uint8Array(0);for(t=(t=new FlateStream(t)).getBytes(),g=(d=this.pixelBitlength/8)*this.width,f=new Uint8Array(g*this.height),s=t.length,n=p=m=0;p<s;){switch(t[p++]){case 0:for(i=v=0;v<g;i=v+=1)f[n++]=t[p++];break;case 1:for(i=b=0;b<g;i=b+=1)e=t[p++],o=i<d?0:f[n-d],f[n++]=(e+o)%256;break;case 2:for(i=x=0;x<g;i=x+=1)e=t[p++],r=(i-i%d)/d,w=m&&f[(m-1)*g+r*d+i%d],f[n++]=(w+e)%256;break;case 3:for(i=k=0;k<g;i=k+=1)e=t[p++],r=(i-i%d)/d,o=i<d?0:f[n-d],w=m&&f[(m-1)*g+r*d+i%d],f[n++]=(e+Math.floor((o+w)/2))%256;break;case 4:for(i=C=0;C<g;i=C+=1)e=t[p++],r=(i-i%d)/d,o=i<d?0:f[n-d],0===m?w=y=0:(w=f[(m-1)*g+r*d+i%d],y=r&&f[(m-1)*g+(r-1)*d+i%d]),a=o+w-y,c=Math.abs(a-o),l=Math.abs(a-w),a=Math.abs(a-y),f[n++]=(e+(c<=l&&c<=a?o:l<=a?w:y))%256;break;default:throw new Error("Invalid filter algorithm: "+t[p-1])}m++}return f},e.prototype.decodePalette=function(){for(var a,u,r=this.palette,s=this.transparency.indexed||[],o=new Uint8Array((s.length||0)+r.length),i=0,t=(r.length,0),e=a=0,c=r.length;a<c;e=a+=3)o[i++]=r[e],o[i++]=r[e+1],o[i++]=r[e+2],o[i++]=null!=(u=s[t++])?u:255;return o},e.prototype.copyToImageData=function(t,e){var i,o,s,a,c,u,h,d,r=this.colors,l=null,n=this.hasAlphaChannel;if(this.palette.length&&(l=null!=(d=this._decodedPalette)?d:this._decodedPalette=this.decodePalette(),r=4,n=!0),u=(i=t.data||t).length,s=l||e,o=a=0,1===r)for(;o<u;)c=l?4*e[o/4]:a,h=s[c++],i[o++]=h,i[o++]=h,i[o++]=h,i[o++]=n?s[c++]:255,a=c;else for(;o<u;)c=l?4*e[o/4]:a,i[o++]=s[c++],i[o++]=s[c++],i[o++]=s[c++],i[o++]=n?s[c++]:255,a=c},e.prototype.decode=function(){var t=new Uint8Array(this.width*this.height*4);return this.copyToImageData(t,this.decodePixels()),t};try{c=t.document.createElement("canvas"),u=c.getContext("2d")}catch(l){return-1}return a=function(t){return u.width=t.width,u.height=t.height,u.clearRect(0,0,t.width,t.height),u.putImageData(t,0,0),(t=new Image).src=c.toDataURL(),t},e.prototype.decodeFrames=function(t){var e,n,r,i,o,s,c,u;if(this.animation){for(u=[],n=o=0,s=(c=this.animation.frames).length;o<s;n=++o)e=c[n],r=t.createImageData(e.width,e.height),i=this.decodePixels(new Uint8Array(e.data)),this.copyToImageData(r,i),e.imageData=r,u.push(e.image=a(r));return u}},e.prototype.renderFrame=function(t,e){var o=this.animation.frames,n=o[e],o=o[e-1];return 0===e&&t.clearRect(0,0,this.width,this.height),1===(null!=o?o.disposeOp:void 0)?t.clearRect(o.xOffset,o.yOffset,o.width,o.height):2===(null!=o?o.disposeOp:void 0)&&t.putImageData(o.imageData,o.xOffset,o.yOffset),0===n.blendOp&&t.clearRect(n.xOffset,n.yOffset,n.width,n.height),t.drawImage(n.image,n.xOffset,n.yOffset)},e.prototype.animate=function(t){var e,a=this,n=0,s=this.animation,i=s.numFrames,r=s.frames,o=s.numPlays;return(e=function(){var s=n++%i,c=r[s];return a.renderFrame(t,s),1<i&&n/i<o?a.animation._timeout=setTimeout(e,c.delay):void 0})()},e.prototype.stopAnimation=function(){var t;return clearTimeout(null!=(t=this.animation)?t._timeout:void 0)},e.prototype.render=function(t){var n;return t._png&&t._png.stopAnimation(),t._png=this,t.width=this.width,t.height=this.height,t=t.getContext("2d"),this.animation?(this.decodeFrames(t),this.animate(t)):(n=t.createImageData(this.width,this.height),this.copyToImageData(n,this.decodePixels()),t.putImageData(n,0,0))},e}();t.PNG=e}("undefined"!=typeof window&&window||this),function(){function t(){this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=null}return t.prototype={ensureBuffer:function(t){var e=this.buffer,n=e?e.byteLength:0;if(t<n)return e;for(var r=512;r<t;)r<<=1;for(var i=new Uint8Array(r),o=0;o<n;++o)i[o]=e[o];return this.buffer=i},getByte:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock()}return this.buffer[this.pos++]},getBytes:function(t){var e=this.pos;if(t){this.ensureBuffer(e+t);for(var n=e+t;!this.eof&&this.bufferLength<n;)this.readBlock();t=this.bufferLength;t<n&&(n=t)}else{for(;!this.eof;)this.readBlock();n=this.bufferLength}return this.pos=n,this.buffer.subarray(e,n)},lookChar:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock()}return String.fromCharCode(this.buffer[this.pos])},getChar:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock()}return String.fromCharCode(this.buffer[this.pos++])},makeSubStream:function(t,e,n){for(var r=t+e;this.bufferLength<=r&&!this.eof;)this.readBlock();return new Stream(this.buffer,t,e,n)},skip:function(t){this.pos+=t=t||1},reset:function(){this.pos=0}},t}()),FlateStream=function(){function t(t){throw new Error(t)}function e(e){var n=0,r=e[n++],n=e[+n];-1!=r&&-1!=n||t("Invalid header in flate stream"),8!=(15&r)&&t("Unknown compression method in flate stream"),((r<<8)+n)%31!=0&&t("Bad FCHECK in flate stream"),32&n&&t("FDICT bit set in flate stream"),this.bytes=e,this.bytesPos=2,this.codeSize=0,this.codeBuf=0,DecodeStream.call(this)}var n,r,i,o,s;if("undefined"!=typeof Uint32Array)return n=new Uint32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=new Uint32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),i=new Uint32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),o=[new Uint32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],s=[new Uint32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],(e.prototype=Object.create(DecodeStream.prototype)).getBits=function(e){for(var n,r=this.codeSize,i=this.codeBuf,o=this.bytes,s=this.bytesPos;r<e;)void 0===(n=o[s++])&&t("Bad encoding in flate stream"),i|=n<<r,r+=8;return n=i&(1<<e)-1,this.codeBuf=i>>e,this.codeSize=r-=e,this.bytesPos=s,n},e.prototype.getCode=function(e){for(var c,n=e[0],r=e[1],i=this.codeSize,o=this.codeBuf,s=this.bytes,a=this.bytesPos;i<r;)void 0===(c=s[a++])&&t("Bad encoding in flate stream"),o|=c<<i,i+=8;e=n[o&(1<<r)-1],n=e>>16,e&=65535;return(0==i||i<n||0==n)&&t("Bad encoding in flate stream"),this.codeBuf=o>>n,this.codeSize=i-n,this.bytesPos=a,e},e.prototype.generateHuffmanTable=function(t){for(var e=t.length,n=0,r=0;r<e;++r)t[r]>n&&(n=t[r]);for(var i=1<<n,o=new Uint32Array(i),s=1,a=0,c=2;s<=n;++s,a<<=1,c<<=1)for(var u=0;u<e;++u)if(t[u]==s){for(var l=0,h=a,r=0;r<s;++r)l=l<<1|1&h,h>>=1;for(r=l;r<i;r+=c)o[r]=s<<16|u;++a}return[o,n]},e.prototype.readBlock=function(){function e(t,e,n,r,i){for(var o=t.getBits(n)+r;0<o--;)e[C++]=i}var w,y,a=this.getBits(3);if(1&a&&(this.eof=!0),0==(a>>=1)){var c,u=this.bytes,l=this.bytesPos,h=(void 0===(c=u[l++])&&t("Bad block header in flate stream"),c),d=(void 0===(c=u[l++])&&t("Bad block header in flate stream"),h|=c<<8,void 0===(c=u[l++])&&t("Bad block header in flate stream"),c),d=(void 0===(c=u[l++])&&t("Bad block header in flate stream"),(d|=c<<8)!=(65535&~h)&&t("Bad uncompressed block length in flate stream"),this.codeBuf=0,this.codeSize=0,this.bufferLength),p=this.ensureBuffer(d+h),m=d+h;this.bufferLength=m;for(var g=d;g<m;++g){if(void 0===(c=u[l++])){this.eof=!0;break}p[g]=c}this.bytesPos=l}else{if(1==a)w=o,y=s;else if(2==a){for(var h=this.getBits(5)+257,d=this.getBits(5)+1,x=this.getBits(4)+4,k=Array(n.length),C=0;C<x;)k[n[C++]]=this.getBits(3);for(var E=this.generateHuffmanTable(k),S=0,C=0,T=h+d,_=new Array(T);C<T;){var q=this.getCode(E);16==q?e(this,_,2,3,S):17==q?e(this,_,3,3,S=0):18==q?e(this,_,7,11,S=0):_[C++]=S=q}w=this.generateHuffmanTable(_.slice(0,h)),y=this.generateHuffmanTable(_.slice(h,T))}else t("Unknown block type in flate stream");for(var I=(p=this.buffer)?p.length:0,P=this.bufferLength;;)if((A=this.getCode(w))<256)I<=P+1&&(I=(p=this.ensureBuffer(P+1)).length),p[P++]=A;else{if(256==A)return void(this.bufferLength=P);var A,O=(A=r[A-=257])>>16,S=(65535&A)+(O=0<O?this.getBits(O):O),R=(A=this.getCode(y),(65535&(A=i[A]))+(O=0<(O=A>>16)?this.getBits(O):O));I<=P+S&&(I=(p=this.ensureBuffer(P+S)).length);for(var N=0;N<S;++N,++P)p[P]=p[P-R]}}},e}(),requirejs,require,define;!function(t){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";void 0===t.btoa&&(t.btoa=function(t){var s,a,c,u,l=0,h=0,d="",f=[];if(!t)return t;for(;s=(u=t.charCodeAt(l++)<<16|t.charCodeAt(l++)<<8|t.charCodeAt(l++))>>12&63,a=u>>6&63,c=63&u,f[h++]=e.charAt(u>>18&63)+e.charAt(s)+e.charAt(a)+e.charAt(c),l<t.length;);var d=f.join(""),p=t.length%3;return(p?d.slice(0,p-3):d)+"===".slice(p||3)}),void 0===t.atob&&(t.atob=function(t){var n,r,a,c,u,l=0,h=0,f=[];if(!t)return t;for(t+="";n=(u=e.indexOf(t.charAt(l++))<<18|e.indexOf(t.charAt(l++))<<12|(a=e.indexOf(t.charAt(l++)))<<6|(c=e.indexOf(t.charAt(l++))))>>16&255,r=u>>8&255,u=255&u,f[h++]=64==a?String.fromCharCode(n):64==c?String.fromCharCode(n,r):String.fromCharCode(n,r,u),l<t.length;);return f.join("")}),Array.prototype.map||(Array.prototype.map=function(t){if(null==this||"function"!=typeof t)throw new TypeError;for(var e=Object(this),n=e.length>>>0,r=new Array(n),i=1<arguments.length?arguments[1]:void 0,o=0;o<n;o++)o in e&&(r[o]=t.call(i,e[o],o,e));return r}),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t,e){"use strict";if(null==this||"function"!=typeof t)throw new TypeError;for(var n=Object(this),r=n.length>>>0,i=0;i<r;i++)i in n&&t.call(e,n[i],i,n)}),Object.keys||(Object.keys=function(){"use strict";var t=Object.prototype.hasOwnProperty,e=!{toString:null}.propertyIsEnumerable("toString"),n=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],r=n.length;return function(i){if("object"!=typeof i&&("function"!=typeof i||null===i))throw new TypeError;var o,s,a=[];for(o in i)t.call(i,o)&&a.push(o);if(e)for(s=0;s<r;s++)t.call(i,n[s])&&a.push(n[s]);return a}}()),String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),String.prototype.trimLeft||(String.prototype.trimLeft=function(){return this.replace(/^\s+/g,"")}),String.prototype.trimRight||(String.prototype.trimRight=function(){return this.replace(/\s+$/g,"")})}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this),"object"==typeof require&&("undefined"==typeof require_baseUrl_override&&(require_baseUrl_override="../"),require.config({baseUrl:require_baseUrl_override,shim:{"plugins/standard_fonts_metrics":{deps:["jspdf"]},"plugins/split_text_to_size":{deps:["jspdf"]},"plugins/annotations":{deps:["jspdf","plugins/standard_fonts_metrics","plugins/split_text_to_size"]},"plugins/outline":{deps:["jspdf"]},"plugins/addimage":{deps:["jspdf"]},"plugins/png_support":{deps:["jspdf","libs/png_support/png","libs/png_support/zlib"]},"plugins/from_html":{deps:["jspdf"]},"plugins/context2d":{deps:["jspdf","plugins/png_support","plugins/addimage","libs/css_colors"]},"libs/html2canvas/dist/html2canvas":{deps:["jspdf"]},"plugins/canvas":{deps:["jspdf"]},html2pdf:{deps:["jspdf","plugins/standard_fonts_metrics","plugins/split_text_to_size","plugins/png_support","plugins/context2d","plugins/canvas","plugins/annotations","libs/html2canvas/dist/html2canvas"]},"test/test_harness":{deps:["jspdf","jspdf.plugin.standard_fonts_metrics","jspdf.plugin.split_text_to_size"]}},paths:{html2pdf:"libs/html2pdf"}})),!function(global){function isFunction(t){return"[object Function]"===ostring.call(t)}function isArray(t){return"[object Array]"===ostring.call(t)}function each(t,e){if(t)for(var n=0;n<t.length&&(!t[n]||!e(t[n],n,t));n+=1);}function eachReverse(t,e){if(t)for(var n=t.length-1;-1<n&&(!t[n]||!e(t[n],n,t));--n);}function hasProp(t,e){return hasOwn.call(t,e)}function getOwn(t,e){return hasProp(t,e)&&t[e]}function eachProp(t,e){for(var n in t)if(hasProp(t,n)&&e(t[n],n))break}function mixin(t,e,n,r){e&&eachProp(e,function(e,i){!n&&hasProp(t,i)||(!r||"object"!=typeof e||!e||isArray(e)||isFunction(e)||e instanceof RegExp?t[i]=e:(t[i]||(t[i]={}),mixin(t[i],e,n,r)))})}function bind(t,e){return function(){return e.apply(t,arguments)}}function scripts(){return document.getElementsByTagName("script")}function defaultOnError(t){throw t}function getGlobal(t){var e;return t&&(e=global,each(t.split("."),function(t){e=e[t]}),e)}function makeError(t,e,n,r){e=new Error(e+"\nhttp://requirejs.org/docs/errors.html#"+t);return e.requireType=t,e.requireModules=r,n&&(e.originalError=n),e}function newContext(t){function n(t,n,r){var o,s,a,c,u,h,d,f,p,g=n&&n.split("/"),w=C.map,y=w&&w["*"];if(t&&(n=(t=t.split("/")).length-1,C.nodeIdCompat&&jsSuffixRegExp.test(t[n])&&(t[n]=t[n].replace(jsSuffixRegExp,"")),function(t){for(var n,e=0;e<t.length;e++)if("."===(n=t[e]))t.splice(e,1),--e;else if(".."===n){if(0===e||1==e&&".."===t[2]||".."===t[e-1])continue;0<e&&(t.splice(e-1,2),e-=2)}}(t="."===t[0].charAt(0)&&g?g.slice(0,g.length-1).concat(t):t),t=t.join("/")),r&&w&&(g||y)){t:for(a=(s=t.split("/")).length;0<a;--a){if(u=s.slice(0,a).join("/"),g)for(c=g.length;0<c;--c)if(o=(o=getOwn(w,g.slice(0,c).join("/")))&&getOwn(o,u)){h=o,d=a;break t}!f&&y&&getOwn(y,u)&&(f=getOwn(y,u),p=a)}!h&&f&&(h=f,d=p),h&&(s.splice(0,d,h),t=s.join("/"))}return getOwn(C.pkgs,t)||t}function r(t){isBrowser&&each(scripts(),function(e){return e.getAttribute("data-requiremodule")===t&&e.getAttribute("data-requirecontext")===b.contextName?(e.parentNode.removeChild(e),!0):void 0})}function i(t){var e=getOwn(C.paths,t);return e&&isArray(e)&&1<e.length&&(e.shift(),b.require.undef(t),b.makeRequire(null,{skipMap:!0})([t]),1)}function o(t){var e,n=t?t.indexOf("!"):-1;return-1<n&&(e=t.substring(0,n),t=t.substring(n+1,t.length)),[e,t]}function s(t,e,r,i){var s,a,u,l=null,h=e?e.name:null,d=t,f=!0,p="";return t||(f=!1,t="_@r"+(A+=1)),l=(u=o(t))[0],t=u[1],l&&(l=n(l,h,i),a=getOwn(q,l)),t&&(l?p=a&&a.normalize?a.normalize(t,function(t){return n(t,h,i)}):-1===t.indexOf("!")?n(t,h,i):t:(l=(u=o(p=n(t,h,i)))[0],p=u[1],r=!0,s=b.nameToUrl(p))),{prefix:l,name:p,parentMap:e,unnormalized:!!(t=!l||a||r?"":"_unnormalized"+(O+=1)),url:s,originalName:d,isDefine:f,id:(l?l+"!"+p:p)+t}}function a(t){var e=t.id;return getOwn(E,e)||(E[e]=new b.Module(t))}function c(t,e,n){var r=t.id,i=getOwn(E,r);!hasProp(q,r)||i&&!i.defineEmitComplete?(i=a(t)).error&&"error"===e?n(i.error):i.on(e,n):"defined"===e&&n(q[r])}function u(t,e){var n=t.requireModules,r=!1;e?e(t):(each(n,function(e){e=getOwn(E,e);e&&(e.error=t,e.events.error)&&(r=!0,e.emit("error",t))}),r||req.onError(t))}function l(){globalDefQueue.length&&(apsp.apply(_,[_.length,0].concat(globalDefQueue)),globalDefQueue=[])}function h(t){delete E[t],delete S[t]}function f(){var e,n=1e3*C.waitSeconds,o=n&&b.startTime+n<(new Date).getTime(),s=[],a=[],c=!1,l=!0;if(!y){if(y=!0,eachProp(S,function(t){var n=t.map,u=n.id;if(t.enabled&&(n.isDefine||a.push(t),!t.error))if(!t.inited&&o)i(u)?c=e=!0:(s.push(u),r(u));else if(!t.inited&&t.fetched&&n.isDefine&&(c=!0,!n.prefix))return l=!1}),o&&s.length)return(n=makeError("timeout","Load timeout for modules: "+s,null,s)).contextName=b.contextName,u(n);l&&each(a,function(t){!function d(t,e,n){var r=t.map.id;t.error?t.emit("error",t.error):(e[r]=!0,each(t.depMaps,function(r,i){var r=r.id,s=getOwn(E,r);!s||t.depMatched[i]||n[r]||(getOwn(e,r)?(t.defineDep(i,q[r]),t.check()):d(s,e,n))}),n[r]=!0)}(t,{},{})}),o&&!e||!c||!isBrowser&&!isWebWorker||(k=k||setTimeout(function(){k=0,f()},50)),y=!1}}function p(t){hasProp(q,t[0])||a(s(t[0],null,!0)).init(t[1],t[2])}function m(t,e,n,r){t.detachEvent&&!isOpera?r&&t.detachEvent(r,e):t.removeEventListener(n,e,!1)}function g(t){t=t.currentTarget||t.srcElement;return m(t,b.onScriptLoad,"load","onreadystatechange"),m(t,b.onScriptError,"error"),{node:t,id:t&&t.getAttribute("data-requiremodule")}}function w(){var t;for(l();_.length;){if(null===(t=_.shift())[0])return u(makeError("mismatch","Mismatched anonymous define() module: "+t[t.length-1]));p(t)}}var y,b,k,C={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},E={},S={},T={},_=[],q={},I={},P={},A=1,O=1,x={require:function(t){return t.require||(t.require=b.makeRequire(t.map))},exports:function(t){return t.usingExports=!0,t.map.isDefine?t.exports?q[t.map.id]=t.exports:t.exports=q[t.map.id]={}:void 0},module:function(t){return t.module||(t.module={id:t.map.id,uri:t.map.url,config:function(){return getOwn(C.config,t.map.id)||{}},exports:t.exports||(t.exports={})})}},v=function(t){this.events=getOwn(T,t.id)||{},this.map=t,this.shim=getOwn(C.shim,t.id),this.depExports=[],this.depMaps=[],this.depMatched=[],this.pluginMaps={},this.depCount=0};return v.prototype={init:function(t,e,n,r){r=r||{},this.inited||(this.factory=e,n?this.on("error",n):this.events.error&&(n=bind(this,function(t){this.emit("error",t)})),this.depMaps=t&&t.slice(0),this.errback=n,this.inited=!0,this.ignore=r.ignore,r.enabled||this.enabled?this.enable():this.check())},defineDep:function(t,e){this.depMatched[t]||(this.depMatched[t]=!0,--this.depCount,this.depExports[t]=e)},fetch:function(){var t;if(!this.fetched)return this.fetched=!0,b.startTime=(new Date).getTime(),t=this.map,this.shim?void b.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],bind(this,function(){return t.prefix?this.callPlugin():this.load()})):t.prefix?this.callPlugin():this.load()},load:function(){var t=this.map.url;I[t]||(I[t]=!0,b.load(this.map.id,t))},check:function(){if(this.enabled&&!this.enabling){var t,n=this.map.id,r=this.depExports,i=this.exports,o=this.factory;if(this.inited){if(this.error)this.emit("error",this.error);else if(!this.defining){if(this.defining=!0,this.depCount<1&&!this.defined){if(isFunction(o)){if(this.events.error&&this.map.isDefine||req.onError!==defaultOnError)try{i=b.execCb(n,o,r,i)}catch(s){t=s}else i=b.execCb(n,o,r,i);if(this.map.isDefine&&void 0===i&&((r=this.module)?i=r.exports:this.usingExports&&(i=this.exports)),t)return t.requireMap=this.map,t.requireModules=this.map.isDefine?[this.map.id]:null,t.requireType=this.map.isDefine?"define":"require",u(this.error=t)}else i=o;this.exports=i,this.map.isDefine&&!this.ignore&&(q[n]=i,req.onResourceLoad)&&req.onResourceLoad(b,this.map,this.depMaps),h(n),this.defined=!0}this.defining=!1,this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var t=this.map,e=t.id,r=s(t.prefix);this.depMaps.push(r),c(r,"defined",bind(this,function(r){var i,l,d=getOwn(P,this.map.id),f=this.map.name,p=this.map.parentMap?this.map.parentMap.name:null,m=b.makeRequire(t.parentMap,{enableBuildCallback:!0});return this.map.unnormalized?(r.normalize&&(f=r.normalize(f,function(t){return n(t,p,!0)})||""),c(f=s(t.prefix+"!"+f,this.map.parentMap),"defined",bind(this,function(t){this.init([],function(){return t},null,{enabled:!0,ignore:!0})})),void((l=getOwn(E,f.id))&&(this.depMaps.push(f),this.events.error&&l.on("error",bind(this,function(t){this.emit("error",t)})),l.enable()))):d?(this.map.url=b.nameToUrl(d),void this.load()):((i=bind(this,function(t){this.init([],function(){return t},null,{enabled:!0})})).error=bind(this,function(t){this.inited=!0,(this.error=t).requireModules=[e],eachProp(E,function(t){0===t.map.id.indexOf(e+"_unnormalized")&&h(t.map.id)}),u(t)}),i.fromText=bind(this,function(n,r){var o=t.name,c=s(o),l=useInteractive;r&&(n=r),l&&(useInteractive=!1),a(c),hasProp(C.config,e)&&(C.config[o]=C.config[e]);try{req.exec(n)}catch(h){return u(makeError("fromtexteval","fromText eval for "+e+" failed: "+h,h,[e]))}l&&(useInteractive=!0),this.depMaps.push(c),b.completeLoad(o),m([o],i)}),void r.load(t.name,m,i,C))})),b.enable(r,this),this.pluginMaps[r.id]=r},enable:function(){(S[this.map.id]=this).enabled=!0,this.enabling=!0,each(this.depMaps,bind(this,function(t,e){var r,i;if("string"==typeof t){if(t=s(t,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap),this.depMaps[e]=t,i=getOwn(x,t.id))return void(this.depExports[e]=i(this));this.depCount+=1,c(t,"defined",bind(this,function(t){this.defineDep(e,t),this.check()})),this.errback&&c(t,"error",bind(this,this.errback))}i=t.id,r=E[i],hasProp(x,i)||!r||r.enabled||b.enable(t,this)})),eachProp(this.pluginMaps,bind(this,function(t){var e=getOwn(E,t.id);e&&!e.enabled&&b.enable(t,this)})),this.enabling=!1,this.check()},on:function(t,e){(this.events[t]||(this.events[t]=[])).push(e)},emit:function(t,e){each(this.events[t],function(t){t(e)}),"error"===t&&delete this.events[t]}},(b={config:C,contextName:t,registry:E,defined:q,urlFetched:I,defQueue:_,Module:v,makeModuleMap:s,nextTick:req.nextTick,onError:u,configure:function(t){t.baseUrl&&"/"!==t.baseUrl.charAt(t.baseUrl.length-1)&&(t.baseUrl+="/");var e=C.shim,n={paths:!0,bundles:!0,config:!0,map:!0};eachProp(t,function(t,e){n[e]?(C[e]||(C[e]={}),mixin(C[e],t,!0,!0)):C[e]=t}),t.bundles&&eachProp(t.bundles,function(t,e){each(t,function(t){t!==e&&(P[t]=e)})}),t.shim&&(eachProp(t.shim,function(t,n){!(t=isArray(t)?{deps:t}:t).exports&&!t.init||t.exportsFn||(t.exportsFn=b.makeShimExports(t)),e[n]=t}),C.shim=e),t.packages&&each(t.packages,function(t){var n=(t="string"==typeof t?{name:t}:t).name;t.location&&(C.paths[n]=t.location),C.pkgs[n]=t.name+"/"+(t.main||"main").replace(currDirRegExp,"").replace(jsSuffixRegExp,"")}),eachProp(E,function(t,e){t.inited||t.map.unnormalized||(t.map=s(e))}),(t.deps||t.callback)&&b.require(t.deps||[],t.callback)},makeShimExports:function(t){return function(){var e;return(e=t.init?t.init.apply(global,arguments):e)||t.exports&&getGlobal(t.exports)}},makeRequire:function(e,i){function o(n,r,c){var l,d;return i.enableBuildCallback&&r&&isFunction(r)&&(r.__requireJsBuild=!0),"string"==typeof n?isFunction(r)?u(makeError("requireargs","Invalid require call"),c):e&&hasProp(x,n)?x[n](E[e.id]):req.get?req.get(b,n,e,o):(l=s(n,e,!1,!0).id,hasProp(q,l)?q[l]:u(makeError("notloaded",'Module name "'+l+'" has not been loaded yet for context: '+t+(e?"":". Use require([])")))):(w(),b.nextTick(function(){w(),(d=a(s(null,e))).skipMap=i.skipMap,d.init(n,r,c,{enabled:!0}),f()}),o)}return i=i||{},mixin(o,{isBrowser:isBrowser,toUrl:function(t){var r,i=t.lastIndexOf("."),o=t.split("/")[0];return-1!==i&&(!("."===o||".."===o)||1<i)&&(r=t.substring(i,t.length),t=t.substring(0,i)),b.nameToUrl(n(t,e&&e.id,!0),r,!0)},defined:function(t){return hasProp(q,s(t,e,!1,!0).id)},specified:function(t){return t=s(t,e,!1,!0).id,hasProp(q,t)||hasProp(E,t)}}),e||(o.undef=function(t){l();var n=s(t,e,!0),i=getOwn(E,t);r(t),delete q[t],delete I[n.url],delete T[t],eachReverse(_,function(e,n){e[0]===t&&_.splice(n,1)}),i&&(i.events.defined&&(T[t]=i.events),h(t))}),o},enable:function(t){getOwn(E,t.id)&&a(t).enable()},completeLoad:function(t){var e,n,r,o=getOwn(C.shim,t)||{},s=o.exports;for(l();_.length;){if(null===(n=_.shift())[0]){if(n[0]=t,e)break;e=!0}else n[0]===t&&(e=!0);p(n)}if(r=getOwn(E,t),!e&&!hasProp(q,t)&&r&&!r.inited){if(!(!C.enforceDefine||s&&getGlobal(s)))return i(t)?void 0:u(makeError("nodefine","No define call for "+t,null,[t]));p([t,o.deps||[],o.exportsFn])}f()},nameToUrl:function(t,e,n){var r,i,o,a,c,l=getOwn(C.pkgs,t);if(l=getOwn(P,t=l?l:t))return b.nameToUrl(l,e,n);if(req.jsExtRegExp.test(t))a=t+(e||"");else{for(r=C.paths,o=(i=t.split("/")).length;0<o;--o)if(c=getOwn(r,i.slice(0,o).join("/"))){isArray(c)&&(c=c[0]),i.splice(0,o,c);break}a=i.join("/"),a=("/"===(a+=e||(/^data\:|\?/.test(a)||n?"":".js")).charAt(0)||a.match(/^[\w\+\.\-]+:/)?"":C.baseUrl)+a}return C.urlArgs?a+((-1===a.indexOf("?")?"?":"&")+C.urlArgs):a},load:function(t,e){req.load(b,t,e)},execCb:function(t,e,n,r){return e.apply(r,n)},onScriptLoad:function(t){"load"!==t.type&&!readyRegExp.test((t.currentTarget||t.srcElement).readyState)||(interactiveScript=null,t=g(t),b.completeLoad(t.id))},onScriptError:function(t){var e=g(t);return i(e.id)?void 0:u(makeError("scripterror","Script error for: "+e.id,t,[e.id]))}}).require=b.makeRequire(),b}function getInteractiveScript(){return interactiveScript&&"interactive"===interactiveScript.readyState||eachReverse(scripts(),function(t){return"interactive"===t.readyState?interactiveScript=t:void 0}),interactiveScript}var req,s,head,baseElement,dataMain,src,interactiveScript,currentlyAddingScript,mainScript,subPath,version="2.1.15",commentRegExp=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm,cjsRequireRegExp=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,jsSuffixRegExp=/\.js$/,currDirRegExp=/^\.\//,op=Object.prototype,ostring=op.toString,hasOwn=op.hasOwnProperty,ap=Array.prototype,apsp=ap.splice,isBrowser=!("undefined"==typeof window||"undefined"==typeof navigator||!window.document),isWebWorker=!isBrowser&&"undefined"!=typeof importScripts,readyRegExp=isBrowser&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,defContextName="_",isOpera="undefined"!=typeof opera&&"[object Opera]"===opera.toString(),contexts={},cfg={},globalDefQueue=[],useInteractive=!1;if(void 0===define){if(void 0!==requirejs){if(isFunction(requirejs))return;cfg=requirejs,requirejs=void 0}void 0===require||isFunction(require)||(cfg=require,require=void 0),req=requirejs=function(t,e,n,r){var o,s=defContextName;return isArray(t)||"string"==typeof t||(o=t,isArray(e)?(t=e,e=n,n=r):t=[]),o&&o.context&&(s=o.context),r=(r=getOwn(contexts,s))||(contexts[s]=req.s.newContext(s)),o&&r.configure(o),r.require(t,e,n)},req.config=function(t){return req(t)},req.nextTick="undefined"!=typeof setTimeout?function(t){setTimeout(t,4)}:function(t){t()},require=require||req,req.version=version,req.jsExtRegExp=/^\/|:|\?|\.js$/,req.isBrowser=isBrowser,s=req.s={contexts:contexts,newContext:newContext},req({}),each(["toUrl","undef","defined","specified"],function(t){req[t]=function(){var e=contexts[defContextName];return e.require[t].apply(e,arguments)}}),isBrowser&&(head=s.head=document.getElementsByTagName("head")[0],baseElement=document.getElementsByTagName("base")[0],baseElement)&&(head=s.head=baseElement.parentNode),req.onError=defaultOnError,req.createNode=function(t){var e=t.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");return e.type=t.scriptType||"text/javascript",e.charset="utf-8",e.async=!0,e},req.load=function(t,e,n){var i=t&&t.config||{};if(isBrowser)return(i=req.createNode(i,e,n)).setAttribute("data-requirecontext",t.contextName),i.setAttribute("data-requiremodule",e),!i.attachEvent||i.attachEvent.toString&&i.attachEvent.toString().indexOf("[native code")<0||isOpera?(i.addEventListener("load",t.onScriptLoad,!1),i.addEventListener("error",t.onScriptError,!1)):(useInteractive=!0,i.attachEvent("onreadystatechange",t.onScriptLoad)),i.src=n,currentlyAddingScript=i,baseElement?head.insertBefore(i,baseElement):head.appendChild(i),currentlyAddingScript=null,i;if(isWebWorker)try{importScripts(n),t.completeLoad(e)}catch(o){t.onError(makeError("importscripts","importScripts failed for "+e+" at "+n,o,[e]))}},isBrowser&&!cfg.skipDataMain&&eachReverse(scripts(),function(t){return head=head||t.parentNode,(dataMain=t.getAttribute("data-main"))?(mainScript=dataMain,cfg.baseUrl||(mainScript=(src=mainScript.split("/")).pop(),subPath=src.length?src.join("/")+"/":"./",cfg.baseUrl=subPath),mainScript=mainScript.replace(jsSuffixRegExp,""),req.jsExtRegExp.test(mainScript)&&(mainScript=dataMain),cfg.deps=cfg.deps?cfg.deps.concat(mainScript):[mainScript],!0):void 0}),define=function(t,e,n){var r,i;"string"!=typeof t&&(n=e,e=t,t=null),isArray(e)||(n=e,e=null),!e&&isFunction(n)&&(e=[],n.length)&&(n.toString().replace(commentRegExp,"").replace(cjsRequireRegExp,function(t,n){e.push(n)}),e=(1===n.length?["require"]:["require","exports","module"]).concat(e)),useInteractive&&(r=currentlyAddingScript||getInteractiveScript())&&(t=t||r.getAttribute("data-requiremodule"),i=contexts[r.getAttribute("data-requirecontext")]),(i?i.defQueue:globalDefQueue).push([t,e,n])},define.amd={jQuery:!0},req.exec=function(text){return eval(text)},req(cfg)}}(this)}({},function(){return this}())}.call(this)}.call(this,require("_process"))},{_process:1042,buffer:113}],662:[function(require,module,exports){"use strict";for(var isObject=function(val){return null!==val&&!Array.isArray(val)&&"object"==typeof val},codes={3:"Cancel",6:"Help",8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",28:"Convert",29:"NonConvert",30:"Accept",31:"ModeChange",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",41:"Select",42:"Print",43:"Execute",44:"PrintScreen",45:"Insert",46:"Delete",48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],91:"OS",93:"ContextMenu",144:"NumLock",145:"ScrollLock",181:"VolumeMute",182:"VolumeDown",183:"VolumeUp",186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"'],224:"Meta",225:"AltGraph",246:"Attn",247:"CrSel",248:"ExSel",249:"EraseEof",250:"Play",251:"ZoomOut"},i=0;i<24;i+=1)codes[112+i]="F"+(i+1);for(var j=0;j<26;j+=1){var n=j+65;codes[n]=[String.fromCharCode(n+32),String.fromCharCode(n)]}var keyboardKey={codes:codes,getCode:function(eventOrKey){return isObject(eventOrKey)?eventOrKey.keyCode||eventOrKey.which||this[eventOrKey.key]:this[eventOrKey]},getKey:function(eventOrCode){var name,isEvent=isObject(eventOrCode);return isEvent&&eventOrCode.key?eventOrCode.key:(name=codes[isEvent?eventOrCode.keyCode||eventOrCode.which:eventOrCode],Array.isArray(name)?isEvent?name[eventOrCode.shiftKey?1:0]:name[0]:name)},Cancel:3,Help:6,Backspace:8,Tab:9,Clear:12,Enter:13,Shift:16,Control:17,Alt:18,Pause:19,CapsLock:20,Escape:27,Convert:28,NonConvert:29,Accept:30,ModeChange:31," ":32,PageUp:33,PageDown:34,End:35,Home:36,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,Select:41,Print:42,Execute:43,PrintScreen:44,Insert:45,Delete:46,0:48,")":48,1:49,"!":49,2:50,"@":50,3:51,"#":51,4:52,$:52,5:53,"%":53,6:54,"^":54,7:55,"&":55,8:56,"*":56,9:57,"(":57,a:65,A:65,b:66,B:66,c:67,C:67,d:68,D:68,e:69,E:69,f:70,F:70,g:71,G:71,h:72,H:72,i:73,I:73,j:74,J:74,k:75,K:75,l:76,L:76,m:77,M:77,n:78,N:78,o:79,O:79,p:80,P:80,q:81,Q:81,r:82,R:82,s:83,S:83,t:84,T:84,u:85,U:85,v:86,V:86,w:87,W:87,x:88,X:88,y:89,Y:89,z:90,Z:90,OS:91,ContextMenu:93,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,F16:127,F17:128,F18:129,F19:130,F20:131,F21:132,F22:133,F23:134,F24:135,NumLock:144,ScrollLock:145,VolumeMute:181,VolumeDown:182,VolumeUp:183,";":186,":":186,"=":187,"+":187,",":188,"<":188,"-":189,_:189,".":190,">":190,"/":191,"?":191,"`":192,"~":192,"[":219,"{":219,"\\":220,"|":220,"]":221,"}":221,"'":222,'"':222,Meta:224,AltGraph:225,Attn:246,CrSel:247,ExSel:248,EraseEof:249,Play:250,ZoomOut:251};keyboardKey.Spacebar=keyboardKey[" "],keyboardKey.Digit0=keyboardKey[0],keyboardKey.Digit1=keyboardKey[1],keyboardKey.Digit2=keyboardKey[2],keyboardKey.Digit3=keyboardKey[3],keyboardKey.Digit4=keyboardKey[4],keyboardKey.Digit5=keyboardKey[5],keyboardKey.Digit6=keyboardKey[6],keyboardKey.Digit7=keyboardKey[7],keyboardKey.Digit8=keyboardKey[8],keyboardKey.Digit9=keyboardKey[9],keyboardKey.Tilde=keyboardKey["~"],keyboardKey.GraveAccent=keyboardKey["`"],keyboardKey.ExclamationPoint=keyboardKey["!"],keyboardKey.AtSign=keyboardKey["@"],keyboardKey.PoundSign=keyboardKey["#"],keyboardKey.PercentSign=keyboardKey["%"],keyboardKey.Caret=keyboardKey["^"],keyboardKey.Ampersand=keyboardKey["&"],keyboardKey.PlusSign=keyboardKey["+"],keyboardKey.MinusSign=keyboardKey["-"],keyboardKey.EqualsSign=keyboardKey["="],keyboardKey.DivisionSign=keyboardKey["/"],keyboardKey.MultiplicationSign=keyboardKey["*"],keyboardKey.Comma=keyboardKey[","],keyboardKey.Decimal=keyboardKey["."],keyboardKey.Colon=keyboardKey[":"],keyboardKey.Semicolon=keyboardKey[";"],keyboardKey.Pipe=keyboardKey["|"],keyboardKey.BackSlash=keyboardKey["\\"],keyboardKey.QuestionMark=keyboardKey["?"],keyboardKey.SingleQuote=keyboardKey["'"],keyboardKey.DoubleQuote=keyboardKey['"'],keyboardKey.LeftCurlyBrace=keyboardKey["{"],keyboardKey.RightCurlyBrace=keyboardKey["}"],keyboardKey.LeftParenthesis=keyboardKey["("],keyboardKey.RightParenthesis=keyboardKey[")"],keyboardKey.LeftAngleBracket=keyboardKey["<"],keyboardKey.RightAngleBracket=keyboardKey[">"],keyboardKey.LeftSquareBracket=keyboardKey["["],keyboardKey.RightSquareBracket=keyboardKey["]"],module.exports=keyboardKey},{}],663:[function(require,module,exports){require=require("./_getNative")(require("./_root"),"DataView");module.exports=require},{"./_getNative":819,"./_root":875}],664:[function(require,module,exports){var hashClear=require("./_hashClear"),hashDelete=require("./_hashDelete"),hashGet=require("./_hashGet"),hashHas=require("./_hashHas"),require=require("./_hashSet");function Hash(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=require,module.exports=Hash},{"./_hashClear":830,"./_hashDelete":831,"./_hashGet":832,"./_hashHas":833,"./_hashSet":834}],665:[function(require,module,exports){var baseCreate=require("./_baseCreate"),require=require("./_baseLodash");function LazyWrapper(value){this.__wrapped__=value,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}LazyWrapper.prototype=baseCreate(require.prototype),module.exports=LazyWrapper.prototype.constructor=LazyWrapper},{"./_baseCreate":701,"./_baseLodash":734}],666:[function(require,module,exports){var listCacheClear=require("./_listCacheClear"),listCacheDelete=require("./_listCacheDelete"),listCacheGet=require("./_listCacheGet"),listCacheHas=require("./_listCacheHas"),require=require("./_listCacheSet");function ListCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=require,module.exports=ListCache},{"./_listCacheClear":849,"./_listCacheDelete":850,"./_listCacheGet":851,"./_listCacheHas":852,"./_listCacheSet":853}],667:[function(require,module,exports){var baseCreate=require("./_baseCreate"),require=require("./_baseLodash");function LodashWrapper(value,chainAll){this.__wrapped__=value,this.__actions__=[],this.__chain__=!!chainAll,this.__index__=0,this.__values__=void 0}LodashWrapper.prototype=baseCreate(require.prototype),module.exports=LodashWrapper.prototype.constructor=LodashWrapper},{"./_baseCreate":701,"./_baseLodash":734}],668:[function(require,module,exports){require=require("./_getNative")(require("./_root"),"Map");module.exports=require},{"./_getNative":819,"./_root":875}],669:[function(require,module,exports){var mapCacheClear=require("./_mapCacheClear"),mapCacheDelete=require("./_mapCacheDelete"),mapCacheGet=require("./_mapCacheGet"),mapCacheHas=require("./_mapCacheHas"),require=require("./_mapCacheSet");function MapCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=require,module.exports=MapCache},{"./_mapCacheClear":854,"./_mapCacheDelete":855,"./_mapCacheGet":856,"./_mapCacheHas":857,"./_mapCacheSet":858}],670:[function(require,module,exports){require=require("./_getNative")(require("./_root"),"Promise");module.exports=require},{"./_getNative":819,"./_root":875}],671:[function(require,module,exports){require=require("./_getNative")(require("./_root"),"Set");module.exports=require},{"./_getNative":819,"./_root":875}],672:[function(require,module,exports){var MapCache=require("./_MapCache"),setCacheAdd=require("./_setCacheAdd"),require=require("./_setCacheHas");function SetCache(values){var index=-1,length=null==values?0:values.length;for(this.__data__=new MapCache;++index<length;)this.add(values[index])}SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=require,module.exports=SetCache},{"./_MapCache":669,"./_setCacheAdd":877,"./_setCacheHas":878}],673:[function(require,module,exports){var ListCache=require("./_ListCache"),stackClear=require("./_stackClear"),stackDelete=require("./_stackDelete"),stackGet=require("./_stackGet"),stackHas=require("./_stackHas"),require=require("./_stackSet");function Stack(entries){entries=this.__data__=new ListCache(entries);this.size=entries.size}Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=require,module.exports=Stack},{"./_ListCache":666,"./_stackClear":884,"./_stackDelete":885,"./_stackGet":886,"./_stackHas":887,"./_stackSet":888}],674:[function(require,module,exports){require=require("./_root").Symbol;module.exports=require},{"./_root":875}],675:[function(require,module,exports){require=require("./_root").Uint8Array;module.exports=require},{"./_root":875}],676:[function(require,module,exports){require=require("./_getNative")(require("./_root"),"WeakMap");module.exports=require},{"./_getNative":819,"./_root":875}],677:[function(require,module,exports){module.exports=function(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}},{}],678:[function(require,module,exports){module.exports=function(array,setter,iteratee,accumulator){for(var index=-1,length=null==array?0:array.length;++index<length;){var value=array[index];setter(accumulator,value,iteratee(value),array)}return accumulator}},{}],679:[function(require,module,exports){module.exports=function(array,iteratee){for(var index=-1,length=null==array?0:array.length;++index<length&&!1!==iteratee(array[index],index,array););return array}},{}],680:[function(require,module,exports){module.exports=function(array,predicate){for(var index=-1,length=null==array?0:array.length;++index<length;)if(!predicate(array[index],index,array))return!1;return!0}},{}],681:[function(require,module,exports){module.exports=function(array,predicate){for(var index=-1,length=null==array?0:array.length,resIndex=0,result=[];++index<length;){var value=array[index];predicate(value,index,array)&&(result[resIndex++]=value)}return result}},{}],682:[function(require,module,exports){var baseIndexOf=require("./_baseIndexOf");module.exports=function(array,value){return!!(null==array?0:array.length)&&-1<baseIndexOf(array,value,0)}},{"./_baseIndexOf":717}],683:[function(require,module,exports){module.exports=function(array,value,comparator){for(var index=-1,length=null==array?0:array.length;++index<length;)if(comparator(value,array[index]))return!0;return!1}},{}],684:[function(require,module,exports){var baseTimes=require("./_baseTimes"),isArguments=require("./isArguments"),isArray=require("./isArray"),isBuffer=require("./isBuffer"),isIndex=require("./_isIndex"),isTypedArray=require("./isTypedArray"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(value,inherited){var key,isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(key in value)!inherited&&!hasOwnProperty.call(value,key)||skipIndexes&&("length"==key||isBuff&&("offset"==key||"parent"==key)||isType&&("buffer"==key||"byteLength"==key||"byteOffset"==key)||isIndex(key,length))||result.push(key);return result}},{"./_baseTimes":757,"./_isIndex":840,"./isArguments":960,"./isArray":961,"./isBuffer":965,"./isTypedArray":981}],685:[function(require,module,exports){module.exports=function(array,iteratee){for(var index=-1,length=null==array?0:array.length,result=Array(length);++index<length;)result[index]=iteratee(array[index],index,array);return result}},{}],686:[function(require,module,exports){module.exports=function(array,values){for(var index=-1,length=values.length,offset=array.length;++index<length;)array[offset+index]=values[index];return array}},{}],687:[function(require,module,exports){module.exports=function(array,iteratee,accumulator,initAccum){var index=-1,length=null==array?0:array.length;for(initAccum&&length&&(accumulator=array[++index]);++index<length;)accumulator=iteratee(accumulator,array[index],index,array);return accumulator}},{}],688:[function(require,module,exports){module.exports=function(array,predicate){for(var index=-1,length=null==array?0:array.length;++index<length;)if(predicate(array[index],index,array))return!0;return!1}},{}],689:[function(require,module,exports){require=require("./_baseProperty")("length");module.exports=require},{"./_baseProperty":744}],690:[function(require,module,exports){module.exports=function(string){return string.split("")}},{}],691:[function(require,module,exports){var reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;module.exports=function(string){return string.match(reAsciiWord)||[]}},{}],692:[function(require,module,exports){var baseAssignValue=require("./_baseAssignValue"),eq=require("./eq");module.exports=function(object,key,value){(void 0===value||eq(object[key],value))&&(void 0!==value||key in object)||baseAssignValue(object,key,value)}},{"./_baseAssignValue":698,"./eq":911}],693:[function(require,module,exports){var baseAssignValue=require("./_baseAssignValue"),eq=require("./eq"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(object,key,value){var objValue=object[key];hasOwnProperty.call(object,key)&&eq(objValue,value)&&(void 0!==value||key in object)||baseAssignValue(object,key,value)}},{"./_baseAssignValue":698,"./eq":911}],694:[function(require,module,exports){var eq=require("./eq");module.exports=function(array,key){for(var length=array.length;length--;)if(eq(array[length][0],key))return length;return-1}},{"./eq":911}],695:[function(require,module,exports){var baseEach=require("./_baseEach");module.exports=function(collection,setter,iteratee,accumulator){return baseEach(collection,function(value,key,collection){setter(accumulator,value,iteratee(value),collection)}),accumulator}},{"./_baseEach":703}],696:[function(require,module,exports){var copyObject=require("./_copyObject"),keys=require("./keys");module.exports=function(object,source){return object&&copyObject(source,keys(source),object)}},{"./_copyObject":781,"./keys":986}],697:[function(require,module,exports){var copyObject=require("./_copyObject"),keysIn=require("./keysIn");module.exports=function(object,source){return object&&copyObject(source,keysIn(source),object)}},{"./_copyObject":781,"./keysIn":987}],698:[function(require,module,exports){var defineProperty=require("./_defineProperty");module.exports=function(object,key,value){"__proto__"==key&&defineProperty?defineProperty(object,key,{configurable:!0,enumerable:!0,value:value,writable:!0}):object[key]=value}},{"./_defineProperty":806}],699:[function(require,module,exports){module.exports=function(number,lower,upper){return number=number==number&&(void 0!==upper&&(number=number<=upper?number:upper),void 0!==lower)?lower<=number?number:lower:number}},{}],700:[function(require,module,exports){var Stack=require("./_Stack"),arrayEach=require("./_arrayEach"),assignValue=require("./_assignValue"),baseAssign=require("./_baseAssign"),baseAssignIn=require("./_baseAssignIn"),cloneBuffer=require("./_cloneBuffer"),copyArray=require("./_copyArray"),copySymbols=require("./_copySymbols"),copySymbolsIn=require("./_copySymbolsIn"),getAllKeys=require("./_getAllKeys"),getAllKeysIn=require("./_getAllKeysIn"),getTag=require("./_getTag"),initCloneArray=require("./_initCloneArray"),initCloneByTag=require("./_initCloneByTag"),initCloneObject=require("./_initCloneObject"),isArray=require("./isArray"),isBuffer=require("./isBuffer"),isMap=require("./isMap"),isObject=require("./isObject"),isSet=require("./isSet"),keys=require("./keys"),keysIn=require("./keysIn"),cloneableTags={};cloneableTags["[object Arguments]"]=cloneableTags["[object Array]"]=cloneableTags["[object ArrayBuffer]"]=cloneableTags["[object DataView]"]=cloneableTags["[object Boolean]"]=cloneableTags["[object Date]"]=cloneableTags["[object Float32Array]"]=cloneableTags["[object Float64Array]"]=cloneableTags["[object Int8Array]"]=cloneableTags["[object Int16Array]"]=cloneableTags["[object Int32Array]"]=cloneableTags["[object Map]"]=cloneableTags["[object Number]"]=cloneableTags["[object Object]"]=cloneableTags["[object RegExp]"]=cloneableTags["[object Set]"]=cloneableTags["[object String]"]=cloneableTags["[object Symbol]"]=cloneableTags["[object Uint8Array]"]=cloneableTags["[object Uint8ClampedArray]"]=cloneableTags["[object Uint16Array]"]=cloneableTags["[object Uint32Array]"]=!0,cloneableTags["[object Error]"]=cloneableTags["[object Function]"]=cloneableTags["[object WeakMap]"]=!1,module.exports=function baseClone(value,bitmask,customizer,key,object,stack){var result,isDeep=1&bitmask,isFlat=2&bitmask,isFull=4&bitmask;if(void 0===(result=customizer?object?customizer(value,key,object,stack):customizer(value):result)){if(!isObject(value))return value;if(key=isArray(value)){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc="[object Function]"==tag||"[object GeneratorFunction]"==tag;if(isBuffer(value))return cloneBuffer(value,isDeep);if("[object Object]"==tag||"[object Arguments]"==tag||isFunc&&!object){if(result=isFlat||isFunc?{}:initCloneObject(value),!isDeep)return isFlat?copySymbolsIn(value,baseAssignIn(result,value)):copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,isDeep)}}if(isFunc=(stack=stack||new Stack).get(value))return isFunc;stack.set(value,result),isSet(value)?value.forEach(function(subValue){result.add(baseClone(subValue,bitmask,customizer,subValue,value,stack))}):isMap(value)&&value.forEach(function(subValue,key){result.set(key,baseClone(subValue,bitmask,customizer,key,value,stack))});var props=key?void 0:(isFull?isFlat?getAllKeysIn:getAllKeys:isFlat?keysIn:keys)(value);arrayEach(props||value,function(subValue,key){props&&(subValue=value[key=subValue]),assignValue(result,key,baseClone(subValue,bitmask,customizer,key,value,stack))})}return result}},{"./_Stack":673,"./_arrayEach":679,"./_assignValue":693,"./_baseAssign":696,"./_baseAssignIn":697,"./_cloneBuffer":771,"./_copyArray":780,"./_copySymbols":782,"./_copySymbolsIn":783,"./_getAllKeys":812,"./_getAllKeysIn":813,"./_getTag":824,"./_initCloneArray":835,"./_initCloneByTag":836,"./_initCloneObject":837,"./isArray":961,"./isBuffer":965,"./isMap":971,"./isObject":974,"./isSet":978,"./keys":986,"./keysIn":987}],701:[function(require,module,exports){var isObject=require("./isObject"),objectCreate=Object.create;function object(){}module.exports=function(proto){if(!isObject(proto))return{};if(objectCreate)return objectCreate(proto);object.prototype=proto;proto=new object;return object.prototype=void 0,proto}},{"./isObject":974}],702:[function(require,module,exports){var SetCache=require("./_SetCache"),arrayIncludes=require("./_arrayIncludes"),arrayIncludesWith=require("./_arrayIncludesWith"),arrayMap=require("./_arrayMap"),baseUnary=require("./_baseUnary"),cacheHas=require("./_cacheHas");module.exports=function(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(length){iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):200<=values.length&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index<length;){var value=array[index],computed=null==iteratee?value:iteratee(value),value=comparator||0!==value?value:0;if(isCommon&&computed==computed){for(var valuesIndex=valuesLength;valuesIndex--;)if(values[valuesIndex]===computed)continue outer;result.push(value)}else includes(values,computed,comparator)||result.push(value)}}return result}},{"./_SetCache":672,"./_arrayIncludes":682,"./_arrayIncludesWith":683,"./_arrayMap":685,"./_baseUnary":760,"./_cacheHas":763}],703:[function(require,module,exports){var baseForOwn=require("./_baseForOwn"),require=require("./_createBaseEach")(baseForOwn);module.exports=require},{"./_baseForOwn":710,"./_createBaseEach":788}],704:[function(require,module,exports){var baseEach=require("./_baseEach");module.exports=function(collection,predicate){var result=!0;return baseEach(collection,function(value,index,collection){return result=!!predicate(value,index,collection)}),result}},{"./_baseEach":703}],705:[function(require,module,exports){var isSymbol=require("./isSymbol");module.exports=function(array,iteratee,comparator){for(var index=-1,length=array.length;++index<length;){var computed,result,value=array[index],current=iteratee(value);null!=current&&(void 0===computed?current==current&&!isSymbol(current):comparator(current,computed))&&(computed=current,result=value)}return result}},{"./isSymbol":980}],706:[function(require,module,exports){var baseEach=require("./_baseEach");module.exports=function(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}},{"./_baseEach":703}],707:[function(require,module,exports){module.exports=function(array,predicate,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?1:-1);fromRight?index--:++index<length;)if(predicate(array[index],index,array))return index;return-1}},{}],708:[function(require,module,exports){var arrayPush=require("./_arrayPush"),isFlattenable=require("./_isFlattenable");module.exports=function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate=predicate||isFlattenable,result=result||[];++index<length;){var value=array[index];0<depth&&predicate(value)?1<depth?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}},{"./_arrayPush":686,"./_isFlattenable":839}],709:[function(require,module,exports){require=require("./_createBaseFor")();module.exports=require},{"./_createBaseFor":789}],710:[function(require,module,exports){var baseFor=require("./_baseFor"),keys=require("./keys");module.exports=function(object,iteratee){return object&&baseFor(object,iteratee,keys)}},{"./_baseFor":709,"./keys":986}],711:[function(require,module,exports){var castPath=require("./_castPath"),toKey=require("./_toKey");module.exports=function(object,path){for(var index=0,length=(path=castPath(path,object)).length;null!=object&&index<length;)object=object[toKey(path[index++])];return index&&index==length?object:void 0}},{"./_castPath":766,"./_toKey":893}],712:[function(require,module,exports){var arrayPush=require("./_arrayPush"),isArray=require("./isArray");module.exports=function(object,keysFunc,symbolsFunc){return keysFunc=keysFunc(object),isArray(object)?keysFunc:arrayPush(keysFunc,symbolsFunc(object))}},{"./_arrayPush":686,"./isArray":961}],713:[function(require,module,exports){var Symbol=require("./_Symbol"),getRawTag=require("./_getRawTag"),objectToString=require("./_objectToString"),symToStringTag=Symbol?Symbol.toStringTag:void 0;module.exports=function(value){return null==value?void 0===value?"[object Undefined]":"[object Null]":(symToStringTag&&symToStringTag in Object(value)?getRawTag:objectToString)(value)}},{"./_Symbol":674,"./_getRawTag":821,"./_objectToString":868}],714:[function(require,module,exports){var hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(object,key){return null!=object&&hasOwnProperty.call(object,key)}},{}],715:[function(require,module,exports){module.exports=function(object,key){return null!=object&&key in Object(object)}},{}],716:[function(require,module,exports){var nativeMax=Math.max,nativeMin=Math.min;module.exports=function(number,start,end){return number>=nativeMin(start,end)&&number<nativeMax(start,end)}},{}],717:[function(require,module,exports){var baseFindIndex=require("./_baseFindIndex"),baseIsNaN=require("./_baseIsNaN"),strictIndexOf=require("./_strictIndexOf");module.exports=function(array,value,fromIndex){return value==value?strictIndexOf(array,value,fromIndex):baseFindIndex(array,baseIsNaN,fromIndex)}},{"./_baseFindIndex":707,"./_baseIsNaN":726,"./_strictIndexOf":889}],718:[function(require,module,exports){var SetCache=require("./_SetCache"),arrayIncludes=require("./_arrayIncludes"),arrayIncludesWith=require("./_arrayIncludesWith"),arrayMap=require("./_arrayMap"),baseUnary=require("./_baseUnary"),cacheHas=require("./_cacheHas"),nativeMin=Math.min;module.exports=function(arrays,iteratee,comparator){for(var includes=comparator?arrayIncludesWith:arrayIncludes,length=arrays[0].length,othLength=arrays.length,othIndex=othLength,caches=Array(othLength),maxLength=1/0,result=[];othIndex--;){var array=arrays[othIndex];othIndex&&iteratee&&(array=arrayMap(array,baseUnary(iteratee))),maxLength=nativeMin(array.length,maxLength),caches[othIndex]=!comparator&&(iteratee||120<=length&&120<=array.length)?new SetCache(othIndex&&array):void 0}var array=arrays[0],index=-1,seen=caches[0];outer:for(;++index<length&&result.length<maxLength;){var value=array[index],computed=iteratee?iteratee(value):value,value=comparator||0!==value?value:0;if(!(seen?cacheHas(seen,computed):includes(result,computed,comparator))){for(othIndex=othLength;--othIndex;){var cache=caches[othIndex];if(!(cache?cacheHas(cache,computed):includes(arrays[othIndex],computed,comparator)))continue outer}seen&&seen.push(computed),result.push(value)}}return result}},{"./_SetCache":672,"./_arrayIncludes":682,"./_arrayIncludesWith":683,"./_arrayMap":685,"./_baseUnary":760,"./_cacheHas":763}],719:[function(require,module,exports){var baseForOwn=require("./_baseForOwn");module.exports=function(object,setter,iteratee,accumulator){return baseForOwn(object,function(value,key,object){setter(accumulator,iteratee(value),key,object)}),accumulator}},{"./_baseForOwn":710}],720:[function(require,module,exports){var apply=require("./_apply"),castPath=require("./_castPath"),last=require("./last"),parent=require("./_parent"),toKey=require("./_toKey");module.exports=function(object,path,args){return path=castPath(path,object),null==(path=null==(object=parent(object,path))?object:object[toKey(last(path))])?void 0:apply(path,object,args)}},{"./_apply":677,"./_castPath":766,"./_parent":871,"./_toKey":893,"./last":988}],721:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isObjectLike=require("./isObjectLike");module.exports=function(value){return isObjectLike(value)&&"[object Arguments]"==baseGetTag(value)}},{"./_baseGetTag":713,"./isObjectLike":975}],722:[function(require,module,exports){var baseIsEqualDeep=require("./_baseIsEqualDeep"),isObjectLike=require("./isObjectLike");module.exports=function baseIsEqual(value,other,bitmask,customizer,stack){return value===other||(null==value||null==other||!isObjectLike(value)&&!isObjectLike(other)?value!=value&&other!=other:baseIsEqualDeep(value,other,bitmask,customizer,baseIsEqual,stack))}},{"./_baseIsEqualDeep":723,"./isObjectLike":975}],723:[function(require,module,exports){var Stack=require("./_Stack"),equalArrays=require("./_equalArrays"),equalByTag=require("./_equalByTag"),equalObjects=require("./_equalObjects"),getTag=require("./_getTag"),isArray=require("./isArray"),isBuffer=require("./isBuffer"),isTypedArray=require("./isTypedArray"),objectTag="[object Object]",hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(object,other,bitmask,customizer,equalFunc,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=objIsArr?"[object Array]":getTag(object),othIsArr=othIsArr?"[object Array]":getTag(other),objIsObj=(objTag="[object Arguments]"==objTag?objectTag:objTag)==objectTag,othIsObj=(othIsArr="[object Arguments]"==othIsArr?objectTag:othIsArr)==objectTag;if((othIsArr=objTag==othIsArr)&&isBuffer(object)){if(!isBuffer(other))return!1;objIsObj=!(objIsArr=!0)}if(othIsArr&&!objIsObj)return stack=stack||new Stack,objIsArr||isTypedArray(object)?equalArrays(object,other,bitmask,customizer,equalFunc,stack):equalByTag(object,other,objTag,bitmask,customizer,equalFunc,stack);if(!(1&bitmask)){objIsArr=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),objTag=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(objIsArr||objTag)return equalFunc(objIsArr?object.value():object,objTag?other.value():other,bitmask,customizer,stack=stack||new Stack)}return othIsArr&&(stack=stack||new Stack,equalObjects(object,other,bitmask,customizer,equalFunc,stack))}},{"./_Stack":673,"./_equalArrays":807,"./_equalByTag":808,"./_equalObjects":809,"./_getTag":824,"./isArray":961,"./isBuffer":965,"./isTypedArray":981}],724:[function(require,module,exports){var getTag=require("./_getTag"),isObjectLike=require("./isObjectLike");module.exports=function(value){return isObjectLike(value)&&"[object Map]"==getTag(value)}},{"./_getTag":824,"./isObjectLike":975}],725:[function(require,module,exports){var Stack=require("./_Stack"),baseIsEqual=require("./_baseIsEqual");module.exports=function(object,source,matchData,customizer){var index=matchData.length,length=index,noCustomizer=!customizer;if(null==object)return!length;for(object=Object(object);index--;){var data=matchData[index];if(noCustomizer&&data[2]?data[1]!==object[data[0]]:!(data[0]in object))return!1}for(;++index<length;){var key=(data=matchData[index])[0],objValue=object[key],srcValue=data[1];if(noCustomizer&&data[2]){if(void 0===objValue&&!(key in object))return!1}else{var result,stack=new Stack;if(!(void 0===(result=customizer?customizer(objValue,srcValue,key,object,source,stack):result)?baseIsEqual(srcValue,objValue,3,customizer,stack):result))return!1}}return!0}},{"./_Stack":673,"./_baseIsEqual":722}],726:[function(require,module,exports){module.exports=function(value){return value!=value}},{}],727:[function(require,module,exports){var isFunction=require("./isFunction"),isMasked=require("./_isMasked"),isObject=require("./isObject"),toSource=require("./_toSource"),reIsHostCtor=/^\[object .+?Constructor\]$/,require=Function.prototype,objectProto=Object.prototype,require=require.toString,objectProto=objectProto.hasOwnProperty,reIsNative=RegExp("^"+require.call(objectProto).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");module.exports=function(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)?reIsNative:reIsHostCtor).test(toSource(value))}},{"./_isMasked":845,"./_toSource":894,"./isFunction":969,"./isObject":974}],728:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isObjectLike=require("./isObjectLike");module.exports=function(value){return isObjectLike(value)&&"[object RegExp]"==baseGetTag(value)}},{"./_baseGetTag":713,"./isObjectLike":975}],729:[function(require,module,exports){var getTag=require("./_getTag"),isObjectLike=require("./isObjectLike");module.exports=function(value){return isObjectLike(value)&&"[object Set]"==getTag(value)}},{"./_getTag":824,"./isObjectLike":975}],730:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isLength=require("./isLength"),isObjectLike=require("./isObjectLike"),typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags["[object Arguments]"]=typedArrayTags["[object Array]"]=typedArrayTags["[object ArrayBuffer]"]=typedArrayTags["[object Boolean]"]=typedArrayTags["[object DataView]"]=typedArrayTags["[object Date]"]=typedArrayTags["[object Error]"]=typedArrayTags["[object Function]"]=typedArrayTags["[object Map]"]=typedArrayTags["[object Number]"]=typedArrayTags["[object Object]"]=typedArrayTags["[object RegExp]"]=typedArrayTags["[object Set]"]=typedArrayTags["[object String]"]=typedArrayTags["[object WeakMap]"]=!1,module.exports=function(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]}},{"./_baseGetTag":713,"./isLength":970,"./isObjectLike":975}],731:[function(require,module,exports){var baseMatches=require("./_baseMatches"),baseMatchesProperty=require("./_baseMatchesProperty"),identity=require("./identity"),isArray=require("./isArray"),property=require("./property");module.exports=function(value){return"function"==typeof value?value:null==value?identity:"object"==typeof value?isArray(value)?baseMatchesProperty(value[0],value[1]):baseMatches(value):property(value)}},{"./_baseMatches":737,"./_baseMatchesProperty":738,"./identity":954,"./isArray":961,"./property":998}],732:[function(require,module,exports){var isPrototype=require("./_isPrototype"),nativeKeys=require("./_nativeKeys"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(object){if(!isPrototype(object))return nativeKeys(object);var key,result=[];for(key in Object(object))hasOwnProperty.call(object,key)&&"constructor"!=key&&result.push(key);return result}},{"./_isPrototype":846,"./_nativeKeys":865}],733:[function(require,module,exports){var isObject=require("./isObject"),isPrototype=require("./_isPrototype"),nativeKeysIn=require("./_nativeKeysIn"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(object){if(!isObject(object))return nativeKeysIn(object);var key,isProto=isPrototype(object),result=[];for(key in object)("constructor"!=key||!isProto&&hasOwnProperty.call(object,key))&&result.push(key);return result}},{"./_isPrototype":846,"./_nativeKeysIn":866,"./isObject":974}],734:[function(require,module,exports){module.exports=function(){}},{}],735:[function(require,module,exports){module.exports=function(value,other){return value<other}},{}],736:[function(require,module,exports){var baseEach=require("./_baseEach"),isArrayLike=require("./isArrayLike");module.exports=function(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}},{"./_baseEach":703,"./isArrayLike":962}],737:[function(require,module,exports){var baseIsMatch=require("./_baseIsMatch"),getMatchData=require("./_getMatchData"),matchesStrictComparable=require("./_matchesStrictComparable");module.exports=function(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}},{"./_baseIsMatch":725,"./_getMatchData":818,"./_matchesStrictComparable":860}],738:[function(require,module,exports){var baseIsEqual=require("./_baseIsEqual"),get=require("./get"),hasIn=require("./hasIn"),isKey=require("./_isKey"),isStrictComparable=require("./_isStrictComparable"),matchesStrictComparable=require("./_matchesStrictComparable"),toKey=require("./_toKey");module.exports=function(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return void 0===objValue&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,3)}}},{"./_baseIsEqual":722,"./_isKey":842,"./_isStrictComparable":847,"./_matchesStrictComparable":860,"./_toKey":893,"./get":950,"./hasIn":952}],739:[function(require,module,exports){var Stack=require("./_Stack"),assignMergeValue=require("./_assignMergeValue"),baseFor=require("./_baseFor"),baseMergeDeep=require("./_baseMergeDeep"),isObject=require("./isObject"),keysIn=require("./keysIn"),safeGet=require("./_safeGet");module.exports=function baseMerge(object,source,srcIndex,customizer,stack){object!==source&&baseFor(source,function(srcValue,key){var newValue;stack=stack||new Stack,isObject(srcValue)?baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack):(newValue=customizer?customizer(safeGet(object,key),srcValue,key+"",object,source,stack):void 0,assignMergeValue(object,key,newValue=void 0===newValue?srcValue:newValue))},keysIn)}},{"./_Stack":673,"./_assignMergeValue":692,"./_baseFor":709,"./_baseMergeDeep":740,"./_safeGet":876,"./isObject":974,"./keysIn":987}],740:[function(require,module,exports){var assignMergeValue=require("./_assignMergeValue"),cloneBuffer=require("./_cloneBuffer"),cloneTypedArray=require("./_cloneTypedArray"),copyArray=require("./_copyArray"),initCloneObject=require("./_initCloneObject"),isArguments=require("./isArguments"),isArray=require("./isArray"),isArrayLikeObject=require("./isArrayLikeObject"),isBuffer=require("./isBuffer"),isFunction=require("./isFunction"),isObject=require("./isObject"),isPlainObject=require("./isPlainObject"),isTypedArray=require("./isTypedArray"),safeGet=require("./_safeGet"),toPlainObject=require("./toPlainObject");module.exports=function(object,source,key,srcIndex,mergeFunc,customizer,stack){var isArr,isBuff,isTyped,objValue=safeGet(object,key),srcValue=safeGet(source,key),stacked=stack.get(srcValue);stacked||((source=void 0===(stacked=customizer?customizer(objValue,srcValue,key+"",object,source,stack):void 0))&&(isBuff=!(isArr=isArray(srcValue))&&isBuffer(srcValue),isTyped=!isArr&&!isBuff&&isTypedArray(srcValue),stacked=srcValue,isArr||isBuff||isTyped?stacked=isArray(objValue)?objValue:isArrayLikeObject(objValue)?copyArray(objValue):isBuff?cloneBuffer(srcValue,!(source=!1)):isTyped?cloneTypedArray(srcValue,!(source=!1)):[]:isPlainObject(srcValue)||isArguments(srcValue)?isArguments(stacked=objValue)?stacked=toPlainObject(objValue):isObject(objValue)&&!isFunction(objValue)||(stacked=initCloneObject(srcValue)):source=!1),source&&(stack.set(srcValue,stacked),mergeFunc(stacked,srcValue,srcIndex,customizer,stack),stack.delete(srcValue))),assignMergeValue(object,key,stacked)}},{"./_assignMergeValue":692,"./_cloneBuffer":771,"./_cloneTypedArray":775,"./_copyArray":780,"./_initCloneObject":837,"./_safeGet":876,"./isArguments":960,"./isArray":961,"./isArrayLikeObject":963,"./isBuffer":965,"./isFunction":969,"./isObject":974,"./isPlainObject":976,"./isTypedArray":981,"./toPlainObject":1020}],741:[function(require,module,exports){var arrayMap=require("./_arrayMap"),baseGet=require("./_baseGet"),baseIteratee=require("./_baseIteratee"),baseMap=require("./_baseMap"),baseSortBy=require("./_baseSortBy"),baseUnary=require("./_baseUnary"),compareMultiple=require("./_compareMultiple"),identity=require("./identity"),isArray=require("./isArray");module.exports=function(collection,iteratees,orders){iteratees=iteratees.length?arrayMap(iteratees,function(iteratee){return isArray(iteratee)?function(value){return baseGet(value,1===iteratee.length?iteratee[0]:iteratee)}:iteratee}):[identity];var index=-1,collection=(iteratees=arrayMap(iteratees,baseUnary(baseIteratee)),baseMap(collection,function(value,key,collection){return{criteria:arrayMap(iteratees,function(iteratee){return iteratee(value)}),index:++index,value:value}}));return baseSortBy(collection,function(object,other){return compareMultiple(object,other,orders)})}},{"./_arrayMap":685,"./_baseGet":711,"./_baseIteratee":731,"./_baseMap":736,"./_baseSortBy":755,"./_baseUnary":760,"./_compareMultiple":777,"./identity":954,"./isArray":961}],742:[function(require,module,exports){var basePickBy=require("./_basePickBy"),hasIn=require("./hasIn");module.exports=function(object,paths){return basePickBy(object,paths,function(value,path){return hasIn(object,path)})}},{"./_basePickBy":743,"./hasIn":952}],743:[function(require,module,exports){var baseGet=require("./_baseGet"),baseSet=require("./_baseSet"),castPath=require("./_castPath");module.exports=function(object,paths,predicate){for(var index=-1,length=paths.length,result={};++index<length;){var path=paths[index],value=baseGet(object,path);predicate(value,path)&&baseSet(result,castPath(path,object),value)}return result}},{"./_baseGet":711,"./_baseSet":750,"./_castPath":766}],744:[function(require,module,exports){module.exports=function(key){return function(object){return null==object?void 0:object[key]}}},{}],745:[function(require,module,exports){var baseGet=require("./_baseGet");module.exports=function(path){return function(object){return baseGet(object,path)}}},{"./_baseGet":711}],746:[function(require,module,exports){module.exports=function(object){return function(key){return null==object?void 0:object[key]}}},{}],747:[function(require,module,exports){var nativeCeil=Math.ceil,nativeMax=Math.max;module.exports=function(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}},{}],748:[function(require,module,exports){module.exports=function(collection,iteratee,accumulator,initAccum,eachFunc){return eachFunc(collection,function(value,index,collection){accumulator=initAccum?(initAccum=!1,value):iteratee(accumulator,value,index,collection)}),accumulator}},{}],749:[function(require,module,exports){var identity=require("./identity"),overRest=require("./_overRest"),setToString=require("./_setToString");module.exports=function(func,start){return setToString(overRest(func,start,identity),func+"")}},{"./_overRest":870,"./_setToString":881,"./identity":954}],750:[function(require,module,exports){var assignValue=require("./_assignValue"),castPath=require("./_castPath"),isIndex=require("./_isIndex"),isObject=require("./isObject"),toKey=require("./_toKey");module.exports=function(object,path,value,customizer){if(isObject(object))for(var index=-1,length=(path=castPath(path,object)).length,lastIndex=length-1,nested=object;null!=nested&&++index<length;){var objValue,key=toKey(path[index]),newValue=value;if("__proto__"===key||"constructor"===key||"prototype"===key)return object;index!=lastIndex&&(objValue=nested[key],void 0===(newValue=customizer?customizer(objValue,key,nested):void 0))&&(newValue=isObject(objValue)?objValue:isIndex(path[index+1])?[]:{}),assignValue(nested,key,newValue),nested=nested[key]}return object}},{"./_assignValue":693,"./_castPath":766,"./_isIndex":840,"./_toKey":893,"./isObject":974}],751:[function(require,module,exports){var identity=require("./identity"),metaMap=require("./_metaMap");module.exports=metaMap?function(func,data){return metaMap.set(func,data),func}:identity},{"./_metaMap":863,"./identity":954}],752:[function(require,module,exports){var constant=require("./constant"),defineProperty=require("./_defineProperty"),require=require("./identity");module.exports=defineProperty?function(func,string){return defineProperty(func,"toString",{configurable:!0,enumerable:!1,value:constant(string),writable:!0})}:require},{"./_defineProperty":806,"./constant":905,"./identity":954}],753:[function(require,module,exports){module.exports=function(array,start,end){for(var index=-1,length=array.length,result=((end=length<end?length:end)<0&&(end+=length),length=end<(start=start<0?length<-start?0:length+start:start)?0:end-start>>>0,start>>>=0,Array(length));++index<length;)result[index]=array[index+start];return result}},{}],754:[function(require,module,exports){var baseEach=require("./_baseEach");module.exports=function(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return!(result=predicate(value,index,collection))}),!!result}},{"./_baseEach":703}],755:[function(require,module,exports){module.exports=function(array,comparer){var length=array.length;for(array.sort(comparer);length--;)array[length]=array[length].value;return array}},{}],756:[function(require,module,exports){module.exports=function(array,iteratee){for(var result,index=-1,length=array.length;++index<length;){var current=iteratee(array[index]);void 0!==current&&(result=void 0===result?current:result+current)}return result}},{}],757:[function(require,module,exports){module.exports=function(n,iteratee){for(var index=-1,result=Array(n);++index<n;)result[index]=iteratee(index);return result}},{}],758:[function(require,module,exports){var Symbol=require("./_Symbol"),arrayMap=require("./_arrayMap"),isArray=require("./isArray"),isSymbol=require("./isSymbol"),require=Symbol?Symbol.prototype:void 0,symbolToString=require?require.toString:void 0;module.exports=function baseToString(value){var result;return"string"==typeof value?value:isArray(value)?arrayMap(value,baseToString)+"":isSymbol(value)?symbolToString?symbolToString.call(value):"":"0"==(result=value+"")&&1/value==-1/0?"-0":result}},{"./_Symbol":674,"./_arrayMap":685,"./isArray":961,"./isSymbol":980}],759:[function(require,module,exports){var trimmedEndIndex=require("./_trimmedEndIndex"),reTrimStart=/^\s+/;module.exports=function(string){return string&&string.slice(0,trimmedEndIndex(string)+1).replace(reTrimStart,"")}},{"./_trimmedEndIndex":895}],760:[function(require,module,exports){module.exports=function(func){return function(value){return func(value)}}},{}],761:[function(require,module,exports){var SetCache=require("./_SetCache"),arrayIncludes=require("./_arrayIncludes"),arrayIncludesWith=require("./_arrayIncludesWith"),cacheHas=require("./_cacheHas"),createSet=require("./_createSet"),setToArray=require("./_setToArray");module.exports=function(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=!0,result=[],seen=result;if(comparator)isCommon=!1,includes=arrayIncludesWith;else if(200<=length){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index<length;){var value=array[index],computed=iteratee?iteratee(value):value,value=comparator||0!==value?value:0;if(isCommon&&computed==computed){for(var seenIndex=seen.length;seenIndex--;)if(seen[seenIndex]===computed)continue outer;iteratee&&seen.push(computed),result.push(value)}else includes(seen,computed,comparator)||(seen!==result&&seen.push(computed),result.push(value))}return result}},{"./_SetCache":672,"./_arrayIncludes":682,"./_arrayIncludesWith":683,"./_cacheHas":763,"./_createSet":803,"./_setToArray":880}],762:[function(require,module,exports){var arrayMap=require("./_arrayMap");module.exports=function(object,props){return arrayMap(props,function(key){return object[key]})}},{"./_arrayMap":685}],763:[function(require,module,exports){module.exports=function(cache,key){return cache.has(key)}},{}],764:[function(require,module,exports){var isArrayLikeObject=require("./isArrayLikeObject");module.exports=function(value){return isArrayLikeObject(value)?value:[]}},{"./isArrayLikeObject":963}],765:[function(require,module,exports){var identity=require("./identity");module.exports=function(value){return"function"==typeof value?value:identity}},{"./identity":954}],766:[function(require,module,exports){var isArray=require("./isArray"),isKey=require("./_isKey"),stringToPath=require("./_stringToPath"),toString=require("./toString");module.exports=function(value,object){return isArray(value)?value:isKey(value,object)?[value]:stringToPath(toString(value))}},{"./_isKey":842,"./_stringToPath":892,"./isArray":961,"./toString":1021}],767:[function(require,module,exports){var baseSlice=require("./_baseSlice");module.exports=function(array,start,end){var length=array.length;return end=void 0===end?length:end,!start&&length<=end?array:baseSlice(array,start,end)}},{"./_baseSlice":753}],768:[function(require,module,exports){var baseIndexOf=require("./_baseIndexOf");module.exports=function(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&-1<baseIndexOf(chrSymbols,strSymbols[index],0););return index}},{"./_baseIndexOf":717}],769:[function(require,module,exports){var baseIndexOf=require("./_baseIndexOf");module.exports=function(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index<length&&-1<baseIndexOf(chrSymbols,strSymbols[index],0););return index}},{"./_baseIndexOf":717}],770:[function(require,module,exports){var Uint8Array=require("./_Uint8Array");module.exports=function(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}},{"./_Uint8Array":675}],771:[function(require,module,exports){var require=require("./_root"),exports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=exports&&"object"==typeof module&&module&&!module.nodeType&&module,freeModule=freeModule&&freeModule.exports===exports?require.Buffer:void 0,allocUnsafe=freeModule?freeModule.allocUnsafe:void 0;module.exports=function(buffer,isDeep){return isDeep?buffer.slice():(isDeep=buffer.length,isDeep=allocUnsafe?allocUnsafe(isDeep):new buffer.constructor(isDeep),buffer.copy(isDeep),isDeep)}},{"./_root":875}],772:[function(require,module,exports){var cloneArrayBuffer=require("./_cloneArrayBuffer");module.exports=function(dataView,isDeep){return isDeep=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer,new dataView.constructor(isDeep,dataView.byteOffset,dataView.byteLength)}},{"./_cloneArrayBuffer":770}],773:[function(require,module,exports){var reFlags=/\w*$/;module.exports=function(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}},{}],774:[function(require,module,exports){var require=require("./_Symbol"),require=require?require.prototype:void 0,symbolValueOf=require?require.valueOf:void 0;module.exports=function(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}},{"./_Symbol":674}],775:[function(require,module,exports){var cloneArrayBuffer=require("./_cloneArrayBuffer");module.exports=function(typedArray,isDeep){return isDeep=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer,new typedArray.constructor(isDeep,typedArray.byteOffset,typedArray.length)}},{"./_cloneArrayBuffer":770}],776:[function(require,module,exports){var isSymbol=require("./isSymbol");module.exports=function(value,other){if(value!==other){var valIsDefined=void 0!==value,valIsNull=null===value,valIsReflexive=value==value,valIsSymbol=isSymbol(value),othIsDefined=void 0!==other,othIsNull=null===other,othIsReflexive=other==other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&other<value||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&value<other||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}},{"./isSymbol":980}],777:[function(require,module,exports){var compareAscending=require("./_compareAscending");module.exports=function(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index<length;){var result=compareAscending(objCriteria[index],othCriteria[index]);if(result)return ordersLength<=index?result:result*("desc"==orders[index]?-1:1)}return object.index-other.index}},{"./_compareAscending":776}],778:[function(require,module,exports){var nativeMax=Math.max;module.exports=function(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndex<leftLength;)result[leftIndex]=partials[leftIndex];for(;++argsIndex<holdersLength;)(isUncurried||argsIndex<argsLength)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}},{}],779:[function(require,module,exports){var nativeMax=Math.max;module.exports=function(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndex<rangeLength;)result[argsIndex]=args[argsIndex];for(var offset=argsIndex;++rightIndex<rightLength;)result[offset+rightIndex]=partials[rightIndex];for(;++holdersIndex<holdersLength;)(isUncurried||argsIndex<argsLength)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}},{}],780:[function(require,module,exports){module.exports=function(source,array){var index=-1,length=source.length;for(array=array||Array(length);++index<length;)array[index]=source[index];return array}},{}],781:[function(require,module,exports){var assignValue=require("./_assignValue"),baseAssignValue=require("./_baseAssignValue");module.exports=function(source,props,object,customizer){for(var isNew=!object,index=(object=object||{},-1),length=props.length;++index<length;){var key=props[index],newValue=customizer?customizer(object[key],source[key],key,object,source):void 0;void 0===newValue&&(newValue=source[key]),(isNew?baseAssignValue:assignValue)(object,key,newValue)}return object}},{"./_assignValue":693,"./_baseAssignValue":698}],782:[function(require,module,exports){var copyObject=require("./_copyObject"),getSymbols=require("./_getSymbols");module.exports=function(source,object){return copyObject(source,getSymbols(source),object)}},{"./_copyObject":781,"./_getSymbols":822}],783:[function(require,module,exports){var copyObject=require("./_copyObject"),getSymbolsIn=require("./_getSymbolsIn");module.exports=function(source,object){return copyObject(source,getSymbolsIn(source),object)}},{"./_copyObject":781,"./_getSymbolsIn":823}],784:[function(require,module,exports){require=require("./_root")["__core-js_shared__"];module.exports=require},{"./_root":875}],785:[function(require,module,exports){module.exports=function(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}},{}],786:[function(require,module,exports){var arrayAggregator=require("./_arrayAggregator"),baseAggregator=require("./_baseAggregator"),baseIteratee=require("./_baseIteratee"),isArray=require("./isArray");module.exports=function(setter,initializer){return function(collection,iteratee){var func=isArray(collection)?arrayAggregator:baseAggregator,accumulator=initializer?initializer():{};return func(collection,setter,baseIteratee(iteratee,2),accumulator)}}},{"./_arrayAggregator":678,"./_baseAggregator":695,"./_baseIteratee":731,"./isArray":961}],787:[function(require,module,exports){var baseRest=require("./_baseRest"),isIterateeCall=require("./_isIterateeCall");module.exports=function(assigner){return baseRest(function(object,sources){var index=-1,length=sources.length,customizer=1<length?sources[length-1]:void 0,guard=2<length?sources[2]:void 0,customizer=3<assigner.length&&"function"==typeof customizer?(length--,customizer):void 0;for(guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=length<3?void 0:customizer,length=1),object=Object(object);++index<length;){var source=sources[index];source&&assigner(object,source,index,customizer)}return object})}},{"./_baseRest":749,"./_isIterateeCall":841}],788:[function(require,module,exports){var isArrayLike=require("./isArrayLike");module.exports=function(eachFunc,fromRight){return function(collection,iteratee){if(null!=collection){if(!isArrayLike(collection))return eachFunc(collection,iteratee);for(var length=collection.length,index=fromRight?length:-1,iterable=Object(collection);(fromRight?index--:++index<length)&&!1!==iteratee(iterable[index],index,iterable););}return collection}}},{"./isArrayLike":962}],789:[function(require,module,exports){module.exports=function(fromRight){return function(object,iteratee,keysFunc){for(var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;length--;){var key=props[fromRight?length:++index];if(!1===iteratee(iterable[key],key,iterable))break}return object}}},{}],790:[function(require,module,exports){var createCtor=require("./_createCtor"),root=require("./_root");module.exports=function(func,bitmask,thisArg){var isBind=1&bitmask,Ctor=createCtor(func);return function wrapper(){return(this&&this!==root&&this instanceof wrapper?Ctor:func).apply(isBind?thisArg:this,arguments)}}},{"./_createCtor":793,"./_root":875}],791:[function(require,module,exports){var castSlice=require("./_castSlice"),hasUnicode=require("./_hasUnicode"),stringToArray=require("./_stringToArray"),toString=require("./toString");module.exports=function(methodName){return function(string){string=toString(string);var strSymbols=hasUnicode(string)?stringToArray(string):void 0,chr=strSymbols?strSymbols[0]:string.charAt(0),strSymbols=strSymbols?castSlice(strSymbols,1).join(""):string.slice(1);return chr[methodName]()+strSymbols}}},{"./_castSlice":767,"./_hasUnicode":828,"./_stringToArray":891,"./toString":1021}],792:[function(require,module,exports){var arrayReduce=require("./_arrayReduce"),deburr=require("./deburr"),words=require("./words"),reApos=RegExp("['’]","g");module.exports=function(callback){return function(string){return arrayReduce(words(deburr(string).replace(reApos,"")),callback,"")}}},{"./_arrayReduce":687,"./deburr":907,"./words":1029}],793:[function(require,module,exports){var baseCreate=require("./_baseCreate"),isObject=require("./isObject");module.exports=function(Ctor){return function(){var args=arguments;switch(args.length){case 0:return new Ctor;case 1:return new Ctor(args[0]);case 2:return new Ctor(args[0],args[1]);case 3:return new Ctor(args[0],args[1],args[2]);case 4:return new Ctor(args[0],args[1],args[2],args[3]);case 5:return new Ctor(args[0],args[1],args[2],args[3],args[4]);case 6:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5]);case 7:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5],args[6])}var thisBinding=baseCreate(Ctor.prototype),result=Ctor.apply(thisBinding,args);return isObject(result)?result:thisBinding}}},{"./_baseCreate":701,"./isObject":974}],794:[function(require,module,exports){var apply=require("./_apply"),createCtor=require("./_createCtor"),createHybrid=require("./_createHybrid"),createRecurry=require("./_createRecurry"),getHolder=require("./_getHolder"),replaceHolders=require("./_replaceHolders"),root=require("./_root");module.exports=function(func,bitmask,arity){var Ctor=createCtor(func);return function wrapper(){for(var length=arguments.length,args=Array(length),index=length,placeholder=getHolder(wrapper);index--;)args[index]=arguments[index];placeholder=length<3&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);return(length-=placeholder.length)<arity?createRecurry(func,bitmask,createHybrid,wrapper.placeholder,void 0,args,placeholder,void 0,void 0,arity-length):apply(this&&this!==root&&this instanceof wrapper?Ctor:func,this,args)}}},{"./_apply":677,"./_createCtor":793,"./_createHybrid":797,"./_createRecurry":801,"./_getHolder":816,"./_replaceHolders":874,"./_root":875}],795:[function(require,module,exports){var baseIteratee=require("./_baseIteratee"),isArrayLike=require("./isArrayLike"),keys=require("./keys");module.exports=function(findIndexFunc){return function(collection,predicate,fromIndex){var iteratee,iterable=Object(collection),predicate=(isArrayLike(collection)||(iteratee=baseIteratee(predicate,3),collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}),findIndexFunc(collection,predicate,fromIndex));return-1<predicate?iterable[iteratee?collection[predicate]:predicate]:void 0}}},{"./_baseIteratee":731,"./isArrayLike":962,"./keys":986}],796:[function(require,module,exports){var LodashWrapper=require("./_LodashWrapper"),flatRest=require("./_flatRest"),getData=require("./_getData"),getFuncName=require("./_getFuncName"),isArray=require("./isArray"),isLaziable=require("./_isLaziable");module.exports=function(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError("Expected a function");prereq&&!wrapper&&"wrapper"==getFuncName(func)&&(wrapper=new LodashWrapper([],!0))}for(index=wrapper?index:length;++index<length;)var func=funcs[index],funcName=getFuncName(func),data="wrapper"==funcName?getData(func):void 0,wrapper=data&&isLaziable(data[0])&&424==data[1]&&!data[4].length&&1==data[9]?wrapper[getFuncName(data[0])].apply(wrapper,data[3]):1==func.length&&isLaziable(func)?wrapper[funcName]():wrapper.thru(func);return function(){var args=arguments,value=args[0];if(wrapper&&1==args.length&&isArray(value))return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++index<length;)result=funcs[index].call(this,result);return result}})}},{"./_LodashWrapper":667,"./_flatRest":810,"./_getData":814,"./_getFuncName":815,"./_isLaziable":844,"./isArray":961}],797:[function(require,module,exports){var composeArgs=require("./_composeArgs"),composeArgsRight=require("./_composeArgsRight"),countHolders=require("./_countHolders"),createCtor=require("./_createCtor"),createRecurry=require("./_createRecurry"),getHolder=require("./_getHolder"),reorder=require("./_reorder"),replaceHolders=require("./_replaceHolders"),root=require("./_root");function createHybrid(func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity){var isAry=128&bitmask,isBind=1&bitmask,isBindKey=2&bitmask,isCurried=24&bitmask,isFlip=512&bitmask,Ctor=isBindKey?void 0:createCtor(func);return function wrapper(){for(var placeholder,holdersCount,length=arguments.length,args=Array(length),index=length;index--;)args[index]=arguments[index];return isCurried&&(placeholder=getHolder(wrapper),holdersCount=countHolders(args,placeholder)),partials&&(args=composeArgs(args,partials,holders,isCurried)),partialsRight&&(args=composeArgsRight(args,partialsRight,holdersRight,isCurried)),length-=holdersCount,isCurried&&length<arity?(holdersCount=replaceHolders(args,placeholder),createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,holdersCount,argPos,ary,arity-length)):(placeholder=isBind?thisArg:this,holdersCount=isBindKey?placeholder[func]:func,length=args.length,argPos?args=reorder(args,argPos):isFlip&&1<length&&args.reverse(),isAry&&ary<length&&(args.length=ary),(holdersCount=this&&this!==root&&this instanceof wrapper?Ctor||createCtor(holdersCount):holdersCount).apply(placeholder,args))}}module.exports=createHybrid},{"./_composeArgs":778,"./_composeArgsRight":779,"./_countHolders":785,"./_createCtor":793,"./_createRecurry":801,"./_getHolder":816,"./_reorder":873,"./_replaceHolders":874,"./_root":875}],798:[function(require,module,exports){var baseInverter=require("./_baseInverter");module.exports=function(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}},{"./_baseInverter":719}],799:[function(require,module,exports){var apply=require("./_apply"),createCtor=require("./_createCtor"),root=require("./_root");module.exports=function(func,bitmask,thisArg,partials){var isBind=1&bitmask,Ctor=createCtor(func);return function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndex<leftLength;)args[leftIndex]=partials[leftIndex];for(;argsLength--;)args[leftIndex++]=arguments[++argsIndex];return apply(fn,isBind?thisArg:this,args)}}},{"./_apply":677,"./_createCtor":793,"./_root":875}],800:[function(require,module,exports){var baseRange=require("./_baseRange"),isIterateeCall=require("./_isIterateeCall"),toFinite=require("./toFinite");module.exports=function(fromRight){return function(start,end,step){return step&&"number"!=typeof step&&isIterateeCall(start,end,step)&&(end=step=void 0),start=toFinite(start),void 0===end?(end=start,start=0):end=toFinite(end),step=void 0===step?start<end?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}},{"./_baseRange":747,"./_isIterateeCall":841,"./toFinite":1016}],801:[function(require,module,exports){var isLaziable=require("./_isLaziable"),setData=require("./_setData"),setWrapToString=require("./_setWrapToString");module.exports=function(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=8&bitmask,thisArg=(4&(bitmask=(bitmask|(isCurry?32:64))&~(isCurry?64:32))||(bitmask&=-4),[func,bitmask,thisArg,isCurry?partials:void 0,isCurry?holders:void 0,isCurry?void 0:partials,isCurry?void 0:holders,argPos,ary,arity]),partials=wrapFunc.apply(void 0,thisArg);return isLaziable(func)&&setData(partials,thisArg),partials.placeholder=placeholder,setWrapToString(partials,func,bitmask)}},{"./_isLaziable":844,"./_setData":879,"./_setWrapToString":882}],802:[function(require,module,exports){var root=require("./_root"),toInteger=require("./toInteger"),toNumber=require("./toNumber"),toString=require("./toString"),nativeIsFinite=root.isFinite,nativeMin=Math.min;module.exports=function(methodName){var func=Math[methodName];return function(number,precision){var value,pair;return number=toNumber(number),(precision=null==precision?0:nativeMin(toInteger(precision),292))&&nativeIsFinite(number)?(pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision)),+((pair=(toString(value)+"e").split("e"))[0]+"e"+(+pair[1]-precision))):func(number)}}},{"./_root":875,"./toInteger":1017,"./toNumber":1018,"./toString":1021}],803:[function(require,module,exports){var Set=require("./_Set"),noop=require("./noop"),require=require("./_setToArray"),require=Set&&1/require(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:noop;module.exports=require},{"./_Set":671,"./_setToArray":880,"./noop":994}],804:[function(require,module,exports){var baseSetData=require("./_baseSetData"),createBind=require("./_createBind"),createCurry=require("./_createCurry"),createHybrid=require("./_createHybrid"),createPartial=require("./_createPartial"),getData=require("./_getData"),mergeData=require("./_mergeData"),setData=require("./_setData"),setWrapToString=require("./_setWrapToString"),toInteger=require("./toInteger"),nativeMax=Math.max;module.exports=function(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var length,holdersRight,partialsRight,isBindKey=2&bitmask;if(isBindKey||"function"==typeof func)return(length=partials?partials.length:0)||(bitmask&=-97,partials=holders=void 0),ary=void 0===ary?ary:nativeMax(toInteger(ary),0),arity=void 0===arity?arity:toInteger(arity),length-=holders?holders.length:0,64&bitmask&&(partialsRight=partials,holdersRight=holders,partials=holders=void 0),partialsRight=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity],(holdersRight=isBindKey?void 0:getData(func))&&mergeData(partialsRight,holdersRight),func=partialsRight[0],bitmask=partialsRight[1],thisArg=partialsRight[2],partials=partialsRight[3],holders=partialsRight[4],!(arity=partialsRight[9]=void 0===partialsRight[9]?isBindKey?0:func.length:nativeMax(partialsRight[9]-length,0))&&24&bitmask&&(bitmask&=-25),argPos=bitmask&&1!=bitmask?8==bitmask||16==bitmask?createCurry(func,bitmask,arity):32!=bitmask&&33!=bitmask||holders.length?createHybrid.apply(void 0,partialsRight):createPartial(func,bitmask,thisArg,partials):createBind(func,bitmask,thisArg),setWrapToString((holdersRight?baseSetData:setData)(argPos,partialsRight),func,bitmask);throw new TypeError("Expected a function")}},{"./_baseSetData":751,"./_createBind":790,"./_createCurry":794,"./_createHybrid":797,"./_createPartial":799,"./_getData":814,"./_mergeData":862,"./_setData":879,"./_setWrapToString":882,"./toInteger":1017}],805:[function(require,module,exports){require=require("./_basePropertyOf")({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","Ĳ":"IJ","ĳ":"ij","Œ":"Oe","œ":"oe","ŉ":"'n","ſ":"s"});module.exports=require},{"./_basePropertyOf":746}],806:[function(require,module,exports){var getNative=require("./_getNative"),require=function(){try{var func=getNative(Object,"defineProperty");return func({},"",{}),func}catch(e){}}();module.exports=require},{"./_getNative":819}],807:[function(require,module,exports){var SetCache=require("./_SetCache"),arraySome=require("./_arraySome"),cacheHas=require("./_cacheHas");module.exports=function(array,other,bitmask,customizer,equalFunc,stack){var isPartial=1&bitmask,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&arrLength<othLength))return!1;var othLength=stack.get(array),othStacked=stack.get(other);if(othLength&&othStacked)return othLength==other&&othStacked==array;var index=-1,result=!0,seen=2&bitmask?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index<arrLength;){var compared,arrValue=array[index],othValue=other[index];if(void 0!==(compared=customizer?isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack):compared)){if(compared)continue;result=!1;break}if(seen){if(!arraySome(other,function(othValue,othIndex){if(!cacheHas(seen,othIndex)&&(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack)))return seen.push(othIndex)})){result=!1;break}}else if(arrValue!==othValue&&!equalFunc(arrValue,othValue,bitmask,customizer,stack)){result=!1;break}}return stack.delete(array),stack.delete(other),result}},{"./_SetCache":672,"./_arraySome":688,"./_cacheHas":763}],808:[function(require,module,exports){var Symbol=require("./_Symbol"),Uint8Array=require("./_Uint8Array"),eq=require("./eq"),equalArrays=require("./_equalArrays"),mapToArray=require("./_mapToArray"),setToArray=require("./_setToArray"),require=Symbol?Symbol.prototype:void 0,symbolValueOf=require?require.valueOf:void 0;module.exports=function(object,other,tag,bitmask,customizer,equalFunc,stack){switch(tag){case"[object DataView]":if(object.byteLength!=other.byteLength||object.byteOffset!=other.byteOffset)return!1;object=object.buffer,other=other.buffer;case"[object ArrayBuffer]":return object.byteLength==other.byteLength&&equalFunc(new Uint8Array(object),new Uint8Array(other))?!0:!1;case"[object Boolean]":case"[object Date]":case"[object Number]":return eq(+object,+other);case"[object Error]":return object.name==other.name&&object.message==other.message;case"[object RegExp]":case"[object String]":return object==other+"";case"[object Map]":var convert=mapToArray;case"[object Set]":convert=convert||setToArray;if(object.size!=other.size&&!(1&bitmask))return!1;var stacked=stack.get(object);if(stacked)return stacked==other;bitmask|=2,stack.set(object,other);stacked=equalArrays(convert(object),convert(other),bitmask,customizer,equalFunc,stack);return stack.delete(object),stacked;case"[object Symbol]":if(symbolValueOf)return symbolValueOf.call(object)==symbolValueOf.call(other)}return!1}},{"./_Symbol":674,"./_Uint8Array":675,"./_equalArrays":807,"./_mapToArray":859,"./_setToArray":880,"./eq":911}],809:[function(require,module,exports){var getAllKeys=require("./_getAllKeys"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(object,other,bitmask,customizer,equalFunc,stack){var isPartial=1&bitmask,objProps=getAllKeys(object),objLength=objProps.length;if(objLength!=getAllKeys(other).length&&!isPartial)return!1;for(var index=objLength;index--;){var key=objProps[index];if(!(isPartial?key in other:hasOwnProperty.call(other,key)))return!1}var objStacked=stack.get(object),othStacked=stack.get(other);if(objStacked&&othStacked)return objStacked==other&&othStacked==object;for(var result=!0,skipCtor=(stack.set(object,other),stack.set(other,object),isPartial);++index<objLength;){var compared,objValue=object[key=objProps[index]],othValue=other[key];if(!(void 0===(compared=customizer?isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack):compared)?objValue===othValue||equalFunc(objValue,othValue,bitmask,customizer,stack):compared)){result=!1;break}skipCtor=skipCtor||"constructor"==key}return result&&!skipCtor&&(objStacked=object.constructor)!=(othStacked=other.constructor)&&"constructor"in object&&"constructor"in other&&!("function"==typeof objStacked&&objStacked instanceof objStacked&&"function"==typeof othStacked&&othStacked instanceof othStacked)&&(result=!1),stack.delete(object),stack.delete(other),result}},{"./_getAllKeys":812}],810:[function(require,module,exports){var flatten=require("./flatten"),overRest=require("./_overRest"),setToString=require("./_setToString");module.exports=function(func){return setToString(overRest(func,void 0,flatten),func+"")}},{"./_overRest":870,"./_setToString":881,"./flatten":919}],811:[function(require,module,exports){!function(global){!function(){var freeGlobal="object"==typeof global&&global&&global.Object===Object&&global;module.exports=freeGlobal}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],812:[function(require,module,exports){var baseGetAllKeys=require("./_baseGetAllKeys"),getSymbols=require("./_getSymbols"),keys=require("./keys");module.exports=function(object){return baseGetAllKeys(object,keys,getSymbols)}},{"./_baseGetAllKeys":712,"./_getSymbols":822,"./keys":986}],813:[function(require,module,exports){var baseGetAllKeys=require("./_baseGetAllKeys"),getSymbolsIn=require("./_getSymbolsIn"),keysIn=require("./keysIn");module.exports=function(object){return baseGetAllKeys(object,keysIn,getSymbolsIn)}},{"./_baseGetAllKeys":712,"./_getSymbolsIn":823,"./keysIn":987}],814:[function(require,module,exports){var metaMap=require("./_metaMap"),require=require("./noop");module.exports=metaMap?function(func){return metaMap.get(func)}:require},{"./_metaMap":863,"./noop":994}],815:[function(require,module,exports){var realNames=require("./_realNames"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(func){for(var result=func.name+"",array=realNames[result],length=hasOwnProperty.call(realNames,result)?array.length:0;length--;){var data=array[length],otherFunc=data.func;if(null==otherFunc||otherFunc==func)return data.name}return result}},{"./_realNames":872}],816:[function(require,module,exports){module.exports=function(func){return func.placeholder}},{}],817:[function(require,module,exports){var isKeyable=require("./_isKeyable");module.exports=function(map,key){return map=map.__data__,isKeyable(key)?map["string"==typeof key?"string":"hash"]:map.map}},{"./_isKeyable":843}],818:[function(require,module,exports){var isStrictComparable=require("./_isStrictComparable"),keys=require("./keys");module.exports=function(object){for(var result=keys(object),length=result.length;length--;){var key=result[length],value=object[key];result[length]=[key,value,isStrictComparable(value)]}return result}},{"./_isStrictComparable":847,"./keys":986}],819:[function(require,module,exports){var baseIsNative=require("./_baseIsNative"),getValue=require("./_getValue");module.exports=function(object,key){return object=getValue(object,key),baseIsNative(object)?object:void 0}},{"./_baseIsNative":727,"./_getValue":825}],820:[function(require,module,exports){require=require("./_overArg")(Object.getPrototypeOf,Object);module.exports=require},{"./_overArg":869}],821:[function(require,module,exports){var require=require("./_Symbol"),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=require?require.toStringTag:void 0;module.exports=function(value){var isOwn=hasOwnProperty.call(value,symToStringTag),tag=value[symToStringTag];try{var unmasked=!(value[symToStringTag]=void 0)}catch(e){}var result=nativeObjectToString.call(value);return unmasked&&(isOwn?value[symToStringTag]=tag:delete value[symToStringTag]),result}},{"./_Symbol":674}],822:[function(require,module,exports){var arrayFilter=require("./_arrayFilter"),require=require("./stubArray"),propertyIsEnumerable=Object.prototype.propertyIsEnumerable,nativeGetSymbols=Object.getOwnPropertySymbols;module.exports=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:require},{"./_arrayFilter":681,"./stubArray":1010}],823:[function(require,module,exports){var arrayPush=require("./_arrayPush"),getPrototype=require("./_getPrototype"),getSymbols=require("./_getSymbols"),require=require("./stubArray"),nativeGetSymbols=Object.getOwnPropertySymbols;module.exports=nativeGetSymbols?function(object){for(var result=[];object;)arrayPush(result,getSymbols(object)),object=getPrototype(object);return result}:require},{"./_arrayPush":686,"./_getPrototype":820,"./_getSymbols":822,"./stubArray":1010}],824:[function(require,module,exports){var DataView=require("./_DataView"),Map=require("./_Map"),Promise=require("./_Promise"),Set=require("./_Set"),WeakMap=require("./_WeakMap"),baseGetTag=require("./_baseGetTag"),toSource=require("./_toSource"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),require=baseGetTag;(DataView&&"[object DataView]"!=require(new DataView(new ArrayBuffer(1)))||Map&&"[object Map]"!=require(new Map)||Promise&&"[object Promise]"!=require(Promise.resolve())||Set&&"[object Set]"!=require(new Set)||WeakMap&&"[object WeakMap]"!=require(new WeakMap))&&(require=function(value){var result=baseGetTag(value),value="[object Object]"==result?value.constructor:void 0,value=value?toSource(value):"";if(value)switch(value){case dataViewCtorString:return"[object DataView]";case mapCtorString:return"[object Map]";case promiseCtorString:return"[object Promise]";case setCtorString:return"[object Set]";case weakMapCtorString:return"[object WeakMap]"}return result}),module.exports=require},{"./_DataView":663,"./_Map":668,"./_Promise":670,"./_Set":671,"./_WeakMap":676,"./_baseGetTag":713,"./_toSource":894}],825:[function(require,module,exports){module.exports=function(object,key){return null==object?void 0:object[key]}},{}],826:[function(require,module,exports){var reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /;module.exports=function(source){return(source=source.match(reWrapDetails))?source[1].split(reSplitDetails):[]}},{}],827:[function(require,module,exports){var castPath=require("./_castPath"),isArguments=require("./isArguments"),isArray=require("./isArray"),isIndex=require("./_isIndex"),isLength=require("./isLength"),toKey=require("./_toKey");module.exports=function(object,path,hasFunc){for(var index=-1,length=(path=castPath(path,object)).length,result=!1;++index<length;){var key=toKey(path[index]);if(!(result=null!=object&&hasFunc(object,key)))break;object=object[key]}return result||++index!=length?result:!!(length=null==object?0:object.length)&&isLength(length)&&isIndex(key,length)&&(isArray(object)||isArguments(object))}},{"./_castPath":766,"./_isIndex":840,"./_toKey":893,"./isArguments":960,"./isArray":961,"./isLength":970}],828:[function(require,module,exports){var reHasUnicode=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");module.exports=function(string){return reHasUnicode.test(string)}},{}],829:[function(require,module,exports){var reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;module.exports=function(string){return reHasUnicodeWord.test(string)}},{}],830:[function(require,module,exports){var nativeCreate=require("./_nativeCreate");module.exports=function(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0}},{"./_nativeCreate":864}],831:[function(require,module,exports){module.exports=function(key){return key=this.has(key)&&delete this.__data__[key],this.size-=key?1:0,key}},{}],832:[function(require,module,exports){var nativeCreate=require("./_nativeCreate"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(key){var result,data=this.__data__;return nativeCreate?"__lodash_hash_undefined__"===(result=data[key])?void 0:result:hasOwnProperty.call(data,key)?data[key]:void 0}},{"./_nativeCreate":864}],833:[function(require,module,exports){var nativeCreate=require("./_nativeCreate"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)}},{"./_nativeCreate":864}],834:[function(require,module,exports){var nativeCreate=require("./_nativeCreate");module.exports=function(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&void 0===value?"__lodash_hash_undefined__":value,this}},{"./_nativeCreate":864}],835:[function(require,module,exports){var hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(array){var length=array.length,result=new array.constructor(length);return length&&"string"==typeof array[0]&&hasOwnProperty.call(array,"index")&&(result.index=array.index,result.input=array.input),result}},{}],836:[function(require,module,exports){var cloneArrayBuffer=require("./_cloneArrayBuffer"),cloneDataView=require("./_cloneDataView"),cloneRegExp=require("./_cloneRegExp"),cloneSymbol=require("./_cloneSymbol"),cloneTypedArray=require("./_cloneTypedArray");module.exports=function(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case"[object ArrayBuffer]":return cloneArrayBuffer(object);case"[object Boolean]":case"[object Date]":return new Ctor(+object);case"[object DataView]":return cloneDataView(object,isDeep);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return cloneTypedArray(object,isDeep);case"[object Map]":return new Ctor;case"[object Number]":case"[object String]":return new Ctor(object);case"[object RegExp]":return cloneRegExp(object);case"[object Set]":return new Ctor;case"[object Symbol]":return cloneSymbol(object)}}},{"./_cloneArrayBuffer":770,"./_cloneDataView":772,"./_cloneRegExp":773,"./_cloneSymbol":774,"./_cloneTypedArray":775}],837:[function(require,module,exports){var baseCreate=require("./_baseCreate"),getPrototype=require("./_getPrototype"),isPrototype=require("./_isPrototype");module.exports=function(object){return"function"!=typeof object.constructor||isPrototype(object)?{}:baseCreate(getPrototype(object))}},{"./_baseCreate":701,"./_getPrototype":820,"./_isPrototype":846}],838:[function(require,module,exports){var reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;module.exports=function(source,details){var lastIndex,length=details.length;return length?(details[lastIndex=length-1]=(1<length?"& ":"")+details[lastIndex],details=details.join(2<length?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")):source}},{}],839:[function(require,module,exports){var Symbol=require("./_Symbol"),isArguments=require("./isArguments"),isArray=require("./isArray"),spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0;module.exports=function(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}},{"./_Symbol":674,"./isArguments":960,"./isArray":961}],840:[function(require,module,exports){var reIsUint=/^(?:0|[1-9]\d*)$/;module.exports=function(value,length){var type=typeof value;return!!(length=null==length?9007199254740991:length)&&("number"==type||"symbol"!=type&&reIsUint.test(value))&&-1<value&&value%1==0&&value<length}},{}],841:[function(require,module,exports){var eq=require("./eq"),isArrayLike=require("./isArrayLike"),isIndex=require("./_isIndex"),isObject=require("./isObject");module.exports=function(value,index,object){var type;return!!isObject(object)&&!!("number"==(type=typeof index)?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)&&eq(object[index],value)}},{"./_isIndex":840,"./eq":911,"./isArrayLike":962,"./isObject":974}],842:[function(require,module,exports){var isArray=require("./isArray"),isSymbol=require("./isSymbol"),reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/;module.exports=function(value,object){var type;return!isArray(value)&&(!("number"!=(type=typeof value)&&"symbol"!=type&&"boolean"!=type&&null!=value&&!isSymbol(value))||reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object))}},{"./isArray":961,"./isSymbol":980}],843:[function(require,module,exports){module.exports=function(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}},{}],844:[function(require,module,exports){var LazyWrapper=require("./_LazyWrapper"),getData=require("./_getData"),getFuncName=require("./_getFuncName"),lodash=require("./wrapperLodash");module.exports=function(func){var funcName=getFuncName(func),other=lodash[funcName];return"function"==typeof other&&funcName in LazyWrapper.prototype&&(func===other||!!(funcName=getData(other))&&func===funcName[0])}},{"./_LazyWrapper":665,"./_getData":814,"./_getFuncName":815,"./wrapperLodash":1030}],845:[function(require,module,exports){var require=require("./_coreJsData"),maskSrcKey=(require=/[^.]+$/.exec(require&&require.keys&&require.keys.IE_PROTO||""))?"Symbol(src)_1."+require:"";module.exports=function(func){return!!maskSrcKey&&maskSrcKey in func}},{"./_coreJsData":784}],846:[function(require,module,exports){var objectProto=Object.prototype;module.exports=function(value){var Ctor=value&&value.constructor;return value===("function"==typeof Ctor&&Ctor.prototype||objectProto)}},{}],847:[function(require,module,exports){var isObject=require("./isObject");module.exports=function(value){return value==value&&!isObject(value)}},{"./isObject":974}],848:[function(require,module,exports){module.exports=function(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}},{}],849:[function(require,module,exports){module.exports=function(){this.__data__=[],this.size=0}},{}],850:[function(require,module,exports){var assocIndexOf=require("./_assocIndexOf"),splice=Array.prototype.splice;module.exports=function(key){var data=this.__data__;return!((key=assocIndexOf(data,key))<0||(key==data.length-1?data.pop():splice.call(data,key,1),--this.size,0))}},{"./_assocIndexOf":694}],851:[function(require,module,exports){var assocIndexOf=require("./_assocIndexOf");module.exports=function(key){var data=this.__data__;return(key=assocIndexOf(data,key))<0?void 0:data[key][1]}},{"./_assocIndexOf":694}],852:[function(require,module,exports){var assocIndexOf=require("./_assocIndexOf");module.exports=function(key){return-1<assocIndexOf(this.__data__,key)}},{"./_assocIndexOf":694}],853:[function(require,module,exports){var assocIndexOf=require("./_assocIndexOf");module.exports=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}},{"./_assocIndexOf":694}],854:[function(require,module,exports){var Hash=require("./_Hash"),ListCache=require("./_ListCache"),Map=require("./_Map");module.exports=function(){this.size=0,this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}}},{"./_Hash":664,"./_ListCache":666,"./_Map":668}],855:[function(require,module,exports){var getMapData=require("./_getMapData");module.exports=function(key){return key=getMapData(this,key).delete(key),this.size-=key?1:0,key}},{"./_getMapData":817}],856:[function(require,module,exports){var getMapData=require("./_getMapData");module.exports=function(key){return getMapData(this,key).get(key)}},{"./_getMapData":817}],857:[function(require,module,exports){var getMapData=require("./_getMapData");module.exports=function(key){return getMapData(this,key).has(key)}},{"./_getMapData":817}],858:[function(require,module,exports){var getMapData=require("./_getMapData");module.exports=function(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this}},{"./_getMapData":817}],859:[function(require,module,exports){module.exports=function(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}},{}],860:[function(require,module,exports){module.exports=function(key,srcValue){return function(object){return null!=object&&object[key]===srcValue&&(void 0!==srcValue||key in Object(object))}}},{}],861:[function(require,module,exports){var memoize=require("./memoize");module.exports=function(func){var cache=(func=memoize(func,function(key){return 500===cache.size&&cache.clear(),key})).cache;return func}},{"./memoize":991}],862:[function(require,module,exports){var composeArgs=require("./_composeArgs"),composeArgsRight=require("./_composeArgsRight"),replaceHolders=require("./_replaceHolders"),nativeMin=Math.min;module.exports=function(data,source){var partials,bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCombo=128==srcBitmask&&8==bitmask||128==srcBitmask&&256==bitmask&&data[7].length<=source[8]||384==srcBitmask&&source[7].length<=source[8]&&8==bitmask;return(newBitmask<131||isCombo)&&(1&srcBitmask&&(data[2]=source[2],newBitmask|=1&bitmask?0:4),(isCombo=source[3])&&(partials=data[3],data[3]=partials?composeArgs(partials,isCombo,source[4]):isCombo,data[4]=partials?replaceHolders(data[3],"__lodash_placeholder__"):source[4]),(isCombo=source[5])&&(partials=data[5],data[5]=partials?composeArgsRight(partials,isCombo,source[6]):isCombo,data[6]=partials?replaceHolders(data[5],"__lodash_placeholder__"):source[6]),(isCombo=source[7])&&(data[7]=isCombo),128&srcBitmask&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask),data}},{"./_composeArgs":778,"./_composeArgsRight":779,"./_replaceHolders":874}],863:[function(require,module,exports){require=require("./_WeakMap"),require=require&&new require;module.exports=require},{"./_WeakMap":676}],864:[function(require,module,exports){require=require("./_getNative")(Object,"create");module.exports=require},{"./_getNative":819}],865:[function(require,module,exports){require=require("./_overArg")(Object.keys,Object);module.exports=require},{"./_overArg":869}],866:[function(require,module,exports){module.exports=function(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}},{}],867:[function(require,module,exports){var require=require("./_freeGlobal"),exports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=exports&&"object"==typeof module&&module&&!module.nodeType&&module,freeProcess=freeModule&&freeModule.exports===exports&&require.process,exports=function(){try{var types=freeModule&&freeModule.require&&freeModule.require("util").types;return types?types:freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}();module.exports=exports},{"./_freeGlobal":811}],868:[function(require,module,exports){var nativeObjectToString=Object.prototype.toString;module.exports=function(value){return nativeObjectToString.call(value)}},{}],869:[function(require,module,exports){module.exports=function(func,transform){return function(arg){return func(transform(arg))}}},{}],870:[function(require,module,exports){var apply=require("./_apply"),nativeMax=Math.max;module.exports=function(func,start,transform){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index<length;)array[index]=args[start+index];for(var index=-1,otherArgs=Array(start+1);++index<start;)otherArgs[index]=args[index];return otherArgs[start]=transform(array),apply(func,this,otherArgs)}}},{"./_apply":677}],871:[function(require,module,exports){var baseGet=require("./_baseGet"),baseSlice=require("./_baseSlice");module.exports=function(object,path){return path.length<2?object:baseGet(object,baseSlice(path,0,-1))}},{"./_baseGet":711,"./_baseSlice":753}],872:[function(require,module,exports){module.exports={}},{}],873:[function(require,module,exports){var copyArray=require("./_copyArray"),isIndex=require("./_isIndex"),nativeMin=Math.min;module.exports=function(array,indexes){for(var arrLength=array.length,length=nativeMin(indexes.length,arrLength),oldArray=copyArray(array);length--;){var index=indexes[length];array[length]=isIndex(index,arrLength)?oldArray[index]:void 0}return array}},{"./_copyArray":780,"./_isIndex":840}],874:[function(require,module,exports){module.exports=function(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++index<length;){var value=array[index];value!==placeholder&&"__lodash_placeholder__"!==value||(array[index]="__lodash_placeholder__",result[resIndex++]=index)}return result}},{}],875:[function(require,module,exports){var require=require("./_freeGlobal"),freeSelf="object"==typeof self&&self&&self.Object===Object&&self,require=require||freeSelf||Function("return this")();module.exports=require},{"./_freeGlobal":811}],876:[function(require,module,exports){module.exports=function(object,key){if(("constructor"!==key||"function"!=typeof object[key])&&"__proto__"!=key)return object[key]}},{}],877:[function(require,module,exports){module.exports=function(value){return this.__data__.set(value,"__lodash_hash_undefined__"),this}},{}],878:[function(require,module,exports){module.exports=function(value){return this.__data__.has(value)}},{}],879:[function(require,module,exports){var baseSetData=require("./_baseSetData"),require=require("./_shortOut")(baseSetData);module.exports=require},{"./_baseSetData":751,"./_shortOut":883}],880:[function(require,module,exports){module.exports=function(set){var index=-1,result=Array(set.size);return set.forEach(function(value){result[++index]=value}),result}},{}],881:[function(require,module,exports){var baseSetToString=require("./_baseSetToString"),require=require("./_shortOut")(baseSetToString);module.exports=require},{"./_baseSetToString":752,"./_shortOut":883}],882:[function(require,module,exports){var getWrapDetails=require("./_getWrapDetails"),insertWrapDetails=require("./_insertWrapDetails"),setToString=require("./_setToString"),updateWrapDetails=require("./_updateWrapDetails");module.exports=function(wrapper,reference,bitmask){return setToString(wrapper,insertWrapDetails(reference+="",updateWrapDetails(getWrapDetails(reference),bitmask)))}},{"./_getWrapDetails":826,"./_insertWrapDetails":838,"./_setToString":881,"./_updateWrapDetails":899}],883:[function(require,module,exports){var nativeNow=Date.now;module.exports=function(func){var count=0,lastCalled=0;return function(){var stamp=nativeNow(),remaining=16-(stamp-lastCalled);if(lastCalled=stamp,0<remaining){if(800<=++count)return arguments[0]}else count=0;return func.apply(void 0,arguments)}}},{}],884:[function(require,module,exports){var ListCache=require("./_ListCache");module.exports=function(){this.__data__=new ListCache,this.size=0}},{"./_ListCache":666}],885:[function(require,module,exports){module.exports=function(key){var data=this.__data__,key=data.delete(key);return this.size=data.size,key}},{}],886:[function(require,module,exports){module.exports=function(key){return this.__data__.get(key)}},{}],887:[function(require,module,exports){module.exports=function(key){return this.__data__.has(key)}},{}],888:[function(require,module,exports){var ListCache=require("./_ListCache"),Map=require("./_Map"),MapCache=require("./_MapCache");module.exports=function(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length<199)return pairs.push([key,value]),this.size=++data.size,this;data=this.__data__=new MapCache(pairs)}return data.set(key,value),this.size=data.size,this}},{"./_ListCache":666,"./_Map":668,"./_MapCache":669}],889:[function(require,module,exports){module.exports=function(array,value,fromIndex){for(var index=fromIndex-1,length=array.length;++index<length;)if(array[index]===value)return index;return-1}},{}],890:[function(require,module,exports){var asciiSize=require("./_asciiSize"),hasUnicode=require("./_hasUnicode"),unicodeSize=require("./_unicodeSize");module.exports=function(string){return(hasUnicode(string)?unicodeSize:asciiSize)(string)}},{"./_asciiSize":689,"./_hasUnicode":828,"./_unicodeSize":896}],891:[function(require,module,exports){var asciiToArray=require("./_asciiToArray"),hasUnicode=require("./_hasUnicode"),unicodeToArray=require("./_unicodeToArray");module.exports=function(string){return(hasUnicode(string)?unicodeToArray:asciiToArray)(string)}},{"./_asciiToArray":690,"./_hasUnicode":828,"./_unicodeToArray":897}],892:[function(require,module,exports){var require=require("./_memoizeCapped"),rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reEscapeChar=/\\(\\)?/g,require=require(function(string){var result=[];return 46===string.charCodeAt(0)&&result.push(""),string.replace(rePropName,function(match,number,quote,subString){result.push(quote?subString.replace(reEscapeChar,"$1"):number||match)}),result});module.exports=require},{"./_memoizeCapped":861}],893:[function(require,module,exports){var isSymbol=require("./isSymbol");module.exports=function(value){var result;return"string"==typeof value||isSymbol(value)?value:"0"==(result=value+"")&&1/value==-1/0?"-0":result}},{"./isSymbol":980}],894:[function(require,module,exports){var funcToString=Function.prototype.toString;module.exports=function(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}},{}],895:[function(require,module,exports){var reWhitespace=/\s/;module.exports=function(string){for(var index=string.length;index--&&reWhitespace.test(string.charAt(index)););return index}},{}],896:[function(require,module,exports){var rsCombo="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",reOptMod="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),rsCombo="(?:"+["[^\\ud800-\\udfff]"+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,"[\\ud800-\\udfff]"].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsCombo+reOptMod,"g");module.exports=function(string){for(var result=reUnicode.lastIndex=0;reUnicode.test(string);)++result;return result}},{}],897:[function(require,module,exports){var rsCombo="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",reOptMod="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),rsCombo="(?:"+["[^\\ud800-\\udfff]"+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,"[\\ud800-\\udfff]"].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsCombo+reOptMod,"g");module.exports=function(string){return string.match(reUnicode)||[]}},{}],898:[function(require,module,exports){var rsBreakRange="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsBreak="["+rsBreakRange+"]",rsLower="[a-z\\xdf-\\xf6\\xf8-\\xff]",rsBreakRange="[^\\ud800-\\udfff"+rsBreakRange+"\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="[A-Z\\xc0-\\xd6\\xd8-\\xde]",rsBreakRange="(?:"+rsLower+"|"+rsBreakRange+")",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",reOptMod="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),rsRegional="(?:"+["[\\u2700-\\u27bf]",rsRegional,rsSurrPair].join("|")+")"+reOptMod,reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[rsBreak,rsUpper,"$"].join("|")+")","(?:[A-Z\\xc0-\\xd6\\xd8-\\xde]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[rsBreak,rsUpper+rsBreakRange,"$"].join("|")+")",rsUpper+"?"+rsBreakRange+"+(?:['’](?:d|ll|m|re|s|t|ve))?",rsUpper+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])","\\d+",rsRegional].join("|"),"g");module.exports=function(string){return string.match(reUnicodeWord)||[]}},{}],899:[function(require,module,exports){var arrayEach=require("./_arrayEach"),arrayIncludes=require("./_arrayIncludes"),wrapFlags=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]];module.exports=function(details,bitmask){return arrayEach(wrapFlags,function(pair){var value="_."+pair[0];bitmask&pair[1]&&!arrayIncludes(details,value)&&details.push(value)}),details.sort()}},{"./_arrayEach":679,"./_arrayIncludes":682}],900:[function(require,module,exports){var LazyWrapper=require("./_LazyWrapper"),LodashWrapper=require("./_LodashWrapper"),copyArray=require("./_copyArray");module.exports=function(wrapper){var result;return wrapper instanceof LazyWrapper?wrapper.clone():((result=new LodashWrapper(wrapper.__wrapped__,wrapper.__chain__)).__actions__=copyArray(wrapper.__actions__),result.__index__=wrapper.__index__,result.__values__=wrapper.__values__,result)}},{"./_LazyWrapper":665,"./_LodashWrapper":667,"./_copyArray":780}],901:[function(require,module,exports){var createWrap=require("./_createWrap");module.exports=function(func,n,guard){return n=guard?void 0:n,n=func&&null==n?func.length:n,createWrap(func,128,void 0,void 0,void 0,void 0,n)}},{"./_createWrap":804}],902:[function(require,module,exports){var baseClamp=require("./_baseClamp"),toNumber=require("./toNumber");module.exports=function(number,lower,upper){return void 0===upper&&(upper=lower,lower=void 0),void 0!==upper&&(upper=(upper=toNumber(upper))==upper?upper:0),void 0!==lower&&(lower=(lower=toNumber(lower))==lower?lower:0),baseClamp(toNumber(number),lower,upper)}},{"./_baseClamp":699,"./toNumber":1018}],903:[function(require,module,exports){var baseClone=require("./_baseClone");module.exports=function(value){return baseClone(value,4)}},{"./_baseClone":700}],904:[function(require,module,exports){module.exports=function(array){for(var index=-1,length=null==array?0:array.length,resIndex=0,result=[];++index<length;){var value=array[index];value&&(result[resIndex++]=value)}return result}},{}],905:[function(require,module,exports){module.exports=function(value){return function(){return value}}},{}],906:[function(require,module,exports){var createWrap=require("./_createWrap");function curry(func,arity,guard){func=createWrap(func,8,void 0,void 0,void 0,void 0,void 0,arity=guard?void 0:arity);return func.placeholder=curry.placeholder,func}curry.placeholder={},module.exports=curry},{"./_createWrap":804}],907:[function(require,module,exports){var deburrLetter=require("./_deburrLetter"),toString=require("./toString"),reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reComboMark=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");module.exports=function(string){return(string=toString(string))&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}},{"./_deburrLetter":805,"./toString":1021}],908:[function(require,module,exports){var baseDifference=require("./_baseDifference"),baseFlatten=require("./_baseFlatten"),baseRest=require("./_baseRest"),isArrayLikeObject=require("./isArrayLikeObject"),require=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0)):[]});module.exports=require},{"./_baseDifference":702,"./_baseFlatten":708,"./_baseRest":749,"./isArrayLikeObject":963}],909:[function(require,module,exports){var baseSlice=require("./_baseSlice"),toInteger=require("./toInteger");module.exports=function(array,n,guard){var length=null==array?0:array.length;return length?(n=guard||void 0===n?1:toInteger(n),baseSlice(array,0,(n=length-n)<0?0:n)):[]}},{"./_baseSlice":753,"./toInteger":1017}],910:[function(require,module,exports){module.exports=require("./forEach")},{"./forEach":921}],911:[function(require,module,exports){module.exports=function(value,other){return value===other||value!=value&&other!=other}},{}],912:[function(require,module,exports){var toString=require("./toString"),reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source);module.exports=function(string){return(string=toString(string))&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}},{"./toString":1021}],913:[function(require,module,exports){var arrayEvery=require("./_arrayEvery"),baseEvery=require("./_baseEvery"),baseIteratee=require("./_baseIteratee"),isArray=require("./isArray"),isIterateeCall=require("./_isIterateeCall");module.exports=function(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=void 0),func(collection,baseIteratee(predicate,3))}},{"./_arrayEvery":680,"./_baseEvery":704,"./_baseIteratee":731,"./_isIterateeCall":841,"./isArray":961}],914:[function(require,module,exports){var arrayFilter=require("./_arrayFilter"),baseFilter=require("./_baseFilter"),baseIteratee=require("./_baseIteratee"),isArray=require("./isArray");module.exports=function(collection,predicate){return(isArray(collection)?arrayFilter:baseFilter)(collection,baseIteratee(predicate,3))}},{"./_arrayFilter":681,"./_baseFilter":706,"./_baseIteratee":731,"./isArray":961}],915:[function(require,module,exports){require=require("./_createFind")(require("./findIndex"));module.exports=require},{"./_createFind":795,"./findIndex":916}],916:[function(require,module,exports){var baseFindIndex=require("./_baseFindIndex"),baseIteratee=require("./_baseIteratee"),toInteger=require("./toInteger"),nativeMax=Math.max;module.exports=function(array,predicate,fromIndex){var length=null==array?0:array.length;return length?((fromIndex=null==fromIndex?0:toInteger(fromIndex))<0&&(fromIndex=nativeMax(length+fromIndex,0)),baseFindIndex(array,baseIteratee(predicate,3),fromIndex)):-1}},{"./_baseFindIndex":707,"./_baseIteratee":731,"./toInteger":1017}],917:[function(require,module,exports){module.exports=require("./head")},{"./head":953}],918:[function(require,module,exports){var baseFlatten=require("./_baseFlatten"),map=require("./map");module.exports=function(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}},{"./_baseFlatten":708,"./map":989}],919:[function(require,module,exports){var baseFlatten=require("./_baseFlatten");module.exports=function(array){return(null==array?0:array.length)?baseFlatten(array,1):[]}},{"./_baseFlatten":708}],920:[function(require,module,exports){require=require("./_createFlow")();module.exports=require},{"./_createFlow":796}],921:[function(require,module,exports){var arrayEach=require("./_arrayEach"),baseEach=require("./_baseEach"),castFunction=require("./_castFunction"),isArray=require("./isArray");module.exports=function(collection,iteratee){return(isArray(collection)?arrayEach:baseEach)(collection,castFunction(iteratee))}},{"./_arrayEach":679,"./_baseEach":703,"./_castFunction":765,"./isArray":961}],922:[function(require,module,exports){var mapping=require("./_mapping"),fallbackHolder=require("./placeholder"),push=Array.prototype.push;function baseAry(func,n){return 2==n?function(a,b){return func(a,b)}:function(a){return func(a)}}function cloneArray(array){for(var length=array?array.length:0,result=Array(length);length--;)result[length]=array[length];return result}function wrapImmutable(func,cloner){return function(){var length=arguments.length;if(length){for(var args=Array(length);length--;)args[length]=arguments[length];var result=args[0]=cloner.apply(void 0,args);return func.apply(void 0,args),result}}}module.exports=function baseConvert(util,name,func,options){var isLib="function"==typeof name,isObj=name===Object(name);if(isObj&&(options=func,func=name,name=void 0),null==func)throw new TypeError;var _,pairs,config={cap:!("cap"in(options=options||{}))||options.cap,curry:!("curry"in options)||options.curry,fixed:!("fixed"in options)||options.fixed,immutable:!("immutable"in options)||options.immutable,rearg:!("rearg"in options)||options.rearg},defaultHolder=isLib?func:fallbackHolder,forceCurry="curry"in options&&options.curry,forceFixed="fixed"in options&&options.fixed,forceRearg="rearg"in options&&options.rearg,pristine=isLib?func.runInContext():void 0,helpers=isLib?func:{ary:util.ary,assign:util.assign,clone:util.clone,curry:util.curry,forEach:util.forEach,isArray:util.isArray,isError:util.isError,isFunction:util.isFunction,isWeakMap:util.isWeakMap,iteratee:util.iteratee,keys:util.keys,rearg:util.rearg,toInteger:util.toInteger,toPath:util.toPath},ary=helpers.ary,assign=helpers.assign,clone=helpers.clone,curry=helpers.curry,each=helpers.forEach,isArray=helpers.isArray,isError=helpers.isError,isFunction=helpers.isFunction,isWeakMap=helpers.isWeakMap,keys=helpers.keys,rearg=helpers.rearg,toInteger=helpers.toInteger,toPath=helpers.toPath,aryMethodKeys=keys(mapping.aryMethod),wrappers={castArray:function(castArray){return function(){var value=arguments[0];return isArray(value)?castArray(cloneArray(value)):castArray.apply(void 0,arguments)}},iteratee:function(iteratee){return function(){var func=arguments[0],arity=arguments[1],length=(func=iteratee(func,arity)).length;return!config.cap||"number"!=typeof arity||(arity=2<arity?arity-2:1,length&&length<=arity)?func:baseAry(func,arity)}},mixin:function(mixin){return function(source){var pairs,func=this;return isFunction(func)?(pairs=[],each(keys(source),function(key){isFunction(source[key])&&pairs.push([key,func.prototype[key]])}),mixin(func,Object(source)),each(pairs,function(pair){var value=pair[1];isFunction(value)?func.prototype[pair[0]]=value:delete func.prototype[pair[0]]}),func):mixin(func,Object(source))}},nthArg:function(nthArg){return function(n){var arity=n<0?1:toInteger(n)+1;return curry(nthArg(n),arity)}},rearg:function(rearg){return function(func,indexes){var arity=indexes?indexes.length:0;return curry(rearg(func,indexes),arity)}},runInContext:function(runInContext){return function(context){return baseConvert(util,runInContext(context),options)}}};function castCap(name,func){if(config.cap){var indexes=mapping.iterateeRearg[name];if(indexes)return function(func,indexes){return overArg(func,function(func){var n=indexes.length;return function(func,n){return 2==n?function(a,b){return func.apply(void 0,arguments)}:function(a){return func.apply(void 0,arguments)}}(rearg(baseAry(func,n),indexes),n)})}(func,indexes);if(indexes=!isLib&&mapping.iterateeAry[name])return function(func,n){return overArg(func,function(func){return"function"==typeof func?baseAry(func,n):func})}(func,indexes)}return func}function castFixed(name,func,n){return!config.fixed||!forceFixed&&mapping.skipFixed[name]?func:void 0===(name=(name=mapping.methodSpread[name])&&name.start)?ary(func,n):function(func,start){return function(){for(var length=arguments.length,lastIndex=length-1,args=Array(length);length--;)args[length]=arguments[length];var array=args[start],otherArgs=args.slice(0,start);return array&&push.apply(otherArgs,array),start!=lastIndex&&push.apply(otherArgs,args.slice(start+1)),func.apply(this,otherArgs)}}(func,name)}function castRearg(name,func,n){return config.rearg&&1<n&&(forceRearg||!mapping.skipRearg[name])?rearg(func,mapping.methodRearg[name]||mapping.aryRearg[n]):func}function cloneByPath(object,path){for(var index=-1,length=(path=toPath(path)).length,lastIndex=length-1,nested=object=clone(Object(object));null!=nested&&++index<length;){var key=path[index],value=nested[key];null==value||isFunction(value)||isError(value)||isWeakMap(value)||(nested[key]=clone(index==lastIndex?value:Object(value))),nested=nested[key]}return object}function createConverter(name,func){var realName=mapping.aliasToReal[name]||name,methodName=mapping.remap[realName]||realName,oldOptions=options;return function(options){var newUtil=isLib?pristine:helpers,newFunc=isLib?pristine[methodName]:func,options=assign(assign({},oldOptions),options);return baseConvert(newUtil,realName,newFunc,options)}}function overArg(func,transform){return function(){var length=arguments.length;if(!length)return func();for(var args=Array(length);length--;)args[length]=arguments[length];var index=config.rearg?0:length-1;return args[index]=transform(args[index]),func.apply(void 0,args)}}function wrap(name,func,placeholder){var result,realName=mapping.aliasToReal[name]||name,wrapped=func;return(name=wrappers[realName])?wrapped=name(func):config.immutable&&(mapping.mutate.array[realName]?wrapped=wrapImmutable(func,cloneArray):mapping.mutate.object[realName]?wrapped=wrapImmutable(func,function(func){return function(object){return func({},object)}}(func)):mapping.mutate.set[realName]&&(wrapped=wrapImmutable(func,cloneByPath))),each(aryMethodKeys,function(aryKey){return each(mapping.aryMethod[aryKey],function(otherName){var n;if(realName==otherName)return otherName=(otherName=mapping.methodSpread[realName])&&otherName.afterRearg,result=otherName?castFixed(realName,castRearg(realName,wrapped,aryKey),aryKey):castRearg(realName,castFixed(realName,wrapped,aryKey),aryKey),result=castCap(realName,result),otherName=result,n=aryKey,result=forceCurry||config.curry&&1<n?curry(otherName,n):otherName,!1}),!result}),(result=(result=result||wrapped)==func?forceCurry?curry(result,1):function(){return func.apply(this,arguments)}:result).convert=createConverter(realName,func),result.placeholder=func.placeholder=placeholder,result}return isObj?(_=func,pairs=[],each(aryMethodKeys,function(aryKey){each(mapping.aryMethod[aryKey],function(key){var func=_[mapping.remap[key]||key];func&&pairs.push([key,wrap(key,func,_)])})}),each(keys(_),function(key){var func=_[key];if("function"==typeof func){for(var length=pairs.length;length--;)if(pairs[length][0]==key)return;func.convert=createConverter(key,func),pairs.push([key,func])}}),each(pairs,function(pair){_[pair[0]]=pair[1]}),_.convert=function(options){return _.runInContext.convert(options)(void 0)},_.placeholder=_,each(keys(_),function(key){each(mapping.realToAlias[key]||[],function(alias){_[alias]=_[key]})}),_):wrap(name,func,defaultHolder)}},{"./_mapping":924,"./placeholder":942}],923:[function(require,module,exports){module.exports={cap:!1,curry:!1,fixed:!1,immutable:!1,rearg:!1}},{}],924:[function(require,module,exports){exports.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},exports.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},exports.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},exports.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},exports.iterateeRearg={mapKeys:[1],reduceRight:[1,0]},exports.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},exports.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},exports.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},exports.realToAlias=function(){var key,hasOwnProperty=Object.prototype.hasOwnProperty,object=exports.aliasToReal,result={};for(key in object){var value=object[key];hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]}return result}(),exports.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},exports.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},exports.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},{}],925:[function(require,module,exports){module.exports={ary:require("../ary"),assign:require("../_baseAssign"),clone:require("../clone"),curry:require("../curry"),forEach:require("../_arrayEach"),isArray:require("../isArray"),isError:require("../isError"),isFunction:require("../isFunction"),isWeakMap:require("../isWeakMap"),iteratee:require("../iteratee"),keys:require("../_baseKeys"),rearg:require("../rearg"),toInteger:require("../toInteger"),toPath:require("../toPath")}},{"../_arrayEach":679,"../_baseAssign":696,"../_baseKeys":732,"../ary":901,"../clone":903,"../curry":906,"../isArray":961,"../isError":968,"../isFunction":969,"../isWeakMap":983,"../iteratee":984,"../rearg":1e3,"../toInteger":1017,"../toPath":1019}],926:[function(require,module,exports){var func=require("./convert")("compact",require("../compact"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../compact":904,"./_falseOptions":923,"./convert":927,"./placeholder":942}],927:[function(require,module,exports){var baseConvert=require("./_baseConvert"),util=require("./_util");module.exports=function(name,func,options){return baseConvert(util,name,func,options)}},{"./_baseConvert":922,"./_util":925}],928:[function(require,module,exports){var func=require("./convert")("difference",require("../difference"));func.placeholder=require("./placeholder"),module.exports=func},{"../difference":908,"./convert":927,"./placeholder":942}],929:[function(require,module,exports){var func=require("./convert")("filter",require("../filter"));func.placeholder=require("./placeholder"),module.exports=func},{"../filter":914,"./convert":927,"./placeholder":942}],930:[function(require,module,exports){var func=require("./convert")("flatMap",require("../flatMap"));func.placeholder=require("./placeholder"),module.exports=func},{"../flatMap":918,"./convert":927,"./placeholder":942}],931:[function(require,module,exports){var func=require("./convert")("flow",require("../flow"));func.placeholder=require("./placeholder"),module.exports=func},{"../flow":920,"./convert":927,"./placeholder":942}],932:[function(require,module,exports){var func=require("./convert")("identity",require("../identity"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../identity":954,"./_falseOptions":923,"./convert":927,"./placeholder":942}],933:[function(require,module,exports){var func=require("./convert")("isFunction",require("../isFunction"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../isFunction":969,"./_falseOptions":923,"./convert":927,"./placeholder":942}],934:[function(require,module,exports){var func=require("./convert")("isNil",require("../isNil"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../isNil":972,"./_falseOptions":923,"./convert":927,"./placeholder":942}],935:[function(require,module,exports){var func=require("./convert")("isObject",require("../isObject"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../isObject":974,"./_falseOptions":923,"./convert":927,"./placeholder":942}],936:[function(require,module,exports){var func=require("./convert")("isPlainObject",require("../isPlainObject"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../isPlainObject":976,"./_falseOptions":923,"./convert":927,"./placeholder":942}],937:[function(require,module,exports){var func=require("./convert")("keys",require("../keys"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../keys":986,"./_falseOptions":923,"./convert":927,"./placeholder":942}],938:[function(require,module,exports){var func=require("./convert")("map",require("../map"));func.placeholder=require("./placeholder"),module.exports=func},{"../map":989,"./convert":927,"./placeholder":942}],939:[function(require,module,exports){var func=require("./convert")("memoize",require("../memoize"));func.placeholder=require("./placeholder"),module.exports=func},{"../memoize":991,"./convert":927,"./placeholder":942}],940:[function(require,module,exports){var func=require("./convert")("min",require("../min"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../min":993,"./_falseOptions":923,"./convert":927,"./placeholder":942}],941:[function(require,module,exports){var func=require("./convert")("pick",require("../pick"));func.placeholder=require("./placeholder"),module.exports=func},{"../pick":996,"./convert":927,"./placeholder":942}],942:[function(require,module,exports){module.exports={}},{}],943:[function(require,module,exports){var func=require("./convert")("sortBy",require("../sortBy"));func.placeholder=require("./placeholder"),module.exports=func},{"../sortBy":1006,"./convert":927,"./placeholder":942}],944:[function(require,module,exports){var func=require("./convert")("split",require("../split"));func.placeholder=require("./placeholder"),module.exports=func},{"../split":1007,"./convert":927,"./placeholder":942}],945:[function(require,module,exports){var func=require("./convert")("sum",require("../sum"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../sum":1012,"./_falseOptions":923,"./convert":927,"./placeholder":942}],946:[function(require,module,exports){var func=require("./convert")("take",require("../take"));func.placeholder=require("./placeholder"),module.exports=func},{"../take":1013,"./convert":927,"./placeholder":942}],947:[function(require,module,exports){var func=require("./convert")("toArray",require("../toArray"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../toArray":1015,"./_falseOptions":923,"./convert":927,"./placeholder":942}],948:[function(require,module,exports){var func=require("./convert")("trim",require("../trim"));func.placeholder=require("./placeholder"),module.exports=func},{"../trim":1023,"./convert":927,"./placeholder":942}],949:[function(require,module,exports){var func=require("./convert")("uniq",require("../uniq"),require("./_falseOptions"));func.placeholder=require("./placeholder"),module.exports=func},{"../uniq":1025,"./_falseOptions":923,"./convert":927,"./placeholder":942}],950:[function(require,module,exports){var baseGet=require("./_baseGet");module.exports=function(object,path,defaultValue){return void 0===(object=null==object?void 0:baseGet(object,path))?defaultValue:object}},{"./_baseGet":711}],951:[function(require,module,exports){var baseHas=require("./_baseHas"),hasPath=require("./_hasPath");module.exports=function(object,path){return null!=object&&hasPath(object,path,baseHas)}},{"./_baseHas":714,"./_hasPath":827}],952:[function(require,module,exports){var baseHasIn=require("./_baseHasIn"),hasPath=require("./_hasPath");module.exports=function(object,path){return null!=object&&hasPath(object,path,baseHasIn)}},{"./_baseHasIn":715,"./_hasPath":827}],953:[function(require,module,exports){module.exports=function(array){return array&&array.length?array[0]:void 0}},{}],954:[function(require,module,exports){module.exports=function(value){return value}},{}],955:[function(require,module,exports){var baseInRange=require("./_baseInRange"),toFinite=require("./toFinite"),toNumber=require("./toNumber");module.exports=function(number,start,end){return start=toFinite(start),void 0===end?(end=start,start=0):end=toFinite(end),number=toNumber(number),baseInRange(number,start,end)}},{"./_baseInRange":716,"./toFinite":1016,"./toNumber":1018}],956:[function(require,module,exports){var baseIndexOf=require("./_baseIndexOf"),isArrayLike=require("./isArrayLike"),isString=require("./isString"),toInteger=require("./toInteger"),values=require("./values"),nativeMax=Math.max;module.exports=function(collection,value,fromIndex,guard){return collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0,guard=collection.length,fromIndex<0&&(fromIndex=nativeMax(guard+fromIndex,0)),isString(collection)?fromIndex<=guard&&-1<collection.indexOf(value,fromIndex):!!guard&&-1<baseIndexOf(collection,value,fromIndex)}},{"./_baseIndexOf":717,"./isArrayLike":962,"./isString":979,"./toInteger":1017,"./values":1027}],957:[function(require,module,exports){var arrayMap=require("./_arrayMap"),baseIntersection=require("./_baseIntersection"),baseRest=require("./_baseRest"),castArrayLikeObject=require("./_castArrayLikeObject"),require=baseRest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[]});module.exports=require},{"./_arrayMap":685,"./_baseIntersection":718,"./_baseRest":749,"./_castArrayLikeObject":764}],958:[function(require,module,exports){var constant=require("./constant"),createInverter=require("./_createInverter"),require=require("./identity"),nativeObjectToString=Object.prototype.toString,createInverter=createInverter(function(result,value,key){result[value=null!=value&&"function"!=typeof value.toString?nativeObjectToString.call(value):value]=key},constant(require));module.exports=createInverter},{"./_createInverter":798,"./constant":905,"./identity":954}],959:[function(require,module,exports){var baseInvoke=require("./_baseInvoke"),require=require("./_baseRest")(baseInvoke);module.exports=require},{"./_baseInvoke":720,"./_baseRest":749}],960:[function(require,module,exports){var baseIsArguments=require("./_baseIsArguments"),isObjectLike=require("./isObjectLike"),require=Object.prototype,hasOwnProperty=require.hasOwnProperty,propertyIsEnumerable=require.propertyIsEnumerable,require=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")};module.exports=require},{"./_baseIsArguments":721,"./isObjectLike":975}],961:[function(require,module,exports){var isArray=Array.isArray;module.exports=isArray},{}],962:[function(require,module,exports){var isFunction=require("./isFunction"),isLength=require("./isLength");module.exports=function(value){return null!=value&&isLength(value.length)&&!isFunction(value)}},{"./isFunction":969,"./isLength":970}],963:[function(require,module,exports){var isArrayLike=require("./isArrayLike"),isObjectLike=require("./isObjectLike");module.exports=function(value){return isObjectLike(value)&&isArrayLike(value)}},{"./isArrayLike":962,"./isObjectLike":975}],964:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isObjectLike=require("./isObjectLike");module.exports=function(value){return!0===value||!1===value||isObjectLike(value)&&"[object Boolean]"==baseGetTag(value)}},{"./_baseGetTag":713,"./isObjectLike":975}],965:[function(require,module,exports){var root=require("./_root"),require=require("./stubFalse"),exports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=exports&&"object"==typeof module&&module&&!module.nodeType&&module,freeModule=freeModule&&freeModule.exports===exports?root.Buffer:void 0,exports=freeModule?freeModule.isBuffer:void 0;module.exports=exports||require},{"./_root":875,"./stubFalse":1011}],966:[function(require,module,exports){var baseKeys=require("./_baseKeys"),getTag=require("./_getTag"),isArguments=require("./isArguments"),isArray=require("./isArray"),isArrayLike=require("./isArrayLike"),isBuffer=require("./isBuffer"),isPrototype=require("./_isPrototype"),isTypedArray=require("./isTypedArray"),hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(value){if(null!=value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isTypedArray(value)||isArguments(value)))return!value.length;var key,tag=getTag(value);if("[object Map]"==tag||"[object Set]"==tag)return!value.size;if(isPrototype(value))return!baseKeys(value).length;for(key in value)if(hasOwnProperty.call(value,key))return!1}return!0}},{"./_baseKeys":732,"./_getTag":824,"./_isPrototype":846,"./isArguments":960,"./isArray":961,"./isArrayLike":962,"./isBuffer":965,"./isTypedArray":981}],967:[function(require,module,exports){var baseIsEqual=require("./_baseIsEqual");module.exports=function(value,other){return baseIsEqual(value,other)}},{"./_baseIsEqual":722}],968:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isObjectLike=require("./isObjectLike"),isPlainObject=require("./isPlainObject");module.exports=function(value){var tag;return!!isObjectLike(value)&&("[object Error]"==(tag=baseGetTag(value))||"[object DOMException]"==tag||"string"==typeof value.message&&"string"==typeof value.name&&!isPlainObject(value))}},{"./_baseGetTag":713,"./isObjectLike":975,"./isPlainObject":976}],969:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isObject=require("./isObject");module.exports=function(value){return!!isObject(value)&&("[object Function]"==(value=baseGetTag(value))||"[object GeneratorFunction]"==value||"[object AsyncFunction]"==value||"[object Proxy]"==value)}},{"./_baseGetTag":713,"./isObject":974}],970:[function(require,module,exports){module.exports=function(value){return"number"==typeof value&&-1<value&&value%1==0&&value<=9007199254740991}},{}],971:[function(require,module,exports){var baseIsMap=require("./_baseIsMap"),baseUnary=require("./_baseUnary"),require=require("./_nodeUtil"),require=require&&require.isMap,baseUnary=require?baseUnary(require):baseIsMap;module.exports=baseUnary},{"./_baseIsMap":724,"./_baseUnary":760,"./_nodeUtil":867}],972:[function(require,module,exports){module.exports=function(value){return null==value}},{}],973:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isObjectLike=require("./isObjectLike");module.exports=function(value){return"number"==typeof value||isObjectLike(value)&&"[object Number]"==baseGetTag(value)}},{"./_baseGetTag":713,"./isObjectLike":975}],974:[function(require,module,exports){module.exports=function(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}},{}],975:[function(require,module,exports){module.exports=function(value){return null!=value&&"object"==typeof value}},{}],976:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),getPrototype=require("./_getPrototype"),isObjectLike=require("./isObjectLike"),require=Function.prototype,objectProto=Object.prototype,funcToString=require.toString,hasOwnProperty=objectProto.hasOwnProperty,objectCtorString=funcToString.call(Object);module.exports=function(value){return!(!isObjectLike(value)||"[object Object]"!=baseGetTag(value))&&(null===(value=getPrototype(value))||"function"==typeof(value=hasOwnProperty.call(value,"constructor")&&value.constructor)&&value instanceof value&&funcToString.call(value)==objectCtorString)}},{"./_baseGetTag":713,"./_getPrototype":820,"./isObjectLike":975}],977:[function(require,module,exports){var baseIsRegExp=require("./_baseIsRegExp"),baseUnary=require("./_baseUnary"),require=require("./_nodeUtil"),require=require&&require.isRegExp,baseUnary=require?baseUnary(require):baseIsRegExp;module.exports=baseUnary},{"./_baseIsRegExp":728,"./_baseUnary":760,"./_nodeUtil":867}],978:[function(require,module,exports){var baseIsSet=require("./_baseIsSet"),baseUnary=require("./_baseUnary"),require=require("./_nodeUtil"),require=require&&require.isSet,baseUnary=require?baseUnary(require):baseIsSet;module.exports=baseUnary},{"./_baseIsSet":729,"./_baseUnary":760,"./_nodeUtil":867}],979:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isArray=require("./isArray"),isObjectLike=require("./isObjectLike");module.exports=function(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&"[object String]"==baseGetTag(value)}},{"./_baseGetTag":713,"./isArray":961,"./isObjectLike":975}],980:[function(require,module,exports){var baseGetTag=require("./_baseGetTag"),isObjectLike=require("./isObjectLike");module.exports=function(value){return"symbol"==typeof value||isObjectLike(value)&&"[object Symbol]"==baseGetTag(value)}},{"./_baseGetTag":713,"./isObjectLike":975}],981:[function(require,module,exports){var baseIsTypedArray=require("./_baseIsTypedArray"),baseUnary=require("./_baseUnary"),require=require("./_nodeUtil"),require=require&&require.isTypedArray,baseUnary=require?baseUnary(require):baseIsTypedArray;module.exports=baseUnary},{"./_baseIsTypedArray":730,"./_baseUnary":760,"./_nodeUtil":867}],982:[function(require,module,exports){module.exports=function(value){return void 0===value}},{}],983:[function(require,module,exports){var getTag=require("./_getTag"),isObjectLike=require("./isObjectLike");module.exports=function(value){return isObjectLike(value)&&"[object WeakMap]"==getTag(value)}},{"./_getTag":824,"./isObjectLike":975}],984:[function(require,module,exports){var baseClone=require("./_baseClone"),baseIteratee=require("./_baseIteratee");module.exports=function(func){return baseIteratee("function"==typeof func?func:baseClone(func,1))}},{"./_baseClone":700,"./_baseIteratee":731}],985:[function(require,module,exports){var baseAssignValue=require("./_baseAssignValue"),require=require("./_createAggregator")(function(result,value,key){baseAssignValue(result,key,value)});module.exports=require},{"./_baseAssignValue":698,"./_createAggregator":786}],986:[function(require,module,exports){var arrayLikeKeys=require("./_arrayLikeKeys"),baseKeys=require("./_baseKeys"),isArrayLike=require("./isArrayLike");module.exports=function(object){return(isArrayLike(object)?arrayLikeKeys:baseKeys)(object)}},{"./_arrayLikeKeys":684,"./_baseKeys":732,"./isArrayLike":962}],987:[function(require,module,exports){var arrayLikeKeys=require("./_arrayLikeKeys"),baseKeysIn=require("./_baseKeysIn"),isArrayLike=require("./isArrayLike");module.exports=function(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}},{"./_arrayLikeKeys":684,"./_baseKeysIn":733,"./isArrayLike":962}],988:[function(require,module,exports){module.exports=function(array){var length=null==array?0:array.length;return length?array[length-1]:void 0}},{}],989:[function(require,module,exports){var arrayMap=require("./_arrayMap"),baseIteratee=require("./_baseIteratee"),baseMap=require("./_baseMap"),isArray=require("./isArray");module.exports=function(collection,iteratee){return(isArray(collection)?arrayMap:baseMap)(collection,baseIteratee(iteratee,3))}},{"./_arrayMap":685,"./_baseIteratee":731,"./_baseMap":736,"./isArray":961}],990:[function(require,module,exports){var baseAssignValue=require("./_baseAssignValue"),baseForOwn=require("./_baseForOwn"),baseIteratee=require("./_baseIteratee");module.exports=function(object,iteratee){var result={};return iteratee=baseIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}},{"./_baseAssignValue":698,"./_baseForOwn":710,"./_baseIteratee":731}],991:[function(require,module,exports){var MapCache=require("./_MapCache");function memoize(func,resolver){if("function"!=typeof func||null!=resolver&&"function"!=typeof resolver)throw new TypeError("Expected a function");function memoized(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;return cache.has(key)?cache.get(key):(args=func.apply(this,args),memoized.cache=cache.set(key,args)||cache,args)}return memoized.cache=new(memoize.Cache||MapCache),memoized}memoize.Cache=MapCache,module.exports=memoize},{"./_MapCache":669}],992:[function(require,module,exports){var baseMerge=require("./_baseMerge"),require=require("./_createAssigner")(function(object,source,srcIndex){baseMerge(object,source,srcIndex)});module.exports=require},{"./_baseMerge":739,"./_createAssigner":787}],993:[function(require,module,exports){var baseExtremum=require("./_baseExtremum"),baseLt=require("./_baseLt"),identity=require("./identity");module.exports=function(array){return array&&array.length?baseExtremum(array,identity,baseLt):void 0}},{"./_baseExtremum":705,"./_baseLt":735,"./identity":954}],994:[function(require,module,exports){module.exports=function(){}},{}],995:[function(require,module,exports){var baseRest=require("./_baseRest"),createWrap=require("./_createWrap"),getHolder=require("./_getHolder"),replaceHolders=require("./_replaceHolders"),partialRight=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partialRight));return createWrap(func,64,void 0,partials,holders)});partialRight.placeholder={},module.exports=partialRight},{"./_baseRest":749,"./_createWrap":804,"./_getHolder":816,"./_replaceHolders":874}],996:[function(require,module,exports){var basePick=require("./_basePick"),require=require("./_flatRest")(function(object,paths){return null==object?{}:basePick(object,paths)});module.exports=require},{"./_basePick":742,"./_flatRest":810}],997:[function(require,module,exports){var arrayMap=require("./_arrayMap"),baseIteratee=require("./_baseIteratee"),basePickBy=require("./_basePickBy"),getAllKeysIn=require("./_getAllKeysIn");module.exports=function(object,predicate){var props;return null==object?{}:(props=arrayMap(getAllKeysIn(object),function(prop){return[prop]}),predicate=baseIteratee(predicate),basePickBy(object,props,function(value,path){return predicate(value,path[0])}))}},{"./_arrayMap":685,"./_baseIteratee":731,"./_basePickBy":743,"./_getAllKeysIn":813}],998:[function(require,module,exports){var baseProperty=require("./_baseProperty"),basePropertyDeep=require("./_basePropertyDeep"),isKey=require("./_isKey"),toKey=require("./_toKey");module.exports=function(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path)}},{"./_baseProperty":744,"./_basePropertyDeep":745,"./_isKey":842,"./_toKey":893}],999:[function(require,module,exports){require=require("./_createRange")();module.exports=require},{"./_createRange":800}],1e3:[function(require,module,exports){var createWrap=require("./_createWrap"),require=require("./_flatRest"),require=require(function(func,indexes){return createWrap(func,256,void 0,void 0,void 0,indexes)});module.exports=require},{"./_createWrap":804,"./_flatRest":810}],1001:[function(require,module,exports){var arrayReduce=require("./_arrayReduce"),baseEach=require("./_baseEach"),baseIteratee=require("./_baseIteratee"),baseReduce=require("./_baseReduce"),isArray=require("./isArray");module.exports=function(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,baseIteratee(iteratee,4),accumulator,initAccum,baseEach)}},{"./_arrayReduce":687,"./_baseEach":703,"./_baseIteratee":731,"./_baseReduce":748,"./isArray":961}],1002:[function(require,module,exports){require=require("./_createRound")("round");module.exports=require},{"./_createRound":802}],1003:[function(require,module,exports){var baseSet=require("./_baseSet");module.exports=function(object,path,value){return null==object?object:baseSet(object,path,value)}},{"./_baseSet":750}],1004:[function(require,module,exports){var baseKeys=require("./_baseKeys"),getTag=require("./_getTag"),isArrayLike=require("./isArrayLike"),isString=require("./isString"),stringSize=require("./_stringSize");module.exports=function(collection){var tag;return null==collection?0:isArrayLike(collection)?isString(collection)?stringSize(collection):collection.length:"[object Map]"==(tag=getTag(collection))||"[object Set]"==tag?collection.size:baseKeys(collection).length}},{"./_baseKeys":732,"./_getTag":824,"./_stringSize":890,"./isArrayLike":962,"./isString":979}],1005:[function(require,module,exports){var arraySome=require("./_arraySome"),baseIteratee=require("./_baseIteratee"),baseSome=require("./_baseSome"),isArray=require("./isArray"),isIterateeCall=require("./_isIterateeCall");module.exports=function(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=void 0),func(collection,baseIteratee(predicate,3))}},{"./_arraySome":688,"./_baseIteratee":731,"./_baseSome":754,"./_isIterateeCall":841,"./isArray":961}],1006:[function(require,module,exports){var baseFlatten=require("./_baseFlatten"),baseOrderBy=require("./_baseOrderBy"),baseRest=require("./_baseRest"),isIterateeCall=require("./_isIterateeCall"),require=baseRest(function(collection,iteratees){var length;return null==collection?[]:(1<(length=iteratees.length)&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:2<length&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[]))});module.exports=require},{"./_baseFlatten":708,"./_baseOrderBy":741,"./_baseRest":749,"./_isIterateeCall":841}],1007:[function(require,module,exports){var baseToString=require("./_baseToString"),castSlice=require("./_castSlice"),hasUnicode=require("./_hasUnicode"),isIterateeCall=require("./_isIterateeCall"),isRegExp=require("./isRegExp"),stringToArray=require("./_stringToArray"),toString=require("./toString");module.exports=function(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=void 0),(limit=void 0===limit?4294967295:limit>>>0)?(string=toString(string))&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&!(separator=baseToString(separator))&&hasUnicode(string)?castSlice(stringToArray(string),0,limit):string.split(separator,limit):[]}},{"./_baseToString":758,"./_castSlice":767,"./_hasUnicode":828,"./_isIterateeCall":841,"./_stringToArray":891,"./isRegExp":977,"./toString":1021}],1008:[function(require,module,exports){var createCompounder=require("./_createCompounder"),upperFirst=require("./upperFirst"),require=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)});module.exports=require},{"./_createCompounder":792,"./upperFirst":1026}],1009:[function(require,module,exports){var baseClamp=require("./_baseClamp"),baseToString=require("./_baseToString"),toInteger=require("./toInteger"),toString=require("./toString");module.exports=function(string,target,position){return string=toString(string),position=null==position?0:baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}},{"./_baseClamp":699,"./_baseToString":758,"./toInteger":1017,"./toString":1021}],1010:[function(require,module,exports){module.exports=function(){return[]}},{}],1011:[function(require,module,exports){module.exports=function(){return!1}},{}],1012:[function(require,module,exports){var baseSum=require("./_baseSum"),identity=require("./identity");module.exports=function(array){return array&&array.length?baseSum(array,identity):0}},{"./_baseSum":756,"./identity":954}],1013:[function(require,module,exports){var baseSlice=require("./_baseSlice"),toInteger=require("./toInteger");module.exports=function(array,n,guard){return array&&array.length?(n=guard||void 0===n?1:toInteger(n),baseSlice(array,0,n<0?0:n)):[]}},{"./_baseSlice":753,"./toInteger":1017}],1014:[function(require,module,exports){var baseTimes=require("./_baseTimes"),castFunction=require("./_castFunction"),toInteger=require("./toInteger"),nativeMin=Math.min;module.exports=function(n,iteratee){if((n=toInteger(n))<1||9007199254740991<n)return[];for(var index=4294967295,length=nativeMin(n,4294967295),length=(iteratee=castFunction(iteratee),n-=4294967295,baseTimes(length,iteratee));++index<n;)iteratee(index);return length}},{"./_baseTimes":757,"./_castFunction":765,"./toInteger":1017}],1015:[function(require,module,exports){var Symbol=require("./_Symbol"),copyArray=require("./_copyArray"),getTag=require("./_getTag"),isArrayLike=require("./isArrayLike"),isString=require("./isString"),iteratorToArray=require("./_iteratorToArray"),mapToArray=require("./_mapToArray"),setToArray=require("./_setToArray"),stringToArray=require("./_stringToArray"),values=require("./values"),symIterator=Symbol?Symbol.iterator:void 0;module.exports=function(value){var tag;return value?isArrayLike(value)?(isString(value)?stringToArray:copyArray)(value):symIterator&&value[symIterator]?iteratorToArray(value[symIterator]()):("[object Map]"==(tag=getTag(value))?mapToArray:"[object Set]"==tag?setToArray:values)(value):[]}},{"./_Symbol":674,"./_copyArray":780,"./_getTag":824,"./_iteratorToArray":848,"./_mapToArray":859,"./_setToArray":880,"./_stringToArray":891,"./isArrayLike":962,"./isString":979,"./values":1027}],1016:[function(require,module,exports){var toNumber=require("./toNumber");module.exports=function(value){return value?(value=toNumber(value))===1/0||value===-1/0?17976931348623157e292*(value<0?-1:1):value==value?value:0:0===value?value:0}},{"./toNumber":1018}],1017:[function(require,module,exports){var toFinite=require("./toFinite");module.exports=function(value){var remainder=(value=toFinite(value))%1;return value==value?remainder?value-remainder:value:0}},{"./toFinite":1016}],1018:[function(require,module,exports){var baseTrim=require("./_baseTrim"),isObject=require("./isObject"),isSymbol=require("./isSymbol"),reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt;module.exports=function(value){if("number"==typeof value)return value;if(isSymbol(value))return NaN;if(isObject(value)&&(other="function"==typeof value.valueOf?value.valueOf():value,value=isObject(other)?other+"":other),"string"!=typeof value)return 0===value?value:+value;value=baseTrim(value);var other=reIsBinary.test(value);return other||reIsOctal.test(value)?freeParseInt(value.slice(2),other?2:8):reIsBadHex.test(value)?NaN:+value}},{"./_baseTrim":759,"./isObject":974,"./isSymbol":980}],1019:[function(require,module,exports){var arrayMap=require("./_arrayMap"),copyArray=require("./_copyArray"),isArray=require("./isArray"),isSymbol=require("./isSymbol"),stringToPath=require("./_stringToPath"),toKey=require("./_toKey"),toString=require("./toString");module.exports=function(value){return isArray(value)?arrayMap(value,toKey):isSymbol(value)?[value]:copyArray(stringToPath(toString(value)))}},{"./_arrayMap":685,"./_copyArray":780,"./_stringToPath":892,"./_toKey":893,"./isArray":961,"./isSymbol":980,"./toString":1021}],1020:[function(require,module,exports){var copyObject=require("./_copyObject"),keysIn=require("./keysIn");module.exports=function(value){return copyObject(value,keysIn(value))}},{"./_copyObject":781,"./keysIn":987}],1021:[function(require,module,exports){var baseToString=require("./_baseToString");module.exports=function(value){return null==value?"":baseToString(value)}},{"./_baseToString":758}],1022:[function(require,module,exports){var arrayEach=require("./_arrayEach"),baseCreate=require("./_baseCreate"),baseForOwn=require("./_baseForOwn"),baseIteratee=require("./_baseIteratee"),getPrototype=require("./_getPrototype"),isArray=require("./isArray"),isBuffer=require("./isBuffer"),isFunction=require("./isFunction"),isObject=require("./isObject"),isTypedArray=require("./isTypedArray");module.exports=function(object,iteratee,accumulator){var Ctor,isArr=isArray(object),isArrLike=isArr||isBuffer(object)||isTypedArray(object);return iteratee=baseIteratee(iteratee,4),null==accumulator&&(Ctor=object&&object.constructor,accumulator=isArrLike?isArr?new Ctor:[]:isObject(object)&&isFunction(Ctor)?baseCreate(getPrototype(object)):{}),(isArrLike?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object)}),accumulator}},{"./_arrayEach":679,"./_baseCreate":701,"./_baseForOwn":710,"./_baseIteratee":731,"./_getPrototype":820,"./isArray":961,"./isBuffer":965,"./isFunction":969,"./isObject":974,"./isTypedArray":981}],1023:[function(require,module,exports){var baseToString=require("./_baseToString"),baseTrim=require("./_baseTrim"),castSlice=require("./_castSlice"),charsEndIndex=require("./_charsEndIndex"),charsStartIndex=require("./_charsStartIndex"),stringToArray=require("./_stringToArray"),toString=require("./toString");module.exports=function(string,chars,guard){var start;return(string=toString(string))&&(guard||void 0===chars)?baseTrim(string):string&&(chars=baseToString(chars))?(guard=stringToArray(string),chars=stringToArray(chars),start=charsStartIndex(guard,chars),chars=charsEndIndex(guard,chars)+1,castSlice(guard,start,chars).join("")):string}},{"./_baseToString":758,"./_baseTrim":759,"./_castSlice":767,"./_charsEndIndex":768,"./_charsStartIndex":769,"./_stringToArray":891,"./toString":1021}],1024:[function(require,module,exports){var baseFlatten=require("./_baseFlatten"),baseRest=require("./_baseRest"),baseUniq=require("./_baseUniq"),isArrayLikeObject=require("./isArrayLikeObject"),require=baseRest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0))});module.exports=require},{"./_baseFlatten":708,"./_baseRest":749,"./_baseUniq":761,"./isArrayLikeObject":963}],1025:[function(require,module,exports){var baseUniq=require("./_baseUniq");module.exports=function(array){return array&&array.length?baseUniq(array):[]}},{"./_baseUniq":761}],1026:[function(require,module,exports){require=require("./_createCaseFirst")("toUpperCase");module.exports=require},{"./_createCaseFirst":791}],1027:[function(require,module,exports){var baseValues=require("./_baseValues"),keys=require("./keys");module.exports=function(object){return null==object?[]:baseValues(object,keys(object))}},{"./_baseValues":762,"./keys":986}],1028:[function(require,module,exports){var baseDifference=require("./_baseDifference"),baseRest=require("./_baseRest"),isArrayLikeObject=require("./isArrayLikeObject"),require=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,values):[]});module.exports=require},{"./_baseDifference":702,"./_baseRest":749,"./isArrayLikeObject":963}],1029:[function(require,module,exports){var asciiWords=require("./_asciiWords"),hasUnicodeWord=require("./_hasUnicodeWord"),toString=require("./toString"),unicodeWords=require("./_unicodeWords");module.exports=function(string,pattern,guard){return string=toString(string),void 0===(pattern=guard?void 0:pattern)?(hasUnicodeWord(string)?unicodeWords:asciiWords)(string):string.match(pattern)||[]}},{"./_asciiWords":691,"./_hasUnicodeWord":829,"./_unicodeWords":898,"./toString":1021}],1030:[function(require,module,exports){var LazyWrapper=require("./_LazyWrapper"),LodashWrapper=require("./_LodashWrapper"),baseLodash=require("./_baseLodash"),isArray=require("./isArray"),isObjectLike=require("./isObjectLike"),wrapperClone=require("./_wrapperClone"),hasOwnProperty=Object.prototype.hasOwnProperty;function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper)return value;if(hasOwnProperty.call(value,"__wrapped__"))return wrapperClone(value)}return new LodashWrapper(value)}lodash.prototype=baseLodash.prototype,module.exports=lodash.prototype.constructor=lodash},{"./_LazyWrapper":665,"./_LodashWrapper":667,"./_baseLodash":734,"./_wrapperClone":900,"./isArray":961,"./isObjectLike":975}],1031:[function(require,module,exports){var global,factory;global=this,factory=function(){"use strict";var hookCallback;function hooks(){return hookCallback.apply(null,arguments)}function isArray(input){return input instanceof Array||"[object Array]"===Object.prototype.toString.call(input)}function isObject(input){return null!=input&&"[object Object]"===Object.prototype.toString.call(input)}function hasOwnProp(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function isObjectEmpty(obj){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(obj).length;for(var k in obj)if(hasOwnProp(obj,k))return;return 1}function isNumber(input){return"number"==typeof input||"[object Number]"===Object.prototype.toString.call(input)}function isDate(input){return input instanceof Date||"[object Date]"===Object.prototype.toString.call(input)}function map(arr,fn){for(var res=[],arrLen=arr.length,i=0;i<arrLen;++i)res.push(fn(arr[i],i));return res}function extend(a,b){for(var i in b)hasOwnProp(b,i)&&(a[i]=b[i]);return hasOwnProp(b,"toString")&&(a.toString=b.toString),hasOwnProp(b,"valueOf")&&(a.valueOf=b.valueOf),a}function createUTC(input,format,locale,strict){return createLocalOrUTC(input,format,locale,strict,!0).utc()}function getParsingFlags(m){return null==m._pf&&(m._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}),m._pf}function isValid(m){if(null==m._isValid){var flags=getParsingFlags(m),parsedParts=some.call(flags.parsedDateParts,function(i){return null!=i}),parsedParts=!isNaN(m._d.getTime())&&flags.overflow<0&&!flags.empty&&!flags.invalidEra&&!flags.invalidMonth&&!flags.invalidWeekday&&!flags.weekdayMismatch&&!flags.nullInput&&!flags.invalidFormat&&!flags.userInvalidated&&(!flags.meridiem||flags.meridiem&&parsedParts);if(m._strict&&(parsedParts=parsedParts&&0===flags.charsLeftOver&&0===flags.unusedTokens.length&&void 0===flags.bigHour),null!=Object.isFrozen&&Object.isFrozen(m))return parsedParts;m._isValid=parsedParts}return m._isValid}function createInvalid(flags){var m=createUTC(NaN);return null!=flags?extend(getParsingFlags(m),flags):getParsingFlags(m).userInvalidated=!0,m}var some=Array.prototype.some||function(fun){for(var t=Object(this),len=t.length>>>0,i=0;i<len;i++)if(i in t&&fun.call(this,t[i],i,t))return!0;return!1},momentProperties=hooks.momentProperties=[],updateInProgress=!1;function copyConfig(to,from){var i,prop,val,momentPropertiesLen=momentProperties.length;if(void 0!==from._isAMomentObject&&(to._isAMomentObject=from._isAMomentObject),void 0!==from._i&&(to._i=from._i),void 0!==from._f&&(to._f=from._f),void 0!==from._l&&(to._l=from._l),void 0!==from._strict&&(to._strict=from._strict),void 0!==from._tzm&&(to._tzm=from._tzm),void 0!==from._isUTC&&(to._isUTC=from._isUTC),void 0!==from._offset&&(to._offset=from._offset),void 0!==from._pf&&(to._pf=getParsingFlags(from)),void 0!==from._locale&&(to._locale=from._locale),0<momentPropertiesLen)for(i=0;i<momentPropertiesLen;i++)void 0!==(val=from[prop=momentProperties[i]])&&(to[prop]=val);return to}function Moment(config){copyConfig(this,config),this._d=new Date(null!=config._d?config._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===updateInProgress&&(updateInProgress=!0,hooks.updateOffset(this),updateInProgress=!1)}function isMoment(obj){return obj instanceof Moment||null!=obj&&null!=obj._isAMomentObject}function warn(msg){!1===hooks.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+msg)}function deprecate(msg,fn){var firstTime=!0;return extend(function(){if(null!=hooks.deprecationHandler&&hooks.deprecationHandler(null,msg),firstTime){for(var arg,key,args=[],argLen=arguments.length,i=0;i<argLen;i++){if(arg="","object"==typeof arguments[i]){for(key in arg+="\n["+i+"] ",arguments[0])hasOwnProp(arguments[0],key)&&(arg+=key+": "+arguments[0][key]+", ");arg=arg.slice(0,-2)}else arg=arguments[i];args.push(arg)}warn(msg+"\nArguments: "+Array.prototype.slice.call(args).join("")+"\n"+(new Error).stack),firstTime=!1}return fn.apply(this,arguments)},fn)}var deprecations={};function deprecateSimple(name,msg){null!=hooks.deprecationHandler&&hooks.deprecationHandler(name,msg),deprecations[name]||(warn(msg),deprecations[name]=!0)}function isFunction(input){return"undefined"!=typeof Function&&input instanceof Function||"[object Function]"===Object.prototype.toString.call(input)}function mergeConfigs(parentConfig,childConfig){var prop,res=extend({},parentConfig);for(prop in childConfig)hasOwnProp(childConfig,prop)&&(isObject(parentConfig[prop])&&isObject(childConfig[prop])?(res[prop]={},extend(res[prop],parentConfig[prop]),extend(res[prop],childConfig[prop])):null!=childConfig[prop]?res[prop]=childConfig[prop]:delete res[prop]);for(prop in parentConfig)hasOwnProp(parentConfig,prop)&&!hasOwnProp(childConfig,prop)&&isObject(parentConfig[prop])&&(res[prop]=extend({},res[prop]));return res}function Locale(config){null!=config&&this.set(config)}hooks.suppressDeprecationWarnings=!1,hooks.deprecationHandler=null;var keys=Object.keys||function(obj){var i,res=[];for(i in obj)hasOwnProp(obj,i)&&res.push(i);return res};function zeroFill(number,targetLength,forceSign){var absNumber=""+Math.abs(number);return(0<=number?forceSign?"+":"":"-")+Math.pow(10,Math.max(0,targetLength-absNumber.length)).toString().substr(1)+absNumber}var formattingTokens=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,localFormattingTokens=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,formatFunctions={},formatTokenFunctions={};function addFormatToken(token,padded,ordinal,callback){var func="string"==typeof callback?function(){return this[callback]()}:callback;token&&(formatTokenFunctions[token]=func),padded&&(formatTokenFunctions[padded[0]]=function(){return zeroFill(func.apply(this,arguments),padded[1],padded[2])}),ordinal&&(formatTokenFunctions[ordinal]=function(){return this.localeData().ordinal(func.apply(this,arguments),token)})}function formatMoment(m,format){return m.isValid()?(format=expandFormat(format,m.localeData()),formatFunctions[format]=formatFunctions[format]||function(format){for(var input,array=format.match(formattingTokens),i=0,length=array.length;i<length;i++)formatTokenFunctions[array[i]]?array[i]=formatTokenFunctions[array[i]]:array[i]=(input=array[i]).match(/\[[\s\S]/)?input.replace(/^\[|\]$/g,""):input.replace(/\\/g,"");return function(mom){for(var output="",i=0;i<length;i++)output+=isFunction(array[i])?array[i].call(mom,format):array[i];return output}}(format),formatFunctions[format](m)):m.localeData().invalidDate()}function expandFormat(format,locale){var i=5;function replaceLongDateFormatTokens(input){return locale.longDateFormat(input)||input}for(localFormattingTokens.lastIndex=0;0<=i&&localFormattingTokens.test(format);)format=format.replace(localFormattingTokens,replaceLongDateFormatTokens),localFormattingTokens.lastIndex=0,--i;return format}var aliases={};function addUnitAlias(unit,shorthand){var lowerCase=unit.toLowerCase();aliases[lowerCase]=aliases[lowerCase+"s"]=aliases[shorthand]=unit}function normalizeUnits(units){return"string"==typeof units?aliases[units]||aliases[units.toLowerCase()]:void 0}function normalizeObjectUnits(inputObject){var normalizedProp,prop,normalizedInput={};for(prop in inputObject)hasOwnProp(inputObject,prop)&&(normalizedProp=normalizeUnits(prop))&&(normalizedInput[normalizedProp]=inputObject[prop]);return normalizedInput}var priorities={};function addUnitPriority(unit,priority){priorities[unit]=priority}function isLeapYear(year){return year%4==0&&year%100!=0||year%400==0}function absFloor(number){return number<0?Math.ceil(number)||0:Math.floor(number)}function toInt(argumentForCoercion){var argumentForCoercion=+argumentForCoercion,value=0;return value=0!=argumentForCoercion&&isFinite(argumentForCoercion)?absFloor(argumentForCoercion):value}function makeGetSet(unit,keepTime){return function(value){return null!=value?(set$1(this,unit,value),hooks.updateOffset(this,keepTime),this):get(this,unit)}}function get(mom,unit){return mom.isValid()?mom._d["get"+(mom._isUTC?"UTC":"")+unit]():NaN}function set$1(mom,unit,value){mom.isValid()&&!isNaN(value)&&("FullYear"===unit&&isLeapYear(mom.year())&&1===mom.month()&&29===mom.date()?(value=toInt(value),mom._d["set"+(mom._isUTC?"UTC":"")+unit](value,mom.month(),daysInMonth(value,mom.month()))):mom._d["set"+(mom._isUTC?"UTC":"")+unit](value))}var match1=/\d/,match2=/\d\d/,match3=/\d{3}/,match4=/\d{4}/,match6=/[+-]?\d{6}/,match1to2=/\d\d?/,match3to4=/\d\d\d\d?/,match5to6=/\d\d\d\d\d\d?/,match1to3=/\d{1,3}/,match1to4=/\d{1,4}/,match1to6=/[+-]?\d{1,6}/,matchUnsigned=/\d+/,matchSigned=/[+-]?\d+/,matchOffset=/Z|[+-]\d\d:?\d\d/gi,matchShortOffset=/Z|[+-]\d\d(?::?\d\d)?/gi,matchWord=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;function addRegexToken(token,regex,strictRegex){regexes[token]=isFunction(regex)?regex:function(isStrict,localeData){return isStrict&&strictRegex?strictRegex:regex}}function getParseRegexForToken(token,config){return hasOwnProp(regexes,token)?regexes[token](config._strict,config._locale):new RegExp(regexEscape(token.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(matched,p1,p2,p3,p4){return p1||p2||p3||p4})))}function regexEscape(s){return s.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var regexes={},tokens={};function addParseToken(token,callback){var i,tokenLen,func=callback;for("string"==typeof token&&(token=[token]),isNumber(callback)&&(func=function(input,array){array[callback]=toInt(input)}),tokenLen=token.length,i=0;i<tokenLen;i++)tokens[token[i]]=func}function addWeekParseToken(token,callback){addParseToken(token,function(input,array,config,token){config._w=config._w||{},callback(input,config._w,config,token)})}function addTimeToArrayFromToken(token,input,config){null!=input&&hasOwnProp(tokens,token)&&tokens[token](input,config._a,config,token)}var indexOf,YEAR=0,MONTH=1,DATE=2,HOUR=3,MINUTE=4,SECOND=5,MILLISECOND=6,WEEK=7,WEEKDAY=8;function daysInMonth(year,month){var x;return isNaN(year)||isNaN(month)?NaN:(x=(month%(x=12)+x)%x,year+=(month-x)/12,1==x?isLeapYear(year)?29:28:31-x%7%2)}indexOf=Array.prototype.indexOf||function(o){for(var i=0;i<this.length;++i)if(this[i]===o)return i;return-1},addFormatToken("M",["MM",2],"Mo",function(){return this.month()+1}),addFormatToken("MMM",0,0,function(format){return this.localeData().monthsShort(this,format)}),addFormatToken("MMMM",0,0,function(format){return this.localeData().months(this,format)}),addUnitAlias("month","M"),addUnitPriority("month",8),addRegexToken("M",match1to2),addRegexToken("MM",match1to2,match2),addRegexToken("MMM",function(isStrict,locale){return locale.monthsShortRegex(isStrict)}),addRegexToken("MMMM",function(isStrict,locale){return locale.monthsRegex(isStrict)}),addParseToken(["M","MM"],function(input,array){array[MONTH]=toInt(input)-1}),addParseToken(["MMM","MMMM"],function(input,array,config,token){token=config._locale.monthsParse(input,token,config._strict);null!=token?array[MONTH]=token:getParsingFlags(config).invalidMonth=input});var defaultLocaleMonths="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),defaultLocaleMonthsShort="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),MONTHS_IN_FORMAT=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,defaultMonthsShortRegex=matchWord,defaultMonthsRegex=matchWord;function setMonth(mom,value){var dayOfMonth;if(mom.isValid()){if("string"==typeof value)if(/^\d+$/.test(value))value=toInt(value);else if(!isNumber(value=mom.localeData().monthsParse(value)))return;dayOfMonth=Math.min(mom.date(),daysInMonth(mom.year(),value)),mom._d["set"+(mom._isUTC?"UTC":"")+"Month"](value,dayOfMonth)}}function getSetMonth(value){return null!=value?(setMonth(this,value),hooks.updateOffset(this,!0),this):get(this,"Month")}function computeMonthsParse(){function cmpLenRev(a,b){return b.length-a.length}for(var mom,shortPieces=[],longPieces=[],mixedPieces=[],i=0;i<12;i++)mom=createUTC([2e3,i]),shortPieces.push(this.monthsShort(mom,"")),longPieces.push(this.months(mom,"")),mixedPieces.push(this.months(mom,"")),mixedPieces.push(this.monthsShort(mom,""));for(shortPieces.sort(cmpLenRev),longPieces.sort(cmpLenRev),mixedPieces.sort(cmpLenRev),i=0;i<12;i++)shortPieces[i]=regexEscape(shortPieces[i]),longPieces[i]=regexEscape(longPieces[i]);for(i=0;i<24;i++)mixedPieces[i]=regexEscape(mixedPieces[i]);this._monthsRegex=new RegExp("^("+mixedPieces.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+longPieces.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+shortPieces.join("|")+")","i")}function daysInYear(year){return isLeapYear(year)?366:365}addFormatToken("Y",0,0,function(){var y=this.year();return y<=9999?zeroFill(y,4):"+"+y}),addFormatToken(0,["YY",2],0,function(){return this.year()%100}),addFormatToken(0,["YYYY",4],0,"year"),addFormatToken(0,["YYYYY",5],0,"year"),addFormatToken(0,["YYYYYY",6,!0],0,"year"),addUnitAlias("year","y"),addUnitPriority("year",1),addRegexToken("Y",matchSigned),addRegexToken("YY",match1to2,match2),addRegexToken("YYYY",match1to4,match4),addRegexToken("YYYYY",match1to6,match6),addRegexToken("YYYYYY",match1to6,match6),addParseToken(["YYYYY","YYYYYY"],YEAR),addParseToken("YYYY",function(input,array){array[YEAR]=2===input.length?hooks.parseTwoDigitYear(input):toInt(input)}),addParseToken("YY",function(input,array){array[YEAR]=hooks.parseTwoDigitYear(input)}),addParseToken("Y",function(input,array){array[YEAR]=parseInt(input,10)}),hooks.parseTwoDigitYear=function(input){return toInt(input)+(68<toInt(input)?1900:2e3)};var getSetYear=makeGetSet("FullYear",!0);function createDate(y,m,d,h,M,s,ms){var date;return y<100&&0<=y?(date=new Date(y+400,m,d,h,M,s,ms),isFinite(date.getFullYear())&&date.setFullYear(y)):date=new Date(y,m,d,h,M,s,ms),date}function createUTCDate(y){var args;return y<100&&0<=y?((args=Array.prototype.slice.call(arguments))[0]=y+400,args=new Date(Date.UTC.apply(null,args)),isFinite(args.getUTCFullYear())&&args.setUTCFullYear(y)):args=new Date(Date.UTC.apply(null,arguments)),args}function firstWeekOffset(year,dow,doy){doy=7+dow-doy;return doy-(7+createUTCDate(year,0,doy).getUTCDay()-dow)%7-1}function dayOfYearFromWeeks(year,week,weekday,dow,doy){var resYear,week=1+7*(week-1)+(7+weekday-dow)%7+firstWeekOffset(year,dow,doy),weekday=week<=0?daysInYear(resYear=year-1)+week:week>daysInYear(year)?(resYear=year+1,week-daysInYear(year)):(resYear=year,week);return{year:resYear,dayOfYear:weekday}}function weekOfYear(mom,dow,doy){var resWeek,resYear,weekOffset=firstWeekOffset(mom.year(),dow,doy),weekOffset=Math.floor((mom.dayOfYear()-weekOffset-1)/7)+1;return weekOffset<1?resWeek=weekOffset+weeksInYear(resYear=mom.year()-1,dow,doy):weekOffset>weeksInYear(mom.year(),dow,doy)?(resWeek=weekOffset-weeksInYear(mom.year(),dow,doy),resYear=mom.year()+1):(resYear=mom.year(),resWeek=weekOffset),{week:resWeek,year:resYear}}function weeksInYear(year,dow,doy){var weekOffset=firstWeekOffset(year,dow,doy),dow=firstWeekOffset(year+1,dow,doy);return(daysInYear(year)-weekOffset+dow)/7}addFormatToken("w",["ww",2],"wo","week"),addFormatToken("W",["WW",2],"Wo","isoWeek"),addUnitAlias("week","w"),addUnitAlias("isoWeek","W"),addUnitPriority("week",5),addUnitPriority("isoWeek",5),addRegexToken("w",match1to2),addRegexToken("ww",match1to2,match2),addRegexToken("W",match1to2),addRegexToken("WW",match1to2,match2),addWeekParseToken(["w","ww","W","WW"],function(input,week,config,token){week[token.substr(0,1)]=toInt(input)});function shiftWeekdays(ws,n){return ws.slice(n,7).concat(ws.slice(0,n))}addFormatToken("d",0,"do","day"),addFormatToken("dd",0,0,function(format){return this.localeData().weekdaysMin(this,format)}),addFormatToken("ddd",0,0,function(format){return this.localeData().weekdaysShort(this,format)}),addFormatToken("dddd",0,0,function(format){return this.localeData().weekdays(this,format)}),addFormatToken("e",0,0,"weekday"),addFormatToken("E",0,0,"isoWeekday"),addUnitAlias("day","d"),addUnitAlias("weekday","e"),addUnitAlias("isoWeekday","E"),addUnitPriority("day",11),addUnitPriority("weekday",11),addUnitPriority("isoWeekday",11),addRegexToken("d",match1to2),addRegexToken("e",match1to2),addRegexToken("E",match1to2),addRegexToken("dd",function(isStrict,locale){return locale.weekdaysMinRegex(isStrict)}),addRegexToken("ddd",function(isStrict,locale){return locale.weekdaysShortRegex(isStrict)}),addRegexToken("dddd",function(isStrict,locale){return locale.weekdaysRegex(isStrict)}),addWeekParseToken(["dd","ddd","dddd"],function(input,week,config,token){token=config._locale.weekdaysParse(input,token,config._strict);null!=token?week.d=token:getParsingFlags(config).invalidWeekday=input}),addWeekParseToken(["d","e","E"],function(input,week,config,token){week[token]=toInt(input)});var defaultLocaleWeekdays="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),defaultLocaleWeekdaysShort="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),defaultLocaleWeekdaysMin="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),defaultWeekdaysRegex=matchWord,defaultWeekdaysShortRegex=matchWord,defaultWeekdaysMinRegex=matchWord;function computeWeekdaysParse(){function cmpLenRev(a,b){return b.length-a.length}for(var minp,shortp,mom,minPieces=[],shortPieces=[],longPieces=[],mixedPieces=[],i=0;i<7;i++)mom=createUTC([2e3,1]).day(i),minp=regexEscape(this.weekdaysMin(mom,"")),shortp=regexEscape(this.weekdaysShort(mom,"")),mom=regexEscape(this.weekdays(mom,"")),minPieces.push(minp),shortPieces.push(shortp),longPieces.push(mom),mixedPieces.push(minp),mixedPieces.push(shortp),mixedPieces.push(mom);minPieces.sort(cmpLenRev),shortPieces.sort(cmpLenRev),longPieces.sort(cmpLenRev),mixedPieces.sort(cmpLenRev),this._weekdaysRegex=new RegExp("^("+mixedPieces.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+longPieces.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+shortPieces.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+minPieces.join("|")+")","i")}function hFormat(){return this.hours()%12||12}function meridiem(token,lowercase){addFormatToken(token,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),lowercase)})}function matchMeridiem(isStrict,locale){return locale._meridiemParse}addFormatToken("H",["HH",2],0,"hour"),addFormatToken("h",["hh",2],0,hFormat),addFormatToken("k",["kk",2],0,function(){return this.hours()||24}),addFormatToken("hmm",0,0,function(){return""+hFormat.apply(this)+zeroFill(this.minutes(),2)}),addFormatToken("hmmss",0,0,function(){return""+hFormat.apply(this)+zeroFill(this.minutes(),2)+zeroFill(this.seconds(),2)}),addFormatToken("Hmm",0,0,function(){return""+this.hours()+zeroFill(this.minutes(),2)}),addFormatToken("Hmmss",0,0,function(){return""+this.hours()+zeroFill(this.minutes(),2)+zeroFill(this.seconds(),2)}),meridiem("a",!0),meridiem("A",!1),addUnitAlias("hour","h"),addUnitPriority("hour",13),addRegexToken("a",matchMeridiem),addRegexToken("A",matchMeridiem),addRegexToken("H",match1to2),addRegexToken("h",match1to2),addRegexToken("k",match1to2),addRegexToken("HH",match1to2,match2),addRegexToken("hh",match1to2,match2),addRegexToken("kk",match1to2,match2),addRegexToken("hmm",match3to4),addRegexToken("hmmss",match5to6),addRegexToken("Hmm",match3to4),addRegexToken("Hmmss",match5to6),addParseToken(["H","HH"],HOUR),addParseToken(["k","kk"],function(input,array,config){input=toInt(input);array[HOUR]=24===input?0:input}),addParseToken(["a","A"],function(input,array,config){config._isPm=config._locale.isPM(input),config._meridiem=input}),addParseToken(["h","hh"],function(input,array,config){array[HOUR]=toInt(input),getParsingFlags(config).bigHour=!0}),addParseToken("hmm",function(input,array,config){var pos=input.length-2;array[HOUR]=toInt(input.substr(0,pos)),array[MINUTE]=toInt(input.substr(pos)),getParsingFlags(config).bigHour=!0}),addParseToken("hmmss",function(input,array,config){var pos1=input.length-4,pos2=input.length-2;array[HOUR]=toInt(input.substr(0,pos1)),array[MINUTE]=toInt(input.substr(pos1,2)),array[SECOND]=toInt(input.substr(pos2)),getParsingFlags(config).bigHour=!0}),addParseToken("Hmm",function(input,array,config){var pos=input.length-2;array[HOUR]=toInt(input.substr(0,pos)),array[MINUTE]=toInt(input.substr(pos))}),addParseToken("Hmmss",function(input,array,config){var pos1=input.length-4,pos2=input.length-2;array[HOUR]=toInt(input.substr(0,pos1)),array[MINUTE]=toInt(input.substr(pos1,2)),array[SECOND]=toInt(input.substr(pos2))});matchWord=makeGetSet("Hours",!0);var globalLocale,baseConfig={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:defaultLocaleMonths,monthsShort:defaultLocaleMonthsShort,week:{dow:0,doy:6},weekdays:defaultLocaleWeekdays,weekdaysMin:defaultLocaleWeekdaysMin,weekdaysShort:defaultLocaleWeekdaysShort,meridiemParse:/[ap]\.?m?\.?/i},locales={},localeFamilies={};function normalizeLocale(key){return key&&key.toLowerCase().replace("_","-")}function chooseLocale(names){for(var j,next,locale,split,i=0;i<names.length;){for(j=(split=normalizeLocale(names[i]).split("-")).length,next=(next=normalizeLocale(names[i+1]))?next.split("-"):null;0<j;){if(locale=loadLocale(split.slice(0,j).join("-")))return locale;if(next&&next.length>=j&&function(arr1,arr2){for(var minl=Math.min(arr1.length,arr2.length),i=0;i<minl;i+=1)if(arr1[i]!==arr2[i])return i;return minl}(split,next)>=j-1)break;j--}i++}return globalLocale}function loadLocale(name){var oldLocale;if(void 0===locales[name]&&void 0!==module&&module&&module.exports&&null!=name.match("^[^/\\\\]*$"))try{oldLocale=globalLocale._abbr,require("./locale/"+name),getSetGlobalLocale(oldLocale)}catch(e){locales[name]=null}return locales[name]}function getSetGlobalLocale(key,values){return key&&((values=void 0===values?getLocale(key):defineLocale(key,values))?globalLocale=values:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+key+" not found. Did you forget to load it?")),globalLocale._abbr}function defineLocale(name,config){if(null===config)return delete locales[name],null;var locale,parentConfig=baseConfig;if(config.abbr=name,null!=locales[name])deprecateSimple("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),parentConfig=locales[name]._config;else if(null!=config.parentLocale)if(null!=locales[config.parentLocale])parentConfig=locales[config.parentLocale]._config;else{if(null==(locale=loadLocale(config.parentLocale)))return localeFamilies[config.parentLocale]||(localeFamilies[config.parentLocale]=[]),localeFamilies[config.parentLocale].push({name:name,config:config}),null;parentConfig=locale._config}return locales[name]=new Locale(mergeConfigs(parentConfig,config)),localeFamilies[name]&&localeFamilies[name].forEach(function(x){defineLocale(x.name,x.config)}),getSetGlobalLocale(name),locales[name]}function getLocale(key){var locale;if(!(key=key&&key._locale&&key._locale._abbr?key._locale._abbr:key))return globalLocale;if(!isArray(key)){if(locale=loadLocale(key))return locale;key=[key]}return chooseLocale(key)}function checkOverflow(m){var a=m._a;return a&&-2===getParsingFlags(m).overflow&&(a=a[MONTH]<0||11<a[MONTH]?MONTH:a[DATE]<1||a[DATE]>daysInMonth(a[YEAR],a[MONTH])?DATE:a[HOUR]<0||24<a[HOUR]||24===a[HOUR]&&(0!==a[MINUTE]||0!==a[SECOND]||0!==a[MILLISECOND])?HOUR:a[MINUTE]<0||59<a[MINUTE]?MINUTE:a[SECOND]<0||59<a[SECOND]?SECOND:a[MILLISECOND]<0||999<a[MILLISECOND]?MILLISECOND:-1,getParsingFlags(m)._overflowDayOfYear&&(a<YEAR||DATE<a)&&(a=DATE),getParsingFlags(m)._overflowWeeks&&-1===a&&(a=WEEK),getParsingFlags(m)._overflowWeekday&&-1===a&&(a=WEEKDAY),getParsingFlags(m).overflow=a),m}var extendedIsoRegex=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,basicIsoRegex=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,tzRegex=/Z|[+-]\d\d(?::?\d\d)?/,isoDates=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],isoTimes=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],aspNetJsonRegex=/^\/?Date\((-?\d+)/i,rfc2822=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,obsOffsets={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function configFromISO(config){var i,l,allowTime,dateFormat,timeFormat,tzFormat,string=config._i,match=extendedIsoRegex.exec(string)||basicIsoRegex.exec(string),string=isoDates.length,isoTimesLen=isoTimes.length;if(match){for(getParsingFlags(config).iso=!0,i=0,l=string;i<l;i++)if(isoDates[i][1].exec(match[1])){dateFormat=isoDates[i][0],allowTime=!1!==isoDates[i][2];break}if(null==dateFormat)config._isValid=!1;else{if(match[3]){for(i=0,l=isoTimesLen;i<l;i++)if(isoTimes[i][1].exec(match[3])){timeFormat=(match[2]||" ")+isoTimes[i][0];break}if(null==timeFormat)return void(config._isValid=!1)}if(allowTime||null==timeFormat){if(match[4]){if(!tzRegex.exec(match[4]))return void(config._isValid=!1);tzFormat="Z"}config._f=dateFormat+(timeFormat||"")+(tzFormat||""),configFromStringAndFormat(config)}else config._isValid=!1}}else config._isValid=!1}function extractFromRFC2822Strings(yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr){yearStr=[function(yearStr){yearStr=parseInt(yearStr,10);{if(yearStr<=49)return 2e3+yearStr;if(yearStr<=999)return 1900+yearStr}return yearStr}(yearStr),defaultLocaleMonthsShort.indexOf(monthStr),parseInt(dayStr,10),parseInt(hourStr,10),parseInt(minuteStr,10)];return secondStr&&yearStr.push(parseInt(secondStr,10)),yearStr}function configFromRFC2822(config){var parsedArray,militaryOffset,match=rfc2822.exec(config._i.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,""));match?(parsedArray=extractFromRFC2822Strings(match[4],match[3],match[2],match[5],match[6],match[7]),function(weekdayStr,parsedInput,config){if(!weekdayStr||defaultLocaleWeekdaysShort.indexOf(weekdayStr)===new Date(parsedInput[0],parsedInput[1],parsedInput[2]).getDay())return 1;getParsingFlags(config).weekdayMismatch=!0,config._isValid=!1}(match[1],parsedArray,config)&&(config._a=parsedArray,config._tzm=(parsedArray=match[8],militaryOffset=match[9],match=match[10],parsedArray?obsOffsets[parsedArray]:militaryOffset?0:60*(((parsedArray=parseInt(match,10))-(militaryOffset=parsedArray%100))/100)+militaryOffset),config._d=createUTCDate.apply(null,config._a),config._d.setUTCMinutes(config._d.getUTCMinutes()-config._tzm),getParsingFlags(config).rfc2822=!0)):config._isValid=!1}function defaults(a,b,c){return null!=a?a:null!=b?b:c}function configFromArray(config){var i,currentDate,yearToUse,input=[];if(!config._d){for(currentDate=function(config){var nowValue=new Date(hooks.now());return config._useUTC?[nowValue.getUTCFullYear(),nowValue.getUTCMonth(),nowValue.getUTCDate()]:[nowValue.getFullYear(),nowValue.getMonth(),nowValue.getDate()]}(config),config._w&&null==config._a[DATE]&&null==config._a[MONTH]&&!function(config){var w,weekYear,week,weekday,dow,doy,weekdayOverflow,curWeek;null!=(w=config._w).GG||null!=w.W||null!=w.E?(dow=1,doy=4,weekYear=defaults(w.GG,config._a[YEAR],weekOfYear(createLocal(),1,4).year),week=defaults(w.W,1),((weekday=defaults(w.E,1))<1||7<weekday)&&(weekdayOverflow=!0)):(dow=config._locale._week.dow,doy=config._locale._week.doy,curWeek=weekOfYear(createLocal(),dow,doy),weekYear=defaults(w.gg,config._a[YEAR],curWeek.year),week=defaults(w.w,curWeek.week),null!=w.d?((weekday=w.d)<0||6<weekday)&&(weekdayOverflow=!0):null!=w.e?(weekday=w.e+dow,(w.e<0||6<w.e)&&(weekdayOverflow=!0)):weekday=dow);week<1||week>weeksInYear(weekYear,dow,doy)?getParsingFlags(config)._overflowWeeks=!0:null!=weekdayOverflow?getParsingFlags(config)._overflowWeekday=!0:(curWeek=dayOfYearFromWeeks(weekYear,week,weekday,dow,doy),config._a[YEAR]=curWeek.year,config._dayOfYear=curWeek.dayOfYear)}(config),null!=config._dayOfYear&&(yearToUse=defaults(config._a[YEAR],currentDate[YEAR]),(config._dayOfYear>daysInYear(yearToUse)||0===config._dayOfYear)&&(getParsingFlags(config)._overflowDayOfYear=!0),yearToUse=createUTCDate(yearToUse,0,config._dayOfYear),config._a[MONTH]=yearToUse.getUTCMonth(),config._a[DATE]=yearToUse.getUTCDate()),i=0;i<3&&null==config._a[i];++i)config._a[i]=input[i]=currentDate[i];for(;i<7;i++)config._a[i]=input[i]=null==config._a[i]?2===i?1:0:config._a[i];24===config._a[HOUR]&&0===config._a[MINUTE]&&0===config._a[SECOND]&&0===config._a[MILLISECOND]&&(config._nextDay=!0,config._a[HOUR]=0),config._d=(config._useUTC?createUTCDate:createDate).apply(null,input),yearToUse=config._useUTC?config._d.getUTCDay():config._d.getDay(),null!=config._tzm&&config._d.setUTCMinutes(config._d.getUTCMinutes()-config._tzm),config._nextDay&&(config._a[HOUR]=24),config._w&&void 0!==config._w.d&&config._w.d!==yearToUse&&(getParsingFlags(config).weekdayMismatch=!0)}}function configFromStringAndFormat(config){if(config._f===hooks.ISO_8601)configFromISO(config);else if(config._f===hooks.RFC_2822)configFromRFC2822(config);else{config._a=[],getParsingFlags(config).empty=!0;for(var parsedInput,token,skipped,string=""+config._i,stringLength=string.length,totalParsedInputLength=0,tokens=expandFormat(config._f,config._locale).match(formattingTokens)||[],tokenLen=tokens.length,i=0;i<tokenLen;i++)token=tokens[i],(parsedInput=(string.match(getParseRegexForToken(token,config))||[])[0])&&(0<(skipped=string.substr(0,string.indexOf(parsedInput))).length&&getParsingFlags(config).unusedInput.push(skipped),string=string.slice(string.indexOf(parsedInput)+parsedInput.length),totalParsedInputLength+=parsedInput.length),formatTokenFunctions[token]?(parsedInput?getParsingFlags(config).empty=!1:getParsingFlags(config).unusedTokens.push(token),addTimeToArrayFromToken(token,parsedInput,config)):config._strict&&!parsedInput&&getParsingFlags(config).unusedTokens.push(token);getParsingFlags(config).charsLeftOver=stringLength-totalParsedInputLength,0<string.length&&getParsingFlags(config).unusedInput.push(string),config._a[HOUR]<=12&&!0===getParsingFlags(config).bigHour&&0<config._a[HOUR]&&(getParsingFlags(config).bigHour=void 0),getParsingFlags(config).parsedDateParts=config._a.slice(0),getParsingFlags(config).meridiem=config._meridiem,config._a[HOUR]=function(locale,hour,meridiem){if(null==meridiem)return hour;return null!=locale.meridiemHour?locale.meridiemHour(hour,meridiem):null!=locale.isPM?((locale=locale.isPM(meridiem))&&hour<12&&(hour+=12),hour=locale||12!==hour?hour:0):hour}(config._locale,config._a[HOUR],config._meridiem),null!==(stringLength=getParsingFlags(config).era)&&(config._a[YEAR]=config._locale.erasConvertYear(stringLength,config._a[YEAR])),configFromArray(config),checkOverflow(config)}}function prepareConfig(config){var input=config._i,format=config._f;return config._locale=config._locale||getLocale(config._l),null===input||void 0===format&&""===input?createInvalid({nullInput:!0}):("string"==typeof input&&(config._i=input=config._locale.preparse(input)),isMoment(input)?new Moment(checkOverflow(input)):(isDate(input)?config._d=input:(isArray(format)?function(config){var tempConfig,bestMoment,scoreToBeat,i,currentScore,validFormatFound,bestFormatIsValid=!1,configfLen=config._f.length;if(0===configfLen)getParsingFlags(config).invalidFormat=!0,config._d=new Date(NaN);else{for(i=0;i<configfLen;i++)currentScore=0,validFormatFound=!1,tempConfig=copyConfig({},config),null!=config._useUTC&&(tempConfig._useUTC=config._useUTC),tempConfig._f=config._f[i],configFromStringAndFormat(tempConfig),isValid(tempConfig)&&(validFormatFound=!0),currentScore=(currentScore+=getParsingFlags(tempConfig).charsLeftOver)+10*getParsingFlags(tempConfig).unusedTokens.length,getParsingFlags(tempConfig).score=currentScore,bestFormatIsValid?currentScore<scoreToBeat&&(scoreToBeat=currentScore,bestMoment=tempConfig):(null==scoreToBeat||currentScore<scoreToBeat||validFormatFound)&&(scoreToBeat=currentScore,bestMoment=tempConfig,validFormatFound)&&(bestFormatIsValid=!0);extend(config,bestMoment||tempConfig)}}:format?configFromStringAndFormat:function(config){var input=config._i;void 0===input?config._d=new Date(hooks.now()):isDate(input)?config._d=new Date(input.valueOf()):"string"==typeof input?function(config){var matched=aspNetJsonRegex.exec(config._i);null!==matched?config._d=new Date(+matched[1]):(configFromISO(config),!1===config._isValid&&(delete config._isValid,configFromRFC2822(config),!1===config._isValid)&&(delete config._isValid,config._strict?config._isValid=!1:hooks.createFromInputFallback(config)))}(config):isArray(input)?(config._a=map(input.slice(0),function(obj){return parseInt(obj,10)}),configFromArray(config)):isObject(input)?function(config){var i,dayOrDate;config._d||(dayOrDate=void 0===(i=normalizeObjectUnits(config._i)).day?i.date:i.day,config._a=map([i.year,i.month,dayOrDate,i.hour,i.minute,i.second,i.millisecond],function(obj){return obj&&parseInt(obj,10)}),configFromArray(config))}(config):isNumber(input)?config._d=new Date(input):hooks.createFromInputFallback(config)})(config),isValid(config)||(config._d=null),config))}function createLocalOrUTC(input,format,locale,strict,isUTC){var c={};return!0!==format&&!1!==format||(strict=format,format=void 0),!0!==locale&&!1!==locale||(strict=locale,locale=void 0),(isObject(input)&&isObjectEmpty(input)||isArray(input)&&0===input.length)&&(input=void 0),c._isAMomentObject=!0,c._useUTC=c._isUTC=isUTC,c._l=locale,c._i=input,c._f=format,c._strict=strict,(isUTC=new Moment(checkOverflow(prepareConfig(isUTC=c))))._nextDay&&(isUTC.add(1,"d"),isUTC._nextDay=void 0),isUTC}function createLocal(input,format,locale,strict){return createLocalOrUTC(input,format,locale,strict,!1)}hooks.createFromInputFallback=deprecate("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(config){config._d=new Date(config._i+(config._useUTC?" UTC":""))}),hooks.ISO_8601=function(){},hooks.RFC_2822=function(){};match3to4=deprecate("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var other=createLocal.apply(null,arguments);return this.isValid()&&other.isValid()?other<this?this:other:createInvalid()}),match5to6=deprecate("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var other=createLocal.apply(null,arguments);return this.isValid()&&other.isValid()?this<other?this:other:createInvalid()});function pickBy(fn,moments){var res,i;if(!(moments=1===moments.length&&isArray(moments[0])?moments[0]:moments).length)return createLocal();for(res=moments[0],i=1;i<moments.length;++i)moments[i].isValid()&&!moments[i][fn](res)||(res=moments[i]);return res}var ordering=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Duration(duration){var duration=normalizeObjectUnits(duration),years=duration.year||0,quarters=duration.quarter||0,months=duration.month||0,weeks=duration.week||duration.isoWeek||0,days=duration.day||0,hours=duration.hour||0,minutes=duration.minute||0,seconds=duration.second||0,milliseconds=duration.millisecond||0;this._isValid=function(m){var key,i,unitHasDecimal=!1,orderLen=ordering.length;for(key in m)if(hasOwnProp(m,key)&&(-1===indexOf.call(ordering,key)||null!=m[key]&&isNaN(m[key])))return!1;for(i=0;i<orderLen;++i)if(m[ordering[i]]){if(unitHasDecimal)return!1;parseFloat(m[ordering[i]])!==toInt(m[ordering[i]])&&(unitHasDecimal=!0)}return!0}(duration),this._milliseconds=+milliseconds+1e3*seconds+6e4*minutes+1e3*hours*60*60,this._days=+days+7*weeks,this._months=+months+3*quarters+12*years,this._data={},this._locale=getLocale(),this._bubble()}function isDuration(obj){return obj instanceof Duration}function absRound(number){return number<0?-1*Math.round(-1*number):Math.round(number)}function offset(token,separator){addFormatToken(token,0,0,function(){var offset=this.utcOffset(),sign="+";return offset<0&&(offset=-offset,sign="-"),sign+zeroFill(~~(offset/60),2)+separator+zeroFill(~~offset%60,2)})}offset("Z",":"),offset("ZZ",""),addRegexToken("Z",matchShortOffset),addRegexToken("ZZ",matchShortOffset),addParseToken(["Z","ZZ"],function(input,array,config){config._useUTC=!0,config._tzm=offsetFromString(matchShortOffset,input)});var chunkOffset=/([\+\-]|\d\d)/gi;function offsetFromString(matcher,string){var string=(string||"").match(matcher);return null===string?null:0===(string=60*(matcher=((string[string.length-1]||[])+"").match(chunkOffset)||["-",0,0])[1]+toInt(matcher[2]))?0:"+"===matcher[0]?string:-string}function cloneWithOffset(input,model){var diff;return model._isUTC?(model=model.clone(),diff=(isMoment(input)||isDate(input)?input:createLocal(input)).valueOf()-model.valueOf(),model._d.setTime(model._d.valueOf()+diff),hooks.updateOffset(model,!1),model):createLocal(input).local()}function getDateOffset(m){return-Math.round(m._d.getTimezoneOffset())}function isUtc(){return!!this.isValid()&&this._isUTC&&0===this._offset}hooks.updateOffset=function(){};var aspNetRegex=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,isoRegex=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function createDuration(input,key){var sign,duration=input;return isDuration(input)?duration={ms:input._milliseconds,d:input._days,M:input._months}:isNumber(input)||!isNaN(+input)?(duration={},key?duration[key]=+input:duration.milliseconds=+input):(key=aspNetRegex.exec(input))?(sign="-"===key[1]?-1:1,duration={y:0,d:toInt(key[DATE])*sign,h:toInt(key[HOUR])*sign,m:toInt(key[MINUTE])*sign,s:toInt(key[SECOND])*sign,ms:toInt(absRound(1e3*key[MILLISECOND]))*sign}):(key=isoRegex.exec(input))?(sign="-"===key[1]?-1:1,duration={y:parseIso(key[2],sign),M:parseIso(key[3],sign),w:parseIso(key[4],sign),d:parseIso(key[5],sign),h:parseIso(key[6],sign),m:parseIso(key[7],sign),s:parseIso(key[8],sign)}):null==duration?duration={}:"object"==typeof duration&&("from"in duration||"to"in duration)&&(key=function(base,other){var res;if(!base.isValid()||!other.isValid())return{milliseconds:0,months:0};other=cloneWithOffset(other,base),base.isBefore(other)?res=positiveMomentsDifference(base,other):((res=positiveMomentsDifference(other,base)).milliseconds=-res.milliseconds,res.months=-res.months);return res}(createLocal(duration.from),createLocal(duration.to)),(duration={}).ms=key.milliseconds,duration.M=key.months),sign=new Duration(duration),isDuration(input)&&hasOwnProp(input,"_locale")&&(sign._locale=input._locale),isDuration(input)&&hasOwnProp(input,"_isValid")&&(sign._isValid=input._isValid),sign}function parseIso(inp,sign){inp=inp&&parseFloat(inp.replace(",","."));return(isNaN(inp)?0:inp)*sign}function positiveMomentsDifference(base,other){var res={};return res.months=other.month()-base.month()+12*(other.year()-base.year()),base.clone().add(res.months,"M").isAfter(other)&&--res.months,res.milliseconds=+other-+base.clone().add(res.months,"M"),res}function createAdder(direction,name){return function(val,period){var tmp;return null===period||isNaN(+period)||(deprecateSimple(name,"moment()."+name+"(period, number) is deprecated. Please use moment()."+name+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),tmp=val,val=period,period=tmp),addSubtract(this,createDuration(val,period),direction),this}}function addSubtract(mom,duration,isAdding,updateOffset){var milliseconds=duration._milliseconds,days=absRound(duration._days),duration=absRound(duration._months);mom.isValid()&&(updateOffset=null==updateOffset||updateOffset,duration&&setMonth(mom,get(mom,"Month")+duration*isAdding),days&&set$1(mom,"Date",get(mom,"Date")+days*isAdding),milliseconds&&mom._d.setTime(mom._d.valueOf()+milliseconds*isAdding),updateOffset)&&hooks.updateOffset(mom,days||duration)}createDuration.fn=Duration.prototype,createDuration.invalid=function(){return createDuration(NaN)};defaultLocaleMonths=createAdder(1,"add"),defaultLocaleWeekdays=createAdder(-1,"subtract");function isString(input){return"string"==typeof input||input instanceof String}function isMomentInput(input){return isMoment(input)||isDate(input)||isString(input)||isNumber(input)||function(input){var arrayTest=isArray(input),dataTypeTest=!1;arrayTest&&(dataTypeTest=0===input.filter(function(item){return!isNumber(item)&&isString(input)}).length);return arrayTest&&dataTypeTest}(input)||function(input){var i,property,objectTest=isObject(input)&&!isObjectEmpty(input),propertyTest=!1,properties=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],propertyLen=properties.length;for(i=0;i<propertyLen;i+=1)property=properties[i],propertyTest=propertyTest||hasOwnProp(input,property);return objectTest&&propertyTest}(input)||null==input}function monthDiff(a,b){var wholeMonthDiff,anchor;return a.date()<b.date()?-monthDiff(b,a):-((wholeMonthDiff=12*(b.year()-a.year())+(b.month()-a.month()))+(b-(anchor=a.clone().add(wholeMonthDiff,"months"))<0?(b-anchor)/(anchor-a.clone().add(wholeMonthDiff-1,"months")):(b-anchor)/(a.clone().add(1+wholeMonthDiff,"months")-anchor)))||0}function locale(key){return void 0===key?this._locale._abbr:(null!=(key=getLocale(key))&&(this._locale=key),this)}hooks.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",hooks.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";defaultLocaleWeekdaysMin=deprecate("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(key){return void 0===key?this.localeData():this.locale(key)});function localeData(){return this._locale}var MS_PER_400_YEARS=126227808e5;function mod$1(dividend,divisor){return(dividend%divisor+divisor)%divisor}function localStartOfDate(y,m,d){return y<100&&0<=y?new Date(y+400,m,d)-MS_PER_400_YEARS:new Date(y,m,d).valueOf()}function utcStartOfDate(y,m,d){return y<100&&0<=y?Date.UTC(y+400,m,d)-MS_PER_400_YEARS:Date.UTC(y,m,d)}function matchEraAbbr(isStrict,locale){return locale.erasAbbrRegex(isStrict)}function computeErasParse(){for(var abbrPieces=[],namePieces=[],narrowPieces=[],mixedPieces=[],eras=this.eras(),i=0,l=eras.length;i<l;++i)namePieces.push(regexEscape(eras[i].name)),abbrPieces.push(regexEscape(eras[i].abbr)),narrowPieces.push(regexEscape(eras[i].narrow)),mixedPieces.push(regexEscape(eras[i].name)),mixedPieces.push(regexEscape(eras[i].abbr)),mixedPieces.push(regexEscape(eras[i].narrow));this._erasRegex=new RegExp("^("+mixedPieces.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+namePieces.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+abbrPieces.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+narrowPieces.join("|")+")","i")}function addWeekYearFormatToken(token,getter){addFormatToken(0,[token,token.length],0,getter)}function getSetWeekYearHelper(input,week,weekday,dow,doy){var weeksTarget;return null==input?weekOfYear(this,dow,doy).year:(weeksTarget=weeksInYear(input,dow,doy),function(weekYear,week,weekday,dow,doy){weekYear=dayOfYearFromWeeks(weekYear,week,weekday,dow,doy),week=createUTCDate(weekYear.year,0,weekYear.dayOfYear);return this.year(week.getUTCFullYear()),this.month(week.getUTCMonth()),this.date(week.getUTCDate()),this}.call(this,input,week=weeksTarget<week?weeksTarget:week,weekday,dow,doy))}addFormatToken("N",0,0,"eraAbbr"),addFormatToken("NN",0,0,"eraAbbr"),addFormatToken("NNN",0,0,"eraAbbr"),addFormatToken("NNNN",0,0,"eraName"),addFormatToken("NNNNN",0,0,"eraNarrow"),addFormatToken("y",["y",1],"yo","eraYear"),addFormatToken("y",["yy",2],0,"eraYear"),addFormatToken("y",["yyy",3],0,"eraYear"),addFormatToken("y",["yyyy",4],0,"eraYear"),addRegexToken("N",matchEraAbbr),addRegexToken("NN",matchEraAbbr),addRegexToken("NNN",matchEraAbbr),addRegexToken("NNNN",function(isStrict,locale){return locale.erasNameRegex(isStrict)}),addRegexToken("NNNNN",function(isStrict,locale){return locale.erasNarrowRegex(isStrict)}),addParseToken(["N","NN","NNN","NNNN","NNNNN"],function(input,array,config,token){token=config._locale.erasParse(input,token,config._strict);token?getParsingFlags(config).era=token:getParsingFlags(config).invalidEra=input}),addRegexToken("y",matchUnsigned),addRegexToken("yy",matchUnsigned),addRegexToken("yyy",matchUnsigned),addRegexToken("yyyy",matchUnsigned),addRegexToken("yo",function(isStrict,locale){return locale._eraYearOrdinalRegex||matchUnsigned}),addParseToken(["y","yy","yyy","yyyy"],YEAR),addParseToken(["yo"],function(input,array,config,token){var match;config._locale._eraYearOrdinalRegex&&(match=input.match(config._locale._eraYearOrdinalRegex)),config._locale.eraYearOrdinalParse?array[YEAR]=config._locale.eraYearOrdinalParse(input,match):array[YEAR]=parseInt(input,10)}),addFormatToken(0,["gg",2],0,function(){return this.weekYear()%100}),addFormatToken(0,["GG",2],0,function(){return this.isoWeekYear()%100}),addWeekYearFormatToken("gggg","weekYear"),addWeekYearFormatToken("ggggg","weekYear"),addWeekYearFormatToken("GGGG","isoWeekYear"),addWeekYearFormatToken("GGGGG","isoWeekYear"),addUnitAlias("weekYear","gg"),addUnitAlias("isoWeekYear","GG"),addUnitPriority("weekYear",1),addUnitPriority("isoWeekYear",1),addRegexToken("G",matchSigned),addRegexToken("g",matchSigned),addRegexToken("GG",match1to2,match2),addRegexToken("gg",match1to2,match2),addRegexToken("GGGG",match1to4,match4),addRegexToken("gggg",match1to4,match4),addRegexToken("GGGGG",match1to6,match6),addRegexToken("ggggg",match1to6,match6),addWeekParseToken(["gggg","ggggg","GGGG","GGGGG"],function(input,week,config,token){week[token.substr(0,2)]=toInt(input)}),addWeekParseToken(["gg","GG"],function(input,week,config,token){week[token]=hooks.parseTwoDigitYear(input)}),addFormatToken("Q",0,"Qo","quarter"),addUnitAlias("quarter","Q"),addUnitPriority("quarter",7),addRegexToken("Q",match1),addParseToken("Q",function(input,array){array[MONTH]=3*(toInt(input)-1)}),addFormatToken("D",["DD",2],"Do","date"),addUnitAlias("date","D"),addUnitPriority("date",9),addRegexToken("D",match1to2),addRegexToken("DD",match1to2,match2),addRegexToken("Do",function(isStrict,locale){return isStrict?locale._dayOfMonthOrdinalParse||locale._ordinalParse:locale._dayOfMonthOrdinalParseLenient}),addParseToken(["D","DD"],DATE),addParseToken("Do",function(input,array){array[DATE]=toInt(input.match(match1to2)[0])});match1to4=makeGetSet("Date",!0);addFormatToken("DDD",["DDDD",3],"DDDo","dayOfYear"),addUnitAlias("dayOfYear","DDD"),addUnitPriority("dayOfYear",4),addRegexToken("DDD",match1to3),addRegexToken("DDDD",match3),addParseToken(["DDD","DDDD"],function(input,array,config){config._dayOfYear=toInt(input)}),addFormatToken("m",["mm",2],0,"minute"),addUnitAlias("minute","m"),addUnitPriority("minute",14),addRegexToken("m",match1to2),addRegexToken("mm",match1to2,match2),addParseToken(["m","mm"],MINUTE);var token,match4=makeGetSet("Minutes",!1),match1to6=(addFormatToken("s",["ss",2],0,"second"),addUnitAlias("second","s"),addUnitPriority("second",15),addRegexToken("s",match1to2),addRegexToken("ss",match1to2,match2),addParseToken(["s","ss"],SECOND),makeGetSet("Seconds",!1));for(addFormatToken("S",0,0,function(){return~~(this.millisecond()/100)}),addFormatToken(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),addFormatToken(0,["SSS",3],0,"millisecond"),addFormatToken(0,["SSSS",4],0,function(){return 10*this.millisecond()}),addFormatToken(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),addFormatToken(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),addFormatToken(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),addFormatToken(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),addFormatToken(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),addUnitAlias("millisecond","ms"),addUnitPriority("millisecond",16),addRegexToken("S",match1to3,match1),addRegexToken("SS",match1to3,match2),addRegexToken("SSS",match1to3,match3),token="SSSS";token.length<=9;token+="S")addRegexToken(token,matchUnsigned);function parseMs(input,array){array[MILLISECOND]=toInt(1e3*("0."+input))}for(token="S";token.length<=9;token+="S")addParseToken(token,parseMs);match6=makeGetSet("Milliseconds",!1),addFormatToken("z",0,0,"zoneAbbr"),addFormatToken("zz",0,0,"zoneName");match1=Moment.prototype;function preParsePostFormat(string){return string}match1.add=defaultLocaleMonths,match1.calendar=function(time,formats){1===arguments.length&&(arguments[0]?isMomentInput(arguments[0])?(time=arguments[0],formats=void 0):function(input){for(var objectTest=isObject(input)&&!isObjectEmpty(input),propertyTest=!1,properties=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],i=0;i<properties.length;i+=1)propertyTest=propertyTest||hasOwnProp(input,properties[i]);return objectTest&&propertyTest}(arguments[0])&&(formats=arguments[0],time=void 0):formats=time=void 0);var time=time||createLocal(),sod=cloneWithOffset(time,this).startOf("day"),sod=hooks.calendarFormat(this,sod)||"sameElse",formats=formats&&(isFunction(formats[sod])?formats[sod].call(this,time):formats[sod]);return this.format(formats||this.localeData().calendar(sod,this,createLocal(time)))},match1.clone=function(){return new Moment(this)},match1.diff=function(input,units,asFloat){var that,zoneDelta,output;if(!this.isValid())return NaN;if(!(that=cloneWithOffset(input,this)).isValid())return NaN;switch(zoneDelta=6e4*(that.utcOffset()-this.utcOffset()),units=normalizeUnits(units)){case"year":output=monthDiff(this,that)/12;break;case"month":output=monthDiff(this,that);break;case"quarter":output=monthDiff(this,that)/3;break;case"second":output=(this-that)/1e3;break;case"minute":output=(this-that)/6e4;break;case"hour":output=(this-that)/36e5;break;case"day":output=(this-that-zoneDelta)/864e5;break;case"week":output=(this-that-zoneDelta)/6048e5;break;default:output=this-that}return asFloat?output:absFloor(output)},match1.endOf=function(units){var time,startOfDate;if(void 0!==(units=normalizeUnits(units))&&"millisecond"!==units&&this.isValid()){switch(startOfDate=this._isUTC?utcStartOfDate:localStartOfDate,units){case"year":time=startOfDate(this.year()+1,0,1)-1;break;case"quarter":time=startOfDate(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":time=startOfDate(this.year(),this.month()+1,1)-1;break;case"week":time=startOfDate(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":time=startOfDate(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":time=startOfDate(this.year(),this.month(),this.date()+1)-1;break;case"hour":time=this._d.valueOf(),time+=36e5-mod$1(time+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":time=this._d.valueOf(),time+=6e4-mod$1(time,6e4)-1;break;case"second":time=this._d.valueOf(),time+=1e3-mod$1(time,1e3)-1}this._d.setTime(time),hooks.updateOffset(this,!0)}return this},match1.format=function(inputString){return inputString=inputString||(this.isUtc()?hooks.defaultFormatUtc:hooks.defaultFormat),inputString=formatMoment(this,inputString),this.localeData().postformat(inputString)},match1.from=function(time,withoutSuffix){return this.isValid()&&(isMoment(time)&&time.isValid()||createLocal(time).isValid())?createDuration({to:this,from:time}).locale(this.locale()).humanize(!withoutSuffix):this.localeData().invalidDate()},match1.fromNow=function(withoutSuffix){return this.from(createLocal(),withoutSuffix)},match1.to=function(time,withoutSuffix){return this.isValid()&&(isMoment(time)&&time.isValid()||createLocal(time).isValid())?createDuration({from:this,to:time}).locale(this.locale()).humanize(!withoutSuffix):this.localeData().invalidDate()},match1.toNow=function(withoutSuffix){return this.to(createLocal(),withoutSuffix)},match1.get=function(units){return isFunction(this[units=normalizeUnits(units)])?this[units]():this},match1.invalidAt=function(){return getParsingFlags(this).overflow},match1.isAfter=function(input,units){return input=isMoment(input)?input:createLocal(input),!(!this.isValid()||!input.isValid())&&("millisecond"===(units=normalizeUnits(units)||"millisecond")?this.valueOf()>input.valueOf():input.valueOf()<this.clone().startOf(units).valueOf())},match1.isBefore=function(input,units){return input=isMoment(input)?input:createLocal(input),!(!this.isValid()||!input.isValid())&&("millisecond"===(units=normalizeUnits(units)||"millisecond")?this.valueOf()<input.valueOf():this.clone().endOf(units).valueOf()<input.valueOf())},match1.isBetween=function(from,to,units,inclusivity){return from=isMoment(from)?from:createLocal(from),to=isMoment(to)?to:createLocal(to),!!(this.isValid()&&from.isValid()&&to.isValid())&&("("===(inclusivity=inclusivity||"()")[0]?this.isAfter(from,units):!this.isBefore(from,units))&&(")"===inclusivity[1]?this.isBefore(to,units):!this.isAfter(to,units))},match1.isSame=function(input,units){var input=isMoment(input)?input:createLocal(input);return!(!this.isValid()||!input.isValid())&&("millisecond"===(units=normalizeUnits(units)||"millisecond")?this.valueOf()===input.valueOf():(input=input.valueOf(),this.clone().startOf(units).valueOf()<=input&&input<=this.clone().endOf(units).valueOf()))},match1.isSameOrAfter=function(input,units){return this.isSame(input,units)||this.isAfter(input,units)},match1.isSameOrBefore=function(input,units){return this.isSame(input,units)||this.isBefore(input,units)},match1.isValid=function(){return isValid(this)},match1.lang=defaultLocaleWeekdaysMin,match1.locale=locale,match1.localeData=localeData,match1.max=match5to6,match1.min=match3to4,match1.parsingFlags=function(){return extend({},getParsingFlags(this))},match1.set=function(units,value){if("object"==typeof units)for(var prioritized=function(unitsObj){var u,units=[];for(u in unitsObj)hasOwnProp(unitsObj,u)&&units.push({unit:u,priority:priorities[u]});return units.sort(function(a,b){return a.priority-b.priority}),units}(units=normalizeObjectUnits(units)),prioritizedLen=prioritized.length,i=0;i<prioritizedLen;i++)this[prioritized[i].unit](units[prioritized[i].unit]);else if(isFunction(this[units=normalizeUnits(units)]))return this[units](value);return this},match1.startOf=function(units){var time,startOfDate;if(void 0!==(units=normalizeUnits(units))&&"millisecond"!==units&&this.isValid()){switch(startOfDate=this._isUTC?utcStartOfDate:localStartOfDate,units){case"year":time=startOfDate(this.year(),0,1);break;case"quarter":time=startOfDate(this.year(),this.month()-this.month()%3,1);break;case"month":time=startOfDate(this.year(),this.month(),1);break;case"week":time=startOfDate(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":time=startOfDate(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":time=startOfDate(this.year(),this.month(),this.date());break;case"hour":time=this._d.valueOf(),time-=mod$1(time+(this._isUTC?0:6e4*this.utcOffset()),36e5);break;case"minute":time=this._d.valueOf(),time-=mod$1(time,6e4);break;case"second":time=this._d.valueOf(),time-=mod$1(time,1e3)}this._d.setTime(time),hooks.updateOffset(this,!0)}return this},match1.subtract=defaultLocaleWeekdays,match1.toArray=function(){var m=this;return[m.year(),m.month(),m.date(),m.hour(),m.minute(),m.second(),m.millisecond()]},match1.toObject=function(){var m=this;return{years:m.year(),months:m.month(),date:m.date(),hours:m.hours(),minutes:m.minutes(),seconds:m.seconds(),milliseconds:m.milliseconds()}},match1.toDate=function(){return new Date(this.valueOf())},match1.toISOString=function(keepOffset){var m;return this.isValid()?(m=(keepOffset=!0!==keepOffset)?this.clone().utc():this).year()<0||9999<m.year()?formatMoment(m,keepOffset?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):isFunction(Date.prototype.toISOString)?keepOffset?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",formatMoment(m,"Z")):formatMoment(m,keepOffset?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ"):null},match1.inspect=function(){var zone,func,year;return this.isValid()?(func="moment",zone="",this.isLocal()||(func=0===this.utcOffset()?"moment.utc":"moment.parseZone",zone="Z"),func="["+func+'("]',year=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",this.format(func+year+"-MM-DD[T]HH:mm:ss.SSS"+(zone+'[")]'))):"moment.invalid(/* "+this._i+" */)"},"undefined"!=typeof Symbol&&null!=Symbol.for&&(match1[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),match1.toJSON=function(){return this.isValid()?this.toISOString():null},match1.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},match1.unix=function(){return Math.floor(this.valueOf()/1e3)},match1.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},match1.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},match1.eraName=function(){for(var val,eras=this.localeData().eras(),i=0,l=eras.length;i<l;++i){if(val=this.clone().startOf("day").valueOf(),eras[i].since<=val&&val<=eras[i].until)return eras[i].name;if(eras[i].until<=val&&val<=eras[i].since)return eras[i].name}return""},match1.eraNarrow=function(){for(var val,eras=this.localeData().eras(),i=0,l=eras.length;i<l;++i){if(val=this.clone().startOf("day").valueOf(),eras[i].since<=val&&val<=eras[i].until)return eras[i].narrow;if(eras[i].until<=val&&val<=eras[i].since)return eras[i].narrow}return""},match1.eraAbbr=function(){for(var val,eras=this.localeData().eras(),i=0,l=eras.length;i<l;++i){if(val=this.clone().startOf("day").valueOf(),eras[i].since<=val&&val<=eras[i].until)return eras[i].abbr;if(eras[i].until<=val&&val<=eras[i].since)return eras[i].abbr}return""},match1.eraYear=function(){for(var dir,val,eras=this.localeData().eras(),i=0,l=eras.length;i<l;++i)if(dir=eras[i].since<=eras[i].until?1:-1,val=this.clone().startOf("day").valueOf(),eras[i].since<=val&&val<=eras[i].until||eras[i].until<=val&&val<=eras[i].since)return(this.year()-hooks(eras[i].since).year())*dir+eras[i].offset;return this.year()},match1.year=getSetYear,match1.isLeapYear=function(){return isLeapYear(this.year())},match1.weekYear=function(input){return getSetWeekYearHelper.call(this,input,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},match1.isoWeekYear=function(input){return getSetWeekYearHelper.call(this,input,this.isoWeek(),this.isoWeekday(),1,4)},match1.quarter=match1.quarters=function(input){return null==input?Math.ceil((this.month()+1)/3):this.month(3*(input-1)+this.month()%3)},match1.month=getSetMonth,match1.daysInMonth=function(){return daysInMonth(this.year(),this.month())},match1.week=match1.weeks=function(input){var week=this.localeData().week(this);return null==input?week:this.add(7*(input-week),"d")},match1.isoWeek=match1.isoWeeks=function(input){var week=weekOfYear(this,1,4).week;return null==input?week:this.add(7*(input-week),"d")},match1.weeksInYear=function(){var weekInfo=this.localeData()._week;return weeksInYear(this.year(),weekInfo.dow,weekInfo.doy)},match1.weeksInWeekYear=function(){var weekInfo=this.localeData()._week;return weeksInYear(this.weekYear(),weekInfo.dow,weekInfo.doy)},match1.isoWeeksInYear=function(){return weeksInYear(this.year(),1,4)},match1.isoWeeksInISOWeekYear=function(){return weeksInYear(this.isoWeekYear(),1,4)},match1.date=match1to4,match1.day=match1.days=function(input){var day;return this.isValid()?(day=this._isUTC?this._d.getUTCDay():this._d.getDay(),null!=input?(input=function(input,locale){return"string"!=typeof input?input:isNaN(input)?"number"==typeof(input=locale.weekdaysParse(input))?input:null:parseInt(input,10)}(input,this.localeData()),this.add(input-day,"d")):day):null!=input?this:NaN},match1.weekday=function(input){var weekday;return this.isValid()?(weekday=(this.day()+7-this.localeData()._week.dow)%7,null==input?weekday:this.add(input-weekday,"d")):null!=input?this:NaN},match1.isoWeekday=function(input){var weekday;return this.isValid()?null!=input?(weekday=function(input,locale){return"string"==typeof input?locale.weekdaysParse(input)%7||7:isNaN(input)?null:input}(input,this.localeData()),this.day(this.day()%7?weekday:weekday-7)):this.day()||7:null!=input?this:NaN},match1.dayOfYear=function(input){var dayOfYear=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==input?dayOfYear:this.add(input-dayOfYear,"d")},match1.hour=match1.hours=matchWord,match1.minute=match1.minutes=match4,match1.second=match1.seconds=match1to6,match1.millisecond=match1.milliseconds=match6,match1.utcOffset=function(input,keepLocalTime,keepMinutes){var localAdjust,offset=this._offset||0;if(!this.isValid())return null!=input?this:NaN;if(null==input)return this._isUTC?offset:getDateOffset(this);if("string"==typeof input){if(null===(input=offsetFromString(matchShortOffset,input)))return this}else Math.abs(input)<16&&!keepMinutes&&(input*=60);return!this._isUTC&&keepLocalTime&&(localAdjust=getDateOffset(this)),this._offset=input,this._isUTC=!0,null!=localAdjust&&this.add(localAdjust,"m"),offset!==input&&(!keepLocalTime||this._changeInProgress?addSubtract(this,createDuration(input-offset,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,hooks.updateOffset(this,!0),this._changeInProgress=null)),this},match1.utc=function(keepLocalTime){return this.utcOffset(0,keepLocalTime)},match1.local=function(keepLocalTime){return this._isUTC&&(this.utcOffset(0,keepLocalTime),this._isUTC=!1,keepLocalTime)&&this.subtract(getDateOffset(this),"m"),this},match1.parseZone=function(){var tZone;return null!=this._tzm?this.utcOffset(this._tzm,!1,!0):"string"==typeof this._i&&(null!=(tZone=offsetFromString(matchOffset,this._i))?this.utcOffset(tZone):this.utcOffset(0,!0)),this},match1.hasAlignedHourOffset=function(input){return!!this.isValid()&&(input=input?createLocal(input).utcOffset():0,(this.utcOffset()-input)%60==0)},match1.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},match1.isLocal=function(){return!!this.isValid()&&!this._isUTC},match1.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},match1.isUtc=isUtc,match1.isUTC=isUtc,match1.zoneAbbr=function(){return this._isUTC?"UTC":""},match1.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},match1.dates=deprecate("dates accessor is deprecated. Use date instead.",match1to4),match1.months=deprecate("months accessor is deprecated. Use month instead",getSetMonth),match1.years=deprecate("years accessor is deprecated. Use year instead",getSetYear),match1.zone=deprecate("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(input,keepLocalTime){return null!=input?(this.utcOffset(input="string"!=typeof input?-input:input,keepLocalTime),this):-this.utcOffset()}),match1.isDSTShifted=deprecate("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){var c,other;return void 0===this._isDSTShifted&&(copyConfig(c={},this),(c=prepareConfig(c))._a?(other=(c._isUTC?createUTC:createLocal)(c._a),this._isDSTShifted=this.isValid()&&0<function(array1,array2,dontConvert){for(var len=Math.min(array1.length,array2.length),lengthDiff=Math.abs(array1.length-array2.length),diffs=0,i=0;i<len;i++)(dontConvert&&array1[i]!==array2[i]||!dontConvert&&toInt(array1[i])!==toInt(array2[i]))&&diffs++;return diffs+lengthDiff}(c._a,other.toArray())):this._isDSTShifted=!1),this._isDSTShifted});match2=Locale.prototype;function get$1(format,index,field,setter){var locale=getLocale(),setter=createUTC().set(setter,index);return locale[field](setter,format)}function listMonthsImpl(format,index,field){if(isNumber(format)&&(index=format,format=void 0),format=format||"",null!=index)return get$1(format,index,field,"month");for(var out=[],i=0;i<12;i++)out[i]=get$1(format,i,field,"month");return out}function listWeekdaysImpl(localeSorted,format,index,field){format=("boolean"==typeof localeSorted?isNumber(format)&&(index=format,format=void 0):(format=localeSorted,localeSorted=!1,isNumber(index=format)&&(index=format,format=void 0)),format||"");var i,locale=getLocale(),shift=localeSorted?locale._week.dow:0,out=[];if(null!=index)return get$1(format,(index+shift)%7,field,"day");for(i=0;i<7;i++)out[i]=get$1(format,(i+shift)%7,field,"day");return out}match2.calendar=function(key,mom,now){return isFunction(key=this._calendar[key]||this._calendar.sameElse)?key.call(mom,now):key},match2.longDateFormat=function(key){var format=this._longDateFormat[key],formatUpper=this._longDateFormat[key.toUpperCase()];return format||!formatUpper?format:(this._longDateFormat[key]=formatUpper.match(formattingTokens).map(function(tok){return"MMMM"===tok||"MM"===tok||"DD"===tok||"dddd"===tok?tok.slice(1):tok}).join(""),this._longDateFormat[key])},match2.invalidDate=function(){return this._invalidDate},match2.ordinal=function(number){return this._ordinal.replace("%d",number)},match2.preparse=preParsePostFormat,match2.postformat=preParsePostFormat,match2.relativeTime=function(number,withoutSuffix,string,isFuture){var output=this._relativeTime[string];return isFunction(output)?output(number,withoutSuffix,string,isFuture):output.replace(/%d/i,number)},match2.pastFuture=function(diff,output){return isFunction(diff=this._relativeTime[0<diff?"future":"past"])?diff(output):diff.replace(/%s/i,output)},match2.set=function(config){var prop,i;for(i in config)hasOwnProp(config,i)&&(isFunction(prop=config[i])?this[i]=prop:this["_"+i]=prop);this._config=config,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},match2.eras=function(m,format){for(var date,eras=this._eras||getLocale("en")._eras,i=0,l=eras.length;i<l;++i)switch("string"==typeof eras[i].since&&(date=hooks(eras[i].since).startOf("day"),eras[i].since=date.valueOf()),typeof eras[i].until){case"undefined":eras[i].until=1/0;break;case"string":date=hooks(eras[i].until).startOf("day").valueOf(),eras[i].until=date.valueOf()}return eras},match2.erasParse=function(eraName,format,strict){var i,l,name,abbr,narrow,eras=this.eras();for(eraName=eraName.toUpperCase(),i=0,l=eras.length;i<l;++i)if(name=eras[i].name.toUpperCase(),abbr=eras[i].abbr.toUpperCase(),narrow=eras[i].narrow.toUpperCase(),strict)switch(format){case"N":case"NN":case"NNN":if(abbr===eraName)return eras[i];break;case"NNNN":if(name===eraName)return eras[i];break;case"NNNNN":if(narrow===eraName)return eras[i]}else if(0<=[name,abbr,narrow].indexOf(eraName))return eras[i]},match2.erasConvertYear=function(era,year){var dir=era.since<=era.until?1:-1;return void 0===year?hooks(era.since).year():hooks(era.since).year()+(year-era.offset)*dir},match2.erasAbbrRegex=function(isStrict){return hasOwnProp(this,"_erasAbbrRegex")||computeErasParse.call(this),isStrict?this._erasAbbrRegex:this._erasRegex},match2.erasNameRegex=function(isStrict){return hasOwnProp(this,"_erasNameRegex")||computeErasParse.call(this),isStrict?this._erasNameRegex:this._erasRegex},match2.erasNarrowRegex=function(isStrict){return hasOwnProp(this,"_erasNarrowRegex")||computeErasParse.call(this),isStrict?this._erasNarrowRegex:this._erasRegex},match2.months=function(m,format){return m?(isArray(this._months)?this._months:this._months[(this._months.isFormat||MONTHS_IN_FORMAT).test(format)?"format":"standalone"])[m.month()]:isArray(this._months)?this._months:this._months.standalone},match2.monthsShort=function(m,format){return m?(isArray(this._monthsShort)?this._monthsShort:this._monthsShort[MONTHS_IN_FORMAT.test(format)?"format":"standalone"])[m.month()]:isArray(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},match2.monthsParse=function(monthName,format,strict){var i,mom;if(this._monthsParseExact)return function(monthName,format,strict){var i,ii,mom,monthName=monthName.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],i=0;i<12;++i)mom=createUTC([2e3,i]),this._shortMonthsParse[i]=this.monthsShort(mom,"").toLocaleLowerCase(),this._longMonthsParse[i]=this.months(mom,"").toLocaleLowerCase();return strict?"MMM"===format?-1!==(ii=indexOf.call(this._shortMonthsParse,monthName))?ii:null:-1!==(ii=indexOf.call(this._longMonthsParse,monthName))?ii:null:"MMM"===format?-1!==(ii=indexOf.call(this._shortMonthsParse,monthName))||-1!==(ii=indexOf.call(this._longMonthsParse,monthName))?ii:null:-1!==(ii=indexOf.call(this._longMonthsParse,monthName))||-1!==(ii=indexOf.call(this._shortMonthsParse,monthName))?ii:null}.call(this,monthName,format,strict);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),i=0;i<12;i++){if(mom=createUTC([2e3,i]),strict&&!this._longMonthsParse[i]&&(this._longMonthsParse[i]=new RegExp("^"+this.months(mom,"").replace(".","")+"$","i"),this._shortMonthsParse[i]=new RegExp("^"+this.monthsShort(mom,"").replace(".","")+"$","i")),strict||this._monthsParse[i]||(mom="^"+this.months(mom,"")+"|^"+this.monthsShort(mom,""),this._monthsParse[i]=new RegExp(mom.replace(".",""),"i")),strict&&"MMMM"===format&&this._longMonthsParse[i].test(monthName))return i;if(strict&&"MMM"===format&&this._shortMonthsParse[i].test(monthName))return i;if(!strict&&this._monthsParse[i].test(monthName))return i}},match2.monthsRegex=function(isStrict){return this._monthsParseExact?(hasOwnProp(this,"_monthsRegex")||computeMonthsParse.call(this),isStrict?this._monthsStrictRegex:this._monthsRegex):(hasOwnProp(this,"_monthsRegex")||(this._monthsRegex=defaultMonthsRegex),this._monthsStrictRegex&&isStrict?this._monthsStrictRegex:this._monthsRegex)},match2.monthsShortRegex=function(isStrict){return this._monthsParseExact?(hasOwnProp(this,"_monthsRegex")||computeMonthsParse.call(this),isStrict?this._monthsShortStrictRegex:this._monthsShortRegex):(hasOwnProp(this,"_monthsShortRegex")||(this._monthsShortRegex=defaultMonthsShortRegex),this._monthsShortStrictRegex&&isStrict?this._monthsShortStrictRegex:this._monthsShortRegex)},match2.week=function(mom){return weekOfYear(mom,this._week.dow,this._week.doy).week},match2.firstDayOfYear=function(){return this._week.doy},match2.firstDayOfWeek=function(){return this._week.dow},match2.weekdays=function(m,format){return format=isArray(this._weekdays)?this._weekdays:this._weekdays[m&&!0!==m&&this._weekdays.isFormat.test(format)?"format":"standalone"],!0===m?shiftWeekdays(format,this._week.dow):m?format[m.day()]:format},match2.weekdaysMin=function(m){return!0===m?shiftWeekdays(this._weekdaysMin,this._week.dow):m?this._weekdaysMin[m.day()]:this._weekdaysMin},match2.weekdaysShort=function(m){return!0===m?shiftWeekdays(this._weekdaysShort,this._week.dow):m?this._weekdaysShort[m.day()]:this._weekdaysShort},match2.weekdaysParse=function(weekdayName,format,strict){var i,mom;if(this._weekdaysParseExact)return function(weekdayName,format,strict){var i,ii,mom,weekdayName=weekdayName.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],i=0;i<7;++i)mom=createUTC([2e3,1]).day(i),this._minWeekdaysParse[i]=this.weekdaysMin(mom,"").toLocaleLowerCase(),this._shortWeekdaysParse[i]=this.weekdaysShort(mom,"").toLocaleLowerCase(),this._weekdaysParse[i]=this.weekdays(mom,"").toLocaleLowerCase();return strict?"dddd"===format?-1!==(ii=indexOf.call(this._weekdaysParse,weekdayName))?ii:null:"ddd"===format?-1!==(ii=indexOf.call(this._shortWeekdaysParse,weekdayName))?ii:null:-1!==(ii=indexOf.call(this._minWeekdaysParse,weekdayName))?ii:null:"dddd"===format?-1!==(ii=indexOf.call(this._weekdaysParse,weekdayName))||-1!==(ii=indexOf.call(this._shortWeekdaysParse,weekdayName))||-1!==(ii=indexOf.call(this._minWeekdaysParse,weekdayName))?ii:null:"ddd"===format?-1!==(ii=indexOf.call(this._shortWeekdaysParse,weekdayName))||-1!==(ii=indexOf.call(this._weekdaysParse,weekdayName))||-1!==(ii=indexOf.call(this._minWeekdaysParse,weekdayName))?ii:null:-1!==(ii=indexOf.call(this._minWeekdaysParse,weekdayName))||-1!==(ii=indexOf.call(this._weekdaysParse,weekdayName))||-1!==(ii=indexOf.call(this._shortWeekdaysParse,weekdayName))?ii:null}.call(this,weekdayName,format,strict);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),i=0;i<7;i++){if(mom=createUTC([2e3,1]).day(i),strict&&!this._fullWeekdaysParse[i]&&(this._fullWeekdaysParse[i]=new RegExp("^"+this.weekdays(mom,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[i]=new RegExp("^"+this.weekdaysShort(mom,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[i]=new RegExp("^"+this.weekdaysMin(mom,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[i]||(mom="^"+this.weekdays(mom,"")+"|^"+this.weekdaysShort(mom,"")+"|^"+this.weekdaysMin(mom,""),this._weekdaysParse[i]=new RegExp(mom.replace(".",""),"i")),strict&&"dddd"===format&&this._fullWeekdaysParse[i].test(weekdayName))return i;if(strict&&"ddd"===format&&this._shortWeekdaysParse[i].test(weekdayName))return i;if(strict&&"dd"===format&&this._minWeekdaysParse[i].test(weekdayName))return i;if(!strict&&this._weekdaysParse[i].test(weekdayName))return i}},match2.weekdaysRegex=function(isStrict){return this._weekdaysParseExact?(hasOwnProp(this,"_weekdaysRegex")||computeWeekdaysParse.call(this),isStrict?this._weekdaysStrictRegex:this._weekdaysRegex):(hasOwnProp(this,"_weekdaysRegex")||(this._weekdaysRegex=defaultWeekdaysRegex),this._weekdaysStrictRegex&&isStrict?this._weekdaysStrictRegex:this._weekdaysRegex)},match2.weekdaysShortRegex=function(isStrict){return this._weekdaysParseExact?(hasOwnProp(this,"_weekdaysRegex")||computeWeekdaysParse.call(this),isStrict?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(hasOwnProp(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=defaultWeekdaysShortRegex),this._weekdaysShortStrictRegex&&isStrict?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},match2.weekdaysMinRegex=function(isStrict){return this._weekdaysParseExact?(hasOwnProp(this,"_weekdaysRegex")||computeWeekdaysParse.call(this),isStrict?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(hasOwnProp(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=defaultWeekdaysMinRegex),this._weekdaysMinStrictRegex&&isStrict?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},match2.isPM=function(input){return"p"===(input+"").toLowerCase().charAt(0)},match2.meridiem=function(hours,minutes,isLower){return 11<hours?isLower?"pm":"PM":isLower?"am":"AM"},getSetGlobalLocale("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(number){var b=number%10;return number+(1===toInt(number%100/10)?"th":1==b?"st":2==b?"nd":3==b?"rd":"th")}}),hooks.lang=deprecate("moment.lang is deprecated. Use moment.locale instead.",getSetGlobalLocale),hooks.langData=deprecate("moment.langData is deprecated. Use moment.localeData instead.",getLocale);var mathAbs=Math.abs;function addSubtract$1(duration,input,value,direction){input=createDuration(input,value);return duration._milliseconds+=direction*input._milliseconds,duration._days+=direction*input._days,duration._months+=direction*input._months,duration._bubble()}function absCeil(number){return number<0?Math.floor(number):Math.ceil(number)}function makeAs(alias){return function(){return this.as(alias)}}match1to3=makeAs("ms"),match3=makeAs("s"),defaultLocaleMonths=makeAs("m"),match5to6=makeAs("h"),match3to4=makeAs("d"),defaultLocaleWeekdays=makeAs("w"),matchWord=makeAs("M"),match4=makeAs("Q"),match1to6=makeAs("y");function makeGetter(name){return function(){return this.isValid()?this._data[name]:NaN}}var match6=makeGetter("milliseconds"),match1to4=makeGetter("seconds"),getSetYear=makeGetter("minutes"),match2=makeGetter("hours"),days=makeGetter("days"),months=makeGetter("months"),years=makeGetter("years");var round=Math.round,thresholds={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function relativeTime$1(posNegDuration,withoutSuffix,thresholds,locale){var duration=createDuration(posNegDuration).abs(),seconds=round(duration.as("s")),minutes=round(duration.as("m")),hours=round(duration.as("h")),days=round(duration.as("d")),months=round(duration.as("M")),weeks=round(duration.as("w")),duration=round(duration.as("y")),seconds=(seconds<=thresholds.ss?["s",seconds]:seconds<thresholds.s&&["ss",seconds])||(minutes<=1?["m"]:minutes<thresholds.m&&["mm",minutes])||(hours<=1?["h"]:hours<thresholds.h&&["hh",hours])||(days<=1?["d"]:days<thresholds.d&&["dd",days]);return(seconds=(seconds=null!=thresholds.w?seconds||(weeks<=1?["w"]:weeks<thresholds.w&&["ww",weeks]):seconds)||(months<=1?["M"]:months<thresholds.M&&["MM",months])||(duration<=1?["y"]:["yy",duration]))[2]=withoutSuffix,seconds[3]=0<+posNegDuration,seconds[4]=locale,function(string,number,withoutSuffix,isFuture,locale){return locale.relativeTime(number||1,!!withoutSuffix,string,isFuture)}.apply(null,seconds)}var abs$1=Math.abs;function sign(x){return(0<x)-(x<0)||+x}function toISOString$1(){var seconds,days,months,minutes,hours,years,s,total,ymSign,daysSign,hmsSign;return this.isValid()?(seconds=abs$1(this._milliseconds)/1e3,days=abs$1(this._days),months=abs$1(this._months),(total=this.asSeconds())?(minutes=absFloor(seconds/60),hours=absFloor(minutes/60),seconds%=60,minutes%=60,years=absFloor(months/12),months%=12,s=seconds?seconds.toFixed(3).replace(/\.?0+$/,""):"",ymSign=sign(this._months)!==sign(total)?"-":"",daysSign=sign(this._days)!==sign(total)?"-":"",hmsSign=sign(this._milliseconds)!==sign(total)?"-":"",(total<0?"-":"")+"P"+(years?ymSign+years+"Y":"")+(months?ymSign+months+"M":"")+(days?daysSign+days+"D":"")+(hours||minutes||seconds?"T":"")+(hours?hmsSign+hours+"H":"")+(minutes?hmsSign+minutes+"M":"")+(seconds?hmsSign+s+"S":"")):"P0D"):this.localeData().invalidDate()}var proto$2=Duration.prototype;return proto$2.isValid=function(){return this._isValid},proto$2.abs=function(){var data=this._data;return this._milliseconds=mathAbs(this._milliseconds),this._days=mathAbs(this._days),this._months=mathAbs(this._months),data.milliseconds=mathAbs(data.milliseconds),data.seconds=mathAbs(data.seconds),data.minutes=mathAbs(data.minutes),data.hours=mathAbs(data.hours),data.months=mathAbs(data.months),data.years=mathAbs(data.years),this},proto$2.add=function(input,value){return addSubtract$1(this,input,value,1)},proto$2.subtract=function(input,value){return addSubtract$1(this,input,value,-1)},proto$2.as=function(units){if(!this.isValid())return NaN;var days,months,milliseconds=this._milliseconds;if("month"===(units=normalizeUnits(units))||"quarter"===units||"year"===units)switch(days=this._days+milliseconds/864e5,months=this._months+4800*days/146097,units){case"month":return months;case"quarter":return months/3;case"year":return months/12}else switch(days=this._days+Math.round(146097*this._months/4800),units){case"week":return days/7+milliseconds/6048e5;case"day":return days+milliseconds/864e5;case"hour":return 24*days+milliseconds/36e5;case"minute":return 1440*days+milliseconds/6e4;case"second":return 86400*days+milliseconds/1e3;case"millisecond":return Math.floor(864e5*days)+milliseconds;default:throw new Error("Unknown unit "+units)}},proto$2.asMilliseconds=match1to3,proto$2.asSeconds=match3,proto$2.asMinutes=defaultLocaleMonths,proto$2.asHours=match5to6,proto$2.asDays=match3to4,proto$2.asWeeks=defaultLocaleWeekdays,proto$2.asMonths=matchWord,proto$2.asQuarters=match4,proto$2.asYears=match1to6,proto$2.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*toInt(this._months/12):NaN},proto$2._bubble=function(){var milliseconds=this._milliseconds,days=this._days,months=this._months,data=this._data;return 0<=milliseconds&&0<=days&&0<=months||milliseconds<=0&&days<=0&&months<=0||(milliseconds+=864e5*absCeil(146097*months/4800+days),months=days=0),data.milliseconds=milliseconds%1e3,milliseconds=absFloor(milliseconds/1e3),data.seconds=milliseconds%60,milliseconds=absFloor(milliseconds/60),data.minutes=milliseconds%60,milliseconds=absFloor(milliseconds/60),data.hours=milliseconds%24,days+=absFloor(milliseconds/24),months+=milliseconds=absFloor(4800*days/146097),days-=absCeil(146097*milliseconds/4800),milliseconds=absFloor(months/12),months%=12,data.days=days,data.months=months,data.years=milliseconds,this},proto$2.clone=function(){return createDuration(this)},proto$2.get=function(units){return units=normalizeUnits(units),this.isValid()?this[units+"s"]():NaN},proto$2.milliseconds=match6,proto$2.seconds=match1to4,proto$2.minutes=getSetYear,proto$2.hours=match2,proto$2.days=days,proto$2.weeks=function(){return absFloor(this.days()/7)},proto$2.months=months,proto$2.years=years,proto$2.humanize=function(argWithSuffix,argThresholds){var withSuffix,th;return this.isValid()?(withSuffix=!1,th=thresholds,"object"==typeof argWithSuffix&&(argThresholds=argWithSuffix,argWithSuffix=!1),"boolean"==typeof argWithSuffix&&(withSuffix=argWithSuffix),"object"==typeof argThresholds&&(th=Object.assign({},thresholds,argThresholds),null!=argThresholds.s)&&null==argThresholds.ss&&(th.ss=argThresholds.s-1),argWithSuffix=this.localeData(),argThresholds=relativeTime$1(this,!withSuffix,th,argWithSuffix),withSuffix&&(argThresholds=argWithSuffix.pastFuture(+this,argThresholds)),argWithSuffix.postformat(argThresholds)):this.localeData().invalidDate()},proto$2.toISOString=toISOString$1,proto$2.toString=toISOString$1,proto$2.toJSON=toISOString$1,proto$2.locale=locale,proto$2.localeData=localeData,proto$2.toIsoString=deprecate("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",toISOString$1),proto$2.lang=defaultLocaleWeekdaysMin,addFormatToken("X",0,0,"unix"),addFormatToken("x",0,0,"valueOf"),addRegexToken("x",matchSigned),addRegexToken("X",/[+-]?\d+(\.\d{1,3})?/),addParseToken("X",function(input,array,config){config._d=new Date(1e3*parseFloat(input))}),addParseToken("x",function(input,array,config){config._d=new Date(toInt(input))}),hooks.version="2.29.4",hookCallback=createLocal,hooks.fn=match1,hooks.min=function(){return pickBy("isBefore",[].slice.call(arguments,0))},hooks.max=function(){return pickBy("isAfter",[].slice.call(arguments,0))},hooks.now=function(){return Date.now?Date.now():+new Date},hooks.utc=createUTC,hooks.unix=function(input){return createLocal(1e3*input)},hooks.months=function(format,index){return listMonthsImpl(format,index,"months")},hooks.isDate=isDate,hooks.locale=getSetGlobalLocale,hooks.invalid=createInvalid,hooks.duration=createDuration,hooks.isMoment=isMoment,hooks.weekdays=function(localeSorted,format,index){return listWeekdaysImpl(localeSorted,format,index,"weekdays")},hooks.parseZone=function(){return createLocal.apply(null,arguments).parseZone()},hooks.localeData=getLocale,hooks.isDuration=isDuration,hooks.monthsShort=function(format,index){return listMonthsImpl(format,index,"monthsShort")},hooks.weekdaysMin=function(localeSorted,format,index){return listWeekdaysImpl(localeSorted,format,index,"weekdaysMin")},hooks.defineLocale=defineLocale,hooks.updateLocale=function(name,config){var tmpLocale,parentConfig;return null!=config?(parentConfig=baseConfig,null!=locales[name]&&null!=locales[name].parentLocale?locales[name].set(mergeConfigs(locales[name]._config,config)):(config=mergeConfigs(parentConfig=null!=(tmpLocale=loadLocale(name))?tmpLocale._config:parentConfig,config),null==tmpLocale&&(config.abbr=name),(parentConfig=new Locale(config)).parentLocale=locales[name],locales[name]=parentConfig),getSetGlobalLocale(name)):null!=locales[name]&&(null!=locales[name].parentLocale?(locales[name]=locales[name].parentLocale,name===getSetGlobalLocale()&&getSetGlobalLocale(name)):null!=locales[name]&&delete locales[name]),locales[name]},hooks.locales=function(){return keys(locales)},hooks.weekdaysShort=function(localeSorted,format,index){return listWeekdaysImpl(localeSorted,format,index,"weekdaysShort")},hooks.normalizeUnits=normalizeUnits,hooks.relativeTimeRounding=function(roundingFunction){return void 0===roundingFunction?round:"function"==typeof roundingFunction&&(round=roundingFunction,!0)},hooks.relativeTimeThreshold=function(threshold,limit){return void 0!==thresholds[threshold]&&(void 0===limit?thresholds[threshold]:(thresholds[threshold]=limit,"s"===threshold&&(thresholds.ss=limit-1),!0))},hooks.calendarFormat=function(myMoment,now){return(myMoment=myMoment.diff(now,"days",!0))<-6?"sameElse":myMoment<-1?"lastWeek":myMoment<0?"lastDay":myMoment<1?"sameDay":myMoment<2?"nextDay":myMoment<7?"nextWeek":"sameElse"},hooks.prototype=match1,hooks.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},hooks},"object"==typeof exports&&void 0!==module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):global.moment=factory()},{}],1032:[function(require,module,exports){"use strict";var getOwnPropertySymbols=Object.getOwnPropertySymbols,hasOwnProperty=Object.prototype.hasOwnProperty,propIsEnumerable=Object.prototype.propertyIsEnumerable;module.exports=function(){try{if(Object.assign){var test1=new String("abc");if(test1[5]="de","5"!==Object.getOwnPropertyNames(test1)[0]){for(var test2={},i=0;i<10;i++)test2["_"+String.fromCharCode(i)]=i;var test3,order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n]});if("0123456789"===order2.join(""))return test3={},"abcdefghijklmnopqrst".split("").forEach(function(letter){test3[letter]=letter}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},test3)).join("")?1:void 0}}}catch(err){}}()?Object.assign:function(target,source){for(var from,to=function(val){if(null==val)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(val)}(target),s=1;s<arguments.length;s++){for(var key in from=Object(arguments[s]))hasOwnProperty.call(from,key)&&(to[key]=from[key]);if(getOwnPropertySymbols)for(var symbols=getOwnPropertySymbols(from),i=0;i<symbols.length;i++)propIsEnumerable.call(from,symbols[i])&&(to[symbols[i]]=from[symbols[i]])}return to}},{}],1033:[function(require,module,exports){"use strict";function numberIsNaN(value){return value!=value}module.exports=function(a,b){return 0===a&&0===b?1/a==1/b:a===b||!(!numberIsNaN(a)||!numberIsNaN(b))}},{}],1034:[function(require,module,exports){"use strict";var define=require("define-properties"),callBind=require("call-bind"),implementation=require("./implementation"),getPolyfill=require("./polyfill"),require=require("./shim"),callBind=callBind(getPolyfill(),Object);define(callBind,{getPolyfill:getPolyfill,implementation:implementation,shim:require}),module.exports=callBind},{"./implementation":1033,"./polyfill":1035,"./shim":1036,"call-bind":115,"define-properties":639}],1035:[function(require,module,exports){"use strict";var implementation=require("./implementation");module.exports=function(){return"function"==typeof Object.is?Object.is:implementation}},{"./implementation":1033}],1036:[function(require,module,exports){"use strict";var getPolyfill=require("./polyfill"),define=require("define-properties");module.exports=function(){var polyfill=getPolyfill();return define(Object,{is:polyfill},{is:function(){return Object.is!==polyfill}}),polyfill}},{"./polyfill":1035,"define-properties":639}],1037:[function(require,module,exports){"use strict";var has,toStr,isArgs,hasDontEnumBug,hasProtoEnumBug,dontEnums,equalsConstructorPrototype,excludedKeys,hasAutomationEqualityBug,keysShim;Object.keys||(has=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,isArgs=require("./isArguments"),require=Object.prototype.propertyIsEnumerable,hasDontEnumBug=!require.call({toString:null},"toString"),hasProtoEnumBug=require.call(function(){},"prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],equalsConstructorPrototype=function(o){var ctor=o.constructor;return ctor&&ctor.prototype===o},excludedKeys={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},hasAutomationEqualityBug=function(){if("undefined"!=typeof window)for(var k in window)try{if(!excludedKeys["$"+k]&&has.call(window,k)&&null!==window[k]&&"object"==typeof window[k])try{equalsConstructorPrototype(window[k])}catch(e){return!0}}catch(e){return!0}return!1}(),keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toStr.call(object),isArguments=isArgs(object),isString=isObject&&"[object String]"===toStr.call(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");var skipProto=hasProtoEnumBug&&isFunction;if(isString&&0<object.length&&!has.call(object,0))for(var i=0;i<object.length;++i)theKeys.push(String(i));if(isArguments&&0<object.length)for(var j=0;j<object.length;++j)theKeys.push(String(j));else for(var name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(String(name));if(hasDontEnumBug)for(var skipConstructor=function(o){if("undefined"==typeof window||!hasAutomationEqualityBug)return equalsConstructorPrototype(o);try{return equalsConstructorPrototype(o)}catch(e){return!1}}(object),k=0;k<dontEnums.length;++k)skipConstructor&&"constructor"===dontEnums[k]||!has.call(object,dontEnums[k])||theKeys.push(dontEnums[k]);return theKeys}),module.exports=keysShim},{"./isArguments":1039}],1038:[function(require,module,exports){"use strict";var slice=Array.prototype.slice,isArgs=require("./isArguments"),origKeys=Object.keys,keysShim=origKeys?function(o){return origKeys(o)}:require("./implementation"),originalKeys=Object.keys;keysShim.shim=function(){return Object.keys?function(){var args=Object.keys(arguments);return args&&args.length===arguments.length}(1,2)||(Object.keys=function(object){return isArgs(object)?originalKeys(slice.call(object)):originalKeys(object)}):Object.keys=keysShim,Object.keys||keysShim},module.exports=keysShim},{"./implementation":1037,"./isArguments":1039}],1039:[function(require,module,exports){"use strict";var toStr=Object.prototype.toString;module.exports=function(value){var str=toStr.call(value);return"[object Arguments]"===str||"[object Array]"!==str&&null!==value&&"object"==typeof value&&"number"==typeof value.length&&0<=value.length&&"[object Function]"===toStr.call(value.callee)}},{}],1040:[function(require,module,exports){var isarray=require("isarray"),PATH_REGEXP=(module.exports=pathToRegexp,module.exports.parse=parse,module.exports.compile=function(str,options){return tokensToFunction(parse(str,options),options)},module.exports.tokensToFunction=tokensToFunction,module.exports.tokensToRegExp=tokensToRegExp,new RegExp(["(\\\\.)","([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))"].join("|"),"g"));function parse(str,options){for(var tokens=[],key=0,index=0,path="",defaultDelimiter=options&&options.delimiter||"/";null!=(res=PATH_REGEXP.exec(str));){var capture,group,modifier,asterisk,res,m=res[0],escaped=res[1],offset=res.index;path+=str.slice(index,offset),index=offset+m.length,escaped?path+=escaped[1]:(offset=str[index],m=res[2],escaped=res[3],capture=res[4],group=res[5],modifier=res[6],asterisk=res[7],offset=(path&&(tokens.push(path),path=""),null!=m&&null!=offset&&offset!==m),res=res[2]||defaultDelimiter,tokens.push({name:escaped||key++,prefix:m||"",delimiter:res,optional:"?"===modifier||"*"===modifier,repeat:"+"===modifier||"*"===modifier,partial:offset,asterisk:!!asterisk,pattern:(escaped=capture||group)?escaped.replace(/([=!:$\/()])/g,"\\$1"):asterisk?".*":"[^"+escapeString(res)+"]+?"}))}return index<str.length&&(path+=str.substr(index)),path&&tokens.push(path),tokens}function encodeURIComponentPretty(str){return encodeURI(str).replace(/[\/?#]/g,function(c){return"%"+c.charCodeAt(0).toString(16).toUpperCase()})}function tokensToFunction(tokens,options){for(var matches=new Array(tokens.length),i=0;i<tokens.length;i++)"object"==typeof tokens[i]&&(matches[i]=new RegExp("^(?:"+tokens[i].pattern+")$",flags(options)));return function(obj,opts){for(var path="",data=obj||{},encode=(opts||{}).pretty?encodeURIComponentPretty:encodeURIComponent,i=0;i<tokens.length;i++){var token=tokens[i];if("string"==typeof token)path+=token;else{var segment,value=data[token.name];if(null==value){if(token.optional){token.partial&&(path+=token.prefix);continue}throw new TypeError('Expected "'+token.name+'" to be defined')}if(isarray(value)){if(!token.repeat)throw new TypeError('Expected "'+token.name+'" to not repeat, but received `'+JSON.stringify(value)+"`");if(0===value.length){if(token.optional)continue;throw new TypeError('Expected "'+token.name+'" to not be empty')}for(var j=0;j<value.length;j++){if(segment=encode(value[j]),!matches[i].test(segment))throw new TypeError('Expected all "'+token.name+'" to match "'+token.pattern+'", but received `'+JSON.stringify(segment)+"`");path+=(0===j?token.prefix:token.delimiter)+segment}}else{if(segment=token.asterisk?encodeURI(value).replace(/[?#]/g,function(c){return"%"+c.charCodeAt(0).toString(16).toUpperCase()}):encode(value),!matches[i].test(segment))throw new TypeError('Expected "'+token.name+'" to match "'+token.pattern+'", but received "'+segment+'"');path+=token.prefix+segment}}}return path}}function escapeString(str){return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g,"\\$1")}function attachKeys(re,keys){return re.keys=keys,re}function flags(options){return options&&options.sensitive?"":"i"}function tokensToRegExp(tokens,keys,options){isarray(keys)||(options=keys||options,keys=[]);for(var strict=(options=options||{}).strict,end=!1!==options.end,route="",i=0;i<tokens.length;i++){var prefix,capture,token=tokens[i];"string"==typeof token?route+=escapeString(token):(prefix=escapeString(token.prefix),capture="(?:"+token.pattern+")",keys.push(token),token.repeat&&(capture+="(?:"+prefix+capture+")*"),route+=capture=token.optional?token.partial?prefix+"("+capture+")?":"(?:"+prefix+"("+capture+"))?":prefix+"("+capture+")")}var delimiter=escapeString(options.delimiter||"/"),endsWithDelimiter=route.slice(-delimiter.length)===delimiter;return strict||(route=(endsWithDelimiter?route.slice(0,-delimiter.length):route)+"(?:"+delimiter+"(?=$))?"),route+=end?"$":strict&&endsWithDelimiter?"":"(?="+delimiter+"|$)",attachKeys(new RegExp("^"+route,flags(options)),keys)}function pathToRegexp(path,keys,options){return isarray(keys)||(options=keys||options,keys=[]),options=options||{},path instanceof RegExp?function(path,keys){var groups=path.source.match(/\((?!\?)/g);if(groups)for(var i=0;i<groups.length;i++)keys.push({name:i,prefix:null,delimiter:null,optional:!1,repeat:!1,partial:!1,asterisk:!1,pattern:null});return attachKeys(path,keys)}(path,keys):(isarray(path)?function(path,keys,options){for(var parts=[],i=0;i<path.length;i++)parts.push(pathToRegexp(path[i],keys,options).source);return attachKeys(new RegExp("(?:"+parts.join("|")+")",flags(options)),keys)}:function(path,keys,options){return tokensToRegExp(parse(path,options),keys,options)})(path,keys,options)}},{isarray:660}],1041:[function(require,module,exports){!function(global){!function(){!function(global,factory){"object"==typeof exports&&void 0!==module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):global.Popper=factory()}(this,function(){"use strict";var isBrowser="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator,timeoutDuration=function(){for(var longerTimeoutBrowsers=["Edge","Trident","Firefox"],i=0;i<longerTimeoutBrowsers.length;i+=1)if(isBrowser&&0<=navigator.userAgent.indexOf(longerTimeoutBrowsers[i]))return 1;return 0}();var debounce=isBrowser&&window.Promise?function(fn){var called=!1;return function(){called||(called=!0,window.Promise.resolve().then(function(){called=!1,fn()}))}}:function(fn){var scheduled=!1;return function(){scheduled||(scheduled=!0,setTimeout(function(){scheduled=!1,fn()},timeoutDuration))}};function isFunction(functionToCheck){return functionToCheck&&"[object Function]"==={}.toString.call(functionToCheck)}function getStyleComputedProperty(element,property){return 1!==element.nodeType?[]:(element=element.ownerDocument.defaultView.getComputedStyle(element,null),property?element[property]:element)}function getParentNode(element){return"HTML"===element.nodeName?element:element.parentNode||element.host}function getScrollParent(element){if(!element)return document.body;switch(element.nodeName){case"HTML":case"BODY":return element.ownerDocument.body;case"#document":return element.body}var _getStyleComputedProp=getStyleComputedProperty(element),overflow=_getStyleComputedProp.overflow,overflowX=_getStyleComputedProp.overflowX,_getStyleComputedProp=_getStyleComputedProp.overflowY;return/(auto|scroll|overlay)/.test(overflow+_getStyleComputedProp+overflowX)?element:getScrollParent(getParentNode(element))}function getReferenceNode(reference){return reference&&reference.referenceNode?reference.referenceNode:reference}var isIE11=isBrowser&&!(!window.MSInputMethodContext||!document.documentMode),isIE10=isBrowser&&/MSIE 10/.test(navigator.userAgent);function isIE(version){return 11===version?isIE11:10!==version&&isIE11||isIE10}function getOffsetParent(element){if(!element)return document.documentElement;for(var noOffsetParent=isIE(10)?document.body:null,offsetParent=element.offsetParent||null;offsetParent===noOffsetParent&&element.nextElementSibling;)offsetParent=(element=element.nextElementSibling).offsetParent;var nodeName=offsetParent&&offsetParent.nodeName;return nodeName&&"BODY"!==nodeName&&"HTML"!==nodeName?-1!==["TH","TD","TABLE"].indexOf(offsetParent.nodeName)&&"static"===getStyleComputedProperty(offsetParent,"position")?getOffsetParent(offsetParent):offsetParent:(element?element.ownerDocument:document).documentElement}function getRoot(node){return null!==node.parentNode?getRoot(node.parentNode):node}function findCommonOffsetParent(element1,element2){var range,start,order;return element1&&element1.nodeType&&element2&&element2.nodeType?(start=(order=element1.compareDocumentPosition(element2)&Node.DOCUMENT_POSITION_FOLLOWING)?element1:element2,order=order?element2:element1,(range=document.createRange()).setStart(start,0),range.setEnd(order,0),element1!==(range=range.commonAncestorContainer)&&element2!==range||start.contains(order)?"BODY"===(order=(start=range).nodeName)||"HTML"!==order&&getOffsetParent(start.firstElementChild)!==start?getOffsetParent(range):range:(order=getRoot(element1)).host?findCommonOffsetParent(order.host,element2):findCommonOffsetParent(element1,getRoot(element2).host)):document.documentElement}function getScroll(element,argument_1){var argument_1="top"===(1<arguments.length&&void 0!==argument_1?argument_1:"top")?"scrollTop":"scrollLeft",nodeName=element.nodeName;return("BODY"===nodeName||"HTML"===nodeName?(nodeName=element.ownerDocument.documentElement,element.ownerDocument.scrollingElement||nodeName):element)[argument_1]}function getBordersSize(styles,axis){var axis="x"===axis?"Left":"Top",sideB="Left"==axis?"Right":"Bottom";return parseFloat(styles["border"+axis+"Width"])+parseFloat(styles["border"+sideB+"Width"])}function getSize(axis,body,html,computedStyle){return Math.max(body["offset"+axis],body["scroll"+axis],html["client"+axis],html["offset"+axis],html["scroll"+axis],isIE(10)?parseInt(html["offset"+axis])+parseInt(computedStyle["margin"+("Height"===axis?"Top":"Left")])+parseInt(computedStyle["margin"+("Height"===axis?"Bottom":"Right")]):0)}function getWindowSizes(document){var body=document.body,document=document.documentElement,computedStyle=isIE(10)&&getComputedStyle(document);return{height:getSize("Height",body,document,computedStyle),width:getSize("Width",body,document,computedStyle)}}var createClass=function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor};function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}function defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var key,source=arguments[i];for(key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target};function getClientRect(offsets){return _extends({},offsets,{right:offsets.left+offsets.width,bottom:offsets.top+offsets.height})}function getBoundingClientRect(element){var rect={};try{isIE(10)?(rect=element.getBoundingClientRect(),scrollTop=getScroll(element,"top"),scrollLeft=getScroll(element,"left"),rect.top+=scrollTop,rect.left+=scrollLeft,rect.bottom+=scrollTop,rect.right+=scrollLeft):rect=element.getBoundingClientRect()}catch(e){}var scrollTop={left:rect.left,top:rect.top,width:rect.right-rect.left,height:rect.bottom-rect.top},scrollLeft="HTML"===element.nodeName?getWindowSizes(element.ownerDocument):{},rect=scrollLeft.width||element.clientWidth||scrollTop.width,scrollLeft=scrollLeft.height||element.clientHeight||scrollTop.height,rect=element.offsetWidth-rect,scrollLeft=element.offsetHeight-scrollLeft;return(rect||scrollLeft)&&(rect-=getBordersSize(element=getStyleComputedProperty(element),"x"),scrollLeft-=getBordersSize(element,"y"),scrollTop.width-=rect,scrollTop.height-=scrollLeft),getClientRect(scrollTop)}function getOffsetRectRelativeToArbitraryNode(children,parent,argument_2){var argument_2=2<arguments.length&&void 0!==argument_2&&argument_2,isIE10=isIE(10),isHTML="HTML"===parent.nodeName,childrenRect=getBoundingClientRect(children),parentRect=getBoundingClientRect(parent),children=getScrollParent(children),styles=getStyleComputedProperty(parent),borderTopWidth=parseFloat(styles.borderTopWidth),borderLeftWidth=parseFloat(styles.borderLeftWidth),parentRect=(argument_2&&isHTML&&(parentRect.top=Math.max(parentRect.top,0),parentRect.left=Math.max(parentRect.left,0)),getClientRect({top:childrenRect.top-parentRect.top-borderTopWidth,left:childrenRect.left-parentRect.left-borderLeftWidth,width:childrenRect.width,height:childrenRect.height}));return parentRect.marginTop=0,parentRect.marginLeft=0,!isIE10&&isHTML&&(childrenRect=parseFloat(styles.marginTop),isHTML=parseFloat(styles.marginLeft),parentRect.top-=borderTopWidth-childrenRect,parentRect.bottom-=borderTopWidth-childrenRect,parentRect.left-=borderLeftWidth-isHTML,parentRect.right-=borderLeftWidth-isHTML,parentRect.marginTop=childrenRect,parentRect.marginLeft=isHTML),parentRect=(isIE10&&!argument_2?parent.contains(children):parent===children&&"BODY"!==children.nodeName)?function(rect,element,argument_2){var argument_2=2<arguments.length&&void 0!==argument_2&&argument_2,scrollTop=getScroll(element,"top"),element=getScroll(element,"left"),argument_2=argument_2?-1:1;return rect.top+=scrollTop*argument_2,rect.bottom+=scrollTop*argument_2,rect.left+=element*argument_2,rect.right+=element*argument_2,rect}(parentRect,parent):parentRect}function getFixedPositionOffsetParent(element){if(!element||!element.parentElement||isIE())return document.documentElement;for(var el=element.parentElement;el&&"none"===getStyleComputedProperty(el,"transform");)el=el.parentElement;return el||document.documentElement}function getBoundaries(popper,reference,padding,boundariesElement,argument_4){var boundariesNode,argument_4=4<arguments.length&&void 0!==argument_4&&argument_4,boundaries={top:0,left:0},offsetParent=argument_4?getFixedPositionOffsetParent(popper):findCommonOffsetParent(popper,getReferenceNode(reference)),offsetParent=("viewport"===boundariesElement?boundaries=function(element,argument_1){var argument_1=1<arguments.length&&void 0!==argument_1&&argument_1,html=element.ownerDocument.documentElement,element=getOffsetRectRelativeToArbitraryNode(element,html),width=Math.max(html.clientWidth,window.innerWidth||0),height=Math.max(html.clientHeight,window.innerHeight||0),scrollTop=argument_1?0:getScroll(html),argument_1=argument_1?0:getScroll(html,"left");return getClientRect({top:scrollTop-element.top+element.marginTop,left:argument_1-element.left+element.marginLeft,width:width,height:height})}(offsetParent,argument_4):(boundariesNode=void 0,"scrollParent"===boundariesElement?"BODY"===(boundariesNode=getScrollParent(getParentNode(reference))).nodeName&&(boundariesNode=popper.ownerDocument.documentElement):boundariesNode="window"===boundariesElement?popper.ownerDocument.documentElement:boundariesElement,reference=getOffsetRectRelativeToArbitraryNode(boundariesNode,offsetParent,argument_4),"HTML"!==boundariesNode.nodeName||function isFixed(element){var nodeName=element.nodeName;return"BODY"!==nodeName&&"HTML"!==nodeName&&("fixed"===getStyleComputedProperty(element,"position")||!!(nodeName=getParentNode(element))&&isFixed(nodeName))}(offsetParent)?boundaries=reference:(argument_4=(boundariesElement=getWindowSizes(popper.ownerDocument)).height,boundariesNode=boundariesElement.width,boundaries.top+=reference.top-reference.marginTop,boundaries.bottom=argument_4+reference.top,boundaries.left+=reference.left-reference.marginLeft,boundaries.right=boundariesNode+reference.left)),"number"==typeof(padding=padding||0));return boundaries.left+=offsetParent?padding:padding.left||0,boundaries.top+=offsetParent?padding:padding.top||0,boundaries.right-=offsetParent?padding:padding.right||0,boundaries.bottom-=offsetParent?padding:padding.bottom||0,boundaries}function computeAutoPlacement(placement,refRect,popper,reference,boundariesElement,argument_5){var rects,argument_5=5<arguments.length&&void 0!==argument_5?argument_5:0;return-1===placement.indexOf("auto")?placement:(reference=getBoundaries(popper,reference,argument_5,boundariesElement),rects={top:{width:reference.width,height:refRect.top-reference.top},right:{width:reference.right-refRect.right,height:reference.height},bottom:{width:reference.width,height:reference.bottom-refRect.bottom},left:{width:refRect.left-reference.left,height:reference.height}},(0<(boundariesElement=(argument_5=Object.keys(rects).map(function(key){return _extends({key:key},rects[key],{area:(key=rects[key]).width*key.height})}).sort(function(a,b){return b.area-a.area})).filter(function(_ref2){var width=_ref2.width,_ref2=_ref2.height;return width>=popper.clientWidth&&_ref2>=popper.clientHeight})).length?boundariesElement:argument_5)[0].key+((refRect=placement.split("-")[1])?"-"+refRect:""))}function getReferenceOffsets(state,popper,reference,argument_3){argument_3=3<arguments.length&&void 0!==argument_3?argument_3:null;return getOffsetRectRelativeToArbitraryNode(reference,argument_3?getFixedPositionOffsetParent(popper):findCommonOffsetParent(popper,getReferenceNode(reference)),argument_3)}function getOuterSizes(element){var styles=element.ownerDocument.defaultView.getComputedStyle(element),x=parseFloat(styles.marginTop||0)+parseFloat(styles.marginBottom||0),styles=parseFloat(styles.marginLeft||0)+parseFloat(styles.marginRight||0);return{width:element.offsetWidth+styles,height:element.offsetHeight+x}}function getOppositePlacement(placement){var hash={left:"right",right:"left",bottom:"top",top:"bottom"};return placement.replace(/left|right|bottom|top/g,function(matched){return hash[matched]})}function getPopperOffsets(popper,referenceOffsets,placement){placement=placement.split("-")[0];var popper=getOuterSizes(popper),popperOffsets={width:popper.width,height:popper.height},isHoriz=-1!==["right","left"].indexOf(placement),mainSide=isHoriz?"top":"left",secondarySide=isHoriz?"left":"top",measurement=isHoriz?"height":"width",isHoriz=isHoriz?"width":"height";return popperOffsets[mainSide]=referenceOffsets[mainSide]+referenceOffsets[measurement]/2-popper[measurement]/2,popperOffsets[secondarySide]=placement===secondarySide?referenceOffsets[secondarySide]-popper[isHoriz]:referenceOffsets[getOppositePlacement(secondarySide)],popperOffsets}function find(arr,check){return Array.prototype.find?arr.find(check):arr.filter(check)[0]}function runModifiers(modifiers,data,ends){var prop,value;return(void 0===ends?modifiers:modifiers.slice(0,(modifiers=modifiers,prop="name",value=ends,Array.prototype.findIndex?modifiers.findIndex(function(cur){return cur[prop]===value}):(ends=find(modifiers,function(obj){return obj[prop]===value}),modifiers.indexOf(ends))))).forEach(function(modifier){modifier.function&&console.warn("`modifier.function` is deprecated, use `modifier.fn`!");var fn=modifier.function||modifier.fn;modifier.enabled&&isFunction(fn)&&(data.offsets.popper=getClientRect(data.offsets.popper),data.offsets.reference=getClientRect(data.offsets.reference),data=fn(data,modifier))}),data}function isModifierEnabled(modifiers,modifierName){return modifiers.some(function(_ref){var name=_ref.name;return _ref.enabled&&name===modifierName})}function getSupportedPropertyName(property){for(var prefixes=[!1,"ms","Webkit","Moz","O"],upperProp=property.charAt(0).toUpperCase()+property.slice(1),i=0;i<prefixes.length;i++){var prefix=prefixes[i],prefix=prefix?""+prefix+upperProp:property;if(void 0!==document.body.style[prefix])return prefix}return null}function getWindow(element){element=element.ownerDocument;return element?element.defaultView:window}function setupEventListeners(reference,options,state,updateBound){state.updateBound=updateBound,getWindow(reference).addEventListener("resize",state.updateBound,{passive:!0});updateBound=getScrollParent(reference);return function attachToScrollParents(scrollParent,event,callback,scrollParents){var isBody="BODY"===scrollParent.nodeName,scrollParent=isBody?scrollParent.ownerDocument.defaultView:scrollParent;scrollParent.addEventListener(event,callback,{passive:!0}),isBody||attachToScrollParents(getScrollParent(scrollParent.parentNode),event,callback,scrollParents),scrollParents.push(scrollParent)}(updateBound,"scroll",state.updateBound,state.scrollParents),state.scrollElement=updateBound,state.eventsEnabled=!0,state}function disableEventListeners(){var reference,state;this.state.eventsEnabled&&(cancelAnimationFrame(this.scheduleUpdate),this.state=(reference=this.reference,state=this.state,getWindow(reference).removeEventListener("resize",state.updateBound),state.scrollParents.forEach(function(target){target.removeEventListener("scroll",state.updateBound)}),state.updateBound=null,state.scrollParents=[],state.scrollElement=null,state.eventsEnabled=!1,state))}function isNumeric(n){return""!==n&&!isNaN(parseFloat(n))&&isFinite(n)}function setStyles(element,styles){Object.keys(styles).forEach(function(prop){var unit="";-1!==["width","height","top","right","bottom","left"].indexOf(prop)&&isNumeric(styles[prop])&&(unit="px"),element.style[prop]=styles[prop]+unit})}function getRoundedOffsets(data,shouldRound){function noRound(v){return v}var _data$offsets=data.offsets,popper=_data$offsets.popper,_data$offsets=_data$offsets.reference,round=Math.round,floor=Math.floor,_data$offsets=round(_data$offsets.width),popperWidth=round(popper.width),isVertical=-1!==["left","right"].indexOf(data.placement),data=-1!==data.placement.indexOf("-"),isVertical=shouldRound?isVertical||data||_data$offsets%2==popperWidth%2?round:floor:noRound,floor=shouldRound?round:noRound;return{left:isVertical(_data$offsets%2==1&&popperWidth%2==1&&!data&&shouldRound?popper.left-1:popper.left),top:floor(popper.top),bottom:floor(popper.bottom),right:isVertical(popper.right)}}var isFirefox=isBrowser&&/Firefox/i.test(navigator.userAgent);function isModifierRequired(modifiers,requestingName,requestedName){var _requesting,requesting=find(modifiers,function(_ref){return _ref.name===requestingName}),modifiers=!!requesting&&modifiers.some(function(modifier){return modifier.name===requestedName&&modifier.enabled&&modifier.order<requesting.order});return modifiers||(_requesting="`"+requestingName+"`",console.warn("`"+requestedName+"`"+" modifier is required by "+_requesting+" modifier in order to work, be sure to include it before "+_requesting+"!")),modifiers}var placements=["auto-start","auto","auto-end","top-start","top","top-end","right-start","right","right-end","bottom-end","bottom","bottom-start","left-end","left","left-start"],validPlacements=placements.slice(3);function clockwise(placement,argument_1){argument_1=1<arguments.length&&void 0!==argument_1&&argument_1,placement=validPlacements.indexOf(placement),placement=validPlacements.slice(placement+1).concat(validPlacements.slice(0,placement));return argument_1?placement.reverse():placement}var BEHAVIORS_FLIP="flip",BEHAVIORS_CLOCKWISE="clockwise",BEHAVIORS_COUNTERCLOCKWISE="counterclockwise";function parseOffset(offset,popperOffsets,referenceOffsets,basePlacement){var offsets=[0,0],useHeight=-1!==["right","left"].indexOf(basePlacement),basePlacement=offset.split(/(\+|\-)/).map(function(frag){return frag.trim()}),offset=basePlacement.indexOf(find(basePlacement,function(frag){return-1!==frag.search(/,|\s/)})),splitRegex=(basePlacement[offset]&&-1===basePlacement[offset].indexOf(",")&&console.warn("Offsets separated by white space(s) are deprecated, use a comma (,) instead."),/\s*,\s*|\s+/);return(-1!==offset?[basePlacement.slice(0,offset).concat([basePlacement[offset].split(splitRegex)[0]]),[basePlacement[offset].split(splitRegex)[1]].concat(basePlacement.slice(offset+1))]:[basePlacement]).map(function(op,index){var measurement=(1===index?!useHeight:useHeight)?"height":"width",mergeWithPrevious=!1;return op.reduce(function(a,b){return""===a[a.length-1]&&-1!==["+","-"].indexOf(b)?(a[a.length-1]=b,mergeWithPrevious=!0,a):mergeWithPrevious?(a[a.length-1]+=b,mergeWithPrevious=!1,a):a.concat(b)},[]).map(function(str){return function(str,measurement,popperOffsets,referenceOffsets){var value=+(split=str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/))[1],split=split[2];return value?0===split.indexOf("%")?getClientRect("%p"===split?popperOffsets:referenceOffsets)[measurement]/100*value:"vh"===split||"vw"===split?("vh"===split?Math.max(document.documentElement.clientHeight,window.innerHeight||0):Math.max(document.documentElement.clientWidth,window.innerWidth||0))/100*value:value:str}(str,measurement,popperOffsets,referenceOffsets)})}).forEach(function(op,index){op.forEach(function(frag,index2){isNumeric(frag)&&(offsets[index]+=frag*("-"===op[index2-1]?-1:1))})}),offsets}var Defaults={placement:"bottom",positionFixed:!1,eventsEnabled:!0,removeOnDestroy:!1,onCreate:function(){},onUpdate:function(){},modifiers:{shift:{order:100,enabled:!0,fn:function(data){var reference,_data$offsets,measurement,placement=data.placement,basePlacement=placement.split("-")[0];return(placement=placement.split("-")[1])&&(reference=(_data$offsets=data.offsets).reference,_data$offsets=_data$offsets.popper,measurement=(basePlacement=-1!==["bottom","top"].indexOf(basePlacement))?"width":"height",basePlacement={start:defineProperty({},basePlacement=basePlacement?"left":"top",reference[basePlacement]),end:defineProperty({},basePlacement,reference[basePlacement]+reference[measurement]-_data$offsets[measurement])},data.offsets.popper=_extends({},_data$offsets,basePlacement[placement])),data}},offset:{order:200,enabled:!0,fn:function(data,_ref){var _ref=_ref.offset,placement=data.placement,popper=(_data$offsets=data.offsets).popper,_data$offsets=_data$offsets.reference,placement=placement.split("-")[0],offsets=void 0,offsets=isNumeric(+_ref)?[+_ref,0]:parseOffset(_ref,popper,_data$offsets,placement);return"left"===placement?(popper.top+=offsets[0],popper.left-=offsets[1]):"right"===placement?(popper.top+=offsets[0],popper.left+=offsets[1]):"top"===placement?(popper.left+=offsets[0],popper.top-=offsets[1]):"bottom"===placement&&(popper.left+=offsets[0],popper.top+=offsets[1]),data.popper=popper,data},offset:0},preventOverflow:{order:300,enabled:!0,fn:function(data,options){var boundariesElement=options.boundariesElement||getOffsetParent(data.instance.popper),transformProp=(data.instance.reference===boundariesElement&&(boundariesElement=getOffsetParent(boundariesElement)),getSupportedPropertyName("transform")),popperStyles=data.instance.popper.style,top=popperStyles.top,left=popperStyles.left,transform=popperStyles[transformProp],boundaries=(popperStyles.top="",popperStyles.left="",popperStyles[transformProp]="",getBoundaries(data.instance.popper,data.instance.reference,options.padding,boundariesElement,data.positionFixed)),boundariesElement=(popperStyles.top=top,popperStyles.left=left,popperStyles[transformProp]=transform,options.boundaries=boundaries,options.priority),popper=data.offsets.popper,check={primary:function(placement){var value=popper[placement];return popper[placement]<boundaries[placement]&&!options.escapeWithReference&&(value=Math.max(popper[placement],boundaries[placement])),defineProperty({},placement,value)},secondary:function(placement){var mainSide="right"===placement?"left":"top",value=popper[mainSide];return popper[placement]>boundaries[placement]&&!options.escapeWithReference&&(value=Math.min(popper[mainSide],boundaries[placement]-("right"===placement?popper.width:popper.height))),defineProperty({},mainSide,value)}};return boundariesElement.forEach(function(placement){var side=-1!==["left","top"].indexOf(placement)?"primary":"secondary";popper=_extends({},popper,check[side](placement))}),data.offsets.popper=popper,data},priority:["left","right","top","bottom"],padding:5,boundariesElement:"scrollParent"},keepTogether:{order:400,enabled:!0,fn:function(data){var popper=(_data$offsets=data.offsets).popper,_data$offsets=_data$offsets.reference,placement=data.placement.split("-")[0],floor=Math.floor,side=(placement=-1!==["top","bottom"].indexOf(placement))?"right":"bottom",opSide=placement?"left":"top",placement=placement?"width":"height";return popper[side]<floor(_data$offsets[opSide])&&(data.offsets.popper[opSide]=floor(_data$offsets[opSide])-popper[placement]),popper[opSide]>floor(_data$offsets[side])&&(data.offsets.popper[opSide]=floor(_data$offsets[side])),data}},arrow:{order:500,enabled:!0,fn:function(data,options){if(isModifierRequired(data.instance.modifiers,"arrow","keepTogether")){options=options.element;if("string"==typeof options){if(!(options=data.instance.popper.querySelector(options)))return data}else if(!data.instance.popper.contains(options))return console.warn("WARNING: `arrow.element` must be child of its popper element!"),data;var placement=data.placement.split("-")[0],_data$offsets=data.offsets,popper=_data$offsets.popper,_data$offsets=_data$offsets.reference,placement=-1!==["left","right"].indexOf(placement),len=placement?"height":"width",sideCapitalized=placement?"Top":"Left",side=sideCapitalized.toLowerCase(),altSide=placement?"left":"top",placement=placement?"bottom":"right",arrowElementSize=getOuterSizes(options)[len],placement=(_data$offsets[placement]-arrowElementSize<popper[side]&&(data.offsets.popper[side]-=popper[side]-(_data$offsets[placement]-arrowElementSize)),_data$offsets[side]+arrowElementSize>popper[placement]&&(data.offsets.popper[side]+=_data$offsets[side]+arrowElementSize-popper[placement]),data.offsets.popper=getClientRect(data.offsets.popper),_data$offsets[side]+_data$offsets[len]/2-arrowElementSize/2),_data$offsets=getStyleComputedProperty(data.instance.popper),popperMarginSide=parseFloat(_data$offsets["margin"+sideCapitalized]),_data$offsets=parseFloat(_data$offsets["border"+sideCapitalized+"Width"]),sideCapitalized=placement-data.offsets.popper[side]-popperMarginSide-_data$offsets,sideCapitalized=Math.max(Math.min(popper[len]-arrowElementSize,sideCapitalized),0);data.arrowElement=options,data.offsets.arrow=(defineProperty(placement={},side,Math.round(sideCapitalized)),defineProperty(placement,altSide,""),placement)}return data},element:"[x-arrow]"},flip:{order:600,enabled:!0,fn:function(data,options){if(!(isModifierEnabled(data.instance.modifiers,"inner")||data.flipped&&data.placement===data.originalPlacement)){var boundaries=getBoundaries(data.instance.popper,data.instance.reference,options.padding,options.boundariesElement,data.positionFixed),placement=data.placement.split("-")[0],placementOpposite=getOppositePlacement(placement),variation=data.placement.split("-")[1]||"",flipOrder=[];switch(options.behavior){case BEHAVIORS_FLIP:flipOrder=[placement,placementOpposite];break;case BEHAVIORS_CLOCKWISE:flipOrder=clockwise(placement);break;case BEHAVIORS_COUNTERCLOCKWISE:flipOrder=clockwise(placement,!0);break;default:flipOrder=options.behavior}flipOrder.forEach(function(step,index){if(placement!==step||flipOrder.length===index+1)return data;placement=data.placement.split("-")[0],placementOpposite=getOppositePlacement(placement);var step=data.offsets.popper,refOffsets=data.offsets.reference,floor=Math.floor,refOffsets="left"===placement&&floor(step.right)>floor(refOffsets.left)||"right"===placement&&floor(step.left)<floor(refOffsets.right)||"top"===placement&&floor(step.bottom)>floor(refOffsets.top)||"bottom"===placement&&floor(step.top)<floor(refOffsets.bottom),overflowsLeft=floor(step.left)<floor(boundaries.left),overflowsRight=floor(step.right)>floor(boundaries.right),overflowsTop=floor(step.top)<floor(boundaries.top),step=floor(step.bottom)>floor(boundaries.bottom),floor="left"===placement&&overflowsLeft||"right"===placement&&overflowsRight||"top"===placement&&overflowsTop||"bottom"===placement&&step,isVertical=-1!==["top","bottom"].indexOf(placement),flippedVariationByRef=!!options.flipVariations&&(isVertical&&"start"===variation&&overflowsLeft||isVertical&&"end"===variation&&overflowsRight||!isVertical&&"start"===variation&&overflowsTop||!isVertical&&"end"===variation&&step),overflowsRight=!!options.flipVariationsByContent&&(isVertical&&"start"===variation&&overflowsRight||isVertical&&"end"===variation&&overflowsLeft||!isVertical&&"start"===variation&&step||!isVertical&&"end"===variation&&overflowsTop),overflowsLeft=flippedVariationByRef||overflowsRight;(refOffsets||floor||overflowsLeft)&&(data.flipped=!0,(refOffsets||floor)&&(placement=flipOrder[index+1]),overflowsLeft&&(variation=function(variation){return"end"===variation?"start":"start"===variation?"end":variation}(variation)),data.placement=placement+(variation?"-"+variation:""),data.offsets.popper=_extends({},data.offsets.popper,getPopperOffsets(data.instance.popper,data.offsets.reference,data.placement)),data=runModifiers(data.instance.modifiers,data,"flip"))})}return data},behavior:"flip",padding:5,boundariesElement:"viewport",flipVariations:!1,flipVariationsByContent:!1},inner:{order:700,enabled:!1,fn:function(data){var placement=data.placement,basePlacement=placement.split("-")[0],popper=(_data$offsets=data.offsets).popper,_data$offsets=_data$offsets.reference,isHoriz=-1!==["left","right"].indexOf(basePlacement),subtractLength=-1===["top","left"].indexOf(basePlacement);return popper[isHoriz?"left":"top"]=_data$offsets[basePlacement]-(subtractLength?popper[isHoriz?"width":"height"]:0),data.placement=getOppositePlacement(placement),data.offsets.popper=getClientRect(popper),data}},hide:{order:800,enabled:!0,fn:function(data){if(isModifierRequired(data.instance.modifiers,"hide","preventOverflow")){var refRect=data.offsets.reference,bound=find(data.instance.modifiers,function(modifier){return"preventOverflow"===modifier.name}).boundaries;if(refRect.bottom<bound.top||refRect.left>bound.right||refRect.top>bound.bottom||refRect.right<bound.left){if(!0===data.hide)return data;data.hide=!0,data.attributes["x-out-of-boundaries"]=""}else{if(!1===data.hide)return data;data.hide=!1,data.attributes["x-out-of-boundaries"]=!1}}return data}},computeStyle:{order:850,enabled:!0,fn:function(data,options){var x=options.x,y=options.y,popper=data.offsets.popper,legacyGpuAccelerationOption=(void 0!==(legacyGpuAccelerationOption=find(data.instance.modifiers,function(modifier){return"applyStyle"===modifier.name}).gpuAcceleration)&&console.warn("WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!"),void 0!==legacyGpuAccelerationOption?legacyGpuAccelerationOption:options.gpuAcceleration),offsetParentRect=getBoundingClientRect(options=getOffsetParent(data.instance.popper)),popper={position:popper.position},offsets=getRoundedOffsets(data,window.devicePixelRatio<2||!isFirefox),x="bottom"===x?"top":"bottom",y="right"===y?"left":"right",prefixedProperty=getSupportedPropertyName("transform"),left=void 0,top=void 0,top="bottom"==x?"HTML"===options.nodeName?-options.clientHeight+offsets.bottom:-offsetParentRect.height+offsets.bottom:offsets.top,left="right"==y?"HTML"===options.nodeName?-options.clientWidth+offsets.right:-offsetParentRect.width+offsets.right:offsets.left,offsetParentRect=(legacyGpuAccelerationOption&&prefixedProperty?(popper[prefixedProperty]="translate3d("+left+"px, "+top+"px, 0)",popper[x]=0,popper[y]=0,popper.willChange="transform"):(options="right"==y?-1:1,popper[x]=top*("bottom"==x?-1:1),popper[y]=left*options,popper.willChange=x+", "+y),{"x-placement":data.placement});return data.attributes=_extends({},offsetParentRect,data.attributes),data.styles=_extends({},popper,data.styles),data.arrowStyles=_extends({},data.offsets.arrow,data.arrowStyles),data},gpuAcceleration:!0,x:"bottom",y:"right"},applyStyle:{order:900,enabled:!0,fn:function(data){var element,attributes;return setStyles(data.instance.popper,data.styles),element=data.instance.popper,attributes=data.attributes,Object.keys(attributes).forEach(function(prop){!1!==attributes[prop]?element.setAttribute(prop,attributes[prop]):element.removeAttribute(prop)}),data.arrowElement&&Object.keys(data.arrowStyles).length&&setStyles(data.arrowElement,data.arrowStyles),data},onLoad:function(reference,popper,options,modifierOptions,state){return state=getReferenceOffsets(state,popper,reference,options.positionFixed),state=computeAutoPlacement(options.placement,state,popper,reference,options.modifiers.flip.boundariesElement,options.modifiers.flip.padding),popper.setAttribute("x-placement",state),setStyles(popper,{position:options.positionFixed?"fixed":"absolute"}),options},gpuAcceleration:void 0}}},Popper=function(){function Popper(reference,popper){var _this=this,options=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},instance=this,Constructor=Popper;if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function");this.scheduleUpdate=function(){return requestAnimationFrame(_this.update)},this.update=debounce(this.update.bind(this)),this.options=_extends({},Popper.Defaults,options),this.state={isDestroyed:!1,isCreated:!1,scrollParents:[]},this.reference=reference&&reference.jquery?reference[0]:reference,this.popper=popper&&popper.jquery?popper[0]:popper,this.options.modifiers={},Object.keys(_extends({},Popper.Defaults.modifiers,options.modifiers)).forEach(function(name){_this.options.modifiers[name]=_extends({},Popper.Defaults.modifiers[name]||{},options.modifiers?options.modifiers[name]:{})}),this.modifiers=Object.keys(this.options.modifiers).map(function(name){return _extends({name:name},_this.options.modifiers[name])}).sort(function(a,b){return a.order-b.order}),this.modifiers.forEach(function(modifierOptions){modifierOptions.enabled&&isFunction(modifierOptions.onLoad)&&modifierOptions.onLoad(_this.reference,_this.popper,_this.options,modifierOptions,_this.state)}),this.update();instance=this.options.eventsEnabled;instance&&this.enableEventListeners(),this.state.eventsEnabled=instance}return createClass(Popper,[{key:"update",value:function(){return function(){var data;this.state.isDestroyed||((data={instance:this,styles:{},arrowStyles:{},attributes:{},flipped:!1,offsets:{}}).offsets.reference=getReferenceOffsets(this.state,this.popper,this.reference,this.options.positionFixed),data.placement=computeAutoPlacement(this.options.placement,data.offsets.reference,this.popper,this.reference,this.options.modifiers.flip.boundariesElement,this.options.modifiers.flip.padding),data.originalPlacement=data.placement,data.positionFixed=this.options.positionFixed,data.offsets.popper=getPopperOffsets(this.popper,data.offsets.reference,data.placement),data.offsets.popper.position=this.options.positionFixed?"fixed":"absolute",data=runModifiers(this.modifiers,data),this.state.isCreated?this.options.onUpdate(data):(this.state.isCreated=!0,this.options.onCreate(data)))}.call(this)}},{key:"destroy",value:function(){return function(){return this.state.isDestroyed=!0,isModifierEnabled(this.modifiers,"applyStyle")&&(this.popper.removeAttribute("x-placement"),this.popper.style.position="",this.popper.style.top="",this.popper.style.left="",this.popper.style.right="",this.popper.style.bottom="",this.popper.style.willChange="",this.popper.style[getSupportedPropertyName("transform")]=""),this.disableEventListeners(),this.options.removeOnDestroy&&this.popper.parentNode.removeChild(this.popper),this}.call(this)}},{key:"enableEventListeners",value:function(){return function(){this.state.eventsEnabled||(this.state=setupEventListeners(this.reference,this.options,this.state,this.scheduleUpdate))}.call(this)}},{key:"disableEventListeners",value:function(){return disableEventListeners.call(this)}}]),Popper}();return Popper.Utils=("undefined"!=typeof window?window:global).PopperUtils,Popper.placements=placements,Popper.Defaults=Defaults,Popper})}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],1042:[function(require,module,exports){var cachedSetTimeout,cachedClearTimeout,module=module.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return(cachedSetTimeout=setTimeout)(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}var currentQueue,queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length)&&drainQueue()}function drainQueue(){if(!draining){for(var timeout=runTimeout(cleanUpNextTick),len=(draining=!0,queue.length);len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,!function(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return(cachedClearTimeout=clearTimeout)(marker);try{cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}module.nextTick=function(fun){var args=new Array(arguments.length-1);if(1<arguments.length)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},module.title="browser",module.browser=!0,module.env={},module.argv=[],module.version="",module.versions={},module.on=noop,module.addListener=noop,module.once=noop,module.off=noop,module.removeListener=noop,module.removeAllListeners=noop,module.emit=noop,module.prependListener=noop,module.prependOnceListener=noop,module.listeners=function(name){return[]},module.binding=function(name){throw new Error("process.binding is not supported")},module.cwd=function(){return"/"},module.chdir=function(dir){throw new Error("process.chdir is not supported")},module.umask=function(){return 0}},{}],1043:[function(require,module,exports){"use strict";function checkPropTypes(typeSpecs,values,location,componentName,getStack){}checkPropTypes.resetWarningCache=function(){},module.exports=checkPropTypes},{"./lib/ReactPropTypesSecret":1047,"./lib/has":1048}],1044:[function(require,module,exports){"use strict";var ReactPropTypesSecret=require("./lib/ReactPropTypesSecret");function emptyFunction(){}function emptyFunctionWithReset(){}emptyFunctionWithReset.resetWarningCache=emptyFunction,module.exports=function(){function shim(props,propName,componentName,location,propFullName,secret){if(secret!==ReactPropTypesSecret)throw(secret=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")).name="Invariant Violation",secret}function getShim(){return shim}var ReactPropTypes={array:shim.isRequired=shim,bigint:shim,bool:shim,func:shim,number:shim,object:shim,string:shim,symbol:shim,any:shim,arrayOf:getShim,element:shim,elementType:shim,instanceOf:getShim,node:shim,objectOf:getShim,oneOf:getShim,oneOfType:getShim,shape:getShim,exact:getShim,checkPropTypes:emptyFunctionWithReset,resetWarningCache:emptyFunction};return ReactPropTypes.PropTypes=ReactPropTypes}},{"./lib/ReactPropTypesSecret":1047}],1045:[function(require,module,exports){"use strict";var ReactIs=require("react-is"),assign=require("object-assign"),ReactPropTypesSecret=require("./lib/ReactPropTypesSecret"),has=require("./lib/has"),checkPropTypes=require("./checkPropTypes"),printWarning=function(){};function emptyFunctionThatReturnsNull(){return null}module.exports=function(isValidElement,throwOnDirectAccess){var ITERATOR_SYMBOL="function"==typeof Symbol&&Symbol.iterator,FAUX_ITERATOR_SYMBOL="@@iterator";var ANONYMOUS="<<anonymous>>",ReactPropTypes={array:createPrimitiveTypeChecker("array"),bigint:createPrimitiveTypeChecker("bigint"),bool:createPrimitiveTypeChecker("boolean"),func:createPrimitiveTypeChecker("function"),number:createPrimitiveTypeChecker("number"),object:createPrimitiveTypeChecker("object"),string:createPrimitiveTypeChecker("string"),symbol:createPrimitiveTypeChecker("symbol"),any:createChainableTypeChecker(emptyFunctionThatReturnsNull),arrayOf:function(typeChecker){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){if("function"!=typeof typeChecker)return new PropTypeError("Property `"+propFullName+"` of component `"+componentName+"` has invalid PropType notation inside arrayOf.");var propValue=props[propName];if(!Array.isArray(propValue))return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+getPropType(propValue)+"` supplied to `"+componentName+"`, expected an array.");for(var i=0;i<propValue.length;i++){var error=typeChecker(propValue,i,componentName,location,propFullName+"["+i+"]",ReactPropTypesSecret);if(error instanceof Error)return error}return null})},element:createChainableTypeChecker(function(props,propName,componentName,location,propFullName){return props=props[propName],isValidElement(props)?null:new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+getPropType(props)+"` supplied to `"+componentName+"`, expected a single ReactElement.")}),elementType:createChainableTypeChecker(function(props,propName,componentName,location,propFullName){return props=props[propName],ReactIs.isValidElementType(props)?null:new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+getPropType(props)+"` supplied to `"+componentName+"`, expected a single ReactElement type.")}),instanceOf:function(expectedClass){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){var expectedClassName;return props[propName]instanceof expectedClass?null:(expectedClassName=expectedClass.name||ANONYMOUS,new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+((location=props[propName]).constructor&&location.constructor.name?location.constructor.name:ANONYMOUS)+"` supplied to `"+componentName+"`, expected instance of `"+expectedClassName+"`."))})},node:createChainableTypeChecker(function(props,propName,componentName,location,propFullName){return isNode(props[propName])?null:new PropTypeError("Invalid "+location+" `"+propFullName+"` supplied to `"+componentName+"`, expected a ReactNode.")}),objectOf:function(typeChecker){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){if("function"!=typeof typeChecker)return new PropTypeError("Property `"+propFullName+"` of component `"+componentName+"` has invalid PropType notation inside objectOf.");var key,propValue=props[propName];if("object"!==(props=getPropType(propValue)))return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+props+"` supplied to `"+componentName+"`, expected an object.");for(key in propValue)if(has(propValue,key)){var error=typeChecker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(error instanceof Error)return error}return null})},oneOf:function(expectedValues){if(Array.isArray(expectedValues))return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){for(var propValue=props[propName],i=0;i<expectedValues.length;i++)if(function(x,y){return x===y?0!==x||1/x==1/y:x!=x&&y!=y}(propValue,expectedValues[i]))return null;props=JSON.stringify(expectedValues,function(key,value){return"symbol"===getPreciseType(value)?String(value):value});return new PropTypeError("Invalid "+location+" `"+propFullName+"` of value `"+String(propValue)+"` supplied to `"+componentName+"`, expected one of "+props+".")});return emptyFunctionThatReturnsNull},oneOfType:function(arrayOfTypeCheckers){if(!Array.isArray(arrayOfTypeCheckers))return emptyFunctionThatReturnsNull;for(var i=0;i<arrayOfTypeCheckers.length;i++){var checker=arrayOfTypeCheckers[i];if("function"!=typeof checker)return printWarning("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+function(value){var type=getPreciseType(value);switch(type){case"array":case"object":return"an "+type;case"boolean":case"date":case"regexp":return"a "+type;default:return type}}(checker)+" at index "+i+"."),emptyFunctionThatReturnsNull}return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){for(var expectedTypes=[],i=0;i<arrayOfTypeCheckers.length;i++){var checkerResult=(0,arrayOfTypeCheckers[i])(props,propName,componentName,location,propFullName,ReactPropTypesSecret);if(null==checkerResult)return null;checkerResult.data&&has(checkerResult.data,"expectedType")&&expectedTypes.push(checkerResult.data.expectedType)}return new PropTypeError("Invalid "+location+" `"+propFullName+"` supplied to `"+componentName+"`"+(0<expectedTypes.length?", expected one of type ["+expectedTypes.join(", ")+"]":"")+".")})},shape:function(shapeTypes){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){var key,propValue=props[propName];if("object"!==(props=getPropType(propValue)))return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+props+"` supplied to `"+componentName+"`, expected `object`.");for(key in shapeTypes){var checker=shapeTypes[key];if("function"!=typeof checker)return invalidValidatorError(componentName,location,propFullName,key,getPreciseType(checker));checker=checker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(checker)return checker}return null})},exact:function(shapeTypes){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){var key,propValue=props[propName],propType=getPropType(propValue);if("object"!==propType)return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+propType+"` supplied to `"+componentName+"`, expected `object`.");for(key in assign({},props[propName],shapeTypes)){var checker=shapeTypes[key];if(has(shapeTypes,key)&&"function"!=typeof checker)return invalidValidatorError(componentName,location,propFullName,key,getPreciseType(checker));if(!checker)return new PropTypeError("Invalid "+location+" `"+propFullName+"` key `"+key+"` supplied to `"+componentName+"`.\nBad object: "+JSON.stringify(props[propName],null,"  ")+"\nValid keys: "+JSON.stringify(Object.keys(shapeTypes),null,"  "));checker=checker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(checker)return checker}return null})}};function PropTypeError(message,data){this.message=message,this.data=data&&"object"==typeof data?data:{},this.stack=""}function createChainableTypeChecker(validate){function checkType(isRequired,props,propName,componentName,location,propFullName,secret){if((componentName=componentName||ANONYMOUS,propFullName=propFullName||propName,secret!==ReactPropTypesSecret)&&throwOnDirectAccess)throw(secret=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types")).name="Invariant Violation",secret;return null==props[propName]?isRequired?null===props[propName]?new PropTypeError("The "+location+" `"+propFullName+"` is marked as required in `"+componentName+"`, but its value is `null`."):new PropTypeError("The "+location+" `"+propFullName+"` is marked as required in `"+componentName+"`, but its value is `undefined`."):null:validate(props,propName,componentName,location,propFullName)}var chainedCheckType=checkType.bind(null,!1);return chainedCheckType.isRequired=checkType.bind(null,!0),chainedCheckType}function createPrimitiveTypeChecker(expectedType){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName,secret){return getPropType(props=props[propName])!==expectedType?new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+getPreciseType(props)+"` supplied to `"+componentName+"`, expected `"+expectedType+"`.",{expectedType:expectedType}):null})}function invalidValidatorError(componentName,location,propFullName,key,type){return new PropTypeError((componentName||"React class")+": "+location+" type `"+propFullName+"."+key+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+type+"`.")}function isNode(propValue){switch(typeof propValue){case"number":case"string":case"undefined":return!0;case"boolean":return!propValue;case"object":if(Array.isArray(propValue))return propValue.every(isNode);if(null!==propValue&&!isValidElement(propValue)){var iteratorFn=function(maybeIterable){if("function"==typeof(maybeIterable=maybeIterable&&(ITERATOR_SYMBOL&&maybeIterable[ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL])))return maybeIterable}(propValue);if(!iteratorFn)return!1;var step,iterator=iteratorFn.call(propValue);if(iteratorFn!==propValue.entries){for(;!(step=iterator.next()).done;)if(!isNode(step.value))return!1}else for(;!(step=iterator.next()).done;){var entry=step.value;if(entry&&!isNode(entry[1]))return!1}}return!0;default:return!1}}function getPropType(propValue){var propType=typeof propValue;return Array.isArray(propValue)?"array":propValue instanceof RegExp?"object":function(propType,propValue){return"symbol"===propType||propValue&&("Symbol"===propValue["@@toStringTag"]||"function"==typeof Symbol&&propValue instanceof Symbol)}(propType,propValue)?"symbol":propType}function getPreciseType(propValue){if(null==propValue)return""+propValue;var propType=getPropType(propValue);if("object"===propType){if(propValue instanceof Date)return"date";if(propValue instanceof RegExp)return"regexp"}return propType}return PropTypeError.prototype=Error.prototype,ReactPropTypes.checkPropTypes=checkPropTypes,ReactPropTypes.resetWarningCache=checkPropTypes.resetWarningCache,ReactPropTypes.PropTypes=ReactPropTypes}},{"./checkPropTypes":1043,"./lib/ReactPropTypesSecret":1047,"./lib/has":1048,"object-assign":1032,"react-is":1385}],1046:[function(require,module,exports){module.exports=require("./factoryWithThrowingShims")()},{"./factoryWithThrowingShims":1044,"./factoryWithTypeCheckers":1045,"react-is":1385}],1047:[function(require,module,exports){"use strict";module.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},{}],1048:[function(require,module,exports){module.exports=Function.call.bind(Object.prototype.hasOwnProperty)},{}],1049:[function(require,module,exports){module.exports=function(){return!1}},{}],1050:[function(require,module,exports){module.exports=function(){return!0}},{}],1051:[function(require,module,exports){module.exports={"@@functional/placeholder":!0}},{}],1052:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return Number(a)+Number(b)})},{"./internal/_curry2":1156}],1053:[function(require,module,exports){var _concat=require("./internal/_concat"),curryN=require("./curryN");module.exports=require("./internal/_curry1")(function(fn){return curryN(fn.length,function(){var idx=0,origFn=arguments[0],list=arguments[arguments.length-1],args=Array.prototype.slice.call(arguments,0);return args[0]=function(){var result=origFn.apply(this,_concat(arguments,[idx,list]));return idx+=1,result},fn.apply(this,args)})})},{"./curryN":1092,"./internal/_concat":1153,"./internal/_curry1":1155}],1054:[function(require,module,exports){var _concat=require("./internal/_concat");module.exports=require("./internal/_curry3")(function(idx,fn,list){var _list;return idx>=list.length||idx<-list.length?list:(idx=(idx<0?list.length:0)+idx,(_list=_concat(list))[idx]=fn(list[idx]),_list)})},{"./internal/_concat":1153,"./internal/_curry3":1157}],1055:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")(["all"],require("./internal/_xall"),function(fn,list){for(var idx=0;idx<list.length;){if(!fn(list[idx]))return!1;idx+=1}return!0}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xall":1196}],1056:[function(require,module,exports){var curryN=require("./curryN"),max=require("./max"),pluck=require("./pluck"),reduce=require("./reduce");module.exports=require("./internal/_curry1")(function(preds){return curryN(reduce(max,0,pluck("length",preds)),function(){for(var idx=0,len=preds.length;idx<len;){if(!preds[idx].apply(this,arguments))return!1;idx+=1}return!0})})},{"./curryN":1092,"./internal/_curry1":1155,"./max":1247,"./pluck":1297,"./reduce":1308}],1057:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(val){return function(){return val}})},{"./internal/_curry1":1155}],1058:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return a&&b})},{"./internal/_curry2":1156}],1059:[function(require,module,exports){var _assertPromise=require("./internal/_assertPromise");module.exports=require("./internal/_curry2")(function(f,p){return _assertPromise("andThen",p),p.then(f)})},{"./internal/_assertPromise":1148,"./internal/_curry2":1156}],1060:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")(["any"],require("./internal/_xany"),function(fn,list){for(var idx=0;idx<list.length;){if(fn(list[idx]))return!0;idx+=1}return!1}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xany":1197}],1061:[function(require,module,exports){var curryN=require("./curryN"),max=require("./max"),pluck=require("./pluck"),reduce=require("./reduce");module.exports=require("./internal/_curry1")(function(preds){return curryN(reduce(max,0,pluck("length",preds)),function(){for(var idx=0,len=preds.length;idx<len;){if(preds[idx].apply(this,arguments))return!0;idx+=1}return!1})})},{"./curryN":1092,"./internal/_curry1":1155,"./max":1247,"./pluck":1297,"./reduce":1308}],1062:[function(require,module,exports){var _concat=require("./internal/_concat"),_reduce=require("./internal/_reduce"),map=require("./map");module.exports=require("./internal/_curry2")(function(applyF,applyX){return"function"==typeof applyX["fantasy-land/ap"]?applyX["fantasy-land/ap"](applyF):"function"==typeof applyF.ap?applyF.ap(applyX):"function"==typeof applyF?function(x){return applyF(x)(applyX(x))}:_reduce(function(acc,f){return _concat(acc,map(f,applyX))},[],applyF)})},{"./internal/_concat":1153,"./internal/_curry2":1156,"./internal/_reduce":1191,"./map":1241}],1063:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")([],require("./internal/_xaperture"),require("./internal/_aperture")))},{"./internal/_aperture":1145,"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xaperture":1198}],1064:[function(require,module,exports){var _concat=require("./internal/_concat");module.exports=require("./internal/_curry2")(function(el,list){return _concat(list,[el])})},{"./internal/_concat":1153,"./internal/_curry2":1156}],1065:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(fn,args){return fn.apply(this,args)})},{"./internal/_curry2":1156}],1066:[function(require,module,exports){var apply=require("./apply"),curryN=require("./curryN"),max=require("./max"),pluck=require("./pluck"),reduce=require("./reduce"),keys=require("./keys"),values=require("./values");function mapValues(fn,obj){return keys(obj).reduce(function(acc,key){return acc[key]=fn(obj[key]),acc},{})}require=require("./internal/_curry1")(function applySpec(spec){return spec=mapValues(function(v){return"function"==typeof v?v:applySpec(v)},spec),curryN(reduce(max,0,pluck("length",values(spec))),function(){var args=arguments;return mapValues(function(f){return apply(f,args)},spec)})});module.exports=require},{"./apply":1065,"./curryN":1092,"./internal/_curry1":1155,"./keys":1228,"./max":1247,"./pluck":1297,"./reduce":1308,"./values":1368}],1067:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(x,f){return f(x)})},{"./internal/_curry2":1156}],1068:[function(require,module,exports){require=require("./internal/_curry3")(function(fn,a,b){a=fn(a),fn=fn(b);return a<fn?-1:fn<a?1:0});module.exports=require},{"./internal/_curry3":1157}],1069:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(prop,val,obj){var p,result={};for(p in obj)result[p]=obj[p];return result[prop]=val,result})},{"./internal/_curry3":1157}],1070:[function(require,module,exports){var _has=require("./internal/_has"),_isArray=require("./internal/_isArray"),_isInteger=require("./internal/_isInteger"),assoc=require("./assoc"),isNil=require("./isNil"),require=require("./internal/_curry3")(function assocPath(path,val,obj){var idx,nextObj;return 0===path.length?val:(idx=path[0],1<path.length&&(nextObj=!isNil(obj)&&_has(idx,obj)?obj[idx]:_isInteger(path[1])?[]:{},val=assocPath(Array.prototype.slice.call(path,1),val,nextObj)),_isInteger(idx)&&_isArray(obj)?((path=[].concat(obj))[idx]=val,path):assoc(idx,val,obj))});module.exports=require},{"./assoc":1069,"./internal/_curry3":1157,"./internal/_has":1167,"./internal/_isArray":1173,"./internal/_isInteger":1176,"./isNil":1225}],1071:[function(require,module,exports){var nAry=require("./nAry");module.exports=require("./internal/_curry1")(function(fn){return nAry(2,fn)})},{"./internal/_curry1":1155,"./nAry":1267}],1072:[function(require,module,exports){var _arity=require("./internal/_arity");module.exports=require("./internal/_curry2")(function(fn,thisObj){return _arity(fn.length,function(){return fn.apply(thisObj,arguments)})})},{"./internal/_arity":1146,"./internal/_curry2":1156}],1073:[function(require,module,exports){var _isFunction=require("./internal/_isFunction"),and=require("./and"),lift=require("./lift");module.exports=require("./internal/_curry2")(function(f,g){return _isFunction(f)?function(){return f.apply(this,arguments)&&g.apply(this,arguments)}:lift(and)(f,g)})},{"./and":1058,"./internal/_curry2":1156,"./internal/_isFunction":1175,"./lift":1237}],1074:[function(require,module,exports){module.exports=require("./curry")(function(fn){return fn.apply(this,Array.prototype.slice.call(arguments,1))})},{"./curry":1091}],1075:[function(require,module,exports){var _makeFlat=require("./internal/_makeFlat"),map=require("./map");module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")(["fantasy-land/chain","chain"],require("./internal/_xchain"),function(fn,monad){return"function"==typeof monad?function(x){return fn(monad(x))(x)}:_makeFlat(!1)(map(fn,monad))}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_makeFlat":1183,"./internal/_xchain":1199,"./map":1241}],1076:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(min,max,value){if(max<min)throw new Error("min must not be greater than max in clamp(min, max, value)");return value<min?min:max<value?max:value})},{"./internal/_curry3":1157}],1077:[function(require,module,exports){var _clone=require("./internal/_clone");module.exports=require("./internal/_curry1")(function(value){return null!=value&&"function"==typeof value.clone?value.clone():_clone(value,[],[],!0)})},{"./internal/_clone":1150,"./internal/_curry1":1155}],1078:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(pred){return function(a,b){return pred(a,b)?-1:pred(b,a)?1:0}})},{"./internal/_curry1":1155}],1079:[function(require,module,exports){module.exports=require("./lift")(require("./not"))},{"./lift":1237,"./not":1270}],1080:[function(require,module,exports){var pipe=require("./pipe"),reverse=require("./reverse");module.exports=function(){if(0===arguments.length)throw new Error("compose requires at least one argument");return pipe.apply(this,reverse(arguments))}},{"./pipe":1293,"./reverse":1317}],1081:[function(require,module,exports){var chain=require("./chain"),compose=require("./compose"),map=require("./map");module.exports=function(){if(0===arguments.length)throw new Error("composeK requires at least one argument");var init=Array.prototype.slice.call(arguments),last=init.pop();return compose(compose.apply(this,map(chain,init)),last)}},{"./chain":1075,"./compose":1080,"./map":1241}],1082:[function(require,module,exports){var pipeP=require("./pipeP"),reverse=require("./reverse");module.exports=function(){if(0===arguments.length)throw new Error("composeP requires at least one argument");return pipeP.apply(this,reverse(arguments))}},{"./pipeP":1295,"./reverse":1317}],1083:[function(require,module,exports){var pipeWith=require("./pipeWith"),reverse=require("./reverse");module.exports=require("./internal/_curry2")(function(xf,list){return pipeWith.apply(this,[xf,reverse(list)])})},{"./internal/_curry2":1156,"./pipeWith":1296,"./reverse":1317}],1084:[function(require,module,exports){var _isArray=require("./internal/_isArray"),_isFunction=require("./internal/_isFunction"),_isString=require("./internal/_isString"),toString=require("./toString");module.exports=require("./internal/_curry2")(function(a,b){if(_isArray(a)){if(_isArray(b))return a.concat(b);throw new TypeError(toString(b)+" is not an array")}if(_isString(a)){if(_isString(b))return a+b;throw new TypeError(toString(b)+" is not a string")}if(null!=a&&_isFunction(a["fantasy-land/concat"]))return a["fantasy-land/concat"](b);if(null!=a&&_isFunction(a.concat))return a.concat(b);throw new TypeError(toString(a)+' does not have a method named "concat" or "fantasy-land/concat"')})},{"./internal/_curry2":1156,"./internal/_isArray":1173,"./internal/_isFunction":1175,"./internal/_isString":1181,"./toString":1346}],1085:[function(require,module,exports){var _arity=require("./internal/_arity"),map=require("./map"),max=require("./max"),reduce=require("./reduce");module.exports=require("./internal/_curry1")(function(pairs){var arity=reduce(max,0,map(function(pair){return pair[0].length},pairs));return _arity(arity,function(){for(var idx=0;idx<pairs.length;){if(pairs[idx][0].apply(this,arguments))return pairs[idx][1].apply(this,arguments);idx+=1}})})},{"./internal/_arity":1146,"./internal/_curry1":1155,"./map":1241,"./max":1247,"./reduce":1308}],1086:[function(require,module,exports){var constructN=require("./constructN");module.exports=require("./internal/_curry1")(function(Fn){return constructN(Fn.length,Fn)})},{"./constructN":1087,"./internal/_curry1":1155}],1087:[function(require,module,exports){var curry=require("./curry"),nAry=require("./nAry");module.exports=require("./internal/_curry2")(function(n,Fn){if(10<n)throw new Error("Constructor with greater than ten arguments");return 0===n?function(){return new Fn}:curry(nAry(n,function($0,$1,$2,$3,$4,$5,$6,$7,$8,$9){switch(arguments.length){case 1:return new Fn($0);case 2:return new Fn($0,$1);case 3:return new Fn($0,$1,$2);case 4:return new Fn($0,$1,$2,$3);case 5:return new Fn($0,$1,$2,$3,$4);case 6:return new Fn($0,$1,$2,$3,$4,$5);case 7:return new Fn($0,$1,$2,$3,$4,$5,$6);case 8:return new Fn($0,$1,$2,$3,$4,$5,$6,$7);case 9:return new Fn($0,$1,$2,$3,$4,$5,$6,$7,$8);case 10:return new Fn($0,$1,$2,$3,$4,$5,$6,$7,$8,$9)}}))})},{"./curry":1091,"./internal/_curry2":1156,"./nAry":1267}],1088:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_includes"))},{"./internal/_curry2":1156,"./internal/_includes":1169}],1089:[function(require,module,exports){var _map=require("./internal/_map"),curryN=require("./curryN"),max=require("./max"),pluck=require("./pluck"),reduce=require("./reduce");module.exports=require("./internal/_curry2")(function(after,fns){return curryN(reduce(max,0,pluck("length",fns)),function(){var args=arguments,context=this;return after.apply(context,_map(function(fn){return fn.apply(context,args)},fns))})})},{"./curryN":1092,"./internal/_curry2":1156,"./internal/_map":1184,"./max":1247,"./pluck":1297,"./reduce":1308}],1090:[function(require,module,exports){module.exports=require("./reduceBy")(function(acc,elem){return acc+1},0)},{"./reduceBy":1309}],1091:[function(require,module,exports){var curryN=require("./curryN");module.exports=require("./internal/_curry1")(function(fn){return curryN(fn.length,fn)})},{"./curryN":1092,"./internal/_curry1":1155}],1092:[function(require,module,exports){var _arity=require("./internal/_arity"),_curry1=require("./internal/_curry1"),_curryN=require("./internal/_curryN");module.exports=require("./internal/_curry2")(function(length,fn){return 1===length?_curry1(fn):_arity(length,_curryN(length,[],fn))})},{"./internal/_arity":1146,"./internal/_curry1":1155,"./internal/_curry2":1156,"./internal/_curryN":1158}],1093:[function(require,module,exports){module.exports=require("./add")(-1)},{"./add":1052}],1094:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(d,v){return null==v||v!=v?d:v})},{"./internal/_curry2":1156}],1095:[function(require,module,exports){require=require("./internal/_curry3")(function(fn,a,b){a=fn(a),fn=fn(b);return fn<a?-1:a<fn?1:0});module.exports=require},{"./internal/_curry3":1157}],1096:[function(require,module,exports){var _Set=require("./internal/_Set"),require=require("./internal/_curry2")(function(first,second){for(var out=[],idx=0,firstLen=first.length,secondLen=second.length,toFilterOut=new _Set,i=0;i<secondLen;i+=1)toFilterOut.add(second[i]);for(;idx<firstLen;)toFilterOut.add(first[idx])&&(out[out.length]=first[idx]),idx+=1;return out});module.exports=require},{"./internal/_Set":1144,"./internal/_curry2":1156}],1097:[function(require,module,exports){var _includesWith=require("./internal/_includesWith");module.exports=require("./internal/_curry3")(function(pred,first,second){for(var out=[],idx=0,firstLen=first.length;idx<firstLen;)_includesWith(pred,first[idx],second)||_includesWith(pred,first[idx],out)||out.push(first[idx]),idx+=1;return out})},{"./internal/_curry3":1157,"./internal/_includesWith":1170}],1098:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(prop,obj){var p,result={};for(p in obj)result[p]=obj[p];return delete result[prop],result})},{"./internal/_curry2":1156}],1099:[function(require,module,exports){var _isInteger=require("./internal/_isInteger"),_isArray=require("./internal/_isArray"),assoc=require("./assoc"),dissoc=require("./dissoc"),remove=require("./remove"),update=require("./update");module.exports=require("./internal/_curry2")(function dissocPath(path,obj){switch(path.length){case 0:return obj;case 1:return _isInteger(path[0])&&_isArray(obj)?remove(path[0],1,obj):dissoc(path[0],obj);default:var head=path[0],tail=Array.prototype.slice.call(path,1);return null==obj[head]?obj:(_isInteger(head)&&_isArray(obj)?update:assoc)(head,dissocPath(tail,obj[head]),obj)}})},{"./assoc":1069,"./dissoc":1098,"./internal/_curry2":1156,"./internal/_isArray":1173,"./internal/_isInteger":1176,"./remove":1314,"./update":1366}],1100:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return a/b})},{"./internal/_curry2":1156}],1101:[function(require,module,exports){var slice=require("./slice");module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")(["drop"],require("./internal/_xdrop"),function(n,xs){return slice(Math.max(0,n),1/0,xs)}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xdrop":1200,"./slice":1321}],1102:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")([],require("./internal/_xdropLast"),require("./internal/_dropLast")))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_dropLast":1160,"./internal/_xdropLast":1201}],1103:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")([],require("./internal/_xdropLastWhile"),require("./internal/_dropLastWhile")))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_dropLastWhile":1161,"./internal/_xdropLastWhile":1202}],1104:[function(require,module,exports){var equals=require("./equals");module.exports=require("./internal/_curry1")(require("./internal/_dispatchable")([],require("./internal/_xdropRepeatsWith")(equals),require("./dropRepeatsWith")(equals)))},{"./dropRepeatsWith":1105,"./equals":1112,"./internal/_curry1":1155,"./internal/_dispatchable":1159,"./internal/_xdropRepeatsWith":1203}],1105:[function(require,module,exports){var last=require("./last");module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")([],require("./internal/_xdropRepeatsWith"),function(pred,list){var result=[],idx=1,len=list.length;if(0!==len)for(result[0]=list[0];idx<len;)pred(last(result),list[idx])||(result[result.length]=list[idx]),idx+=1;return result}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xdropRepeatsWith":1203,"./last":1230}],1106:[function(require,module,exports){var slice=require("./slice"),require=require("./internal/_curry2")(require("./internal/_dispatchable")(["dropWhile"],require("./internal/_xdropWhile"),function(pred,xs){for(var idx=0,len=xs.length;idx<len&&pred(xs[idx]);)idx+=1;return slice(idx,1/0,xs)}));module.exports=require},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xdropWhile":1204,"./slice":1321}],1107:[function(require,module,exports){var _isFunction=require("./internal/_isFunction"),lift=require("./lift"),or=require("./or");module.exports=require("./internal/_curry2")(function(f,g){return _isFunction(f)?function(){return f.apply(this,arguments)||g.apply(this,arguments)}:lift(or)(f,g)})},{"./internal/_curry2":1156,"./internal/_isFunction":1175,"./lift":1237,"./or":1278}],1108:[function(require,module,exports){var _isArguments=require("./internal/_isArguments"),_isArray=require("./internal/_isArray"),_isObject=require("./internal/_isObject"),_isString=require("./internal/_isString");module.exports=require("./internal/_curry1")(function(x){return null!=x&&"function"==typeof x["fantasy-land/empty"]?x["fantasy-land/empty"]():null!=x&&null!=x.constructor&&"function"==typeof x.constructor["fantasy-land/empty"]?x.constructor["fantasy-land/empty"]():null!=x&&"function"==typeof x.empty?x.empty():null!=x&&null!=x.constructor&&"function"==typeof x.constructor.empty?x.constructor.empty():_isArray(x)?[]:_isString(x)?"":_isObject(x)?{}:_isArguments(x)?function(){return arguments}():void 0})},{"./internal/_curry1":1155,"./internal/_isArguments":1172,"./internal/_isArray":1173,"./internal/_isObject":1178,"./internal/_isString":1181}],1109:[function(require,module,exports){var equals=require("./equals"),takeLast=require("./takeLast");module.exports=require("./internal/_curry2")(function(suffix,list){return equals(takeLast(suffix.length,list),suffix)})},{"./equals":1112,"./internal/_curry2":1156,"./takeLast":1336}],1110:[function(require,module,exports){var equals=require("./equals");module.exports=require("./internal/_curry3")(function(f,x,y){return equals(f(x),f(y))})},{"./equals":1112,"./internal/_curry3":1157}],1111:[function(require,module,exports){var equals=require("./equals");module.exports=require("./internal/_curry3")(function(prop,obj1,obj2){return equals(obj1[prop],obj2[prop])})},{"./equals":1112,"./internal/_curry3":1157}],1112:[function(require,module,exports){var _equals=require("./internal/_equals");module.exports=require("./internal/_curry2")(function(a,b){return _equals(a,b,[],[])})},{"./internal/_curry2":1156,"./internal/_equals":1162}],1113:[function(require,module,exports){require=require("./internal/_curry2")(function evolve(transformations,object){var transformation,key,type,result=object instanceof Array?[]:{};for(key in object)transformation=transformations[key],result[key]="function"==(type=typeof transformation)?transformation(object[key]):transformation&&"object"==type?evolve(transformation,object[key]):object[key];return result});module.exports=require},{"./internal/_curry2":1156}],1114:[function(require,module,exports){var _filter=require("./internal/_filter"),_isObject=require("./internal/_isObject"),_reduce=require("./internal/_reduce"),keys=require("./keys");module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")(["filter"],require("./internal/_xfilter"),function(pred,filterable){return _isObject(filterable)?_reduce(function(acc,key){return pred(filterable[key])&&(acc[key]=filterable[key]),acc},{},keys(filterable)):_filter(pred,filterable)}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_filter":1163,"./internal/_isObject":1178,"./internal/_reduce":1191,"./internal/_xfilter":1206,"./keys":1228}],1115:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")(["find"],require("./internal/_xfind"),function(fn,list){for(var idx=0,len=list.length;idx<len;){if(fn(list[idx]))return list[idx];idx+=1}}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xfind":1207}],1116:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")([],require("./internal/_xfindIndex"),function(fn,list){for(var idx=0,len=list.length;idx<len;){if(fn(list[idx]))return idx;idx+=1}return-1}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xfindIndex":1208}],1117:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")([],require("./internal/_xfindLast"),function(fn,list){for(var idx=list.length-1;0<=idx;){if(fn(list[idx]))return list[idx];--idx}}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xfindLast":1209}],1118:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")([],require("./internal/_xfindLastIndex"),function(fn,list){for(var idx=list.length-1;0<=idx;){if(fn(list[idx]))return idx;--idx}return-1}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xfindLastIndex":1210}],1119:[function(require,module,exports){module.exports=require("./internal/_curry1")(require("./internal/_makeFlat")(!0))},{"./internal/_curry1":1155,"./internal/_makeFlat":1183}],1120:[function(require,module,exports){var curryN=require("./curryN");module.exports=require("./internal/_curry1")(function(fn){return curryN(fn.length,function(a,b){var args=Array.prototype.slice.call(arguments,0);return args[0]=b,args[1]=a,fn.apply(this,args)})})},{"./curryN":1092,"./internal/_curry1":1155}],1121:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_checkForMethod")("forEach",function(fn,list){for(var len=list.length,idx=0;idx<len;)fn(list[idx]),idx+=1;return list}))},{"./internal/_checkForMethod":1149,"./internal/_curry2":1156}],1122:[function(require,module,exports){var keys=require("./keys");module.exports=require("./internal/_curry2")(function(fn,obj){for(var keyList=keys(obj),idx=0;idx<keyList.length;){var key=keyList[idx];fn(obj[key],key,obj),idx+=1}return obj})},{"./internal/_curry2":1156,"./keys":1228}],1123:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(pairs){for(var result={},idx=0;idx<pairs.length;)result[pairs[idx][0]]=pairs[idx][1],idx+=1;return result})},{"./internal/_curry1":1155}],1124:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_checkForMethod")("groupBy",require("./reduceBy")(function(acc,item){return(acc=null==acc?[]:acc).push(item),acc},null)))},{"./internal/_checkForMethod":1149,"./internal/_curry2":1156,"./reduceBy":1309}],1125:[function(require,module,exports){require=require("./internal/_curry2")(function(fn,list){for(var res=[],idx=0,len=list.length;idx<len;){for(var nextidx=idx+1;nextidx<len&&fn(list[nextidx-1],list[nextidx]);)nextidx+=1;res.push(list.slice(idx,nextidx)),idx=nextidx}return res});module.exports=require},{"./internal/_curry2":1156}],1126:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return b<a})},{"./internal/_curry2":1156}],1127:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return b<=a})},{"./internal/_curry2":1156}],1128:[function(require,module,exports){var hasPath=require("./hasPath");module.exports=require("./internal/_curry2")(function(prop,obj){return hasPath([prop],obj)})},{"./hasPath":1130,"./internal/_curry2":1156}],1129:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(prop,obj){return prop in obj})},{"./internal/_curry2":1156}],1130:[function(require,module,exports){var _has=require("./internal/_has"),isNil=require("./isNil"),require=require("./internal/_curry2")(function(_path,obj){if(0===_path.length||isNil(obj))return!1;for(var val=obj,idx=0;idx<_path.length;){if(isNil(val)||!_has(_path[idx],val))return!1;val=val[_path[idx]],idx+=1}return!0});module.exports=require},{"./internal/_curry2":1156,"./internal/_has":1167,"./isNil":1225}],1131:[function(require,module,exports){module.exports=require("./nth")(0)},{"./nth":1271}],1132:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_objectIs"))},{"./internal/_curry2":1156,"./internal/_objectIs":1186}],1133:[function(require,module,exports){module.exports=require("./internal/_curry1")(require("./internal/_identity"))},{"./internal/_curry1":1155,"./internal/_identity":1168}],1134:[function(require,module,exports){var curryN=require("./curryN");module.exports=require("./internal/_curry3")(function(condition,onTrue,onFalse){return curryN(Math.max(condition.length,onTrue.length,onFalse.length),function(){return(condition.apply(this,arguments)?onTrue:onFalse).apply(this,arguments)})})},{"./curryN":1092,"./internal/_curry3":1157}],1135:[function(require,module,exports){module.exports=require("./add")(1)},{"./add":1052}],1136:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_includes"))},{"./internal/_curry2":1156,"./internal/_includes":1169}],1137:[function(require,module,exports){module.exports={},module.exports.F=require("./F"),module.exports.T=require("./T"),module.exports.__=require("./__"),module.exports.add=require("./add"),module.exports.addIndex=require("./addIndex"),module.exports.adjust=require("./adjust"),module.exports.all=require("./all"),module.exports.allPass=require("./allPass"),module.exports.always=require("./always"),module.exports.and=require("./and"),module.exports.any=require("./any"),module.exports.anyPass=require("./anyPass"),module.exports.ap=require("./ap"),module.exports.aperture=require("./aperture"),module.exports.append=require("./append"),module.exports.apply=require("./apply"),module.exports.applySpec=require("./applySpec"),module.exports.applyTo=require("./applyTo"),module.exports.ascend=require("./ascend"),module.exports.assoc=require("./assoc"),module.exports.assocPath=require("./assocPath"),module.exports.binary=require("./binary"),module.exports.bind=require("./bind"),module.exports.both=require("./both"),module.exports.call=require("./call"),module.exports.chain=require("./chain"),module.exports.clamp=require("./clamp"),module.exports.clone=require("./clone"),module.exports.comparator=require("./comparator"),module.exports.complement=require("./complement"),module.exports.compose=require("./compose"),module.exports.composeK=require("./composeK"),module.exports.composeP=require("./composeP"),module.exports.composeWith=require("./composeWith"),module.exports.concat=require("./concat"),module.exports.cond=require("./cond"),module.exports.construct=require("./construct"),module.exports.constructN=require("./constructN"),module.exports.contains=require("./contains"),module.exports.converge=require("./converge"),module.exports.countBy=require("./countBy"),module.exports.curry=require("./curry"),module.exports.curryN=require("./curryN"),module.exports.dec=require("./dec"),module.exports.defaultTo=require("./defaultTo"),module.exports.descend=require("./descend"),module.exports.difference=require("./difference"),module.exports.differenceWith=require("./differenceWith"),module.exports.dissoc=require("./dissoc"),module.exports.dissocPath=require("./dissocPath"),module.exports.divide=require("./divide"),module.exports.drop=require("./drop"),module.exports.dropLast=require("./dropLast"),module.exports.dropLastWhile=require("./dropLastWhile"),module.exports.dropRepeats=require("./dropRepeats"),module.exports.dropRepeatsWith=require("./dropRepeatsWith"),module.exports.dropWhile=require("./dropWhile"),module.exports.either=require("./either"),module.exports.empty=require("./empty"),module.exports.endsWith=require("./endsWith"),module.exports.eqBy=require("./eqBy"),module.exports.eqProps=require("./eqProps"),module.exports.equals=require("./equals"),module.exports.evolve=require("./evolve"),module.exports.filter=require("./filter"),module.exports.find=require("./find"),module.exports.findIndex=require("./findIndex"),module.exports.findLast=require("./findLast"),module.exports.findLastIndex=require("./findLastIndex"),module.exports.flatten=require("./flatten"),module.exports.flip=require("./flip"),module.exports.forEach=require("./forEach"),module.exports.forEachObjIndexed=require("./forEachObjIndexed"),module.exports.fromPairs=require("./fromPairs"),module.exports.groupBy=require("./groupBy"),module.exports.groupWith=require("./groupWith"),module.exports.gt=require("./gt"),module.exports.gte=require("./gte"),module.exports.has=require("./has"),module.exports.hasIn=require("./hasIn"),module.exports.hasPath=require("./hasPath"),module.exports.head=require("./head"),module.exports.identical=require("./identical"),module.exports.identity=require("./identity"),module.exports.ifElse=require("./ifElse"),module.exports.inc=require("./inc"),module.exports.includes=require("./includes"),module.exports.indexBy=require("./indexBy"),module.exports.indexOf=require("./indexOf"),module.exports.init=require("./init"),module.exports.innerJoin=require("./innerJoin"),module.exports.insert=require("./insert"),module.exports.insertAll=require("./insertAll"),module.exports.intersection=require("./intersection"),module.exports.intersperse=require("./intersperse"),module.exports.into=require("./into"),module.exports.invert=require("./invert"),module.exports.invertObj=require("./invertObj"),module.exports.invoker=require("./invoker"),module.exports.is=require("./is"),module.exports.isEmpty=require("./isEmpty"),module.exports.isNil=require("./isNil"),module.exports.join=require("./join"),module.exports.juxt=require("./juxt"),module.exports.keys=require("./keys"),module.exports.keysIn=require("./keysIn"),module.exports.last=require("./last"),module.exports.lastIndexOf=require("./lastIndexOf"),module.exports.length=require("./length"),module.exports.lens=require("./lens"),module.exports.lensIndex=require("./lensIndex"),module.exports.lensPath=require("./lensPath"),module.exports.lensProp=require("./lensProp"),module.exports.lift=require("./lift"),module.exports.liftN=require("./liftN"),module.exports.lt=require("./lt"),module.exports.lte=require("./lte"),module.exports.map=require("./map"),module.exports.mapAccum=require("./mapAccum"),module.exports.mapAccumRight=require("./mapAccumRight"),module.exports.mapObjIndexed=require("./mapObjIndexed"),module.exports.match=require("./match"),module.exports.mathMod=require("./mathMod"),module.exports.max=require("./max"),module.exports.maxBy=require("./maxBy"),module.exports.mean=require("./mean"),module.exports.median=require("./median"),module.exports.memoizeWith=require("./memoizeWith"),module.exports.merge=require("./merge"),module.exports.mergeAll=require("./mergeAll"),module.exports.mergeDeepLeft=require("./mergeDeepLeft"),module.exports.mergeDeepRight=require("./mergeDeepRight"),module.exports.mergeDeepWith=require("./mergeDeepWith"),module.exports.mergeDeepWithKey=require("./mergeDeepWithKey"),module.exports.mergeLeft=require("./mergeLeft"),module.exports.mergeRight=require("./mergeRight"),module.exports.mergeWith=require("./mergeWith"),module.exports.mergeWithKey=require("./mergeWithKey"),module.exports.min=require("./min"),module.exports.minBy=require("./minBy"),module.exports.modulo=require("./modulo"),module.exports.move=require("./move"),module.exports.multiply=require("./multiply"),module.exports.nAry=require("./nAry"),module.exports.negate=require("./negate"),module.exports.none=require("./none"),module.exports.not=require("./not"),module.exports.nth=require("./nth"),module.exports.nthArg=require("./nthArg"),module.exports.o=require("./o"),module.exports.objOf=require("./objOf"),module.exports.of=require("./of"),module.exports.omit=require("./omit"),module.exports.once=require("./once"),module.exports.or=require("./or"),module.exports.otherwise=require("./otherwise"),module.exports.over=require("./over"),module.exports.pair=require("./pair"),module.exports.partial=require("./partial"),module.exports.partialRight=require("./partialRight"),module.exports.partition=require("./partition"),module.exports.path=require("./path"),module.exports.paths=require("./paths"),module.exports.pathEq=require("./pathEq"),module.exports.pathOr=require("./pathOr"),module.exports.pathSatisfies=require("./pathSatisfies"),module.exports.pick=require("./pick"),module.exports.pickAll=require("./pickAll"),module.exports.pickBy=require("./pickBy"),module.exports.pipe=require("./pipe"),module.exports.pipeK=require("./pipeK"),module.exports.pipeP=require("./pipeP"),module.exports.pipeWith=require("./pipeWith"),module.exports.pluck=require("./pluck"),module.exports.prepend=require("./prepend"),module.exports.product=require("./product"),module.exports.project=require("./project"),module.exports.prop=require("./prop"),module.exports.propEq=require("./propEq"),module.exports.propIs=require("./propIs"),module.exports.propOr=require("./propOr"),module.exports.propSatisfies=require("./propSatisfies"),module.exports.props=require("./props"),module.exports.range=require("./range"),module.exports.reduce=require("./reduce"),module.exports.reduceBy=require("./reduceBy"),module.exports.reduceRight=require("./reduceRight"),module.exports.reduceWhile=require("./reduceWhile"),module.exports.reduced=require("./reduced"),module.exports.reject=require("./reject"),module.exports.remove=require("./remove"),module.exports.repeat=require("./repeat"),module.exports.replace=require("./replace"),module.exports.reverse=require("./reverse"),module.exports.scan=require("./scan"),module.exports.sequence=require("./sequence"),module.exports.set=require("./set"),module.exports.slice=require("./slice"),module.exports.sort=require("./sort"),module.exports.sortBy=require("./sortBy"),module.exports.sortWith=require("./sortWith"),module.exports.split=require("./split"),module.exports.splitAt=require("./splitAt"),module.exports.splitEvery=require("./splitEvery"),module.exports.splitWhen=require("./splitWhen"),module.exports.startsWith=require("./startsWith"),module.exports.subtract=require("./subtract"),module.exports.sum=require("./sum"),module.exports.symmetricDifference=require("./symmetricDifference"),module.exports.symmetricDifferenceWith=require("./symmetricDifferenceWith"),module.exports.tail=require("./tail"),module.exports.take=require("./take"),module.exports.takeLast=require("./takeLast"),module.exports.takeLastWhile=require("./takeLastWhile"),module.exports.takeWhile=require("./takeWhile"),module.exports.tap=require("./tap"),module.exports.test=require("./test"),module.exports.andThen=require("./andThen"),module.exports.times=require("./times"),module.exports.toLower=require("./toLower"),module.exports.toPairs=require("./toPairs"),module.exports.toPairsIn=require("./toPairsIn"),module.exports.toString=require("./toString"),module.exports.toUpper=require("./toUpper"),module.exports.transduce=require("./transduce"),module.exports.transpose=require("./transpose"),module.exports.traverse=require("./traverse"),module.exports.trim=require("./trim"),module.exports.tryCatch=require("./tryCatch"),module.exports.type=require("./type"),module.exports.unapply=require("./unapply"),module.exports.unary=require("./unary"),module.exports.uncurryN=require("./uncurryN"),module.exports.unfold=require("./unfold"),module.exports.union=require("./union"),module.exports.unionWith=require("./unionWith"),module.exports.uniq=require("./uniq"),module.exports.uniqBy=require("./uniqBy"),module.exports.uniqWith=require("./uniqWith"),module.exports.unless=require("./unless"),module.exports.unnest=require("./unnest"),module.exports.until=require("./until"),module.exports.update=require("./update"),module.exports.useWith=require("./useWith"),module.exports.values=require("./values"),module.exports.valuesIn=require("./valuesIn"),module.exports.view=require("./view"),module.exports.when=require("./when"),module.exports.where=require("./where"),module.exports.whereEq=require("./whereEq"),module.exports.without=require("./without"),module.exports.xor=require("./xor"),module.exports.xprod=require("./xprod"),module.exports.zip=require("./zip"),module.exports.zipObj=require("./zipObj"),module.exports.zipWith=require("./zipWith"),module.exports.thunkify=require("./thunkify")},{"./F":1049,"./T":1050,"./__":1051,"./add":1052,"./addIndex":1053,"./adjust":1054,"./all":1055,"./allPass":1056,"./always":1057,"./and":1058,"./andThen":1059,"./any":1060,"./anyPass":1061,"./ap":1062,"./aperture":1063,"./append":1064,"./apply":1065,"./applySpec":1066,"./applyTo":1067,"./ascend":1068,"./assoc":1069,"./assocPath":1070,"./binary":1071,"./bind":1072,"./both":1073,"./call":1074,"./chain":1075,"./clamp":1076,"./clone":1077,"./comparator":1078,"./complement":1079,"./compose":1080,"./composeK":1081,"./composeP":1082,"./composeWith":1083,"./concat":1084,"./cond":1085,"./construct":1086,"./constructN":1087,"./contains":1088,"./converge":1089,"./countBy":1090,"./curry":1091,"./curryN":1092,"./dec":1093,"./defaultTo":1094,"./descend":1095,"./difference":1096,"./differenceWith":1097,"./dissoc":1098,"./dissocPath":1099,"./divide":1100,"./drop":1101,"./dropLast":1102,"./dropLastWhile":1103,"./dropRepeats":1104,"./dropRepeatsWith":1105,"./dropWhile":1106,"./either":1107,"./empty":1108,"./endsWith":1109,"./eqBy":1110,"./eqProps":1111,"./equals":1112,"./evolve":1113,"./filter":1114,"./find":1115,"./findIndex":1116,"./findLast":1117,"./findLastIndex":1118,"./flatten":1119,"./flip":1120,"./forEach":1121,"./forEachObjIndexed":1122,"./fromPairs":1123,"./groupBy":1124,"./groupWith":1125,"./gt":1126,"./gte":1127,"./has":1128,"./hasIn":1129,"./hasPath":1130,"./head":1131,"./identical":1132,"./identity":1133,"./ifElse":1134,"./inc":1135,"./includes":1136,"./indexBy":1138,"./indexOf":1139,"./init":1140,"./innerJoin":1141,"./insert":1142,"./insertAll":1143,"./intersection":1217,"./intersperse":1218,"./into":1219,"./invert":1220,"./invertObj":1221,"./invoker":1222,"./is":1223,"./isEmpty":1224,"./isNil":1225,"./join":1226,"./juxt":1227,"./keys":1228,"./keysIn":1229,"./last":1230,"./lastIndexOf":1231,"./length":1232,"./lens":1233,"./lensIndex":1234,"./lensPath":1235,"./lensProp":1236,"./lift":1237,"./liftN":1238,"./lt":1239,"./lte":1240,"./map":1241,"./mapAccum":1242,"./mapAccumRight":1243,"./mapObjIndexed":1244,"./match":1245,"./mathMod":1246,"./max":1247,"./maxBy":1248,"./mean":1249,"./median":1250,"./memoizeWith":1251,"./merge":1252,"./mergeAll":1253,"./mergeDeepLeft":1254,"./mergeDeepRight":1255,"./mergeDeepWith":1256,"./mergeDeepWithKey":1257,"./mergeLeft":1258,"./mergeRight":1259,"./mergeWith":1260,"./mergeWithKey":1261,"./min":1262,"./minBy":1263,"./modulo":1264,"./move":1265,"./multiply":1266,"./nAry":1267,"./negate":1268,"./none":1269,"./not":1270,"./nth":1271,"./nthArg":1272,"./o":1273,"./objOf":1274,"./of":1275,"./omit":1276,"./once":1277,"./or":1278,"./otherwise":1279,"./over":1280,"./pair":1281,"./partial":1282,"./partialRight":1283,"./partition":1284,"./path":1285,"./pathEq":1286,"./pathOr":1287,"./pathSatisfies":1288,"./paths":1289,"./pick":1290,"./pickAll":1291,"./pickBy":1292,"./pipe":1293,"./pipeK":1294,"./pipeP":1295,"./pipeWith":1296,"./pluck":1297,"./prepend":1298,"./product":1299,"./project":1300,"./prop":1301,"./propEq":1302,"./propIs":1303,"./propOr":1304,"./propSatisfies":1305,"./props":1306,"./range":1307,"./reduce":1308,"./reduceBy":1309,"./reduceRight":1310,"./reduceWhile":1311,"./reduced":1312,"./reject":1313,"./remove":1314,"./repeat":1315,"./replace":1316,"./reverse":1317,"./scan":1318,"./sequence":1319,"./set":1320,"./slice":1321,"./sort":1322,"./sortBy":1323,"./sortWith":1324,"./split":1325,"./splitAt":1326,"./splitEvery":1327,"./splitWhen":1328,"./startsWith":1329,"./subtract":1330,"./sum":1331,"./symmetricDifference":1332,"./symmetricDifferenceWith":1333,"./tail":1334,"./take":1335,"./takeLast":1336,"./takeLastWhile":1337,"./takeWhile":1338,"./tap":1339,"./test":1340,"./thunkify":1341,"./times":1342,"./toLower":1343,"./toPairs":1344,"./toPairsIn":1345,"./toString":1346,"./toUpper":1347,"./transduce":1348,"./transpose":1349,"./traverse":1350,"./trim":1351,"./tryCatch":1352,"./type":1353,"./unapply":1354,"./unary":1355,"./uncurryN":1356,"./unfold":1357,"./union":1358,"./unionWith":1359,"./uniq":1360,"./uniqBy":1361,"./uniqWith":1362,"./unless":1363,"./unnest":1364,"./until":1365,"./update":1366,"./useWith":1367,"./values":1368,"./valuesIn":1369,"./view":1370,"./when":1371,"./where":1372,"./whereEq":1373,"./without":1374,"./xor":1375,"./xprod":1376,"./zip":1377,"./zipObj":1378,"./zipWith":1379}],1138:[function(require,module,exports){module.exports=require("./reduceBy")(function(acc,elem){return elem},null)},{"./reduceBy":1309}],1139:[function(require,module,exports){var _indexOf=require("./internal/_indexOf"),_isArray=require("./internal/_isArray");module.exports=require("./internal/_curry2")(function(target,xs){return"function"!=typeof xs.indexOf||_isArray(xs)?_indexOf(xs,target,0):xs.indexOf(target)})},{"./internal/_curry2":1156,"./internal/_indexOf":1171,"./internal/_isArray":1173}],1140:[function(require,module,exports){module.exports=require("./slice")(0,-1)},{"./slice":1321}],1141:[function(require,module,exports){var _includesWith=require("./internal/_includesWith"),_filter=require("./internal/_filter");module.exports=require("./internal/_curry3")(function(pred,xs,ys){return _filter(function(x){return _includesWith(pred,x,ys)},xs)})},{"./internal/_curry3":1157,"./internal/_filter":1163,"./internal/_includesWith":1170}],1142:[function(require,module,exports){require=require("./internal/_curry3")(function(idx,elt,list){idx=idx<list.length&&0<=idx?idx:list.length;list=Array.prototype.slice.call(list,0);return list.splice(idx,0,elt),list});module.exports=require},{"./internal/_curry3":1157}],1143:[function(require,module,exports){require=require("./internal/_curry3")(function(idx,elts,list){return idx=idx<list.length&&0<=idx?idx:list.length,[].concat(Array.prototype.slice.call(list,0,idx),elts,Array.prototype.slice.call(list,idx))});module.exports=require},{"./internal/_curry3":1157}],1144:[function(require,module,exports){var _includes=require("./_includes");function hasOrAdd(item,shouldAdd,set){var prevSize,bIdx,type=typeof item;switch(type){case"string":case"number":return 0===item&&1/item==-1/0?!!set._items["-0"]||(shouldAdd&&(set._items["-0"]=!0),!1):null!==set._nativeSet?shouldAdd?(prevSize=set._nativeSet.size,set._nativeSet.add(item),set._nativeSet.size===prevSize):set._nativeSet.has(item):type in set._items?item in set._items[type]||(shouldAdd&&(set._items[type][item]=!0),!1):(shouldAdd&&(set._items[type]={},set._items[type][item]=!0),!1);case"boolean":return type in set._items?!!set._items[type][bIdx=item?1:0]||(shouldAdd&&(set._items[type][bIdx]=!0),!1):(shouldAdd&&(set._items[type]=item?[!1,!0]:[!0,!1]),!1);case"function":return null!==set._nativeSet?shouldAdd?(prevSize=set._nativeSet.size,set._nativeSet.add(item),set._nativeSet.size===prevSize):set._nativeSet.has(item):type in set._items?!!_includes(item,set._items[type])||(shouldAdd&&set._items[type].push(item),!1):(shouldAdd&&(set._items[type]=[item]),!1);case"undefined":return!!set._items[type]||(shouldAdd&&(set._items[type]=!0),!1);case"object":if(null===item)return!!set._items.null||(shouldAdd&&(set._items.null=!0),!1);default:return(type=Object.prototype.toString.call(item))in set._items?!!_includes(item,set._items[type])||(shouldAdd&&set._items[type].push(item),!1):(shouldAdd&&(set._items[type]=[item]),!1)}}module.exports=function(){function _Set(){this._nativeSet="function"==typeof Set?new Set:null,this._items={}}return _Set.prototype.add=function(item){return!hasOrAdd(item,!0,this)},_Set.prototype.has=function(item){return hasOrAdd(item,!1,this)},_Set}()},{"./_includes":1169}],1145:[function(require,module,exports){module.exports=function(n,list){for(var idx=0,limit=list.length-(n-1),acc=new Array(0<=limit?limit:0);idx<limit;)acc[idx]=Array.prototype.slice.call(list,idx,idx+n),idx+=1;return acc}},{}],1146:[function(require,module,exports){module.exports=function(n,fn){switch(n){case 0:return function(){return fn.apply(this,arguments)};case 1:return function(a0){return fn.apply(this,arguments)};case 2:return function(a0,a1){return fn.apply(this,arguments)};case 3:return function(a0,a1,a2){return fn.apply(this,arguments)};case 4:return function(a0,a1,a2,a3){return fn.apply(this,arguments)};case 5:return function(a0,a1,a2,a3,a4){return fn.apply(this,arguments)};case 6:return function(a0,a1,a2,a3,a4,a5){return fn.apply(this,arguments)};case 7:return function(a0,a1,a2,a3,a4,a5,a6){return fn.apply(this,arguments)};case 8:return function(a0,a1,a2,a3,a4,a5,a6,a7){return fn.apply(this,arguments)};case 9:return function(a0,a1,a2,a3,a4,a5,a6,a7,a8){return fn.apply(this,arguments)};case 10:return function(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9){return fn.apply(this,arguments)};default:throw new Error("First argument to _arity must be a non-negative integer no greater than ten")}}},{}],1147:[function(require,module,exports){module.exports=function(iter){for(var next,list=[];!(next=iter.next()).done;)list.push(next.value);return list}},{}],1148:[function(require,module,exports){var _isFunction=require("./_isFunction"),_toString=require("./_toString");module.exports=function(name,p){if(null==p||!_isFunction(p.then))throw new TypeError("`"+name+"` expected a Promise, received "+_toString(p,[]))}},{"./_isFunction":1175,"./_toString":1195}],1149:[function(require,module,exports){var _isArray=require("./_isArray");module.exports=function(methodname,fn){return function(){var obj,length=arguments.length;return 0===length?fn():_isArray(obj=arguments[length-1])||"function"!=typeof obj[methodname]?fn.apply(this,arguments):obj[methodname].apply(obj,Array.prototype.slice.call(arguments,0,length-1))}}},{"./_isArray":1173}],1150:[function(require,module,exports){var _cloneRegExp=require("./_cloneRegExp"),type=require("../type");module.exports=function _clone(value,refFrom,refTo,deep){function copy(copiedValue){for(var key,len=refFrom.length,idx=0;idx<len;){if(value===refFrom[idx])return refTo[idx];idx+=1}for(key in refFrom[idx+1]=value,refTo[idx+1]=copiedValue,value)copiedValue[key]=deep?_clone(value[key],refFrom,refTo,!0):value[key];return copiedValue}switch(type(value)){case"Object":return copy({});case"Array":return copy([]);case"Date":return new Date(value.valueOf());case"RegExp":return _cloneRegExp(value);default:return value}}},{"../type":1353,"./_cloneRegExp":1151}],1151:[function(require,module,exports){module.exports=function(pattern){return new RegExp(pattern.source,(pattern.global?"g":"")+(pattern.ignoreCase?"i":"")+(pattern.multiline?"m":"")+(pattern.sticky?"y":"")+(pattern.unicode?"u":""))}},{}],1152:[function(require,module,exports){module.exports=function(f){return function(){return!f.apply(this,arguments)}}},{}],1153:[function(require,module,exports){module.exports=function(set1,set2){for(var len1=(set1=set1||[]).length,len2=(set2=set2||[]).length,result=[],idx=0;idx<len1;)result[result.length]=set1[idx],idx+=1;for(idx=0;idx<len2;)result[result.length]=set2[idx],idx+=1;return result}},{}],1154:[function(require,module,exports){var _arity=require("./_arity"),_curry2=require("./_curry2");module.exports=function(concat){return _curry2(function(fn,args){return _arity(Math.max(0,fn.length-args.length),function(){return fn.apply(this,concat(args,arguments))})})}},{"./_arity":1146,"./_curry2":1156}],1155:[function(require,module,exports){var _isPlaceholder=require("./_isPlaceholder");module.exports=function(fn){return function f1(a){return 0===arguments.length||_isPlaceholder(a)?f1:fn.apply(this,arguments)}}},{"./_isPlaceholder":1179}],1156:[function(require,module,exports){var _curry1=require("./_curry1"),_isPlaceholder=require("./_isPlaceholder");module.exports=function(fn){return function f2(a,b){switch(arguments.length){case 0:return f2;case 1:return _isPlaceholder(a)?f2:_curry1(function(_b){return fn(a,_b)});default:return _isPlaceholder(a)&&_isPlaceholder(b)?f2:_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b)}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b)}):fn(a,b)}}}},{"./_curry1":1155,"./_isPlaceholder":1179}],1157:[function(require,module,exports){var _curry1=require("./_curry1"),_curry2=require("./_curry2"),_isPlaceholder=require("./_isPlaceholder");module.exports=function(fn){return function f3(a,b,c){switch(arguments.length){case 0:return f3;case 1:return _isPlaceholder(a)?f3:_curry2(function(_b,_c){return fn(a,_b,_c)});case 2:return _isPlaceholder(a)&&_isPlaceholder(b)?f3:_isPlaceholder(a)?_curry2(function(_a,_c){return fn(_a,b,_c)}):_isPlaceholder(b)?_curry2(function(_b,_c){return fn(a,_b,_c)}):_curry1(function(_c){return fn(a,b,_c)});default:return _isPlaceholder(a)&&_isPlaceholder(b)&&_isPlaceholder(c)?f3:_isPlaceholder(a)&&_isPlaceholder(b)?_curry2(function(_a,_b){return fn(_a,_b,c)}):_isPlaceholder(a)&&_isPlaceholder(c)?_curry2(function(_a,_c){return fn(_a,b,_c)}):_isPlaceholder(b)&&_isPlaceholder(c)?_curry2(function(_b,_c){return fn(a,_b,_c)}):_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b,c)}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b,c)}):_isPlaceholder(c)?_curry1(function(_c){return fn(a,b,_c)}):fn(a,b,c)}}}},{"./_curry1":1155,"./_curry2":1156,"./_isPlaceholder":1179}],1158:[function(require,module,exports){var _arity=require("./_arity"),_isPlaceholder=require("./_isPlaceholder");module.exports=function _curryN(length,received,fn){return function(){for(var result,combined=[],argsIdx=0,left=length,combinedIdx=0;combinedIdx<received.length||argsIdx<arguments.length;)combinedIdx<received.length&&(!_isPlaceholder(received[combinedIdx])||arguments.length<=argsIdx)?result=received[combinedIdx]:(result=arguments[argsIdx],argsIdx+=1),_isPlaceholder(combined[combinedIdx]=result)||--left,combinedIdx+=1;return left<=0?fn.apply(this,combined):_arity(left,_curryN(length,combined,fn))}}},{"./_arity":1146,"./_isPlaceholder":1179}],1159:[function(require,module,exports){var _isArray=require("./_isArray"),_isTransformer=require("./_isTransformer");module.exports=function(methodNames,xf,fn){return function(){if(0===arguments.length)return fn();var args=Array.prototype.slice.call(arguments,0),obj=args.pop();if(!_isArray(obj)){for(var idx=0;idx<methodNames.length;){if("function"==typeof obj[methodNames[idx]])return obj[methodNames[idx]].apply(obj,args);idx+=1}if(_isTransformer(obj))return xf.apply(null,args)(obj)}return fn.apply(this,arguments)}}},{"./_isArray":1173,"./_isTransformer":1182}],1160:[function(require,module,exports){var take=require("../take");module.exports=function(n,xs){return take(n<xs.length?xs.length-n:0,xs)}},{"../take":1335}],1161:[function(require,module,exports){var slice=require("../slice");module.exports=function(pred,xs){for(var idx=xs.length-1;0<=idx&&pred(xs[idx]);)--idx;return slice(0,idx+1,xs)}},{"../slice":1321}],1162:[function(require,module,exports){var _arrayFromIterator=require("./_arrayFromIterator"),_includesWith=require("./_includesWith"),_functionName=require("./_functionName"),_has=require("./_has"),_objectIs=require("./_objectIs"),keys=require("../keys"),type=require("../type");function _uniqContentEquals(aIterator,bIterator,stackA,stackB){aIterator=_arrayFromIterator(aIterator),bIterator=_arrayFromIterator(bIterator);function eq(_a,_b){return _equals(_a,_b,stackA.slice(),stackB.slice())}return!_includesWith(function(b,aItem){return!_includesWith(eq,aItem,b)},bIterator,aIterator)}function _equals(a,b,stackA,stackB){if(!_objectIs(a,b)){var typeA=type(a);if(typeA!==type(b))return!1;if(null==a||null==b)return!1;if("function"==typeof a["fantasy-land/equals"]||"function"==typeof b["fantasy-land/equals"])return"function"==typeof a["fantasy-land/equals"]&&a["fantasy-land/equals"](b)&&"function"==typeof b["fantasy-land/equals"]&&b["fantasy-land/equals"](a);if("function"==typeof a.equals||"function"==typeof b.equals)return"function"==typeof a.equals&&a.equals(b)&&"function"==typeof b.equals&&b.equals(a);switch(typeA){case"Arguments":case"Array":case"Object":if("function"==typeof a.constructor&&"Promise"===_functionName(a.constructor))return a===b;break;case"Boolean":case"Number":case"String":if(typeof a==typeof b&&_objectIs(a.valueOf(),b.valueOf()))break;return!1;case"Date":if(_objectIs(a.valueOf(),b.valueOf()))break;return!1;case"Error":return a.name===b.name&&a.message===b.message;case"RegExp":if(a.source!==b.source||a.global!==b.global||a.ignoreCase!==b.ignoreCase||a.multiline!==b.multiline||a.sticky!==b.sticky||a.unicode!==b.unicode)return!1}for(var idx=stackA.length-1;0<=idx;){if(stackA[idx]===a)return stackB[idx]===b;--idx}switch(typeA){case"Map":return a.size!==b.size?!1:_uniqContentEquals(a.entries(),b.entries(),stackA.concat([a]),stackB.concat([b]));case"Set":return a.size!==b.size?!1:_uniqContentEquals(a.values(),b.values(),stackA.concat([a]),stackB.concat([b]));case"Arguments":case"Array":case"Object":case"Boolean":case"Number":case"String":case"Date":case"Error":case"RegExp":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"ArrayBuffer":break;default:return!1}var keysA=keys(a);if(keysA.length!==keys(b).length)return!1;for(var extendedStackA=stackA.concat([a]),extendedStackB=stackB.concat([b]),idx=keysA.length-1;0<=idx;){var key=keysA[idx];if(!_has(key,b)||!_equals(b[key],a[key],extendedStackA,extendedStackB))return!1;--idx}}return!0}module.exports=_equals},{"../keys":1228,"../type":1353,"./_arrayFromIterator":1147,"./_functionName":1166,"./_has":1167,"./_includesWith":1170,"./_objectIs":1186}],1163:[function(require,module,exports){module.exports=function(fn,list){for(var idx=0,len=list.length,result=[];idx<len;)fn(list[idx])&&(result[result.length]=list[idx]),idx+=1;return result}},{}],1164:[function(require,module,exports){var _forceReduced=require("./_forceReduced"),_isArrayLike=require("./_isArrayLike"),_reduce=require("./_reduce"),_xfBase=require("./_xfBase");module.exports=function(xf){var rxf=function(xf){return{"@@transducer/init":_xfBase.init,"@@transducer/result":function(result){return xf["@@transducer/result"](result)},"@@transducer/step":function(result,input){result=xf["@@transducer/step"](result,input);return result["@@transducer/reduced"]?_forceReduced(result):result}}}(xf);return{"@@transducer/init":_xfBase.init,"@@transducer/result":function(result){return rxf["@@transducer/result"](result)},"@@transducer/step":function(result,input){return _isArrayLike(input)?_reduce(rxf,result,input):_reduce(rxf,result,[input])}}}},{"./_forceReduced":1165,"./_isArrayLike":1174,"./_reduce":1191,"./_xfBase":1205}],1165:[function(require,module,exports){module.exports=function(x){return{"@@transducer/value":x,"@@transducer/reduced":!0}}},{}],1166:[function(require,module,exports){module.exports=function(f){return null==(f=String(f).match(/^function (\w*)/))?"":f[1]}},{}],1167:[function(require,module,exports){module.exports=function(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop)}},{}],1168:[function(require,module,exports){module.exports=function(x){return x}},{}],1169:[function(require,module,exports){var _indexOf=require("./_indexOf");module.exports=function(a,list){return 0<=_indexOf(list,a,0)}},{"./_indexOf":1171}],1170:[function(require,module,exports){module.exports=function(pred,x,list){for(var idx=0,len=list.length;idx<len;){if(pred(x,list[idx]))return!0;idx+=1}return!1}},{}],1171:[function(require,module,exports){var equals=require("../equals");module.exports=function(list,a,idx){var inf,item;if("function"==typeof list.indexOf)switch(typeof a){case"number":if(0===a)for(inf=1/a;idx<list.length;){if(0===(item=list[idx])&&1/item==inf)return idx;idx+=1}else{if(a==a)return list.indexOf(a,idx);for(;idx<list.length;){if("number"==typeof(item=list[idx])&&item!=item)return idx;idx+=1}}return-1;case"string":case"boolean":case"function":case"undefined":return list.indexOf(a,idx);case"object":if(null===a)return list.indexOf(a,idx)}for(;idx<list.length;){if(equals(list[idx],a))return idx;idx+=1}return-1}},{"../equals":1112}],1172:[function(require,module,exports){var _has=require("./_has"),toString=Object.prototype.toString;module.exports=function(){return"[object Arguments]"===toString.call(arguments)?function(x){return"[object Arguments]"===toString.call(x)}:function(x){return _has("callee",x)}}()},{"./_has":1167}],1173:[function(require,module,exports){module.exports=Array.isArray||function(val){return null!=val&&0<=val.length&&"[object Array]"===Object.prototype.toString.call(val)}},{}],1174:[function(require,module,exports){var _isArray=require("./_isArray"),_isString=require("./_isString");module.exports=require("./_curry1")(function(x){return!!_isArray(x)||!!x&&"object"==typeof x&&!_isString(x)&&(1===x.nodeType?!!x.length:0===x.length||0<x.length&&x.hasOwnProperty(0)&&x.hasOwnProperty(x.length-1))})},{"./_curry1":1155,"./_isArray":1173,"./_isString":1181}],1175:[function(require,module,exports){module.exports=function(x){return"[object Function]"===(x=Object.prototype.toString.call(x))||"[object AsyncFunction]"===x||"[object GeneratorFunction]"===x||"[object AsyncGeneratorFunction]"===x}},{}],1176:[function(require,module,exports){module.exports=Number.isInteger||function(n){return n<<0===n}},{}],1177:[function(require,module,exports){module.exports=function(x){return"[object Number]"===Object.prototype.toString.call(x)}},{}],1178:[function(require,module,exports){module.exports=function(x){return"[object Object]"===Object.prototype.toString.call(x)}},{}],1179:[function(require,module,exports){module.exports=function(a){return null!=a&&"object"==typeof a&&!0===a["@@functional/placeholder"]}},{}],1180:[function(require,module,exports){module.exports=function(x){return"[object RegExp]"===Object.prototype.toString.call(x)}},{}],1181:[function(require,module,exports){module.exports=function(x){return"[object String]"===Object.prototype.toString.call(x)}},{}],1182:[function(require,module,exports){module.exports=function(obj){return null!=obj&&"function"==typeof obj["@@transducer/step"]}},{}],1183:[function(require,module,exports){var _isArrayLike=require("./_isArrayLike");module.exports=function(recursive){return function flatt(list){for(var value,jlen,j,result=[],idx=0,ilen=list.length;idx<ilen;){if(_isArrayLike(list[idx]))for(j=0,jlen=(value=recursive?flatt(list[idx]):list[idx]).length;j<jlen;)result[result.length]=value[j],j+=1;else result[result.length]=list[idx];idx+=1}return result}}},{"./_isArrayLike":1174}],1184:[function(require,module,exports){module.exports=function(fn,functor){for(var idx=0,len=functor.length,result=Array(len);idx<len;)result[idx]=fn(functor[idx]),idx+=1;return result}},{}],1185:[function(require,module,exports){var _has=require("./_has");module.exports="function"==typeof Object.assign?Object.assign:function(target){if(null==target)throw new TypeError("Cannot convert undefined or null to object");for(var output=Object(target),idx=1,length=arguments.length;idx<length;){var source=arguments[idx];if(null!=source)for(var nextKey in source)_has(nextKey,source)&&(output[nextKey]=source[nextKey]);idx+=1}return output}},{"./_has":1167}],1186:[function(require,module,exports){module.exports="function"==typeof Object.is?Object.is:function(a,b){return a===b?0!==a||1/a==1/b:a!=a&&b!=b}},{}],1187:[function(require,module,exports){module.exports=function(x){return[x]}},{}],1188:[function(require,module,exports){module.exports=function(f,g){return function(){return g.call(this,f.apply(this,arguments))}}},{}],1189:[function(require,module,exports){module.exports=function(f,g){return function(){var ctx=this;return f.apply(ctx,arguments).then(function(x){return g.call(ctx,x)})}}},{}],1190:[function(require,module,exports){module.exports=function(s){return'"'+s.replace(/\\/g,"\\\\").replace(/[\b]/g,"\\b").replace(/\f/g,"\\f").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\v/g,"\\v").replace(/\0/g,"\\0").replace(/"/g,'\\"')+'"'}},{}],1191:[function(require,module,exports){var _isArrayLike=require("./_isArrayLike"),_xwrap=require("./_xwrap"),bind=require("../bind");function _iterableReduce(xf,acc,iter){for(var step=iter.next();!step.done;){if((acc=xf["@@transducer/step"](acc,step.value))&&acc["@@transducer/reduced"]){acc=acc["@@transducer/value"];break}step=iter.next()}return xf["@@transducer/result"](acc)}function _methodReduce(xf,acc,obj,methodName){return xf["@@transducer/result"](obj[methodName](bind(xf["@@transducer/step"],xf),acc))}var symIterator="undefined"!=typeof Symbol?Symbol.iterator:"@@iterator";module.exports=function(fn,acc,list){if("function"==typeof fn&&(fn=_xwrap(fn)),_isArrayLike(list))return function(xf,acc,list){for(var idx=0,len=list.length;idx<len;){if((acc=xf["@@transducer/step"](acc,list[idx]))&&acc["@@transducer/reduced"]){acc=acc["@@transducer/value"];break}idx+=1}return xf["@@transducer/result"](acc)}(fn,acc,list);if("function"==typeof list["fantasy-land/reduce"])return _methodReduce(fn,acc,list,"fantasy-land/reduce");if(null!=list[symIterator])return _iterableReduce(fn,acc,list[symIterator]());if("function"==typeof list.next)return _iterableReduce(fn,acc,list);if("function"==typeof list.reduce)return _methodReduce(fn,acc,list,"reduce");throw new TypeError("reduce: list must be array or iterable")}},{"../bind":1072,"./_isArrayLike":1174,"./_xwrap":1216}],1192:[function(require,module,exports){module.exports=function(x){return x&&x["@@transducer/reduced"]?x:{"@@transducer/value":x,"@@transducer/reduced":!0}}},{}],1193:[function(require,module,exports){var _objectAssign=require("./_objectAssign"),_identity=require("./_identity"),_isArrayLike=require("./_isArrayLike"),_isTransformer=require("./_isTransformer"),objOf=require("../objOf"),_stepCatArray={"@@transducer/init":Array,"@@transducer/step":function(xs,x){return xs.push(x),xs},"@@transducer/result":_identity},_stepCatString={"@@transducer/init":String,"@@transducer/step":function(a,b){return a+b},"@@transducer/result":_identity},_stepCatObject={"@@transducer/init":Object,"@@transducer/step":function(result,input){return _objectAssign(result,_isArrayLike(input)?objOf(input[0],input[1]):input)},"@@transducer/result":_identity};module.exports=function(obj){if(_isTransformer(obj))return obj;if(_isArrayLike(obj))return _stepCatArray;if("string"==typeof obj)return _stepCatString;if("object"==typeof obj)return _stepCatObject;throw new Error("Cannot create transformer for "+obj)}},{"../objOf":1274,"./_identity":1168,"./_isArrayLike":1174,"./_isTransformer":1182,"./_objectAssign":1185}],1194:[function(require,module,exports){function pad(n){return(n<10?"0":"")+n}var _toISOString="function"==typeof Date.prototype.toISOString?function(d){return d.toISOString()}:function(d){return d.getUTCFullYear()+"-"+pad(d.getUTCMonth()+1)+"-"+pad(d.getUTCDate())+"T"+pad(d.getUTCHours())+":"+pad(d.getUTCMinutes())+":"+pad(d.getUTCSeconds())+"."+(d.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"};module.exports=_toISOString},{}],1195:[function(require,module,exports){var _includes=require("./_includes"),_map=require("./_map"),_quote=require("./_quote"),_toISOString=require("./_toISOString"),keys=require("../keys"),reject=require("../reject");module.exports=function _toString(x,seen){function recur(y){var xs=seen.concat([x]);return _includes(y,xs)?"<Circular>":_toString(y,xs)}function mapPairs(obj,keys){return _map(function(k){return _quote(k)+": "+recur(obj[k])},keys.slice().sort())}switch(Object.prototype.toString.call(x)){case"[object Arguments]":return"(function() { return arguments; }("+_map(recur,x).join(", ")+"))";case"[object Array]":return"["+_map(recur,x).concat(mapPairs(x,reject(function(k){return/^\d+$/.test(k)},keys(x)))).join(", ")+"]";case"[object Boolean]":return"object"==typeof x?"new Boolean("+recur(x.valueOf())+")":x.toString();case"[object Date]":return"new Date("+(isNaN(x.valueOf())?recur(NaN):_quote(_toISOString(x)))+")";case"[object Null]":return"null";case"[object Number]":return"object"==typeof x?"new Number("+recur(x.valueOf())+")":1/x==-1/0?"-0":x.toString(10);case"[object String]":return"object"==typeof x?"new String("+recur(x.valueOf())+")":_quote(x);case"[object Undefined]":return"undefined";default:if("function"==typeof x.toString){var repr=x.toString();if("[object Object]"!==repr)return repr}return"{"+mapPairs(x,keys(x)).join(", ")+"}"}}},{"../keys":1228,"../reject":1313,"./_includes":1169,"./_map":1184,"./_quote":1190,"./_toISOString":1194}],1196:[function(require,module,exports){var _curry2=require("./_curry2"),_reduced=require("./_reduced"),_xfBase=require("./_xfBase"),XAll=function(){function XAll(f,xf){this.xf=xf,this.f=f,this.all=!0}return XAll.prototype["@@transducer/init"]=_xfBase.init,XAll.prototype["@@transducer/result"]=function(result){return this.all&&(result=this.xf["@@transducer/step"](result,!0)),this.xf["@@transducer/result"](result)},XAll.prototype["@@transducer/step"]=function(result,input){return this.f(input)||(this.all=!1,result=_reduced(this.xf["@@transducer/step"](result,!1))),result},XAll}(),require=_curry2(function(f,xf){return new XAll(f,xf)});module.exports=require},{"./_curry2":1156,"./_reduced":1192,"./_xfBase":1205}],1197:[function(require,module,exports){var _curry2=require("./_curry2"),_reduced=require("./_reduced"),_xfBase=require("./_xfBase"),XAny=function(){function XAny(f,xf){this.xf=xf,this.f=f,this.any=!1}return XAny.prototype["@@transducer/init"]=_xfBase.init,XAny.prototype["@@transducer/result"]=function(result){return this.any||(result=this.xf["@@transducer/step"](result,!1)),this.xf["@@transducer/result"](result)},XAny.prototype["@@transducer/step"]=function(result,input){return this.f(input)&&(this.any=!0,result=_reduced(this.xf["@@transducer/step"](result,!0))),result},XAny}(),require=_curry2(function(f,xf){return new XAny(f,xf)});module.exports=require},{"./_curry2":1156,"./_reduced":1192,"./_xfBase":1205}],1198:[function(require,module,exports){var _concat=require("./_concat"),_curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XAperture=function(){function XAperture(n,xf){this.xf=xf,this.pos=0,this.full=!1,this.acc=new Array(n)}return XAperture.prototype["@@transducer/init"]=_xfBase.init,XAperture.prototype["@@transducer/result"]=function(result){return this.acc=null,this.xf["@@transducer/result"](result)},XAperture.prototype["@@transducer/step"]=function(result,input){return this.store(input),this.full?this.xf["@@transducer/step"](result,this.getCopy()):result},XAperture.prototype.store=function(input){this.acc[this.pos]=input,this.pos+=1,this.pos===this.acc.length&&(this.pos=0,this.full=!0)},XAperture.prototype.getCopy=function(){return _concat(Array.prototype.slice.call(this.acc,this.pos),Array.prototype.slice.call(this.acc,0,this.pos))},XAperture}(),require=_curry2(function(n,xf){return new XAperture(n,xf)});module.exports=require},{"./_concat":1153,"./_curry2":1156,"./_xfBase":1205}],1199:[function(require,module,exports){var _flatCat=require("./_flatCat"),map=require("../map");module.exports=require("./_curry2")(function(f,xf){return map(f,_flatCat(xf))})},{"../map":1241,"./_curry2":1156,"./_flatCat":1164}],1200:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XDrop=function(){function XDrop(n,xf){this.xf=xf,this.n=n}return XDrop.prototype["@@transducer/init"]=_xfBase.init,XDrop.prototype["@@transducer/result"]=_xfBase.result,XDrop.prototype["@@transducer/step"]=function(result,input){return 0<this.n?(--this.n,result):this.xf["@@transducer/step"](result,input)},XDrop}(),require=_curry2(function(n,xf){return new XDrop(n,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1201:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XDropLast=function(){function XDropLast(n,xf){this.xf=xf,this.pos=0,this.full=!1,this.acc=new Array(n)}return XDropLast.prototype["@@transducer/init"]=_xfBase.init,XDropLast.prototype["@@transducer/result"]=function(result){return this.acc=null,this.xf["@@transducer/result"](result)},XDropLast.prototype["@@transducer/step"]=function(result,input){return this.full&&(result=this.xf["@@transducer/step"](result,this.acc[this.pos])),this.store(input),result},XDropLast.prototype.store=function(input){this.acc[this.pos]=input,this.pos+=1,this.pos===this.acc.length&&(this.pos=0,this.full=!0)},XDropLast}(),require=_curry2(function(n,xf){return new XDropLast(n,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1202:[function(require,module,exports){var _curry2=require("./_curry2"),_reduce=require("./_reduce"),_xfBase=require("./_xfBase"),XDropLastWhile=function(){function XDropLastWhile(fn,xf){this.f=fn,this.retained=[],this.xf=xf}return XDropLastWhile.prototype["@@transducer/init"]=_xfBase.init,XDropLastWhile.prototype["@@transducer/result"]=function(result){return this.retained=null,this.xf["@@transducer/result"](result)},XDropLastWhile.prototype["@@transducer/step"]=function(result,input){return this.f(input)?this.retain(result,input):this.flush(result,input)},XDropLastWhile.prototype.flush=function(result,input){return result=_reduce(this.xf["@@transducer/step"],result,this.retained),this.retained=[],this.xf["@@transducer/step"](result,input)},XDropLastWhile.prototype.retain=function(result,input){return this.retained.push(input),result},XDropLastWhile}(),require=_curry2(function(fn,xf){return new XDropLastWhile(fn,xf)});module.exports=require},{"./_curry2":1156,"./_reduce":1191,"./_xfBase":1205}],1203:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XDropRepeatsWith=function(){function XDropRepeatsWith(pred,xf){this.xf=xf,this.pred=pred,this.lastValue=void 0,this.seenFirstValue=!1}return XDropRepeatsWith.prototype["@@transducer/init"]=_xfBase.init,XDropRepeatsWith.prototype["@@transducer/result"]=_xfBase.result,XDropRepeatsWith.prototype["@@transducer/step"]=function(result,input){var sameAsLast=!1;return this.seenFirstValue?this.pred(this.lastValue,input)&&(sameAsLast=!0):this.seenFirstValue=!0,this.lastValue=input,sameAsLast?result:this.xf["@@transducer/step"](result,input)},XDropRepeatsWith}(),require=_curry2(function(pred,xf){return new XDropRepeatsWith(pred,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1204:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XDropWhile=function(){function XDropWhile(f,xf){this.xf=xf,this.f=f}return XDropWhile.prototype["@@transducer/init"]=_xfBase.init,XDropWhile.prototype["@@transducer/result"]=_xfBase.result,XDropWhile.prototype["@@transducer/step"]=function(result,input){if(this.f){if(this.f(input))return result;this.f=null}return this.xf["@@transducer/step"](result,input)},XDropWhile}(),require=_curry2(function(f,xf){return new XDropWhile(f,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1205:[function(require,module,exports){module.exports={init:function(){return this.xf["@@transducer/init"]()},result:function(result){return this.xf["@@transducer/result"](result)}}},{}],1206:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XFilter=function(){function XFilter(f,xf){this.xf=xf,this.f=f}return XFilter.prototype["@@transducer/init"]=_xfBase.init,XFilter.prototype["@@transducer/result"]=_xfBase.result,XFilter.prototype["@@transducer/step"]=function(result,input){return this.f(input)?this.xf["@@transducer/step"](result,input):result},XFilter}(),require=_curry2(function(f,xf){return new XFilter(f,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1207:[function(require,module,exports){var _curry2=require("./_curry2"),_reduced=require("./_reduced"),_xfBase=require("./_xfBase"),XFind=function(){function XFind(f,xf){this.xf=xf,this.f=f,this.found=!1}return XFind.prototype["@@transducer/init"]=_xfBase.init,XFind.prototype["@@transducer/result"]=function(result){return this.found||(result=this.xf["@@transducer/step"](result,void 0)),this.xf["@@transducer/result"](result)},XFind.prototype["@@transducer/step"]=function(result,input){return this.f(input)&&(this.found=!0,result=_reduced(this.xf["@@transducer/step"](result,input))),result},XFind}(),require=_curry2(function(f,xf){return new XFind(f,xf)});module.exports=require},{"./_curry2":1156,"./_reduced":1192,"./_xfBase":1205}],1208:[function(require,module,exports){var _curry2=require("./_curry2"),_reduced=require("./_reduced"),_xfBase=require("./_xfBase"),XFindIndex=function(){function XFindIndex(f,xf){this.xf=xf,this.f=f,this.idx=-1,this.found=!1}return XFindIndex.prototype["@@transducer/init"]=_xfBase.init,XFindIndex.prototype["@@transducer/result"]=function(result){return this.found||(result=this.xf["@@transducer/step"](result,-1)),this.xf["@@transducer/result"](result)},XFindIndex.prototype["@@transducer/step"]=function(result,input){return this.idx+=1,this.f(input)&&(this.found=!0,result=_reduced(this.xf["@@transducer/step"](result,this.idx))),result},XFindIndex}(),require=_curry2(function(f,xf){return new XFindIndex(f,xf)});module.exports=require},{"./_curry2":1156,"./_reduced":1192,"./_xfBase":1205}],1209:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XFindLast=function(){function XFindLast(f,xf){this.xf=xf,this.f=f}return XFindLast.prototype["@@transducer/init"]=_xfBase.init,XFindLast.prototype["@@transducer/result"]=function(result){return this.xf["@@transducer/result"](this.xf["@@transducer/step"](result,this.last))},XFindLast.prototype["@@transducer/step"]=function(result,input){return this.f(input)&&(this.last=input),result},XFindLast}(),require=_curry2(function(f,xf){return new XFindLast(f,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1210:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XFindLastIndex=function(){function XFindLastIndex(f,xf){this.xf=xf,this.f=f,this.idx=-1,this.lastIdx=-1}return XFindLastIndex.prototype["@@transducer/init"]=_xfBase.init,XFindLastIndex.prototype["@@transducer/result"]=function(result){return this.xf["@@transducer/result"](this.xf["@@transducer/step"](result,this.lastIdx))},XFindLastIndex.prototype["@@transducer/step"]=function(result,input){return this.idx+=1,this.f(input)&&(this.lastIdx=this.idx),result},XFindLastIndex}(),require=_curry2(function(f,xf){return new XFindLastIndex(f,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1211:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XMap=function(){function XMap(f,xf){this.xf=xf,this.f=f}return XMap.prototype["@@transducer/init"]=_xfBase.init,XMap.prototype["@@transducer/result"]=_xfBase.result,XMap.prototype["@@transducer/step"]=function(result,input){return this.xf["@@transducer/step"](result,this.f(input))},XMap}(),require=_curry2(function(f,xf){return new XMap(f,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1212:[function(require,module,exports){var _curryN=require("./_curryN"),_has=require("./_has"),_xfBase=require("./_xfBase"),XReduceBy=function(){function XReduceBy(valueFn,valueAcc,keyFn,xf){this.valueFn=valueFn,this.valueAcc=valueAcc,this.keyFn=keyFn,this.xf=xf,this.inputs={}}return XReduceBy.prototype["@@transducer/init"]=_xfBase.init,XReduceBy.prototype["@@transducer/result"]=function(result){for(var key in this.inputs)if(_has(key,this.inputs)&&(result=this.xf["@@transducer/step"](result,this.inputs[key]))["@@transducer/reduced"]){result=result["@@transducer/value"];break}return this.inputs=null,this.xf["@@transducer/result"](result)},XReduceBy.prototype["@@transducer/step"]=function(result,input){var key=this.keyFn(input);return this.inputs[key]=this.inputs[key]||[key,this.valueAcc],this.inputs[key][1]=this.valueFn(this.inputs[key][1],input),result},XReduceBy}(),require=_curryN(4,[],function(valueFn,valueAcc,keyFn,xf){return new XReduceBy(valueFn,valueAcc,keyFn,xf)});module.exports=require},{"./_curryN":1158,"./_has":1167,"./_xfBase":1205}],1213:[function(require,module,exports){var _curry2=require("./_curry2"),_reduced=require("./_reduced"),_xfBase=require("./_xfBase"),XTake=function(){function XTake(n,xf){this.xf=xf,this.n=n,this.i=0}return XTake.prototype["@@transducer/init"]=_xfBase.init,XTake.prototype["@@transducer/result"]=_xfBase.result,XTake.prototype["@@transducer/step"]=function(result,input){this.i+=1;result=0===this.n?result:this.xf["@@transducer/step"](result,input);return 0<=this.n&&this.i>=this.n?_reduced(result):result},XTake}(),require=_curry2(function(n,xf){return new XTake(n,xf)});module.exports=require},{"./_curry2":1156,"./_reduced":1192,"./_xfBase":1205}],1214:[function(require,module,exports){var _curry2=require("./_curry2"),_reduced=require("./_reduced"),_xfBase=require("./_xfBase"),XTakeWhile=function(){function XTakeWhile(f,xf){this.xf=xf,this.f=f}return XTakeWhile.prototype["@@transducer/init"]=_xfBase.init,XTakeWhile.prototype["@@transducer/result"]=_xfBase.result,XTakeWhile.prototype["@@transducer/step"]=function(result,input){return this.f(input)?this.xf["@@transducer/step"](result,input):_reduced(result)},XTakeWhile}(),require=_curry2(function(f,xf){return new XTakeWhile(f,xf)});module.exports=require},{"./_curry2":1156,"./_reduced":1192,"./_xfBase":1205}],1215:[function(require,module,exports){var _curry2=require("./_curry2"),_xfBase=require("./_xfBase"),XTap=function(){function XTap(f,xf){this.xf=xf,this.f=f}return XTap.prototype["@@transducer/init"]=_xfBase.init,XTap.prototype["@@transducer/result"]=_xfBase.result,XTap.prototype["@@transducer/step"]=function(result,input){return this.f(input),this.xf["@@transducer/step"](result,input)},XTap}(),require=_curry2(function(f,xf){return new XTap(f,xf)});module.exports=require},{"./_curry2":1156,"./_xfBase":1205}],1216:[function(require,module,exports){var XWrap=function(){function XWrap(fn){this.f=fn}return XWrap.prototype["@@transducer/init"]=function(){throw new Error("init not implemented on XWrap")},XWrap.prototype["@@transducer/result"]=function(acc){return acc},XWrap.prototype["@@transducer/step"]=function(acc,x){return this.f(acc,x)},XWrap}();module.exports=function(fn){return new XWrap(fn)}},{}],1217:[function(require,module,exports){var _includes=require("./internal/_includes"),_filter=require("./internal/_filter"),flip=require("./flip"),uniq=require("./uniq"),require=require("./internal/_curry2")(function(list1,list2){var lookupList,list2=list1.length>list2.length?(lookupList=list1,list2):(lookupList=list2,list1);return uniq(_filter(flip(_includes)(lookupList),list2))});module.exports=require},{"./flip":1120,"./internal/_curry2":1156,"./internal/_filter":1163,"./internal/_includes":1169,"./uniq":1360}],1218:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_checkForMethod")("intersperse",function(separator,list){for(var out=[],idx=0,length=list.length;idx<length;)idx===length-1?out.push(list[idx]):out.push(list[idx],separator),idx+=1;return out}))},{"./internal/_checkForMethod":1149,"./internal/_curry2":1156}],1219:[function(require,module,exports){var _clone=require("./internal/_clone"),_isTransformer=require("./internal/_isTransformer"),_reduce=require("./internal/_reduce"),_stepCat=require("./internal/_stepCat");module.exports=require("./internal/_curry3")(function(acc,xf,list){return _isTransformer(acc)?_reduce(xf(acc),acc["@@transducer/init"](),list):_reduce(xf(_stepCat(acc)),_clone(acc,[],[],!1),list)})},{"./internal/_clone":1150,"./internal/_curry3":1157,"./internal/_isTransformer":1182,"./internal/_reduce":1191,"./internal/_stepCat":1193}],1220:[function(require,module,exports){var _has=require("./internal/_has"),keys=require("./keys");module.exports=require("./internal/_curry1")(function(obj){for(var props=keys(obj),len=props.length,idx=0,out={};idx<len;){var key=props[idx],val=obj[key],val=_has(val,out)?out[val]:out[val]=[];val[val.length]=key,idx+=1}return out})},{"./internal/_curry1":1155,"./internal/_has":1167,"./keys":1228}],1221:[function(require,module,exports){var keys=require("./keys");module.exports=require("./internal/_curry1")(function(obj){for(var props=keys(obj),len=props.length,idx=0,out={};idx<len;){var key=props[idx];out[obj[key]]=key,idx+=1}return out})},{"./internal/_curry1":1155,"./keys":1228}],1222:[function(require,module,exports){var _isFunction=require("./internal/_isFunction"),curryN=require("./curryN"),toString=require("./toString");module.exports=require("./internal/_curry2")(function(arity,method){return curryN(arity+1,function(){var target=arguments[arity];if(null!=target&&_isFunction(target[method]))return target[method].apply(target,Array.prototype.slice.call(arguments,0,arity));throw new TypeError(toString(target)+' does not have a method named "'+method+'"')})})},{"./curryN":1092,"./internal/_curry2":1156,"./internal/_isFunction":1175,"./toString":1346}],1223:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(Ctor,val){return null!=val&&val.constructor===Ctor||val instanceof Ctor})},{"./internal/_curry2":1156}],1224:[function(require,module,exports){var empty=require("./empty"),equals=require("./equals");module.exports=require("./internal/_curry1")(function(x){return null!=x&&equals(x,empty(x))})},{"./empty":1108,"./equals":1112,"./internal/_curry1":1155}],1225:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(x){return null==x})},{"./internal/_curry1":1155}],1226:[function(require,module,exports){module.exports=require("./invoker")(1,"join")},{"./invoker":1222}],1227:[function(require,module,exports){var converge=require("./converge");module.exports=require("./internal/_curry1")(function(fns){return converge(function(){return Array.prototype.slice.call(arguments,0)},fns)})},{"./converge":1089,"./internal/_curry1":1155}],1228:[function(require,module,exports){var _curry1=require("./internal/_curry1"),_has=require("./internal/_has"),_isArguments=require("./internal/_isArguments"),hasEnumBug=!{toString:null}.propertyIsEnumerable("toString"),nonEnumerableProps=["constructor","valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],hasArgsEnumBug=function(){"use strict";return arguments.propertyIsEnumerable("length")}(),require="function"!=typeof Object.keys||hasArgsEnumBug?_curry1(function(obj){if(Object(obj)!==obj)return[];var prop,nIdx,ks=[],checkArgsLength=hasArgsEnumBug&&_isArguments(obj);for(prop in obj)!_has(prop,obj)||checkArgsLength&&"length"===prop||(ks[ks.length]=prop);if(hasEnumBug)for(nIdx=nonEnumerableProps.length-1;0<=nIdx;)_has(prop=nonEnumerableProps[nIdx],obj)&&!function(list,item){for(var idx=0;idx<list.length;){if(list[idx]===item)return!0;idx+=1}return!1}(ks,prop)&&(ks[ks.length]=prop),--nIdx;return ks}):_curry1(function(obj){return Object(obj)!==obj?[]:Object.keys(obj)});module.exports=require},{"./internal/_curry1":1155,"./internal/_has":1167,"./internal/_isArguments":1172}],1229:[function(require,module,exports){require=require("./internal/_curry1")(function(obj){var prop,ks=[];for(prop in obj)ks[ks.length]=prop;return ks});module.exports=require},{"./internal/_curry1":1155}],1230:[function(require,module,exports){module.exports=require("./nth")(-1)},{"./nth":1271}],1231:[function(require,module,exports){var _isArray=require("./internal/_isArray"),equals=require("./equals");module.exports=require("./internal/_curry2")(function(target,xs){if("function"!=typeof xs.lastIndexOf||_isArray(xs)){for(var idx=xs.length-1;0<=idx;){if(equals(xs[idx],target))return idx;--idx}return-1}return xs.lastIndexOf(target)})},{"./equals":1112,"./internal/_curry2":1156,"./internal/_isArray":1173}],1232:[function(require,module,exports){var _isNumber=require("./internal/_isNumber");module.exports=require("./internal/_curry1")(function(list){return null!=list&&_isNumber(list.length)?list.length:NaN})},{"./internal/_curry1":1155,"./internal/_isNumber":1177}],1233:[function(require,module,exports){var map=require("./map");module.exports=require("./internal/_curry2")(function(getter,setter){return function(toFunctorFn){return function(target){return map(function(focus){return setter(focus,target)},toFunctorFn(getter(target)))}}})},{"./internal/_curry2":1156,"./map":1241}],1234:[function(require,module,exports){var lens=require("./lens"),nth=require("./nth"),update=require("./update");module.exports=require("./internal/_curry1")(function(n){return lens(nth(n),update(n))})},{"./internal/_curry1":1155,"./lens":1233,"./nth":1271,"./update":1366}],1235:[function(require,module,exports){var assocPath=require("./assocPath"),lens=require("./lens"),path=require("./path");module.exports=require("./internal/_curry1")(function(p){return lens(path(p),assocPath(p))})},{"./assocPath":1070,"./internal/_curry1":1155,"./lens":1233,"./path":1285}],1236:[function(require,module,exports){var assoc=require("./assoc"),lens=require("./lens"),prop=require("./prop");module.exports=require("./internal/_curry1")(function(k){return lens(prop(k),assoc(k))})},{"./assoc":1069,"./internal/_curry1":1155,"./lens":1233,"./prop":1301}],1237:[function(require,module,exports){var liftN=require("./liftN");module.exports=require("./internal/_curry1")(function(fn){return liftN(fn.length,fn)})},{"./internal/_curry1":1155,"./liftN":1238}],1238:[function(require,module,exports){var _reduce=require("./internal/_reduce"),ap=require("./ap"),curryN=require("./curryN"),map=require("./map");module.exports=require("./internal/_curry2")(function(arity,fn){var lifted=curryN(arity,fn);return curryN(arity,function(){return _reduce(ap,map(lifted,arguments[0]),Array.prototype.slice.call(arguments,1))})})},{"./ap":1062,"./curryN":1092,"./internal/_curry2":1156,"./internal/_reduce":1191,"./map":1241}],1239:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return a<b})},{"./internal/_curry2":1156}],1240:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return a<=b})},{"./internal/_curry2":1156}],1241:[function(require,module,exports){var _map=require("./internal/_map"),_reduce=require("./internal/_reduce"),curryN=require("./curryN"),keys=require("./keys");module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")(["fantasy-land/map","map"],require("./internal/_xmap"),function(fn,functor){switch(Object.prototype.toString.call(functor)){case"[object Function]":return curryN(functor.length,function(){return fn.call(this,functor.apply(this,arguments))});case"[object Object]":return _reduce(function(acc,key){return acc[key]=fn(functor[key]),acc},{},keys(functor));default:return _map(fn,functor)}}))},{"./curryN":1092,"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_map":1184,"./internal/_reduce":1191,"./internal/_xmap":1211,"./keys":1228}],1242:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(fn,acc,list){for(var idx=0,len=list.length,result=[],tuple=[acc];idx<len;)tuple=fn(tuple[0],list[idx]),result[idx]=tuple[1],idx+=1;return[tuple[0],result]})},{"./internal/_curry3":1157}],1243:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(fn,acc,list){for(var idx=list.length-1,result=[],tuple=[acc];0<=idx;)tuple=fn(tuple[0],list[idx]),result[idx]=tuple[1],--idx;return[tuple[0],result]})},{"./internal/_curry3":1157}],1244:[function(require,module,exports){var _reduce=require("./internal/_reduce"),keys=require("./keys");module.exports=require("./internal/_curry2")(function(fn,obj){return _reduce(function(acc,key){return acc[key]=fn(obj[key],key,obj),acc},{},keys(obj))})},{"./internal/_curry2":1156,"./internal/_reduce":1191,"./keys":1228}],1245:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(rx,str){return str.match(rx)||[]})},{"./internal/_curry2":1156}],1246:[function(require,module,exports){var _isInteger=require("./internal/_isInteger");module.exports=require("./internal/_curry2")(function(m,p){return!_isInteger(m)||!_isInteger(p)||p<1?NaN:(m%p+p)%p})},{"./internal/_curry2":1156,"./internal/_isInteger":1176}],1247:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return a<b?b:a})},{"./internal/_curry2":1156}],1248:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(f,a,b){return f(b)>f(a)?b:a})},{"./internal/_curry3":1157}],1249:[function(require,module,exports){var sum=require("./sum");module.exports=require("./internal/_curry1")(function(list){return sum(list)/list.length})},{"./internal/_curry1":1155,"./sum":1331}],1250:[function(require,module,exports){var mean=require("./mean");module.exports=require("./internal/_curry1")(function(list){var idx,len=list.length;return 0===len?NaN:(idx=(len-(len=2-len%2))/2,mean(Array.prototype.slice.call(list,0).sort(function(a,b){return a<b?-1:b<a?1:0}).slice(idx,idx+len)))})},{"./internal/_curry1":1155,"./mean":1249}],1251:[function(require,module,exports){var _arity=require("./internal/_arity"),_has=require("./internal/_has"),require=require("./internal/_curry2")(function(mFn,fn){var cache={};return _arity(fn.length,function(){var key=mFn.apply(this,arguments);return _has(key,cache)||(cache[key]=fn.apply(this,arguments)),cache[key]})});module.exports=require},{"./internal/_arity":1146,"./internal/_curry2":1156,"./internal/_has":1167}],1252:[function(require,module,exports){var _objectAssign=require("./internal/_objectAssign");module.exports=require("./internal/_curry2")(function(l,r){return _objectAssign({},l,r)})},{"./internal/_curry2":1156,"./internal/_objectAssign":1185}],1253:[function(require,module,exports){var _objectAssign=require("./internal/_objectAssign");module.exports=require("./internal/_curry1")(function(list){return _objectAssign.apply(null,[{}].concat(list))})},{"./internal/_curry1":1155,"./internal/_objectAssign":1185}],1254:[function(require,module,exports){var mergeDeepWithKey=require("./mergeDeepWithKey");module.exports=require("./internal/_curry2")(function(lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return lVal},lObj,rObj)})},{"./internal/_curry2":1156,"./mergeDeepWithKey":1257}],1255:[function(require,module,exports){var mergeDeepWithKey=require("./mergeDeepWithKey");module.exports=require("./internal/_curry2")(function(lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return rVal},lObj,rObj)})},{"./internal/_curry2":1156,"./mergeDeepWithKey":1257}],1256:[function(require,module,exports){var mergeDeepWithKey=require("./mergeDeepWithKey");module.exports=require("./internal/_curry3")(function(fn,lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return fn(lVal,rVal)},lObj,rObj)})},{"./internal/_curry3":1157,"./mergeDeepWithKey":1257}],1257:[function(require,module,exports){var _isObject=require("./internal/_isObject"),mergeWithKey=require("./mergeWithKey");module.exports=require("./internal/_curry3")(function mergeDeepWithKey(fn,lObj,rObj){return mergeWithKey(function(k,lVal,rVal){return _isObject(lVal)&&_isObject(rVal)?mergeDeepWithKey(fn,lVal,rVal):fn(k,lVal,rVal)},lObj,rObj)})},{"./internal/_curry3":1157,"./internal/_isObject":1178,"./mergeWithKey":1261}],1258:[function(require,module,exports){var _objectAssign=require("./internal/_objectAssign");module.exports=require("./internal/_curry2")(function(l,r){return _objectAssign({},r,l)})},{"./internal/_curry2":1156,"./internal/_objectAssign":1185}],1259:[function(require,module,exports){var _objectAssign=require("./internal/_objectAssign");module.exports=require("./internal/_curry2")(function(l,r){return _objectAssign({},l,r)})},{"./internal/_curry2":1156,"./internal/_objectAssign":1185}],1260:[function(require,module,exports){var mergeWithKey=require("./mergeWithKey");module.exports=require("./internal/_curry3")(function(fn,l,r){return mergeWithKey(function(_,_l,_r){return fn(_l,_r)},l,r)})},{"./internal/_curry3":1157,"./mergeWithKey":1261}],1261:[function(require,module,exports){var _has=require("./internal/_has"),require=require("./internal/_curry3")(function(fn,l,r){var k,result={};for(k in l)_has(k,l)&&(result[k]=_has(k,r)?fn(k,l[k],r[k]):l[k]);for(k in r)_has(k,r)&&!_has(k,result)&&(result[k]=r[k]);return result});module.exports=require},{"./internal/_curry3":1157,"./internal/_has":1167}],1262:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return b<a?b:a})},{"./internal/_curry2":1156}],1263:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(f,a,b){return f(b)<f(a)?b:a})},{"./internal/_curry3":1157}],1264:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return a%b})},{"./internal/_curry2":1156}],1265:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(from,to,list){var length=list.length,result=list.slice(),from=from<0?length+from:from,length=to<0?length+to:to,to=result.splice(from,1);return from<0||from>=list.length||length<0||length>=list.length?list:[].concat(result.slice(0,length)).concat(to).concat(result.slice(length,list.length))})},{"./internal/_curry3":1157}],1266:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return a*b})},{"./internal/_curry2":1156}],1267:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(n,fn){switch(n){case 0:return function(){return fn.call(this)};case 1:return function(a0){return fn.call(this,a0)};case 2:return function(a0,a1){return fn.call(this,a0,a1)};case 3:return function(a0,a1,a2){return fn.call(this,a0,a1,a2)};case 4:return function(a0,a1,a2,a3){return fn.call(this,a0,a1,a2,a3)};case 5:return function(a0,a1,a2,a3,a4){return fn.call(this,a0,a1,a2,a3,a4)};case 6:return function(a0,a1,a2,a3,a4,a5){return fn.call(this,a0,a1,a2,a3,a4,a5)};case 7:return function(a0,a1,a2,a3,a4,a5,a6){return fn.call(this,a0,a1,a2,a3,a4,a5,a6)};case 8:return function(a0,a1,a2,a3,a4,a5,a6,a7){return fn.call(this,a0,a1,a2,a3,a4,a5,a6,a7)};case 9:return function(a0,a1,a2,a3,a4,a5,a6,a7,a8){return fn.call(this,a0,a1,a2,a3,a4,a5,a6,a7,a8)};case 10:return function(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9){return fn.call(this,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9)};default:throw new Error("First argument to nAry must be a non-negative integer no greater than ten")}})},{"./internal/_curry2":1156}],1268:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(n){return-n})},{"./internal/_curry1":1155}],1269:[function(require,module,exports){var _complement=require("./internal/_complement"),all=require("./all");module.exports=require("./internal/_curry2")(function(fn,input){return all(_complement(fn),input)})},{"./all":1055,"./internal/_complement":1152,"./internal/_curry2":1156}],1270:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(a){return!a})},{"./internal/_curry1":1155}],1271:[function(require,module,exports){var _isString=require("./internal/_isString"),require=require("./internal/_curry2")(function(offset,list){offset=offset<0?list.length+offset:offset;return _isString(list)?list.charAt(offset):list[offset]});module.exports=require},{"./internal/_curry2":1156,"./internal/_isString":1181}],1272:[function(require,module,exports){var curryN=require("./curryN"),nth=require("./nth");module.exports=require("./internal/_curry1")(function(n){return curryN(n<0?1:n+1,function(){return nth(n,arguments)})})},{"./curryN":1092,"./internal/_curry1":1155,"./nth":1271}],1273:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(f,g,x){return f(g(x))})},{"./internal/_curry3":1157}],1274:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(key,val){var obj={};return obj[key]=val,obj})},{"./internal/_curry2":1156}],1275:[function(require,module,exports){module.exports=require("./internal/_curry1")(require("./internal/_of"))},{"./internal/_curry1":1155,"./internal/_of":1187}],1276:[function(require,module,exports){require=require("./internal/_curry2")(function(names,obj){for(var prop,result={},index={},idx=0,len=names.length;idx<len;)idx+=index[names[idx]]=1;for(prop in obj)index.hasOwnProperty(prop)||(result[prop]=obj[prop]);return result});module.exports=require},{"./internal/_curry2":1156}],1277:[function(require,module,exports){var _arity=require("./internal/_arity"),require=require("./internal/_curry1")(function(fn){var result,called=!1;return _arity(fn.length,function(){return called||(called=!0,result=fn.apply(this,arguments)),result})});module.exports=require},{"./internal/_arity":1146,"./internal/_curry1":1155}],1278:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return a||b})},{"./internal/_curry2":1156}],1279:[function(require,module,exports){var _assertPromise=require("./internal/_assertPromise");module.exports=require("./internal/_curry2")(function(f,p){return _assertPromise("otherwise",p),p.then(null,f)})},{"./internal/_assertPromise":1148,"./internal/_curry2":1156}],1280:[function(require,module,exports){function Identity(x){return{value:x,map:function(f){return Identity(f(x))}}}module.exports=require("./internal/_curry3")(function(lens,f,x){return lens(function(y){return Identity(f(y))})(x).value})},{"./internal/_curry3":1157}],1281:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(fst,snd){return[fst,snd]})},{"./internal/_curry2":1156}],1282:[function(require,module,exports){module.exports=require("./internal/_createPartialApplicator")(require("./internal/_concat"))},{"./internal/_concat":1153,"./internal/_createPartialApplicator":1154}],1283:[function(require,module,exports){module.exports=require("./internal/_createPartialApplicator")(require("./flip")(require("./internal/_concat")))},{"./flip":1120,"./internal/_concat":1153,"./internal/_createPartialApplicator":1154}],1284:[function(require,module,exports){module.exports=require("./juxt")([require("./filter"),require("./reject")])},{"./filter":1114,"./juxt":1227,"./reject":1313}],1285:[function(require,module,exports){var paths=require("./paths");module.exports=require("./internal/_curry2")(function(pathAr,obj){return paths([pathAr],obj)[0]})},{"./internal/_curry2":1156,"./paths":1289}],1286:[function(require,module,exports){var equals=require("./equals"),path=require("./path");module.exports=require("./internal/_curry3")(function(_path,val,obj){return equals(path(_path,obj),val)})},{"./equals":1112,"./internal/_curry3":1157,"./path":1285}],1287:[function(require,module,exports){var defaultTo=require("./defaultTo"),path=require("./path");module.exports=require("./internal/_curry3")(function(d,p,obj){return defaultTo(d,path(p,obj))})},{"./defaultTo":1094,"./internal/_curry3":1157,"./path":1285}],1288:[function(require,module,exports){var path=require("./path");module.exports=require("./internal/_curry3")(function(pred,propPath,obj){return pred(path(propPath,obj))})},{"./internal/_curry3":1157,"./path":1285}],1289:[function(require,module,exports){var _isInteger=require("./internal/_isInteger"),nth=require("./nth"),require=require("./internal/_curry2")(function(pathsArray,obj){return pathsArray.map(function(paths){for(var p,val=obj,idx=0;idx<paths.length;){if(null==val)return;p=paths[idx],val=_isInteger(p)?nth(p,val):val[p],idx+=1}return val})});module.exports=require},{"./internal/_curry2":1156,"./internal/_isInteger":1176,"./nth":1271}],1290:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(names,obj){for(var result={},idx=0;idx<names.length;)names[idx]in obj&&(result[names[idx]]=obj[names[idx]]),idx+=1;return result})},{"./internal/_curry2":1156}],1291:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(names,obj){for(var result={},idx=0,len=names.length;idx<len;){var name=names[idx];result[name]=obj[name],idx+=1}return result})},{"./internal/_curry2":1156}],1292:[function(require,module,exports){require=require("./internal/_curry2")(function(test,obj){var prop,result={};for(prop in obj)test(obj[prop],prop,obj)&&(result[prop]=obj[prop]);return result});module.exports=require},{"./internal/_curry2":1156}],1293:[function(require,module,exports){var _arity=require("./internal/_arity"),_pipe=require("./internal/_pipe"),reduce=require("./reduce"),tail=require("./tail");module.exports=function(){if(0===arguments.length)throw new Error("pipe requires at least one argument");return _arity(arguments[0].length,reduce(_pipe,arguments[0],tail(arguments)))}},{"./internal/_arity":1146,"./internal/_pipe":1188,"./reduce":1308,"./tail":1334}],1294:[function(require,module,exports){var composeK=require("./composeK"),reverse=require("./reverse");module.exports=function(){if(0===arguments.length)throw new Error("pipeK requires at least one argument");return composeK.apply(this,reverse(arguments))}},{"./composeK":1081,"./reverse":1317}],1295:[function(require,module,exports){var _arity=require("./internal/_arity"),_pipeP=require("./internal/_pipeP"),reduce=require("./reduce"),tail=require("./tail");module.exports=function(){if(0===arguments.length)throw new Error("pipeP requires at least one argument");return _arity(arguments[0].length,reduce(_pipeP,arguments[0],tail(arguments)))}},{"./internal/_arity":1146,"./internal/_pipeP":1189,"./reduce":1308,"./tail":1334}],1296:[function(require,module,exports){var _arity=require("./internal/_arity"),head=require("./head"),_reduce=require("./internal/_reduce"),tail=require("./tail"),identity=require("./identity"),require=require("./internal/_curry2")(function(xf,list){var headList,tailList;return list.length<=0?identity:(headList=head(list),tailList=tail(list),_arity(headList.length,function(){return _reduce(function(result,f){return xf.call(this,f,result)},headList.apply(this,arguments),tailList)}))});module.exports=require},{"./head":1131,"./identity":1133,"./internal/_arity":1146,"./internal/_curry2":1156,"./internal/_reduce":1191,"./tail":1334}],1297:[function(require,module,exports){var map=require("./map"),prop=require("./prop");module.exports=require("./internal/_curry2")(function(p,list){return map(prop(p),list)})},{"./internal/_curry2":1156,"./map":1241,"./prop":1301}],1298:[function(require,module,exports){var _concat=require("./internal/_concat");module.exports=require("./internal/_curry2")(function(el,list){return _concat([el],list)})},{"./internal/_concat":1153,"./internal/_curry2":1156}],1299:[function(require,module,exports){module.exports=require("./reduce")(require("./multiply"),1)},{"./multiply":1266,"./reduce":1308}],1300:[function(require,module,exports){module.exports=require("./useWith")(require("./internal/_map"),[require("./pickAll"),require("./identity")])},{"./identity":1133,"./internal/_map":1184,"./pickAll":1291,"./useWith":1367}],1301:[function(require,module,exports){var path=require("./path");module.exports=require("./internal/_curry2")(function(p,obj){return path([p],obj)})},{"./internal/_curry2":1156,"./path":1285}],1302:[function(require,module,exports){var equals=require("./equals");module.exports=require("./internal/_curry3")(function(name,val,obj){return equals(val,obj[name])})},{"./equals":1112,"./internal/_curry3":1157}],1303:[function(require,module,exports){var is=require("./is");module.exports=require("./internal/_curry3")(function(type,name,obj){return is(type,obj[name])})},{"./internal/_curry3":1157,"./is":1223}],1304:[function(require,module,exports){var pathOr=require("./pathOr");module.exports=require("./internal/_curry3")(function(val,p,obj){return pathOr(val,[p],obj)})},{"./internal/_curry3":1157,"./pathOr":1287}],1305:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(pred,name,obj){return pred(obj[name])})},{"./internal/_curry3":1157}],1306:[function(require,module,exports){var path=require("./path");module.exports=require("./internal/_curry2")(function(ps,obj){return ps.map(function(p){return path([p],obj)})})},{"./internal/_curry2":1156,"./path":1285}],1307:[function(require,module,exports){var _isNumber=require("./internal/_isNumber"),require=require("./internal/_curry2")(function(from,to){if(!_isNumber(from)||!_isNumber(to))throw new TypeError("Both arguments to range must be numbers");for(var result=[],n=from;n<to;)result.push(n),n+=1;return result});module.exports=require},{"./internal/_curry2":1156,"./internal/_isNumber":1177}],1308:[function(require,module,exports){module.exports=require("./internal/_curry3")(require("./internal/_reduce"))},{"./internal/_curry3":1157,"./internal/_reduce":1191}],1309:[function(require,module,exports){var _clone=require("./internal/_clone"),_has=require("./internal/_has"),_reduce=require("./internal/_reduce");module.exports=require("./internal/_curryN")(4,[],require("./internal/_dispatchable")([],require("./internal/_xreduceBy"),function(valueFn,valueAcc,keyFn,list){return _reduce(function(acc,elt){var key=keyFn(elt);return acc[key]=valueFn(_has(key,acc)?acc[key]:_clone(valueAcc,[],[],!1),elt),acc},{},list)}))},{"./internal/_clone":1150,"./internal/_curryN":1158,"./internal/_dispatchable":1159,"./internal/_has":1167,"./internal/_reduce":1191,"./internal/_xreduceBy":1212}],1310:[function(require,module,exports){require=require("./internal/_curry3")(function(fn,acc,list){for(var idx=list.length-1;0<=idx;)acc=fn(list[idx],acc),--idx;return acc});module.exports=require},{"./internal/_curry3":1157}],1311:[function(require,module,exports){var _reduce=require("./internal/_reduce"),_reduced=require("./internal/_reduced");module.exports=require("./internal/_curryN")(4,[],function(pred,fn,a,list){return _reduce(function(acc,x){return pred(acc,x)?fn(acc,x):_reduced(acc)},a,list)})},{"./internal/_curryN":1158,"./internal/_reduce":1191,"./internal/_reduced":1192}],1312:[function(require,module,exports){module.exports=require("./internal/_curry1")(require("./internal/_reduced"))},{"./internal/_curry1":1155,"./internal/_reduced":1192}],1313:[function(require,module,exports){var _complement=require("./internal/_complement"),filter=require("./filter");module.exports=require("./internal/_curry2")(function(pred,filterable){return filter(_complement(pred),filterable)})},{"./filter":1114,"./internal/_complement":1152,"./internal/_curry2":1156}],1314:[function(require,module,exports){require=require("./internal/_curry3")(function(start,count,list){list=Array.prototype.slice.call(list,0);return list.splice(start,count),list});module.exports=require},{"./internal/_curry3":1157}],1315:[function(require,module,exports){var always=require("./always"),times=require("./times");module.exports=require("./internal/_curry2")(function(value,n){return times(always(value),n)})},{"./always":1057,"./internal/_curry2":1156,"./times":1342}],1316:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(regex,replacement,str){return str.replace(regex,replacement)})},{"./internal/_curry3":1157}],1317:[function(require,module,exports){var _isString=require("./internal/_isString");module.exports=require("./internal/_curry1")(function(list){return _isString(list)?list.split("").reverse().join(""):Array.prototype.slice.call(list,0).reverse()})},{"./internal/_curry1":1155,"./internal/_isString":1181}],1318:[function(require,module,exports){require=require("./internal/_curry3")(function(fn,acc,list){for(var idx=0,len=list.length,result=[acc];idx<len;)acc=fn(acc,list[idx]),result[idx+1]=acc,idx+=1;return result});module.exports=require},{"./internal/_curry3":1157}],1319:[function(require,module,exports){var ap=require("./ap"),map=require("./map"),prepend=require("./prepend"),reduceRight=require("./reduceRight");module.exports=require("./internal/_curry2")(function(of,traversable){return"function"==typeof traversable.sequence?traversable.sequence(of):reduceRight(function(x,acc){return ap(map(prepend,x),acc)},of([]),traversable)})},{"./ap":1062,"./internal/_curry2":1156,"./map":1241,"./prepend":1298,"./reduceRight":1310}],1320:[function(require,module,exports){var always=require("./always"),over=require("./over");module.exports=require("./internal/_curry3")(function(lens,v,x){return over(lens,always(v),x)})},{"./always":1057,"./internal/_curry3":1157,"./over":1280}],1321:[function(require,module,exports){module.exports=require("./internal/_curry3")(require("./internal/_checkForMethod")("slice",function(fromIndex,toIndex,list){return Array.prototype.slice.call(list,fromIndex,toIndex)}))},{"./internal/_checkForMethod":1149,"./internal/_curry3":1157}],1322:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(comparator,list){return Array.prototype.slice.call(list,0).sort(comparator)})},{"./internal/_curry2":1156}],1323:[function(require,module,exports){require=require("./internal/_curry2")(function(fn,list){return Array.prototype.slice.call(list,0).sort(function(a,b){a=fn(a),b=fn(b);return a<b?-1:b<a?1:0})});module.exports=require},{"./internal/_curry2":1156}],1324:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(fns,list){return Array.prototype.slice.call(list,0).sort(function(a,b){for(var result=0,i=0;0===result&&i<fns.length;)result=fns[i](a,b),i+=1;return result})})},{"./internal/_curry2":1156}],1325:[function(require,module,exports){module.exports=require("./invoker")(1,"split")},{"./invoker":1222}],1326:[function(require,module,exports){var length=require("./length"),slice=require("./slice");module.exports=require("./internal/_curry2")(function(index,array){return[slice(0,index,array),slice(index,length(array),array)]})},{"./internal/_curry2":1156,"./length":1232,"./slice":1321}],1327:[function(require,module,exports){var slice=require("./slice"),require=require("./internal/_curry2")(function(n,list){if(n<=0)throw new Error("First argument to splitEvery must be a positive integer");for(var result=[],idx=0;idx<list.length;)result.push(slice(idx,idx+=n,list));return result});module.exports=require},{"./internal/_curry2":1156,"./slice":1321}],1328:[function(require,module,exports){require=require("./internal/_curry2")(function(pred,list){for(var idx=0,len=list.length,prefix=[];idx<len&&!pred(list[idx]);)prefix.push(list[idx]),idx+=1;return[prefix,Array.prototype.slice.call(list,idx)]});module.exports=require},{"./internal/_curry2":1156}],1329:[function(require,module,exports){var equals=require("./equals"),take=require("./take");module.exports=require("./internal/_curry2")(function(prefix,list){return equals(take(prefix.length,list),prefix)})},{"./equals":1112,"./internal/_curry2":1156,"./take":1335}],1330:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return Number(a)-Number(b)})},{"./internal/_curry2":1156}],1331:[function(require,module,exports){module.exports=require("./reduce")(require("./add"),0)},{"./add":1052,"./reduce":1308}],1332:[function(require,module,exports){var concat=require("./concat"),difference=require("./difference");module.exports=require("./internal/_curry2")(function(list1,list2){return concat(difference(list1,list2),difference(list2,list1))})},{"./concat":1084,"./difference":1096,"./internal/_curry2":1156}],1333:[function(require,module,exports){var concat=require("./concat"),differenceWith=require("./differenceWith");module.exports=require("./internal/_curry3")(function(pred,list1,list2){return concat(differenceWith(pred,list1,list2),differenceWith(pred,list2,list1))})},{"./concat":1084,"./differenceWith":1097,"./internal/_curry3":1157}],1334:[function(require,module,exports){module.exports=require("./internal/_curry1")(require("./internal/_checkForMethod")("tail",require("./slice")(1,1/0)))},{"./internal/_checkForMethod":1149,"./internal/_curry1":1155,"./slice":1321}],1335:[function(require,module,exports){var slice=require("./slice");module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")(["take"],require("./internal/_xtake"),function(n,xs){return slice(0,n<0?1/0:n,xs)}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xtake":1213,"./slice":1321}],1336:[function(require,module,exports){var drop=require("./drop");module.exports=require("./internal/_curry2")(function(n,xs){return drop(0<=n?xs.length-n:0,xs)})},{"./drop":1101,"./internal/_curry2":1156}],1337:[function(require,module,exports){var slice=require("./slice");module.exports=require("./internal/_curry2")(function(fn,xs){for(var idx=xs.length-1;0<=idx&&fn(xs[idx]);)--idx;return slice(idx+1,1/0,xs)})},{"./internal/_curry2":1156,"./slice":1321}],1338:[function(require,module,exports){var slice=require("./slice"),require=require("./internal/_curry2")(require("./internal/_dispatchable")(["takeWhile"],require("./internal/_xtakeWhile"),function(fn,xs){for(var idx=0,len=xs.length;idx<len&&fn(xs[idx]);)idx+=1;return slice(0,idx,xs)}));module.exports=require},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xtakeWhile":1214,"./slice":1321}],1339:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./internal/_dispatchable")([],require("./internal/_xtap"),function(fn,x){return fn(x),x}))},{"./internal/_curry2":1156,"./internal/_dispatchable":1159,"./internal/_xtap":1215}],1340:[function(require,module,exports){var _cloneRegExp=require("./internal/_cloneRegExp"),_isRegExp=require("./internal/_isRegExp"),toString=require("./toString");module.exports=require("./internal/_curry2")(function(pattern,str){if(_isRegExp(pattern))return _cloneRegExp(pattern).test(str);throw new TypeError("‘test’ requires a value of type RegExp as its first argument; received "+toString(pattern))})},{"./internal/_cloneRegExp":1151,"./internal/_curry2":1156,"./internal/_isRegExp":1180,"./toString":1346}],1341:[function(require,module,exports){var curryN=require("./curryN");module.exports=require("./internal/_curry1")(function(fn){return curryN(fn.length,function(){var fnArgs=arguments;return function(){return fn.apply(this,fnArgs)}})})},{"./curryN":1092,"./internal/_curry1":1155}],1342:[function(require,module,exports){require=require("./internal/_curry2")(function(fn,n){var list,len=Number(n),idx=0;if(len<0||isNaN(len))throw new RangeError("n must be a non-negative number");for(list=new Array(len);idx<len;)list[idx]=fn(idx),idx+=1;return list});module.exports=require},{"./internal/_curry2":1156}],1343:[function(require,module,exports){module.exports=require("./invoker")(0,"toLowerCase")},{"./invoker":1222}],1344:[function(require,module,exports){var _has=require("./internal/_has"),require=require("./internal/_curry1")(function(obj){var prop,pairs=[];for(prop in obj)_has(prop,obj)&&(pairs[pairs.length]=[prop,obj[prop]]);return pairs});module.exports=require},{"./internal/_curry1":1155,"./internal/_has":1167}],1345:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(obj){var prop,pairs=[];for(prop in obj)pairs[pairs.length]=[prop,obj[prop]];return pairs})},{"./internal/_curry1":1155}],1346:[function(require,module,exports){var _toString=require("./internal/_toString");module.exports=require("./internal/_curry1")(function(val){return _toString(val,[])})},{"./internal/_curry1":1155,"./internal/_toString":1195}],1347:[function(require,module,exports){module.exports=require("./invoker")(0,"toUpperCase")},{"./invoker":1222}],1348:[function(require,module,exports){var _reduce=require("./internal/_reduce"),_xwrap=require("./internal/_xwrap");module.exports=require("./curryN")(4,function(xf,fn,acc,list){return _reduce(xf("function"==typeof fn?_xwrap(fn):fn),acc,list)})},{"./curryN":1092,"./internal/_reduce":1191,"./internal/_xwrap":1216}],1349:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(outerlist){for(var i=0,result=[];i<outerlist.length;){for(var innerlist=outerlist[i],j=0;j<innerlist.length;)void 0===result[j]&&(result[j]=[]),result[j].push(innerlist[j]),j+=1;i+=1}return result})},{"./internal/_curry1":1155}],1350:[function(require,module,exports){var map=require("./map"),sequence=require("./sequence");module.exports=require("./internal/_curry3")(function(of,f,traversable){return"function"==typeof traversable["fantasy-land/traverse"]?traversable["fantasy-land/traverse"](f,of):sequence(of,map(f,traversable))})},{"./internal/_curry3":1157,"./map":1241,"./sequence":1319}],1351:[function(require,module,exports){var require=require("./internal/_curry1"),ws="\t\n\v\f\r                　\u2028\u2029\ufeff",hasProtoTrim="function"==typeof String.prototype.trim;module.exports=require(hasProtoTrim&&!ws.trim()&&"​".trim()?function(str){return str.trim()}:function(str){var beginRx=new RegExp("^["+ws+"]["+ws+"]*"),endRx=new RegExp("["+ws+"]["+ws+"]*$");return str.replace(beginRx,"").replace(endRx,"")})},{"./internal/_curry1":1155}],1352:[function(require,module,exports){var _arity=require("./internal/_arity"),_concat=require("./internal/_concat");module.exports=require("./internal/_curry2")(function(tryer,catcher){return _arity(tryer.length,function(){try{return tryer.apply(this,arguments)}catch(e){return catcher.apply(this,_concat([e],arguments))}})})},{"./internal/_arity":1146,"./internal/_concat":1153,"./internal/_curry2":1156}],1353:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(val){return null===val?"Null":void 0===val?"Undefined":Object.prototype.toString.call(val).slice(8,-1)})},{"./internal/_curry1":1155}],1354:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(fn){return function(){return fn(Array.prototype.slice.call(arguments,0))}})},{"./internal/_curry1":1155}],1355:[function(require,module,exports){var nAry=require("./nAry");module.exports=require("./internal/_curry1")(function(fn){return nAry(1,fn)})},{"./internal/_curry1":1155,"./nAry":1267}],1356:[function(require,module,exports){var curryN=require("./curryN"),require=require("./internal/_curry2")(function(depth,fn){return curryN(depth,function(){for(var endIdx,currentDepth=1,value=fn,idx=0;currentDepth<=depth&&"function"==typeof value;)endIdx=currentDepth===depth?arguments.length:idx+value.length,value=value.apply(this,Array.prototype.slice.call(arguments,idx,endIdx)),currentDepth+=1,idx=endIdx;return value})});module.exports=require},{"./curryN":1092,"./internal/_curry2":1156}],1357:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(fn,seed){for(var pair=fn(seed),result=[];pair&&pair.length;)result[result.length]=pair[0],pair=fn(pair[1]);return result})},{"./internal/_curry2":1156}],1358:[function(require,module,exports){module.exports=require("./internal/_curry2")(require("./compose")(require("./uniq"),require("./internal/_concat")))},{"./compose":1080,"./internal/_concat":1153,"./internal/_curry2":1156,"./uniq":1360}],1359:[function(require,module,exports){var _concat=require("./internal/_concat"),uniqWith=require("./uniqWith");module.exports=require("./internal/_curry3")(function(pred,list1,list2){return uniqWith(pred,_concat(list1,list2))})},{"./internal/_concat":1153,"./internal/_curry3":1157,"./uniqWith":1362}],1360:[function(require,module,exports){module.exports=require("./uniqBy")(require("./identity"))},{"./identity":1133,"./uniqBy":1361}],1361:[function(require,module,exports){var _Set=require("./internal/_Set"),require=require("./internal/_curry2")(function(fn,list){for(var appliedItem,item,set=new _Set,result=[],idx=0;idx<list.length;)appliedItem=fn(item=list[idx]),set.add(appliedItem)&&result.push(item),idx+=1;return result});module.exports=require},{"./internal/_Set":1144,"./internal/_curry2":1156}],1362:[function(require,module,exports){var _includesWith=require("./internal/_includesWith");module.exports=require("./internal/_curry2")(function(pred,list){for(var item,idx=0,len=list.length,result=[];idx<len;)item=list[idx],_includesWith(pred,item,result)||(result[result.length]=item),idx+=1;return result})},{"./internal/_curry2":1156,"./internal/_includesWith":1170}],1363:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(pred,whenFalseFn,x){return pred(x)?x:whenFalseFn(x)})},{"./internal/_curry3":1157}],1364:[function(require,module,exports){module.exports=require("./chain")(require("./internal/_identity"))},{"./chain":1075,"./internal/_identity":1168}],1365:[function(require,module,exports){require=require("./internal/_curry3")(function(pred,fn,init){for(var val=init;!pred(val);)val=fn(val);return val});module.exports=require},{"./internal/_curry3":1157}],1366:[function(require,module,exports){var adjust=require("./adjust"),always=require("./always");module.exports=require("./internal/_curry3")(function(idx,x,list){return adjust(idx,always(x),list)})},{"./adjust":1054,"./always":1057,"./internal/_curry3":1157}],1367:[function(require,module,exports){var curryN=require("./curryN");module.exports=require("./internal/_curry2")(function(fn,transformers){return curryN(transformers.length,function(){for(var args=[],idx=0;idx<transformers.length;)args.push(transformers[idx].call(this,arguments[idx])),idx+=1;return fn.apply(this,args.concat(Array.prototype.slice.call(arguments,transformers.length)))})})},{"./curryN":1092,"./internal/_curry2":1156}],1368:[function(require,module,exports){var keys=require("./keys");module.exports=require("./internal/_curry1")(function(obj){for(var props=keys(obj),len=props.length,vals=[],idx=0;idx<len;)vals[idx]=obj[props[idx]],idx+=1;return vals})},{"./internal/_curry1":1155,"./keys":1228}],1369:[function(require,module,exports){module.exports=require("./internal/_curry1")(function(obj){var prop,vs=[];for(prop in obj)vs[vs.length]=obj[prop];return vs})},{"./internal/_curry1":1155}],1370:[function(require,module,exports){function Const(x){return{value:x,"fantasy-land/map":function(){return this}}}module.exports=require("./internal/_curry2")(function(lens,x){return lens(Const)(x).value})},{"./internal/_curry2":1156}],1371:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(pred,whenTrueFn,x){return pred(x)?whenTrueFn(x):x})},{"./internal/_curry3":1157}],1372:[function(require,module,exports){var _has=require("./internal/_has"),require=require("./internal/_curry2")(function(spec,testObj){for(var prop in spec)if(_has(prop,spec)&&!spec[prop](testObj[prop]))return!1;return!0});module.exports=require},{"./internal/_curry2":1156,"./internal/_has":1167}],1373:[function(require,module,exports){var equals=require("./equals"),map=require("./map"),where=require("./where");module.exports=require("./internal/_curry2")(function(spec,testObj){return where(map(equals,spec),testObj)})},{"./equals":1112,"./internal/_curry2":1156,"./map":1241,"./where":1372}],1374:[function(require,module,exports){var _includes=require("./internal/_includes"),flip=require("./flip"),reject=require("./reject");module.exports=require("./internal/_curry2")(function(xs,list){return reject(flip(_includes)(xs),list)})},{"./flip":1120,"./internal/_curry2":1156,"./internal/_includes":1169,"./reject":1313}],1375:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){return Boolean(!a^!b)})},{"./internal/_curry2":1156}],1376:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){for(var j,idx=0,ilen=a.length,jlen=b.length,result=[];idx<ilen;){for(j=0;j<jlen;)result[result.length]=[a[idx],b[j]],j+=1;idx+=1}return result})},{"./internal/_curry2":1156}],1377:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(a,b){for(var rv=[],idx=0,len=Math.min(a.length,b.length);idx<len;)rv[idx]=[a[idx],b[idx]],idx+=1;return rv})},{"./internal/_curry2":1156}],1378:[function(require,module,exports){module.exports=require("./internal/_curry2")(function(keys,values){for(var idx=0,len=Math.min(keys.length,values.length),out={};idx<len;)out[keys[idx]]=values[idx],idx+=1;return out})},{"./internal/_curry2":1156}],1379:[function(require,module,exports){module.exports=require("./internal/_curry3")(function(fn,a,b){for(var rv=[],idx=0,len=Math.min(a.length,b.length);idx<len;)rv[idx]=fn(a[idx],b[idx]),idx+=1;return rv})},{"./internal/_curry3":1157}],1380:[function(require,module,exports){},{"object-assign":1032,"prop-types/checkPropTypes":1043,react:1427,scheduler:1442,"scheduler/tracing":1443}],1381:[function(require,module,exports){"use strict";var aa=require("react"),n=require("object-assign"),r=require("scheduler");function u(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}if(!aa)throw Error(u(227));var da=!1,ea=null,fa=!1,ha=null,ia={onError:function(a){da=!0,ea=a}};function ja(a,b,c,d,e,f,g,h,k){da=!1,ea=null,function(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(m){this.onError(m)}}.apply(ia,arguments)}var la=null,ma=null,na=null;function oa(a,b,c){var d=a.type||"unknown-event";a.currentTarget=na(c),function(){var l;ja.apply(this,arguments),da&&(l=ea,da=!1,ea=null,fa||(fa=!0,ha=l))}(d,b,void 0,a),a.currentTarget=null}var pa=null,qa={};function ra(){if(pa)for(var a in qa){var b=qa[a],c=pa.indexOf(a);if(!(-1<c))throw Error(u(96,a));if(!sa[c]){if(!b.extractEvents)throw Error(u(97,a));for(var d in c=(sa[c]=b).eventTypes){var e=void 0,f=c[d],g=b,h=d;if(ta.hasOwnProperty(h))throw Error(u(99,h));var k=(ta[h]=f).phasedRegistrationNames;if(k){for(e in k)k.hasOwnProperty(e)&&ua(k[e],g,h);e=!0}else e=!!f.registrationName&&(ua(f.registrationName,g,h),!0);if(!e)throw Error(u(98,d,a))}}}}function ua(a,b,c){if(va[a])throw Error(u(100,a));va[a]=b,wa[a]=b.eventTypes[c].dependencies}var sa=[],ta={},va={},wa={};function xa(a){var c,b=!1;for(c in a)if(a.hasOwnProperty(c)){var d=a[c];if(!qa.hasOwnProperty(c)||qa[c]!==d){if(qa[c])throw Error(u(102,c));qa[c]=d,b=!0}}b&&ra()}var ya=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),za=null,Aa=null,Ba=null;function Ca(a){if(a=ma(a)){if("function"!=typeof za)throw Error(u(280));var b=a.stateNode;b&&(b=la(b),za(a.stateNode,a.type,b))}}function Da(a){Aa?Ba?Ba.push(a):Ba=[a]:Aa=a}function Ea(){if(Aa){var a=Aa,b=Ba;if(Ba=Aa=null,Ca(a),b)for(a=0;a<b.length;a++)Ca(b[a])}}function Fa(a,b){return a(b)}function Ga(a,b,c,d,e){return a(b,c,d,e)}function Ha(){}var Ia=Fa,Ja=!1,Ka=!1;function La(){null===Aa&&null===Ba||(Ha(),Ea())}function Ma(a,b,c){if(Ka)return a(b,c);Ka=!0;try{Ia(a,b,c)}finally{Ka=!1,La()}}var Na=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Oa=Object.prototype.hasOwnProperty,Pa={},Qa={};function v(a,b,c,d,e,f){this.acceptsBooleans=2===b||3===b||4===b,this.attributeName=d,this.attributeNamespace=e,this.mustUseProperty=c,this.propertyName=a,this.type=b,this.sanitizeURL=f}var C={},Ua=("children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){C[a]=new v(a,0,!1,a,null,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];C[b]=new v(b,1,!1,a[1],null,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(a){C[a]=new v(a,2,!1,a.toLowerCase(),null,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){C[a]=new v(a,2,!1,a,null,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){C[a]=new v(a,3,!1,a.toLowerCase(),null,!1)}),["checked","multiple","muted","selected"].forEach(function(a){C[a]=new v(a,3,!0,a,null,!1)}),["capture","download"].forEach(function(a){C[a]=new v(a,4,!1,a,null,!1)}),["cols","rows","size","span"].forEach(function(a){C[a]=new v(a,6,!1,a,null,!1)}),["rowSpan","start"].forEach(function(a){C[a]=new v(a,5,!1,a.toLowerCase(),null,!1)}),/[\-:]([a-z])/g);function Va(a){return a[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,null,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1)}),["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1)}),["tabIndex","crossOrigin"].forEach(function(a){C[a]=new v(a,1,!1,a.toLowerCase(),null,!1)}),C.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0),["src","href","action","formAction"].forEach(function(a){C[a]=new v(a,1,!1,a.toLowerCase(),null,!0)});var Wa=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function Xa(a,b,c,d){var e=C.hasOwnProperty(b)?C[b]:null;(null!==e?0!==e.type:d||!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1])&&(function(a,b,c,d){if(null==b||function(a,b,c,d){if(null===c||0!==c.type)switch(typeof b){case"function":case"symbol":return 1;case"boolean":return d?void 0:null!==c?!c.acceptsBooleans:"data-"!==(a=a.toLowerCase().slice(0,5))&&"aria-"!==a;default:return}}(a,b,c,d))return 1;if(!d&&null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||b<1}}(b,c,e,d)&&(c=null),d||null===e?function(a){return Oa.call(Qa,a)||!Oa.call(Pa,a)&&(Na.test(a)?Qa[a]=!0:void(Pa[a]=!0))}(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3!==e.type&&"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(c=3===(e=e.type)||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c))))}Wa.hasOwnProperty("ReactCurrentDispatcher")||(Wa.ReactCurrentDispatcher={current:null}),Wa.hasOwnProperty("ReactCurrentBatchConfig")||(Wa.ReactCurrentBatchConfig={suspense:null});var Ya=/^(.*)[\\\/]/,require="function"==typeof Symbol&&Symbol.for,Za=require?Symbol.for("react.element"):60103,$a=require?Symbol.for("react.portal"):60106,ab=require?Symbol.for("react.fragment"):60107,bb=require?Symbol.for("react.strict_mode"):60108,cb=require?Symbol.for("react.profiler"):60114,db=require?Symbol.for("react.provider"):60109,eb=require?Symbol.for("react.context"):60110,fb=require?Symbol.for("react.concurrent_mode"):60111,gb=require?Symbol.for("react.forward_ref"):60112,hb=require?Symbol.for("react.suspense"):60113,ib=require?Symbol.for("react.suspense_list"):60120,jb=require?Symbol.for("react.memo"):60115,kb=require?Symbol.for("react.lazy"):60116,lb=require?Symbol.for("react.block"):60121,mb="function"==typeof Symbol&&Symbol.iterator;function nb(a){return null!==a&&"object"==typeof a&&"function"==typeof(a=mb&&a[mb]||a["@@iterator"])?a:null}function pb(a){if(null!=a){if("function"==typeof a)return a.displayName||a.name||null;if("string"==typeof a)return a;switch(a){case ab:return"Fragment";case $a:return"Portal";case cb:return"Profiler";case bb:return"StrictMode";case hb:return"Suspense";case ib:return"SuspenseList"}if("object"==typeof a)switch(a.$$typeof){case eb:return"Context.Consumer";case db:return"Context.Provider";case gb:var b=(b=a.render).displayName||b.name||"";return a.displayName||(""!==b?"ForwardRef("+b+")":"ForwardRef");case jb:return pb(a.type);case lb:return pb(a.render);case kb:if(a=1===a._status?a._result:null)return pb(a)}}return null}function qb(a){var b="";do{switch(a.tag){case 3:case 4:case 6:case 7:case 10:case 9:var c="";break;default:var d=a._debugOwner,e=a._debugSource,f=pb(a.type),c=null;d&&(c=pb(d.type)),d=f,f="",e?f=" (at "+e.fileName.replace(Ya,"")+":"+e.lineNumber+")":c&&(f=" (created by "+c+")"),c="\n    in "+(d||"Unknown")+f}}while(b+=c,a=a.return);return b}function rb(a){switch(typeof a){case"boolean":case"number":case"object":case"string":case"undefined":return a;default:return""}}function sb(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)}function xb(a){a._valueTracker||(a._valueTracker=function(a){var e,f,b=sb(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&void 0!==c&&"function"==typeof c.get&&"function"==typeof c.set)return e=c.get,f=c.set,Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a,f.call(this,a)}}),Object.defineProperty(a,b,{enumerable:c.enumerable}),{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=null,delete a[b]}}}(a))}function yb(a){var b,c,d;if(a)return(b=a._valueTracker)?(c=b.getValue(),d="",(a=d=a?sb(a)?a.checked?"true":"false":a.value:d)!==c&&(b.setValue(a),1)):1}function zb(a,b){var c=b.checked;return n({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Ab(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked,c=rb(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function Bb(a,b){null!=(b=b.checked)&&Xa(a,"checked",b,!1)}function Cb(a,b){Bb(a,b);var c=rb(b.value),d=b.type;if(null!=c)"number"===d?(0===c&&""===a.value||a.value!=c)&&(a.value=""+c):a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d)return void a.removeAttribute("value");b.hasOwnProperty("value")?Db(a,b.type,c):b.hasOwnProperty("defaultValue")&&Db(a,b.type,rb(b.defaultValue)),null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}function Eb(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue,c||b===a.value||(a.value=b),a.defaultValue=b}""!==(c=a.name)&&(a.name=""),a.defaultChecked=!!a._wrapperState.initialChecked,""!==c&&(a.name=c)}function Db(a,b,c){"number"===b&&a.ownerDocument.activeElement===a||(null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c))}function Gb(a,b){return a=n({children:void 0},b),(b=function(a){var b="";return aa.Children.forEach(a,function(a){null!=a&&(b+=a)}),b}(b.children))&&(a.children=b),a}function Hb(a,b,c,d){if(a=a.options,b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{for(c=""+rb(c),b=null,e=0;e<a.length;e++){if(a[e].value===c)return a[e].selected=!0,void(d&&(a[e].defaultSelected=!0));null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}function Ib(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(u(91));return n({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function Jb(a,b){var c=b.value;if(null==c){if(c=b.children,b=b.defaultValue,null!=c){if(null!=b)throw Error(u(92));if(Array.isArray(c)){if(!(c.length<=1))throw Error(u(93));c=c[0]}b=c}c=b=null==b?"":b}a._wrapperState={initialValue:rb(c)}}function Kb(a,b){var c=rb(b.value),d=rb(b.defaultValue);null!=c&&((c=""+c)!==a.value&&(a.value=c),null==b.defaultValue)&&a.defaultValue!==c&&(a.defaultValue=c),null!=d&&(a.defaultValue=""+d)}function Lb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}var require="http://www.w3.org/1999/xhtml",Mb_svg="http://www.w3.org/2000/svg";function Nb(a){switch(a){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Ob(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Nb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}a=function(a,b){if(a.namespaceURI!==Mb_svg||"innerHTML"in a)a.innerHTML=b;else{for((Pb=Pb||document.createElement("div")).innerHTML="<svg>"+b.valueOf().toString()+"</svg>",b=Pb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}};var Pb,a,Qb="undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c)})}:a;function Rb(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType)return void(c.nodeValue=b)}a.textContent=b}function Sb(a,b){var c={};return c[a.toLowerCase()]=b.toLowerCase(),c["Webkit"+a]="webkit"+b,c["Moz"+a]="moz"+b,c}var Tb={animationend:Sb("Animation","AnimationEnd"),animationiteration:Sb("Animation","AnimationIteration"),animationstart:Sb("Animation","AnimationStart"),transitionend:Sb("Transition","TransitionEnd")},Ub={},Vb={};function Wb(a){if(Ub[a])return Ub[a];if(Tb[a]){var c,b=Tb[a];for(c in b)if(b.hasOwnProperty(c)&&c in Vb)return Ub[a]=b[c]}return a}ya&&(Vb=document.createElement("div").style,"AnimationEvent"in window||(delete Tb.animationend.animation,delete Tb.animationiteration.animation,delete Tb.animationstart.animation),"TransitionEvent"in window||delete Tb.transitionend.transition);var Xb=Wb("animationend"),Yb=Wb("animationiteration"),Zb=Wb("animationstart"),$b=Wb("transitionend"),ac="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),bc=new("function"==typeof WeakMap?WeakMap:Map);function cc(a){var b=bc.get(a);return void 0===b&&(b=new Map,bc.set(a,b)),b}function dc(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else for(a=b;0!=(1026&(b=a).effectTag)&&(c=b.return),a=b.return;);return 3===b.tag?c:null}function ec(a){if(13===a.tag){var b=a.memoizedState;if(null!==(b=null===b&&null!==(a=a.alternate)?a.memoizedState:b))return b.dehydrated}return null}function fc(a){if(dc(a)!==a)throw Error(u(188))}function hc(a){if(a=function(a){var b=a.alternate;if(!b){if(null===(b=dc(a)))throw Error(u(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){if(null===(d=e.return))break;c=d}else{if(e.child===f.child){for(f=e.child;f;){if(f===c)return fc(e),a;if(f===d)return fc(e),b;f=f.sibling}throw Error(u(188))}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0,c=e,d=f;break}if(h===d){g=!0,d=e,c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===c){g=!0,c=f,d=e;break}if(h===d){g=!0,d=f,c=e;break}h=h.sibling}if(!g)throw Error(u(189))}}if(c.alternate!==d)throw Error(u(190))}}if(3!==c.tag)throw Error(u(188));return c.stateNode.current===c?a:b}(a))for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b=(b.child.return=b).child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return,b=b.sibling}}return null}function ic(a,b){if(null==b)throw Error(u(30));return null==a?b:Array.isArray(a)?(Array.isArray(b)?a.push.apply(a,b):a.push(b),a):Array.isArray(b)?[a].concat(b):[a,b]}function jc(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)}var kc=null;function lc(a){if(a){var b=a._dispatchListeners,c=a._dispatchInstances;if(Array.isArray(b))for(var d=0;d<b.length&&!a.isPropagationStopped();d++)oa(a,b[d],c[d]);else b&&oa(a,b,c);a._dispatchListeners=null,a._dispatchInstances=null,a.isPersistent()||a.constructor.release(a)}}function mc(a){if(a=kc=null!==a?ic(kc,a):kc,kc=null,a){if(jc(a,lc),kc)throw Error(u(95));if(fa)throw a=ha,fa=!1,ha=null,a}}function nc(a){return 3===(a=(a=a.target||a.srcElement||window).correspondingUseElement?a.correspondingUseElement:a).nodeType?a.parentNode:a}function oc(a){var b;return ya&&((b=(a="on"+a)in document)||((b=document.createElement("div")).setAttribute(a,"return;"),b="function"==typeof b[a]),b)}var pc=[];function qc(a){a.topLevelType=null,a.nativeEvent=null,a.targetInst=null,a.ancestors.length=0,pc.length<10&&pc.push(a)}function rc(a,b,c,d){var e;return pc.length?((e=pc.pop()).topLevelType=a,e.eventSystemFlags=d,e.nativeEvent=b,e.targetInst=c,e):{topLevelType:a,eventSystemFlags:d,nativeEvent:b,targetInst:c,ancestors:[]}}function sc(a){var c=b=a.targetInst;do{if(!c){a.ancestors.push(c);break}var d=c;if(3===d.tag)d=d.stateNode.containerInfo;else{for(;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo}}while(d&&(5!==(b=c.tag)&&6!==b||a.ancestors.push(c),c=tc(d)));for(c=0;c<a.ancestors.length;c++){var b=a.ancestors[c],e=nc(a.nativeEvent),d=a.topLevelType,f=a.nativeEvent,g=a.eventSystemFlags;0===c&&(g|=64);for(var h=null,k=0;k<sa.length;k++){var l=sa[k];(l=l&&l.extractEvents(d,b,f,e,g))&&(h=ic(h,l))}mc(h)}}function uc(a,b,c){if(!c.has(a)){switch(a){case"scroll":vc(b,"scroll",!0);break;case"focus":case"blur":vc(b,"focus",!0),vc(b,"blur",!0),c.set("blur",null),c.set("focus",null);break;case"cancel":case"close":oc(a)&&vc(b,a,!0);break;case"invalid":case"submit":case"reset":break;default:-1===ac.indexOf(a)&&F(a,b)}c.set(a,null)}}var wc,xc,yc,zc=!1,Ac=[],Bc=null,Cc=null,Dc=null,Ec=new Map,Fc=new Map,Gc=[],Hc="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput close cancel copy cut paste click change contextmenu reset submit".split(" "),Ic="focus blur dragenter dragleave mouseover mouseout pointerover pointerout gotpointercapture lostpointercapture".split(" ");function Kc(a,b,c,d,e){return{blockedOn:a,topLevelType:b,eventSystemFlags:32|c,nativeEvent:e,container:d}}function Lc(a,b){switch(a){case"focus":case"blur":Bc=null;break;case"dragenter":case"dragleave":Cc=null;break;case"mouseover":case"mouseout":Dc=null;break;case"pointerover":case"pointerout":Ec.delete(b.pointerId);break;case"gotpointercapture":case"lostpointercapture":Fc.delete(b.pointerId)}}function Mc(a,b,c,d,e,f){return null===a||a.nativeEvent!==f?(a=Kc(b,c,d,e,f),null!==b&&null!==(b=Nc(b))&&xc(b)):a.eventSystemFlags|=d,a}function Qc(a){if(null===a.blockedOn){var c,b=Rc(a.topLevelType,a.eventSystemFlags,a.container,a.nativeEvent);if(null===b)return 1;null!==(c=Nc(b))&&xc(c),a.blockedOn=b}}function Sc(a,b,c){Qc(a)&&c.delete(b)}function Tc(){for(zc=!1;0<Ac.length;){var a=Ac[0];if(null!==a.blockedOn){null!==(a=Nc(a.blockedOn))&&wc(a);break}var b=Rc(a.topLevelType,a.eventSystemFlags,a.container,a.nativeEvent);null!==b?a.blockedOn=b:Ac.shift()}null!==Bc&&Qc(Bc)&&(Bc=null),null!==Cc&&Qc(Cc)&&(Cc=null),null!==Dc&&Qc(Dc)&&(Dc=null),Ec.forEach(Sc),Fc.forEach(Sc)}function Uc(a,b){a.blockedOn===b&&(a.blockedOn=null,zc||(zc=!0,r.unstable_scheduleCallback(r.unstable_NormalPriority,Tc)))}function Vc(a){function b(b){return Uc(b,a)}if(0<Ac.length){Uc(Ac[0],a);for(var c=1;c<Ac.length;c++){var d=Ac[c];d.blockedOn===a&&(d.blockedOn=null)}}for(null!==Bc&&Uc(Bc,a),null!==Cc&&Uc(Cc,a),null!==Dc&&Uc(Dc,a),Ec.forEach(b),Fc.forEach(b),c=0;c<Gc.length;c++)(d=Gc[c]).blockedOn===a&&(d.blockedOn=null);for(;0<Gc.length&&null===(c=Gc[0]).blockedOn;)(function(a){var b=tc(a.target);if(null!==b){var c=dc(b);if(null!==c)if(13===(b=c.tag)){if(null!==(b=ec(c)))return a.blockedOn=b,r.unstable_runWithPriority(a.priority,function(){yc(c)})}else if(3===b&&c.stateNode.hydrate)return a.blockedOn=3===c.tag?c.stateNode.containerInfo:null}a.blockedOn=null})(c),null===c.blockedOn&&Gc.shift()}var Wc={},Yc=new Map,Zc=new Map,$c=["abort","abort",Xb,"animationEnd",Yb,"animationIteration",Zb,"animationStart","canplay","canPlay","canplaythrough","canPlayThrough","durationchange","durationChange","emptied","emptied","encrypted","encrypted","ended","ended","error","error","gotpointercapture","gotPointerCapture","load","load","loadeddata","loadedData","loadedmetadata","loadedMetadata","loadstart","loadStart","lostpointercapture","lostPointerCapture","playing","playing","progress","progress","seeking","seeking","stalled","stalled","suspend","suspend","timeupdate","timeUpdate",$b,"transitionEnd","waiting","waiting"];function ad(a,b){for(var c=0;c<a.length;c+=2){var d=a[c],e=a[c+1],f={phasedRegistrationNames:{bubbled:f="on"+(e[0].toUpperCase()+e.slice(1)),captured:f+"Capture"},dependencies:[d],eventPriority:b};Zc.set(d,b),Yc.set(d,f),Wc[e]=f}}ad("blur blur cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focus focus input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange".split(" "),0),ad("drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel".split(" "),1),ad($c,2);for(var bd="change selectionchange textInput compositionstart compositionend compositionupdate".split(" "),cd=0;cd<bd.length;cd++)Zc.set(bd[cd],0);var dd=r.unstable_UserBlockingPriority,ed=r.unstable_runWithPriority,fd=!0;function F(a,b){vc(b,a,!1)}function vc(a,b,c){var d=Zc.get(b);switch(void 0===d?2:d){case 0:d=function(a,b,c,d){Ja||Ha();var e=id,f=Ja;Ja=!0;try{Ga(e,a,b,c,d)}finally{(Ja=f)||La()}}.bind(null,b,1,a);break;case 1:d=function(a,b,c,d){ed(dd,id.bind(null,a,b,c,d))}.bind(null,b,1,a);break;default:d=id.bind(null,b,1,a)}c?a.addEventListener(b,d,!0):a.addEventListener(b,d,!1)}function id(a,b,c,d){if(fd)if(0<Ac.length&&-1<Hc.indexOf(a))a=Kc(null,a,b,c,d),Ac.push(a);else{var e=Rc(a,b,c,d);if(null===e)Lc(a,d);else if(-1<Hc.indexOf(a))a=Kc(e,a,b,c,d),Ac.push(a);else if(!function(a,b,c,d,e){switch(b){case"focus":return Bc=Mc(Bc,a,b,c,d,e),1;case"dragenter":return Cc=Mc(Cc,a,b,c,d,e),1;case"mouseover":return Dc=Mc(Dc,a,b,c,d,e),1;case"pointerover":var f=e.pointerId;return Ec.set(f,Mc(Ec.get(f)||null,a,b,c,d,e)),1;case"gotpointercapture":return f=e.pointerId,Fc.set(f,Mc(Fc.get(f)||null,a,b,c,d,e)),1}}(e,a,b,c,d)){Lc(a,d),a=rc(a,d,null,b);try{Ma(sc,a)}finally{qc(a)}}}}function Rc(a,b,c,d){if(null!==(c=tc(c=nc(d)))){var e=dc(c);if(null===e)c=null;else{var f=e.tag;if(13===f){if(null!==(c=ec(e)))return c;c=null}else if(3===f){if(e.stateNode.hydrate)return 3===e.tag?e.stateNode.containerInfo:null;c=null}else e!==c&&(c=null)}}a=rc(a,d,c,b);try{Ma(sc,a)}finally{qc(a)}return null}var jd={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},kd=["Webkit","ms","Moz","O"];function ld(a,b,c){return null==b||"boolean"==typeof b||""===b?"":c||"number"!=typeof b||0===b||jd.hasOwnProperty(a)&&jd[a]?(""+b).trim():b+"px"}function md(a,b){for(var c in a=a.style,b){var d,e;b.hasOwnProperty(c)&&(d=0===c.indexOf("--"),e=ld(c,b[c],d),"float"===c&&(c="cssFloat"),d?a.setProperty(c,e):a[c]=e)}}Object.keys(jd).forEach(function(a){kd.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1),jd[b]=jd[a]})});var nd=n({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function od(a,b){if(b){if(nd[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(u(137,a,""));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(u(60));if(!("object"==typeof b.dangerouslySetInnerHTML&&"__html"in b.dangerouslySetInnerHTML))throw Error(u(61))}if(null!=b.style&&"object"!=typeof b.style)throw Error(u(62,""))}}function pd(a,b){if(-1===a.indexOf("-"))return"string"==typeof b.is;switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var qd=require;function rd(a,b){var c=cc(a=9===a.nodeType||11===a.nodeType?a:a.ownerDocument);b=wa[b];for(var d=0;d<b.length;d++)uc(b[d],a,c)}function sd(){}function td(a){if(void 0===(a=a||("undefined"!=typeof document?document:void 0)))return null;try{return a.activeElement||a.body}catch(b){return a.body}}function ud(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function vd(a,b){var d,c=ud(a);for(a=0;c;){if(3===c.nodeType){if(d=a+c.textContent.length,a<=b&&b<=d)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=ud(c)}}function xd(){for(var a=window,b=td();b instanceof a.HTMLIFrameElement;){try{var c="string"==typeof b.contentWindow.location.href}catch(d){c=!1}if(!c)break;b=td((a=b.contentWindow).document)}return b}function yd(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}var zd="$",Ad="/$",Bd="$?",Cd="$!",Dd=null,Ed=null;function Fd(a,b){switch(a){case"button":case"input":case"select":case"textarea":return b.autoFocus}}function Gd(a,b){return"textarea"===a||"option"===a||"noscript"===a||"string"==typeof b.children||"number"==typeof b.children||"object"==typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}var Hd="function"==typeof setTimeout?setTimeout:void 0,Id="function"==typeof clearTimeout?clearTimeout:void 0;function Jd(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a}function Kd(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(c===zd||c===Cd||c===Bd){if(0===b)return a;b--}else c===Ad&&b++}a=a.previousSibling}return null}var $c=Math.random().toString(36).slice(2),Md="__reactInternalInstance$"+$c,Nd="__reactEventHandlers$"+$c,Od="__reactContainere$"+$c;function tc(a){var b=a[Md];if(b)return b;for(var c=a.parentNode;c;){if(b=c[Od]||c[Md]){if(c=b.alternate,null!==b.child||null!==c&&null!==c.child)for(a=Kd(a);null!==a;){if(c=a[Md])return c;a=Kd(a)}return b}c=(a=c).parentNode}return null}function Nc(a){return!(a=a[Md]||a[Od])||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Pd(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(u(33))}function Qd(a){return a[Nd]||null}function Rd(a){for(;(a=a.return)&&5!==a.tag;);return a||null}function Sd(a,b){var c=a.stateNode;if(!c)return null;var d=la(c);if(!d)return null;switch(c=d[b],b){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":a=!(d=(d=!d.disabled)?d:!("button"===(a=a.type)||"input"===a||"select"===a||"textarea"===a));break;default:a=!1}if(a)return null;if(c&&"function"!=typeof c)throw Error(u(231,b,typeof c));return c}function Td(a,b,c){(b=Sd(a,c.dispatchConfig.phasedRegistrationNames[b]))&&(c._dispatchListeners=ic(c._dispatchListeners,b),c._dispatchInstances=ic(c._dispatchInstances,a))}function Ud(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=Rd(b);for(b=c.length;0<b--;)Td(c[b],"captured",a);for(b=0;b<c.length;b++)Td(c[b],"bubbled",a)}}function Vd(a,b,c){a&&c&&c.dispatchConfig.registrationName&&(b=Sd(a,c.dispatchConfig.registrationName))&&(c._dispatchListeners=ic(c._dispatchListeners,b),c._dispatchInstances=ic(c._dispatchInstances,a))}function Wd(a){a&&a.dispatchConfig.registrationName&&Vd(a._targetInst,null,a)}function Xd(a){jc(a,Ud)}var Yd=null,Zd=null,$d=null;function ae(){if($d)return $d;for(var b=Zd,c=b.length,e=("value"in Yd?Yd.value:Yd.textContent),f=e.length,a=0;a<c&&b[a]===e[a];a++);for(var g=c-a,d=1;d<=g&&b[c-d]===e[f-d];d++);return $d=e.slice(a,1<d?1-d:void 0)}function be(){return!0}function ce(){return!1}function G(a,b,c,d){for(var e in this.dispatchConfig=a,this._targetInst=b,this.nativeEvent=c,a=this.constructor.Interface)a.hasOwnProperty(e)&&((b=a[e])?this[e]=b(c):"target"===e?this.target=d:this[e]=c[e]);return this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?be:ce,this.isPropagationStopped=ce,this}function ee(a,b,c,d){var e;return this.eventPool.length?(e=this.eventPool.pop(),this.call(e,a,b,c,d),e):new this(a,b,c,d)}function fe(a){if(!(a instanceof this))throw Error(u(279));a.destructor(),this.eventPool.length<10&&this.eventPool.push(a)}function de(a){a.eventPool=[],a.getPooled=ee,a.release=fe}n(G.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!=typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=be)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!=typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=be)},persist:function(){this.isPersistent=be},isPersistent:ce,destructor:function(){for(var b in this.constructor.Interface)this[b]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null,this.isPropagationStopped=this.isDefaultPrevented=ce,this._dispatchInstances=this._dispatchListeners=null}}),G.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null},G.extend=function(a){function b(){}function c(){return d.apply(this,arguments)}var d=this,e=(b.prototype=d.prototype,new b);return n(e,c.prototype),((c.prototype=e).constructor=c).Interface=n({},d.Interface,a),c.extend=d.extend,de(c),c},de(G);var ge=G.extend({data:null}),he=G.extend({data:null}),ie=[9,13,27,32],je=ya&&"CompositionEvent"in window,require=null,le=(ya&&"documentMode"in document&&(require=document.documentMode),ya&&"TextEvent"in window&&!require),me=ya&&(!je||require&&8<require&&require<=11),ne=String.fromCharCode(32),oe={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},pe=!1;function qe(a,b){switch(a){case"keyup":return-1!==ie.indexOf(b.keyCode);case"keydown":return 229!==b.keyCode;case"keypress":case"mousedown":case"blur":return 1;default:return}}function re(a){return"object"==typeof(a=a.detail)&&"data"in a?a.data:null}var se=!1;var $c={eventTypes:oe,extractEvents:function(a,b,c,d){var e;if(je)b:{switch(a){case"compositionstart":var f=oe.compositionStart;break b;case"compositionend":f=oe.compositionEnd;break b;case"compositionupdate":f=oe.compositionUpdate;break b}f=void 0}else se?qe(a,c)&&(f=oe.compositionEnd):"keydown"===a&&229===c.keyCode&&(f=oe.compositionStart);return e=f?(me&&"ko"!==c.locale&&(se||f!==oe.compositionStart?f===oe.compositionEnd&&se&&(e=ae()):(Zd="value"in(Yd=d)?Yd.value:Yd.textContent,se=!0)),f=ge.getPooled(f,b,c,d),!e&&null===(e=re(c))||(f.data=e),Xd(f),f):null,(a=(le?function(a,b){switch(a){case"compositionend":return re(b);case"keypress":return 32!==b.which?null:(pe=!0,ne);case"textInput":return(a=b.data)===ne&&pe?null:a;default:return null}}:function(a,b){if(se)return"compositionend"===a||!je&&qe(a,b)?(a=ae(),$d=Zd=Yd=null,se=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case"compositionend":return me&&"ko"!==b.locale?null:b.data;default:return null}})(a,c))?((b=he.getPooled(oe.beforeInput,b,c,d)).data=a,Xd(b)):b=null,null===e?b:null===b?e:[e,b]}},we={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function xe(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?we[a.type]:"textarea"===b}var ye={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function ze(a,b,c){return(a=G.getPooled(ye.change,a,b,c)).type="change",Da(c),Xd(a),a}var Ae=null,Be=null;function Ce(a){mc(a)}function De(a){if(yb(Pd(a)))return a}function Ee(a,b){if("change"===a)return b}var Fe=!1;function Ge(){Ae&&(Ae.detachEvent("onpropertychange",He),Be=Ae=null)}function He(a){if("value"===a.propertyName&&De(Be))if(a=ze(Be,a,nc(a)),Ja)mc(a);else{Ja=!0;try{Fa(Ce,a)}finally{Ja=!1,La()}}}function Ie(a,b,c){"focus"===a?(Ge(),Be=c,(Ae=b).attachEvent("onpropertychange",He)):"blur"===a&&Ge()}function Je(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return De(Be)}function Ke(a,b){if("click"===a)return De(b)}function Le(a,b){if("input"===a||"change"===a)return De(b)}ya&&(Fe=oc("input")&&(!document.documentMode||9<document.documentMode));var require={eventTypes:ye,_isInputEventSupported:Fe,extractEvents:function(a,b,c,d){var g,h,e=b?Pd(b):window,f=e.nodeName&&e.nodeName.toLowerCase();if("select"===f||"input"===f&&"file"===e.type?g=Ee:xe(e)?Fe?g=Le:(g=Je,h=Ie):!(f=e.nodeName)||"input"!==f.toLowerCase()||"checkbox"!==e.type&&"radio"!==e.type||(g=Ke),g=g&&g(a,b))return ze(g,c,d);h&&h(a,e,b),"blur"===a&&(a=e._wrapperState)&&a.controlled&&"number"===e.type&&Db(e,"number",e.value)}},Ne=G.extend({view:null,detail:null}),Oe={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Pe(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):!!(a=Oe[a])&&!!b[a]}function Qe(){return Pe}var Re=0,Se=0,Te=!1,Ue=!1,Ve=Ne.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Qe,button:null,buttons:null,relatedTarget:function(a){return a.relatedTarget||(a.fromElement===a.srcElement?a.toElement:a.fromElement)},movementX:function(a){var b;return"movementX"in a?a.movementX:(b=Re,Re=a.screenX,Te?"mousemove"===a.type?a.screenX-b:0:(Te=!0,0))},movementY:function(a){var b;return"movementY"in a?a.movementY:(b=Se,Se=a.screenY,Ue?"mousemove"===a.type?a.screenY-b:0:(Ue=!0,0))}}),We=Ve.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),Xe={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave",dependencies:["pointerout","pointerover"]}},Ye={eventTypes:Xe,extractEvents:function(a,b,c,d,e){var k,l,m,p,f="mouseover"===a||"pointerover"===a,g="mouseout"===a||"pointerout"===a;if(f&&0==(32&e)&&(c.relatedTarget||c.fromElement)||!g&&!f)return null;if(f=d.window===d?d:(f=d.ownerDocument)?f.defaultView||f.parentWindow:window,g?(g=b,null!==(b=(b=c.relatedTarget||c.toElement)?tc(b):null)&&(b!==dc(b)||5!==b.tag&&6!==b.tag)&&(b=null)):g=null,g===b)return null;if("mouseout"===a||"mouseover"===a?(k=Ve,l=Xe.mouseLeave,m=Xe.mouseEnter,p="mouse"):"pointerout"!==a&&"pointerover"!==a||(k=We,l=Xe.pointerLeave,m=Xe.pointerEnter,p="pointer"),a=null==g?f:Pd(g),f=null==b?f:Pd(b),(l=k.getPooled(l,g,c,d)).type=p+"leave",l.target=a,l.relatedTarget=f,(c=k.getPooled(m,b,c,d)).type=p+"enter",c.target=f,c.relatedTarget=a,p=b,(d=g)&&p)a:{for(m=p,g=0,a=k=d;a;a=Rd(a))g++;for(a=0,b=m;b;b=Rd(b))a++;for(;0<g-a;)k=Rd(k),g--;for(;0<a-g;)m=Rd(m),a--;for(;g--;){if(k===m||k===m.alternate)break a;k=Rd(k),m=Rd(m)}k=null}else k=null;for(m=k,k=[];d&&d!==m&&(null===(g=d.alternate)||g!==m);)k.push(d),d=Rd(d);for(d=[];p&&p!==m&&(null===(g=p.alternate)||g!==m);)d.push(p),p=Rd(p);for(p=0;p<k.length;p++)Vd(k[p],"bubbled",l);for(p=d.length;0<p--;)Vd(d[p],"captured",c);return 0==(64&e)?[l]:[l,c]}};var $e="function"==typeof Object.is?Object.is:function(a,b){return a===b&&(0!==a||1/a==1/b)||a!=a&&b!=b},af=Object.prototype.hasOwnProperty;function bf(a,b){if(!$e(a,b)){if("object"!=typeof a||null===a||"object"!=typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++)if(!af.call(b,c[d])||!$e(a[c[d]],b[c[d]]))return!1}return!0}var cf=ya&&"documentMode"in document&&document.documentMode<=11,df={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},ef=null,ff=null,gf=null,hf=!1;function jf(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;return hf||null==ef||ef!==td(c)||(c="selectionStart"in(c=ef)&&yd(c)?{start:c.selectionStart,end:c.selectionEnd}:{anchorNode:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset},gf&&bf(gf,c))?null:(gf=c,(a=G.getPooled(df.select,ff,a,b)).type="select",a.target=ef,Xd(a),a)}var kf={eventTypes:df,extractEvents:function(a,b,c,d,e,f){if(!(f=!(e=f||(d.window===d?d.document:9===d.nodeType?d:d.ownerDocument)))){a:{e=cc(e),f=wa.onSelect;for(var g=0;g<f.length;g++)if(!e.has(f[g])){e=!1;break a}e=!0}f=!e}if(!f)switch(e=b?Pd(b):window,a){case"focus":!xe(e)&&"true"!==e.contentEditable||(ef=e,ff=b,gf=null);break;case"blur":gf=ff=ef=null;break;case"mousedown":hf=!0;break;case"contextmenu":case"mouseup":case"dragend":return hf=!1,jf(c,d);case"selectionchange":if(cf)break;case"keydown":case"keyup":return jf(c,d)}return null}},lf=G.extend({animationName:null,elapsedTime:null,pseudoElement:null}),mf=G.extend({clipboardData:function(a){return("clipboardData"in a?a:window).clipboardData}}),nf=Ne.extend({relatedTarget:null});function of(a){var b=a.keyCode;return"charCode"in a?0===(a=a.charCode)&&13===b&&(a=13):a=b,32<=(a=10===a?13:a)||13===a?a:0}var pf={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},qf={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},rf=Ne.extend({key:function(a){if(a.key){var b=pf[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?13===(a=of(a))?"Enter":String.fromCharCode(a):"keydown"===a.type||"keyup"===a.type?qf[a.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Qe,charCode:function(a){return"keypress"===a.type?of(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?of(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),sf=Ve.extend({dataTransfer:null}),tf=Ne.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Qe}),uf=G.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),vf=Ve.extend({deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:null,deltaMode:null}),wf={eventTypes:Wc,extractEvents:function(a,b,c,d){var e=Yc.get(a);if(!e)return null;switch(a){case"keypress":if(0===of(c))return null;case"keydown":case"keyup":a=rf;break;case"blur":case"focus":a=nf;break;case"click":if(2===c.button)return null;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":a=Ve;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":a=sf;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":a=tf;break;case Xb:case Yb:case Zb:a=lf;break;case $b:a=uf;break;case"scroll":a=Ne;break;case"wheel":a=vf;break;case"copy":case"cut":case"paste":a=mf;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":a=We;break;default:a=G}return Xd(b=a.getPooled(e,b,c,d)),b}},pa=Array.prototype.slice.call("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" "));ra();var la=Qd,ma=Nc,na=Pd,yf=(xa({SimpleEventPlugin:wf,EnterLeaveEventPlugin:Ye,ChangeEventPlugin:require,SelectEventPlugin:kf,BeforeInputEventPlugin:$c}),[]),zf=-1;function H(a){zf<0||(a.current=yf[zf],yf[zf]=null,zf--)}function I(a,b){yf[++zf]=a.current,a.current=b}var Af={},J={current:Af},K={current:!1},Bf=Af;function Cf(a,b){var c=a.type.contextTypes;if(!c)return Af;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var f,e={};for(f in c)e[f]=b[f];return d&&((a=a.stateNode).__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e),e}function L(a){return null!=(a=a.childContextTypes)}function Df(){H(K),H(J)}function Ef(a,b,c){if(J.current!==Af)throw Error(u(168));I(J,b),I(K,c)}function Ff(a,b,c){var e,d=a.stateNode;if(a=b.childContextTypes,"function"!=typeof d.getChildContext)return c;for(e in d=d.getChildContext())if(!(e in a))throw Error(u(108,pb(b)||"Unknown",e));return n({},c,{},d)}function Gf(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Af,Bf=J.current,I(J,a),I(K,K.current)}function Hf(a,b,c){var d=a.stateNode;if(!d)throw Error(u(169));c?(a=Ff(a,b,Bf),d.__reactInternalMemoizedMergedChildContext=a,H(K),H(J),I(J,a)):H(K),I(K,c)}var If=r.unstable_runWithPriority,Jf=r.unstable_scheduleCallback,Kf=r.unstable_cancelCallback,wf=r.unstable_requestPaint,Mf=r.unstable_now,Nf=r.unstable_getCurrentPriorityLevel,Of=r.unstable_ImmediatePriority,Pf=r.unstable_UserBlockingPriority,Qf=r.unstable_NormalPriority,Rf=r.unstable_LowPriority,Sf=r.unstable_IdlePriority,Tf={},Uf=r.unstable_shouldYield,Vf=void 0!==wf?wf:function(){},Wf=null,Xf=null,Yf=!1,Zf=Mf(),$f=Zf<1e4?Mf:function(){return Mf()-Zf};function ag(){switch(Nf()){case Of:return 99;case Pf:return 98;case Qf:return 97;case Rf:return 96;case Sf:return 95;default:throw Error(u(332))}}function bg(a){switch(a){case 99:return Of;case 98:return Pf;case 97:return Qf;case 96:return Rf;case 95:return Sf;default:throw Error(u(332))}}function cg(a,b){return a=bg(a),If(a,b)}function dg(a,b,c){return a=bg(a),Jf(a,b,c)}function eg(a){return null===Wf?(Wf=[a],Xf=Jf(Of,fg)):Wf.push(a),Tf}function gg(){var a;null!==Xf&&(a=Xf,Xf=null,Kf(a)),fg()}function fg(){if(!Yf&&null!==Wf){Yf=!0;var a=0;try{var b=Wf;cg(99,function(){for(;a<b.length;a++)for(var c=b[a];null!==(c=c(!0)););}),Wf=null}catch(c){throw null!==Wf&&(Wf=Wf.slice(a+1)),Jf(Of,gg),c}finally{Yf=!1}}}function hg(a,b,c){return 1073741821-(1+((1073741821-a+b/10)/(c/=10)|0))*c}function ig(a,b){if(a&&a.defaultProps)for(var c in b=n({},b),a=a.defaultProps)void 0===b[c]&&(b[c]=a[c]);return b}var jg={current:null},kg=null,lg=null,mg=null;function ng(){mg=lg=kg=null}function og(a){var b=jg.current;H(jg),a.type._context._currentValue=b}function pg(a,b){for(;null!==a;){var c=a.alternate;if(a.childExpirationTime<b)a.childExpirationTime=b,null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);else{if(!(null!==c&&c.childExpirationTime<b))break;c.childExpirationTime=b}a=a.return}}function qg(a,b){(mg=lg=null)!==(a=(kg=a).dependencies)&&null!==a.firstContext&&(a.expirationTime>=b&&(rg=!0),a.firstContext=null)}function sg(a,b){if(mg!==a&&!1!==b&&0!==b)if("number"==typeof b&&1073741823!==b||(mg=a,b=1073741823),b={context:a,observedBits:b,next:null},null===lg){if(null===kg)throw Error(u(308));lg=b,kg.dependencies={expirationTime:0,firstContext:b,responders:null}}else lg=lg.next=b;return a._currentValue}var tg=!1;function ug(a){a.updateQueue={baseState:a.memoizedState,baseQueue:null,shared:{pending:null},effects:null}}function vg(a,b){a=a.updateQueue,b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,baseQueue:a.baseQueue,shared:a.shared,effects:a.effects})}function wg(a,b){return(a={expirationTime:a,suspenseConfig:b,tag:0,payload:null,callback:null,next:null}).next=a}function xg(a,b){var c;null!==(a=a.updateQueue)&&(null===(c=(a=a.shared).pending)?b.next=b:(b.next=c.next,c.next=b),a.pending=b)}function yg(a,b){var c=a.alternate;null!==c&&vg(c,a),null===(c=(a=a.updateQueue).baseQueue)?(a.baseQueue=b.next=b).next=b:(b.next=c.next,c.next=b)}function zg(a,b,c,d){var e=a.updateQueue,f=(tg=!1,e.baseQueue);if(null!==(g=e.shared.pending)&&(null!==f&&(h=f.next,f.next=g.next,g.next=h),f=g,(e.shared.pending=null)!==(h=a.alternate))&&null!==(h=h.updateQueue)&&(h.baseQueue=g),null!==f){var h=f.next,k=e.baseState,l=0,m=null,p=null,x=null;if(null!==h)for(var z=h;;){if((g=z.expirationTime)<d){var ca={expirationTime:z.expirationTime,suspenseConfig:z.suspenseConfig,tag:z.tag,payload:z.payload,callback:z.callback,next:null};null===x?(p=x=ca,m=k):x=x.next=ca,l<g&&(l=g)}else{null!==x&&(x=x.next={expirationTime:1073741823,suspenseConfig:z.suspenseConfig,tag:z.tag,payload:z.payload,callback:z.callback,next:null}),Ag(g,z.suspenseConfig);a:{var D=a,t=z,g=b,ca=c;switch(t.tag){case 1:if("function"==typeof(D=t.payload)){k=D.call(ca,k,g);break a}k=D;break a;case 3:D.effectTag=-4097&D.effectTag|64;case 0:if(null==(g="function"==typeof(D=t.payload)?D.call(ca,k,g):D))break a;k=n({},k,g);break a;case 2:tg=!0}}null!==z.callback&&(a.effectTag|=32,null===(g=e.effects)?e.effects=[z]:g.push(z))}if(null===(z=z.next)||z===h){if(null===(g=e.shared.pending))break;z=f.next=g.next,g.next=h,e.baseQueue=f=g,e.shared.pending=null}}null===x?m=k:x.next=p,e.baseState=m,e.baseQueue=x,Bg(l),a.expirationTime=l,a.memoizedState=k}}function Cg(a,b,c){if(a=b.effects,(b.effects=null)!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){if(d.callback=null,d=e,e=c,"function"!=typeof d)throw Error(u(191,d));d.call(e)}}}var Dg=Wa.ReactCurrentBatchConfig,Eg=(new aa.Component).refs;function Fg(a,b,c,d){c=null==(c=c(d,b=a.memoizedState))?b:n({},b,c),a.memoizedState=c,0===a.expirationTime&&(a.updateQueue.baseState=c)}var Jg={isMounted:function(a){return!!(a=a._reactInternalFiber)&&dc(a)===a},enqueueSetState:function(a,b,c){a=a._reactInternalFiber;var d=Gg(),e=Dg.suspense;(e=wg(d=Hg(d,a,e),e)).payload=b,null!=c&&(e.callback=c),xg(a,e),Ig(a,d)},enqueueReplaceState:function(a,b,c){a=a._reactInternalFiber;var d=Gg(),e=Dg.suspense;(e=wg(d=Hg(d,a,e),e)).tag=1,e.payload=b,null!=c&&(e.callback=c),xg(a,e),Ig(a,d)},enqueueForceUpdate:function(a,b){a=a._reactInternalFiber;var c=Gg(),d=Dg.suspense;(d=wg(c=Hg(c,a,d),d)).tag=2,null!=b&&(d.callback=b),xg(a,d),Ig(a,c)}};function Kg(a,b,c,d,e,f,g){return"function"==typeof(a=a.stateNode).shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):!(b.prototype&&b.prototype.isPureReactComponent&&bf(c,d)&&bf(e,f))}function Lg(a,b,c){var d=!1,e=Af,f=b.contextType;b=new b(c,f="object"==typeof f&&null!==f?sg(f):(e=L(b)?Bf:J.current,(d=null!=(d=b.contextTypes))?Cf(a,e):Af)),a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null,b.updater=Jg,(a.stateNode=b)._reactInternalFiber=a,d&&((a=a.stateNode).__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f)}function Mg(a,b,c,d){a=b.state,"function"==typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d),"function"==typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d),b.state!==a&&Jg.enqueueReplaceState(b,b.state,null)}function Ng(a,b,c,d){var e=a.stateNode,f=(e.props=c,e.state=a.memoizedState,e.refs=Eg,ug(a),b.contextType);"object"==typeof f&&null!==f?e.context=sg(f):(f=L(b)?Bf:J.current,e.context=Cf(a,f)),zg(a,c,e,d),e.state=a.memoizedState,"function"==typeof(f=b.getDerivedStateFromProps)&&(Fg(a,0,f,c),e.state=a.memoizedState),"function"==typeof b.getDerivedStateFromProps||"function"==typeof e.getSnapshotBeforeUpdate||"function"!=typeof e.UNSAFE_componentWillMount&&"function"!=typeof e.componentWillMount||(b=e.state,"function"==typeof e.componentWillMount&&e.componentWillMount(),"function"==typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Jg.enqueueReplaceState(e,e.state,null),zg(a,c,e,d),e.state=a.memoizedState),"function"==typeof e.componentDidMount&&(a.effectTag|=4)}var Og=Array.isArray;function Pg(a,b,c){if(null!==(a=c.ref)&&"function"!=typeof a&&"object"!=typeof a){if(c._owner){if(c=c._owner){if(1!==c.tag)throw Error(u(309));var d=c.stateNode}var e;if(d)return e=""+a,null!==b&&null!==b.ref&&"function"==typeof b.ref&&b.ref._stringRef===e?b.ref:((b=function(a){var b=d.refs;b===Eg&&(b=d.refs={}),null===a?delete b[e]:b[e]=a})._stringRef=e,b);throw Error(u(147,a))}if("string"!=typeof a)throw Error(u(284));if(!c._owner)throw Error(u(290,a))}return a}function Qg(a,b){if("textarea"!==a.type)throw Error(u(31,"[object Object]"===Object.prototype.toString.call(b)?"object with keys {"+Object.keys(b).join(", ")+"}":b,""))}function Rg(a){function b(b,c){var d;a&&(null!==(d=b.lastEffect)?(d.nextEffect=c,b.lastEffect=c):b.firstEffect=b.lastEffect=c,c.nextEffect=null,c.effectTag=8)}function c(c,d){if(a)for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){return(a=Sg(a,b)).index=0,a.sibling=null,a}function f(b,c,d){if(b.index=d,a){if(null!==(d=b.alternate))return(d=d.index)<c?(b.effectTag=2,c):d;b.effectTag=2}return c}function g(b){return a&&null===b.alternate&&(b.effectTag=2),b}function h(a,b,c,d){return null===b||6!==b.tag?(b=Tg(c,a.mode,d)).return=a:(b=e(b,c)).return=a,b}function k(a,b,c,d){return null!==b&&b.elementType===c.type?((d=e(b,c.props)).ref=Pg(0,b,c),d.return=a):((d=Ug(c.type,c.key,c.props,null,a.mode,d)).ref=Pg(0,b,c),d.return=a),d}function l(a,b,c,d){return null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation?(b=Vg(c,a.mode,d)).return=a:(b=e(b,c.children||[])).return=a,b}function m(a,b,c,d,f){return null===b||7!==b.tag?(b=Wg(c,a.mode,d,f)).return=a:(b=e(b,c)).return=a,b}function p(a,b,c){if("string"==typeof b||"number"==typeof b)return(b=Tg(""+b,a.mode,c)).return=a,b;if("object"==typeof b&&null!==b){switch(b.$$typeof){case Za:return(c=Ug(b.type,b.key,b.props,null,a.mode,c)).ref=Pg(0,null,b),c.return=a,c;case $a:return(b=Vg(b,a.mode,c)).return=a,b}if(Og(b)||nb(b))return(b=Wg(b,a.mode,c,null)).return=a,b;Qg(a,b)}return null}function x(a,b,c,d){var e=null!==b?b.key:null;if("string"==typeof c||"number"==typeof c)return null!==e?null:h(a,b,""+c,d);if("object"==typeof c&&null!==c){switch(c.$$typeof){case Za:return c.key===e?c.type===ab?m(a,b,c.props.children,d,e):k(a,b,c,d):null;case $a:return c.key===e?l(a,b,c,d):null}if(Og(c)||nb(c))return null!==e?null:m(a,b,c,d,null);Qg(a,c)}return null}function z(a,b,c,d,e){if("string"==typeof d||"number"==typeof d)return h(b,a=a.get(c)||null,""+d,e);if("object"==typeof d&&null!==d){switch(d.$$typeof){case Za:return a=a.get(null===d.key?c:d.key)||null,d.type===ab?m(b,a,d.props.children,e,d.key):k(b,a,d,e);case $a:return l(b,a=a.get(null===d.key?c:d.key)||null,d,e)}if(Og(d)||nb(d))return m(b,a=a.get(c)||null,d,e,null);Qg(b,d)}return null}function ca(e,g,h,k){for(var l=null,t=null,m=g,y=g=0,A=null;null!==m&&y<h.length;y++){m.index>y?(A=m,m=null):A=m.sibling;var q=x(e,m,h[y],k);if(null===q){null===m&&(m=A);break}a&&m&&null===q.alternate&&b(e,m),g=f(q,g,y),null===t?l=q:t.sibling=q,t=q,m=A}if(y===h.length)c(e,m);else if(null===m)for(;y<h.length;y++)null!==(m=p(e,h[y],k))&&(g=f(m,g,y),null===t?l=m:t.sibling=m,t=m);else{for(m=d(e,m);y<h.length;y++)null!==(A=z(m,e,y,h[y],k))&&(a&&null!==A.alternate&&m.delete(null===A.key?y:A.key),g=f(A,g,y),null===t?l=A:t.sibling=A,t=A);a&&m.forEach(function(a){return b(e,a)})}return l}function D(e,g,h,l){var k=nb(h);if("function"!=typeof k)throw Error(u(150));if(null==(h=k.call(h)))throw Error(u(151));for(var m=k=null,t=g,y=g=0,A=null,q=h.next();null!==t&&!q.done;y++,q=h.next()){t.index>y?(A=t,t=null):A=t.sibling;var D=x(e,t,q.value,l);if(null===D){null===t&&(t=A);break}a&&t&&null===D.alternate&&b(e,t),g=f(D,g,y),null===m?k=D:m.sibling=D,m=D,t=A}if(q.done)c(e,t);else if(null===t)for(;!q.done;y++,q=h.next())null!==(q=p(e,q.value,l))&&(g=f(q,g,y),null===m?k=q:m.sibling=q,m=q);else{for(t=d(e,t);!q.done;y++,q=h.next())null!==(q=z(t,e,y,q.value,l))&&(a&&null!==q.alternate&&t.delete(null===q.key?y:q.key),g=f(q,g,y),null===m?k=q:m.sibling=q,m=q);a&&t.forEach(function(a){return b(e,a)})}return k}return function(a,d,f,h){var k="object"==typeof f&&null!==f&&f.type===ab&&null===f.key,l="object"==typeof(f=k?f.props.children:f)&&null!==f;if(l)switch(f.$$typeof){case Za:a:{for(l=f.key,k=d;null!==k;){if(k.key===l){switch(k.tag){case 7:if(f.type!==ab)break;c(a,k.sibling),(d=e(k,f.props.children)).return=a,a=d;break a;default:if(k.elementType===f.type){c(a,k.sibling),(d=e(k,f.props)).ref=Pg(0,k,f),d.return=a,a=d;break a}}c(a,k);break}b(a,k),k=k.sibling}a=f.type===ab?((d=Wg(f.props.children,a.mode,h,f.key)).return=a,d):((h=Ug(f.type,f.key,f.props,null,a.mode,h)).ref=Pg(0,d,f),h.return=a,h)}return g(a);case $a:a:{for(k=f.key;null!==d;){if(d.key===k){if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling),(d=e(d,f.children||[])).return=a,a=d;break a}c(a,d);break}b(a,d),d=d.sibling}(d=Vg(f,a.mode,h)).return=a,a=d}return g(a)}if("string"==typeof f||"number"==typeof f)return f=""+f,(d=null!==d&&6===d.tag?(c(a,d.sibling),e(d,f)):(c(a,d),Tg(f,a.mode,h))).return=a,g(a=d);if(Og(f))return ca(a,d,f,h);if(nb(f))return D(a,d,f,h);if(l&&Qg(a,f),void 0===f&&!k)switch(a.tag){case 1:case 0:throw a=a.type,Error(u(152,a.displayName||a.name||"Component"))}return c(a,d)}}var Xg=Rg(!0),Yg=Rg(!1),Zg={},$g={current:Zg},ah={current:Zg},bh={current:Zg};function ch(a){if(a===Zg)throw Error(u(174));return a}function dh(a,b){switch(I(bh,b),I(ah,a),I($g,Zg),a=b.nodeType){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Ob(null,"");break;default:b=Ob(b=(a=8===a?b.parentNode:b).namespaceURI||null,a=a.tagName)}H($g),I($g,b)}function eh(){H($g),H(ah),H(bh)}function fh(a){ch(bh.current);var b=ch($g.current),c=Ob(b,a.type);b!==c&&(I(ah,a),I($g,c))}function gh(a){ah.current===a&&(H($g),H(ah))}var M={current:0};function hh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(null===(c=c.dehydrated)||c.data===Bd||c.data===Cd))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!=(64&b.effectTag))return b}else if(null!==b.child){b=(b.child.return=b).child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return,b=b.sibling}return null}function ih(a,b){return{responder:a,props:b}}var jh=Wa.ReactCurrentDispatcher,kh=Wa.ReactCurrentBatchConfig,lh=0,N=null,O=null,P=null,mh=!1;function Q(){throw Error(u(321))}function nh(a,b){if(null!==b){for(var c=0;c<b.length&&c<a.length;c++)if(!$e(a[c],b[c]))return;return 1}}function oh(a,b,c,d,e,f){if(lh=f,(N=b).memoizedState=null,b.updateQueue=null,b.expirationTime=0,jh.current=null===a||null===a.memoizedState?ph:qh,a=c(d,e),b.expirationTime===lh){f=0;do{if(b.expirationTime=0,!(f<25))throw Error(u(301))}while(f+=1,P=O=null,b.updateQueue=null,jh.current=rh,a=c(d,e),b.expirationTime===lh)}if(jh.current=sh,b=null!==O&&null!==O.next,lh=0,P=O=N=null,mh=!1,b)throw Error(u(300));return a}function th(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===P?N.memoizedState=P=a:P=P.next=a,P}function uh(){a=null===O?null!==(a=N.alternate)?a.memoizedState:null:O.next;var a,b=null===P?N.memoizedState:P.next;if(null!==b)P=b,O=a;else{if(null===a)throw Error(u(310));a={memoizedState:(O=a).memoizedState,baseState:O.baseState,baseQueue:O.baseQueue,queue:O.queue,next:null},null===P?N.memoizedState=P=a:P=P.next=a}return P}function vh(a,b){return"function"==typeof b?b(a):b}function wh(a){var b=uh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;var g,e=(d=O).baseQueue,f=c.pending;if(null!==f&&(null!==e&&(g=e.next,e.next=f.next,f.next=g),d.baseQueue=e=f,c.pending=null),null!==e){var e=e.next,d=d.baseState,h=g=f=null,k=e;do{var m,l=k.expirationTime}while(l<lh?(m={expirationTime:k.expirationTime,suspenseConfig:k.suspenseConfig,action:k.action,eagerReducer:k.eagerReducer,eagerState:k.eagerState,next:null},null===h?(g=h=m,f=d):h=h.next=m,l>N.expirationTime&&Bg(N.expirationTime=l)):(null!==h&&(h=h.next={expirationTime:1073741823,suspenseConfig:k.suspenseConfig,action:k.action,eagerReducer:k.eagerReducer,eagerState:k.eagerState,next:null}),Ag(l,k.suspenseConfig),d=k.eagerReducer===a?k.eagerState:a(d,k.action)),null!==(k=k.next)&&k!==e);null===h?f=d:h.next=g,$e(d,b.memoizedState)||(rg=!0),b.memoizedState=d,b.baseState=f,b.baseQueue=h,c.lastRenderedState=d}return[b.memoizedState,c.dispatch]}function xh(a){var b=uh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;for(var g=e=e.next;f=a(f,g.action),(g=g.next)!==e;);$e(f,b.memoizedState)||(rg=!0),b.memoizedState=f,null===b.baseQueue&&(b.baseState=f),c.lastRenderedState=f}return[f,d]}function yh(a){var b=th();return"function"==typeof a&&(a=a()),b.memoizedState=b.baseState=a,a=(a=b.queue={pending:null,dispatch:null,lastRenderedReducer:vh,lastRenderedState:a}).dispatch=zh.bind(null,N,a),[b.memoizedState,a]}function Ah(a,b,c,d){return a={tag:a,create:b,destroy:c,deps:d,next:null},null===(b=N.updateQueue)?(N.updateQueue=b={lastEffect:null}).lastEffect=a.next=a:null===(c=b.lastEffect)?b.lastEffect=a.next=a:(d=c.next,(c.next=a).next=d,b.lastEffect=a),a}function Bh(){return uh().memoizedState}function Ch(a,b,c,d){var e=th();N.effectTag|=a,e.memoizedState=Ah(1|b,c,void 0,void 0===d?null:d)}function Dh(a,b,c,d){var e=uh(),f=(d=void 0===d?null:d,void 0);if(null!==O){var g=O.memoizedState,f=g.destroy;if(null!==d&&nh(d,g.deps))return void Ah(b,c,f,d)}N.effectTag|=a,e.memoizedState=Ah(1|b,c,f,d)}function Eh(a,b){return Ch(516,4,a,b)}function Fh(a,b){return Dh(516,4,a,b)}function Gh(a,b){return Dh(4,2,a,b)}function Hh(a,b){return"function"==typeof b?(a=a(),b(a),function(){b(null)}):null!=b?(a=a(),b.current=a,function(){b.current=null}):void 0}function Ih(a,b,c){return c=null!=c?c.concat([a]):null,Dh(4,2,Hh.bind(null,b,a),c)}function Jh(){}function Kh(a,b){return th().memoizedState=[a,void 0===b?null:b],a}function Lh(a,b){var c=uh(),d=(b=void 0===b?null:b,c.memoizedState);return null!==d&&null!==b&&nh(b,d[1])?d[0]:(c.memoizedState=[a,b],a)}function Mh(a,b){var c=uh(),d=(b=void 0===b?null:b,c.memoizedState);return null!==d&&null!==b&&nh(b,d[1])?d[0]:(a=a(),c.memoizedState=[a,b],a)}function Nh(a,b,c){var d=ag();cg(d<98?98:d,function(){a(!0)}),cg(97<d?97:d,function(){var d=kh.suspense;kh.suspense=void 0===b?null:b;try{a(!1),c()}finally{kh.suspense=d}})}function zh(a,b,c){var d,e={expirationTime:d=Hg(Gg(),a,e=Dg.suspense),suspenseConfig:e,action:c,eagerReducer:null,eagerState:null,next:null},f=b.pending;if(null===f?e.next=e:(e.next=f.next,f.next=e),b.pending=e,f=a.alternate,a===N||null!==f&&f===N)mh=!0,e.expirationTime=lh,N.expirationTime=lh;else{if(0===a.expirationTime&&(null===f||0===f.expirationTime)&&null!==(f=b.lastRenderedReducer))try{var g=b.lastRenderedState,h=f(g,c);if(e.eagerReducer=f,e.eagerState=h,$e(h,g))return}catch(k){}Ig(a,d)}}var sh={readContext:sg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useResponder:Q,useDeferredValue:Q,useTransition:Q},ph={readContext:sg,useCallback:Kh,useContext:sg,useEffect:Eh,useImperativeHandle:function(a,b,c){return c=null!=c?c.concat([a]):null,Ch(4,2,Hh.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Ch(4,2,a,b)},useMemo:function(a,b){var c=th();return b=void 0===b?null:b,a=a(),c.memoizedState=[a,b],a},useReducer:function(a,b,c){var d=th();return b=void 0!==c?c(b):b,d.memoizedState=d.baseState=b,a=(a=d.queue={pending:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:b}).dispatch=zh.bind(null,N,a),[d.memoizedState,a]},useRef:function(a){return th().memoizedState=a={current:a}},useState:yh,useDebugValue:Jh,useResponder:ih,useDeferredValue:function(a,b){var c=yh(a),d=c[0],e=c[1];return Eh(function(){var c=kh.suspense;kh.suspense=void 0===b?null:b;try{e(a)}finally{kh.suspense=c}},[a,b]),d},useTransition:function(a){var c=(b=yh(!1))[0],b=b[1];return[Kh(Nh.bind(null,b,a),[b,a]),c]}},qh={readContext:sg,useCallback:Lh,useContext:sg,useEffect:Fh,useImperativeHandle:Ih,useLayoutEffect:Gh,useMemo:Mh,useReducer:wh,useRef:Bh,useState:function(){return wh(vh)},useDebugValue:Jh,useResponder:ih,useDeferredValue:function(a,b){var c=wh(vh),d=c[0],e=c[1];return Fh(function(){var c=kh.suspense;kh.suspense=void 0===b?null:b;try{e(a)}finally{kh.suspense=c}},[a,b]),d},useTransition:function(a){var c=(b=wh(vh))[0],b=b[1];return[Lh(Nh.bind(null,b,a),[b,a]),c]}},rh={readContext:sg,useCallback:Lh,useContext:sg,useEffect:Fh,useImperativeHandle:Ih,useLayoutEffect:Gh,useMemo:Mh,useReducer:xh,useRef:Bh,useState:function(){return xh(vh)},useDebugValue:Jh,useResponder:ih,useDeferredValue:function(a,b){var c=xh(vh),d=c[0],e=c[1];return Fh(function(){var c=kh.suspense;kh.suspense=void 0===b?null:b;try{e(a)}finally{kh.suspense=c}},[a,b]),d},useTransition:function(a){var c=(b=xh(vh))[0],b=b[1];return[Lh(Nh.bind(null,b,a),[b,a]),c]}},Oh=null,Ph=null,Qh=!1;function Rh(a,b){var c=Sh(5,null,null,0);c.elementType="DELETED",c.type="DELETED",c.stateNode=b,c.return=a,c.effectTag=8,null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c}function Th(a,b){switch(a.tag){case 5:var c=a.type;return null!==(b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b)&&(a.stateNode=b,1);case 6:return null!==(b=""===a.pendingProps||3!==b.nodeType?null:b)&&(a.stateNode=b,1);default:return}}function Uh(a){if(Qh){var b=Ph;if(b){var c=b;if(!Th(a,b)){if(!(b=Jd(c.nextSibling))||!Th(a,b))return a.effectTag=-1025&a.effectTag|2,Qh=!1,void(Oh=a);Rh(Oh,c)}Oh=a,Ph=Jd(b.firstChild)}else a.effectTag=-1025&a.effectTag|2,Qh=!1,Oh=a}}function Vh(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;Oh=a}function Wh(a){if(a===Oh){if(!Qh)return Vh(a),Qh=!0,0;var b=a.type;if(5!==a.tag||"head"!==b&&"body"!==b&&!Gd(b,a.memoizedProps))for(b=Ph;b;)Rh(a,b),b=Jd(b.nextSibling);if(Vh(a),13===a.tag){if(!(a=null!==(a=a.memoizedState)?a.dehydrated:null))throw Error(u(317));a:{for(a=a.nextSibling,b=0;a;){if(8===a.nodeType){var c=a.data;if(c===Ad){if(0===b){Ph=Jd(a.nextSibling);break a}b--}else c!==zd&&c!==Cd&&c!==Bd||b++}a=a.nextSibling}Ph=null}}else Ph=Oh?Jd(a.stateNode.nextSibling):null;return 1}}function Xh(){Ph=Oh=null,Qh=!1}var Yh=Wa.ReactCurrentOwner,rg=!1;function R(a,b,c,d){b.child=null===a?Yg(b,null,c,d):Xg(b,a.child,c,d)}function Zh(a,b,c,d,e){c=c.render;var f=b.ref;return qg(b,e),d=oh(a,b,c,d,f,e),null===a||rg?(b.effectTag|=1,R(a,b,d,e),b.child):(b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),$h(a,b,e))}function ai(a,b,c,d,e,f){var g;return null===a?"function"!=typeof(g=c.type)||bi(g)||void 0!==g.defaultProps||null!==c.compare||void 0!==c.defaultProps?((a=Ug(c.type,null,d,null,b.mode,f)).ref=b.ref,(a.return=b).child=a):(b.tag=15,b.type=g,ci(a,b,g,d,e,f)):(g=a.child,e<f&&(e=g.memoizedProps,(c=null!==(c=c.compare)?c:bf)(e,d))&&a.ref===b.ref?$h(a,b,f):(b.effectTag|=1,(a=Sg(g,d)).ref=b.ref,(a.return=b).child=a))}function ci(a,b,c,d,e,f){return null!==a&&bf(a.memoizedProps,d)&&a.ref===b.ref&&(rg=!1,e<f)?(b.expirationTime=a.expirationTime,$h(a,b,f)):di(a,b,c,d,f)}function ei(a,b){var c=b.ref;(null===a&&null!==c||null!==a&&a.ref!==c)&&(b.effectTag|=128)}function di(a,b,c,d,e){var f=Cf(b,L(c)?Bf:J.current);return qg(b,e),c=oh(a,b,c,d,f,e),null===a||rg?(b.effectTag|=1,R(a,b,c,e),b.child):(b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),$h(a,b,e))}function fi(a,b,c,d,e){var f,g,h,k,l,m,p,x;return L(c)?(f=!0,Gf(b)):f=!1,qg(b,e),d=null===b.stateNode?(null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),Lg(b,c,d),Ng(b,c,d,e),!0):null===a?(g=b.stateNode,h=b.memoizedProps,g.props=h,k=g.context,l="object"==typeof(l=c.contextType)&&null!==l?sg(l):Cf(b,l=L(c)?Bf:J.current),(p="function"==typeof(m=c.getDerivedStateFromProps)||"function"==typeof g.getSnapshotBeforeUpdate)||"function"!=typeof g.UNSAFE_componentWillReceiveProps&&"function"!=typeof g.componentWillReceiveProps||h===d&&k===l||Mg(0,g,d,l),tg=!1,x=b.memoizedState,g.state=x,zg(b,d,g,e),k=b.memoizedState,h!==d||x!==k||K.current||tg?("function"==typeof m&&(Fg(b,0,m,d),k=b.memoizedState),(h=tg||Kg(b,c,h,d,x,k,l))?(p||"function"!=typeof g.UNSAFE_componentWillMount&&"function"!=typeof g.componentWillMount||("function"==typeof g.componentWillMount&&g.componentWillMount(),"function"==typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"==typeof g.componentDidMount&&(b.effectTag|=4)):("function"==typeof g.componentDidMount&&(b.effectTag|=4),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,h):("function"==typeof g.componentDidMount&&(b.effectTag|=4),!1)):(g=b.stateNode,vg(a,b),h=b.memoizedProps,g.props=b.type===b.elementType?h:ig(b.type,h),k=g.context,l="object"==typeof(l=c.contextType)&&null!==l?sg(l):Cf(b,l=L(c)?Bf:J.current),(p="function"==typeof(m=c.getDerivedStateFromProps)||"function"==typeof g.getSnapshotBeforeUpdate)||"function"!=typeof g.UNSAFE_componentWillReceiveProps&&"function"!=typeof g.componentWillReceiveProps||h===d&&k===l||Mg(0,g,d,l),tg=!1,k=b.memoizedState,g.state=k,zg(b,d,g,e),x=b.memoizedState,h!==d||k!==x||K.current||tg?("function"==typeof m&&(Fg(b,0,m,d),x=b.memoizedState),(m=tg||Kg(b,c,h,d,k,x,l))?(p||"function"!=typeof g.UNSAFE_componentWillUpdate&&"function"!=typeof g.componentWillUpdate||("function"==typeof g.componentWillUpdate&&g.componentWillUpdate(d,x,l),"function"==typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,x,l)),"function"==typeof g.componentDidUpdate&&(b.effectTag|=4),"function"==typeof g.getSnapshotBeforeUpdate&&(b.effectTag|=256)):("function"!=typeof g.componentDidUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=4),"function"!=typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=256),b.memoizedProps=d,b.memoizedState=x),g.props=d,g.state=x,g.context=l,m):("function"!=typeof g.componentDidUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=4),"function"!=typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=256),!1)),gi(a,b,c,d,f,e)}function gi(a,b,c,d,e,f){ei(a,b);var g=0!=(64&b.effectTag);if(!d&&!g)return e&&Hf(b,c,!1),$h(a,b,f);d=b.stateNode,Yh.current=b;var h=g&&"function"!=typeof c.getDerivedStateFromError?null:d.render();return b.effectTag|=1,null!==a&&g?(b.child=Xg(b,a.child,null,f),b.child=Xg(b,null,h,f)):R(a,b,h,f),b.memoizedState=d.state,e&&Hf(b,c,!0),b.child}function hi(a){var b=a.stateNode;b.pendingContext?Ef(0,b.pendingContext,b.pendingContext!==b.context):b.context&&Ef(0,b.context,!1),dh(a,b.containerInfo)}var ii={dehydrated:null,retryTime:0};function ji(a,b,c){var d=b.mode,e=b.pendingProps,f=M.current,g=!1;if(0!=(64&b.effectTag)||0!=(2&f)&&(null===a||null!==a.memoizedState)?(g=!0,b.effectTag&=-65):null!==a&&null===a.memoizedState||void 0===e.fallback||!0===e.unstable_avoidThisFallback||(f|=1),I(M,1&f),null===a){if(void 0!==e.fallback&&Uh(b),g){if(g=e.fallback,0==(2&((e=Wg(null,d,0,null)).return=b).mode))for(a=(null!==b.memoizedState?b.child:b).child,e.child=a;null!==a;)a.return=e,a=a.sibling;return(c=Wg(g,d,c,null)).return=b,e.sibling=c,b.memoizedState=ii,b.child=e,c}return d=e.children,b.memoizedState=null,b.child=Yg(b,null,d,c)}if(null!==a.memoizedState){if(d=(a=a.child).sibling,g){if(e=e.fallback,0==(2&((c=Sg(a,a.pendingProps)).return=b).mode)&&(g=(null!==b.memoizedState?b.child:b).child)!==a.child)for(c.child=g;null!==g;)g.return=c,g=g.sibling;return(d=Sg(d,e)).return=b,c.sibling=d,c.childExpirationTime=0,b.memoizedState=ii,b.child=c,d}return c=Xg(b,a.child,e.children,c),b.memoizedState=null,b.child=c}if(a=a.child,g){if(g=e.fallback,(e=Wg(null,d,0,null)).return=b,null!==(e.child=a)&&(a.return=e),0==(2&b.mode))for(a=(null!==b.memoizedState?b.child:b).child,e.child=a;null!==a;)a.return=e,a=a.sibling;return(c=Wg(g,d,c,null)).return=b,(e.sibling=c).effectTag|=2,e.childExpirationTime=0,b.memoizedState=ii,b.child=e,c}return b.memoizedState=null,b.child=Xg(b,a,e.children,c)}function ki(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b),pg(a.return,b)}function li(a,b,c,d,e,f){var g=a.memoizedState;null===g?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailExpiration:0,tailMode:e,lastEffect:f}:(g.isBackwards=b,g.rendering=null,g.renderingStartTime=0,g.last=d,g.tail=c,g.tailExpiration=0,g.tailMode=e,g.lastEffect=f)}function mi(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;if(R(a,b,d.children,c),0!=(2&(d=M.current)))d=1&d|2,b.effectTag|=64;else{if(null!==a&&0!=(64&a.effectTag))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&ki(a,c);else if(19===a.tag)ki(a,c);else if(null!==a.child){a=(a.child.return=a).child;continue}if(a===b)break;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return,a=a.sibling}d&=1}if(I(M,d),0==(2&b.mode))b.memoizedState=null;else switch(e){case"forwards":for(c=b.child,e=null;null!==c;)null!==(a=c.alternate)&&null===hh(a)&&(e=c),c=c.sibling;null===(c=e)?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null),li(b,!1,e,c,f,b.lastEffect);break;case"backwards":for(e=b.child,b.child=c=null;null!==e;){if(null!==(a=e.alternate)&&null===hh(a)){b.child=e;break}a=e.sibling,e.sibling=c,c=e,e=a}li(b,!0,c,null,f,b.lastEffect);break;case"together":li(b,!1,null,null,void 0,b.lastEffect);break;default:b.memoizedState=null}return b.child}function $h(a,b,c){null!==a&&(b.dependencies=a.dependencies);var d=b.expirationTime;if(0!==d&&Bg(d),b.childExpirationTime<c)return null;if(null!==a&&b.child!==a.child)throw Error(u(153));if(null!==b.child){for(c=Sg(a=b.child,a.pendingProps),(b.child=c).return=b;null!==a.sibling;)a=a.sibling,(c=c.sibling=Sg(a,a.pendingProps)).return=b;c.sibling=null}return b.child}function ri(a,b){switch(a.tailMode){case"hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case"collapsed":for(var c=a.tail,d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}function Ai(a,b){return{value:a,source:b,stack:qb(b)}}var ni=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c=(c.child.return=c).child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return,c=c.sibling}},pi=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){var h,k,g=b.stateNode;switch(ch($g.current),a=null,c){case"input":f=zb(g,f),d=zb(g,d),a=[];break;case"option":f=Gb(g,f),d=Gb(g,d),a=[];break;case"select":f=n({},f,{value:void 0}),d=n({},d,{value:void 0}),a=[];break;case"textarea":f=Ib(g,f),d=Ib(g,d),a=[];break;default:"function"!=typeof f.onClick&&"function"==typeof d.onClick&&(g.onclick=sd)}for(h in od(c,d),c=null,f)if(!d.hasOwnProperty(h)&&f.hasOwnProperty(h)&&null!=f[h])if("style"===h)for(k in g=f[h],g)g.hasOwnProperty(k)&&(c=c||{},c[k]="");else"dangerouslySetInnerHTML"!==h&&"children"!==h&&"suppressContentEditableWarning"!==h&&"suppressHydrationWarning"!==h&&"autoFocus"!==h&&(va.hasOwnProperty(h)?a=a||[]:(a=a||[]).push(h,null));for(h in d){var l=d[h],g=null!=f?f[h]:void 0;if(d.hasOwnProperty(h)&&l!==g&&(null!=l||null!=g))if("style"===h)if(g){for(k in g)!g.hasOwnProperty(k)||l&&l.hasOwnProperty(k)||(c=c||{},c[k]="");for(k in l)l.hasOwnProperty(k)&&g[k]!==l[k]&&(c=c||{},c[k]=l[k])}else c||(a=a||[]).push(h,c),c=l;else"dangerouslySetInnerHTML"===h?(l=l?l.__html:void 0,g=g?g.__html:void 0,null!=l&&g!==l&&(a=a||[]).push(h,l)):"children"===h?g===l||"string"!=typeof l&&"number"!=typeof l||(a=a||[]).push(h,""+l):"suppressContentEditableWarning"!==h&&"suppressHydrationWarning"!==h&&(va.hasOwnProperty(h)?(null!=l&&rd(e,h),a||g===l||(a=[])):(a=a||[]).push(h,l))}c&&(a=a||[]).push("style",c),e=a,(b.updateQueue=e)&&(b.effectTag|=4)}},qi=function(a,b,c,d){c!==d&&(b.effectTag|=4)},Bi="function"==typeof WeakSet?WeakSet:Set;function Ci(a,b){var c=b.source;null===b.stack&&null!==c&&qb(c),null!==c&&pb(c.type),b=b.value,null!==a&&1===a.tag&&pb(a.type);try{console.error(b)}catch(e){setTimeout(function(){throw e})}}function Fi(a){var b=a.ref;if(null!==b)if("function"==typeof b)try{b(null)}catch(c){Ei(a,c)}else b.current=null}function Hi(a,b){if(null!==(b=null!==(b=b.updateQueue)?b.lastEffect:null)){var d,c=b=b.next;do{}while((c.tag&a)===a&&(d=c.destroy,(c.destroy=void 0)!==d)&&d(),(c=c.next)!==b)}}function Ii(a,b){if(null!==(b=null!==(b=b.updateQueue)?b.lastEffect:null)){var d,c=b=b.next;do{}while((c.tag&a)===a&&(d=c.create,c.destroy=d()),(c=c.next)!==b)}}function Ki(a,b,c){switch("function"==typeof Li&&Li(b),b.tag){case 0:case 11:case 14:case 15:case 22:var d;null!==(a=b.updateQueue)&&null!==(a=a.lastEffect)&&(d=a.next,cg(97<c?97:c,function(){var a=d;do{var c=a.destroy;if(void 0!==c){var g=b;try{c()}catch(h){Ei(g,h)}}}while((a=a.next)!==d)}));break;case 1:Fi(b),"function"==typeof(c=b.stateNode).componentWillUnmount&&function(a,b){try{b.props=a.memoizedProps,b.state=a.memoizedState,b.componentWillUnmount()}catch(c){Ei(a,c)}}(b,c);break;case 5:Fi(b);break;case 4:Mi(a,b,c)}}function Oi(a){return 5===a.tag||3===a.tag||4===a.tag}function Pi(a){a:{for(var b=a.return;null!==b;){if(Oi(b)){var c=b;break a}b=b.return}throw Error(u(160))}switch(b=c.stateNode,c.tag){case 5:var d=!1;break;case 3:case 4:b=b.containerInfo,d=!0;break;default:throw Error(u(161))}16&c.effectTag&&(Rb(b,""),c.effectTag&=-17);a:b:for(c=a;;){for(;null===c.sibling;){if(null===c.return||Oi(c.return)){c=null;break a}c=c.return}for(c.sibling.return=c.return,c=c.sibling;5!==c.tag&&6!==c.tag&&18!==c.tag;){if(2&c.effectTag)continue b;if(null===c.child||4===c.tag)continue b;c=(c.child.return=c).child}if(!(2&c.effectTag)){c=c.stateNode;break a}}(d?function Qi(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?(8===c.nodeType?c.parentNode:c).insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null==c&&null===b.onclick&&(b.onclick=sd));else if(4!==d&&(a=a.child,null!==a))for(Qi(a,b,c),a=a.sibling;null!==a;)Qi(a,b,c),a=a.sibling}:function Ri(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Ri(a,b,c),a=a.sibling;null!==a;)Ri(a,b,c),a=a.sibling})(a,c,b)}function Mi(a,b,c){for(var f,g,d=b,e=!1;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(u(160));switch(f=e.stateNode,e.tag){case 5:g=!1;break a;case 3:case 4:f=f.containerInfo,g=!0;break a}e=e.return}e=!0}if(5===d.tag||6===d.tag){a:for(var h=a,k=d,l=c,m=k;;)if(Ki(h,m,l),null!==m.child&&4!==m.tag)m.child.return=m,m=m.child;else{if(m===k)break;for(;null===m.sibling;){if(null===m.return||m.return===k)break a;m=m.return}m.sibling.return=m.return,m=m.sibling}g?(h=f,k=d.stateNode,(8===h.nodeType?h.parentNode:h).removeChild(k)):f.removeChild(d.stateNode)}else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo,g=!0,d=(d.child.return=d).child;continue}}else if(Ki(a,d,c),null!==d.child){d=(d.child.return=d).child;continue}if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;4===(d=d.return).tag&&(e=!1)}d.sibling.return=d.return,d=d.sibling}}function Si(a,b){switch(b.tag){case 0:case 11:case 14:case 15:case 22:return void Hi(3,b);case 1:return;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps,e=null!==a?a.memoizedProps:d,f=(a=b.type,b.updateQueue);if((b.updateQueue=null)!==f){for(c[Nd]=d,"input"===a&&"radio"===d.type&&null!=d.name&&Bb(c,d),pd(a,e),b=pd(a,d),e=0;e<f.length;e+=2){var g=f[e],h=f[e+1];"style"===g?md(c,h):"dangerouslySetInnerHTML"===g?Qb(c,h):"children"===g?Rb(c,h):Xa(c,g,h,b)}switch(a){case"input":Cb(c,d);break;case"textarea":Kb(c,d);break;case"select":b=c._wrapperState.wasMultiple,c._wrapperState.wasMultiple=!!d.multiple,null!=(a=d.value)?Hb(c,!!d.multiple,a,!1):b!==!!d.multiple&&(null!=d.defaultValue?Hb(c,!!d.multiple,d.defaultValue,!0):Hb(c,!!d.multiple,d.multiple?[]:"",!1))}}}return;case 6:if(null===b.stateNode)throw Error(u(162));return void(b.stateNode.nodeValue=b.memoizedProps);case 3:return void((b=b.stateNode).hydrate&&(b.hydrate=!1,Vc(b.containerInfo)));case 12:return;case 13:if(null===(c=b).memoizedState?d=!1:(d=!0,c=b.child,Ti=$f()),null!==c)a:for(a=c;;){if(5===a.tag)f=a.stateNode,d?"function"==typeof(f=f.style).setProperty?f.setProperty("display","none","important"):f.display="none":(f=a.stateNode,e=null!=(e=a.memoizedProps.style)&&e.hasOwnProperty("display")?e.display:null,f.style.display=ld("display",e));else if(6===a.tag)a.stateNode.nodeValue=d?"":a.memoizedProps;else{if(13===a.tag&&null!==a.memoizedState&&null===a.memoizedState.dehydrated){(f=a.child.sibling).return=a,a=f;continue}if(null!==a.child){a=(a.child.return=a).child;continue}}if(a===c)break;for(;null===a.sibling;){if(null===a.return||a.return===c)break a;a=a.return}a.sibling.return=a.return,a=a.sibling}return void Ui(b);case 19:return void Ui(b);case 17:return}throw Error(u(163))}function Ui(a){var c,b=a.updateQueue;null!==b&&((a.updateQueue=null)===(c=a.stateNode)&&(c=a.stateNode=new Bi),b.forEach(function(b){var d=function(a,b){var c=a.stateNode;null!==c&&c.delete(b),(b=0)===b&&(b=Hg(b=Gg(),a,null)),null!==(a=xj(a,b))&&Z(a)}.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))}))}var Wi="function"==typeof WeakMap?WeakMap:Map;function Xi(a,b,c){(c=wg(c,null)).tag=3,c.payload={element:null};var d=b.value;return c.callback=function(){Yi||(Yi=!0,Zi=d),Ci(a,b)},c}function $i(a,b,c){(c=wg(c,null)).tag=3;var e,d=a.type.getDerivedStateFromError,f=("function"==typeof d&&(e=b.value,c.payload=function(){return Ci(a,b),d(e)}),a.stateNode);return null!==f&&"function"==typeof f.componentDidCatch&&(c.callback=function(){"function"!=typeof d&&(null===aj?aj=new Set([this]):aj.add(this),Ci(a,b));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})}),c}var bj=Math.ceil,cj=Wa.ReactCurrentDispatcher,dj=Wa.ReactCurrentOwner,V=0,ej=8,fj=16,gj=32,ti=0,hj=1,ij=2,ui=3,vi=4,jj=5,W=V,T=null,X=null,U=0,S=ti,kj=null,lj=1073741823,mj=1073741823,nj=null,wi=0,oj=!1,Ti=0,pj=500,Y=null,Yi=!1,Zi=null,aj=null,qj=!1,rj=null,sj=90,tj=null,uj=0,vj=null,wj=0;function Gg(){return(W&(fj|gj))!==V?1073741821-($f()/10|0):0!==wj?wj:wj=1073741821-($f()/10|0)}function Hg(a,b,c){if(0==(2&(b=b.mode)))return 1073741823;var d=ag();if(0==(4&b))return 99===d?1073741823:1073741822;if((W&fj)!==V)return U;if(null!==c)a=hg(a,0|c.timeoutMs||5e3,250);else switch(d){case 99:a=1073741823;break;case 98:a=hg(a,150,100);break;case 97:case 96:a=hg(a,5e3,250);break;case 95:a=2;break;default:throw Error(u(326))}return null!==T&&a===U&&--a,a}function Ig(a,b){if(50<uj)throw uj=0,vj=null,Error(u(185));var c;null!==(a=xj(a,b))&&(c=ag(),1073741823===b?(W&ej)!==V&&(W&(fj|gj))===V?yj(a):(Z(a),W===V&&gg()):Z(a),(4&W)===V||98!==c&&99!==c||(null===tj?tj=new Map([[a,b]]):(void 0===(c=tj.get(a))||b<c)&&tj.set(a,b)))}function xj(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate,d=(null!==c&&c.expirationTime<b&&(c.expirationTime=b),a.return),e=null;if(null===d&&3===a.tag)e=a.stateNode;else for(;null!==d;){if(c=d.alternate,d.childExpirationTime<b&&(d.childExpirationTime=b),null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b),null===d.return&&3===d.tag){e=d.stateNode;break}d=d.return}return null!==e&&(T===e&&(Bg(b),S===vi)&&xi(e,U),yi(e,b)),e}function zj(a){var c,b=a.lastExpiredTime;return 0===b&&Aj(a,b=a.firstPendingTime)?(c=a.lastPingedTime,(a=(a=a.nextKnownPendingLevel)<c?c:a)<=2&&b!==a?0:a):b}function Z(a){if(0!==a.lastExpiredTime)a.callbackExpirationTime=1073741823,a.callbackPriority=99,a.callbackNode=eg(yj.bind(null,a));else{var b=zj(a),c=a.callbackNode;if(0===b)null!==c&&(a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90);else{var d=Gg(),d=1073741823===b?99:1===b||2===b?95:(d=10*(1073741821-b)-10*(1073741821-d))<=0?99:d<=250?98:d<=5250?97:95;if(null!==c){var e=a.callbackPriority;if(a.callbackExpirationTime===b&&d<=e)return;c!==Tf&&Kf(c)}a.callbackExpirationTime=b,a.callbackPriority=d,b=1073741823===b?eg(yj.bind(null,a)):dg(d,Bj.bind(null,a),{timeout:10*(1073741821-b)-$f()}),a.callbackNode=b}}}function Bj(a,b){if(wj=0,b)Cj(a,b=Gg()),Z(a);else{var c=zj(a);if(0!==c){if(b=a.callbackNode,(W&(fj|gj))!==V)throw Error(u(327));if(Dj(),a===T&&c===U||Ej(a,c),null!==X){for(var d=W,e=(W|=fj,Fj());;)try{for(;null!==X&&!Uf();)X=Qj(X);break}catch(h){Hj(a,h)}if(ng(),W=d,cj.current=e,S===hj)throw b=kj,Ej(a,c),xi(a,c),Z(a),b;if(null===X)switch(e=a.finishedWork=a.current.alternate,a.finishedExpirationTime=c,d=S,T=null,d){case ti:case hj:throw Error(u(345));case ij:Cj(a,2<c?2:c);break;case ui:if(xi(a,c),c===(d=a.lastSuspendedTime)&&(a.nextKnownPendingLevel=Ij(e)),1073741823===lj&&10<(e=Ti+pj-$f())){if(oj){var f=a.lastPingedTime;if(0===f||c<=f){a.lastPingedTime=c,Ej(a,c);break}}if(0!==(f=zj(a))&&f!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}a.timeoutHandle=Hd(Jj.bind(null,a),e)}else Jj(a);break;case vi:xi(a,c),c===(d=a.lastSuspendedTime)&&(a.nextKnownPendingLevel=Ij(e)),oj&&(0===(e=a.lastPingedTime)||c<=e)?(a.lastPingedTime=c,Ej(a,c)):0!==(e=zj(a))&&e!==c||(0!==d&&d!==c?a.lastPingedTime=d:(1073741823!==mj?d=10*(1073741821-mj)-$f():1073741823===lj?d=0:(d=10*(1073741821-lj)-5e3,(c=10*(1073741821-c)-(e=$f()))<(d=((d=(d=e-d)<0?0:d)<120?120:d<480?480:d<1080?1080:d<1920?1920:d<3e3?3e3:d<4320?4320:1960*bj(d/1960))-d)&&(d=c)),10<d?a.timeoutHandle=Hd(Jj.bind(null,a),d):Jj(a)));break;case jj:if(1073741823!==lj&&null!==nj){var f=lj,g=nj;if(10<(d=(d=0|g.busyMinDurationMs)<=0||(e=0|g.busyDelayMs,(f=$f()-(10*(1073741821-f)-(0|g.timeoutMs||5e3)))<=e)?0:e+d-f)){xi(a,c),a.timeoutHandle=Hd(Jj.bind(null,a),d);break}}Jj(a);break;default:throw Error(u(329))}if(Z(a),a.callbackNode===b)return Bj.bind(null,a)}}}return null}function yj(a){var b=0!==(b=a.lastExpiredTime)?b:1073741823;if((W&(fj|gj))!==V)throw Error(u(327));if(Dj(),a===T&&b===U||Ej(a,b),null!==X){for(var c=W,d=(W|=fj,Fj());;)try{for(;null!==X;)X=Qj(X);break}catch(e){Hj(a,e)}if(ng(),W=c,cj.current=d,S===hj)throw c=kj,Ej(a,b),xi(a,b),Z(a),c;if(null!==X)throw Error(u(261));a.finishedWork=a.current.alternate,a.finishedExpirationTime=b,T=null,Jj(a),Z(a)}return null}function Mj(a,b){var c=W;W|=1;try{return a(b)}finally{(W=c)===V&&gg()}}function Nj(a,b){var c=W;W=-2&W|ej;try{a(b)}finally{(W=c)===V&&gg()}}function Ej(a,b){a.finishedWork=null,a.finishedExpirationTime=0;var c=a.timeoutHandle;if(-1!==c&&(a.timeoutHandle=-1,Id(c)),null!==X)for(c=X.return;null!==c;){var d=c;switch(d.tag){case 1:null!=(d=d.type.childContextTypes)&&Df();break;case 3:eh(),H(K),H(J);break;case 5:gh(d);break;case 4:eh();break;case 13:case 19:H(M);break;case 10:og(d)}c=c.return}X=Sg((T=a).current,null),U=b,S=ti,mj=lj=1073741823,nj=kj=null,wi=0,oj=!1}function Hj(a,b){do{try{if(ng(),jh.current=sh,mh)for(var c=N.memoizedState;null!==c;){var d=c.queue;null!==d&&(d.pending=null),c=c.next}if(lh=0,P=O=N=null,mh=!1,null===X||null===X.return)return S=hj,kj=b,X=null;a:{var e=a,f=X.return,h=b;if(b=U,(g=X).effectTag|=2048,(g.firstEffect=g.lastEffect=null)!==h&&"object"==typeof h&&"function"==typeof h.then){var l,z,ca,x,k=h,m=(0==(2&g.mode)&&((l=g.alternate)?(g.updateQueue=l.updateQueue,g.memoizedState=l.memoizedState,g.expirationTime=l.expirationTime):(g.updateQueue=null,g.memoizedState=null)),0!=(1&M.current)),p=f;do{if(x=(x=13===p.tag)?null!==(z=p.memoizedState)?null!==z.dehydrated:void 0!==(ca=p.memoizedProps).fallback&&(!0!==ca.unstable_avoidThisFallback||!m):x){var t,y,D=p.updateQueue;if(null===D?((t=new Set).add(k),p.updateQueue=t):D.add(k),0==(2&p.mode)){p.effectTag|=64,g.effectTag&=-2981,1===g.tag&&(null===g.alternate?g.tag=17:((y=wg(1073741823,null)).tag=2,xg(g,y))),g.expirationTime=1073741823;break a}var q,h=void 0,g=b,A=e.pingCache;null===A?(A=e.pingCache=new Wi,h=new Set,A.set(k,h)):void 0===(h=A.get(k))&&(h=new Set,A.set(k,h)),h.has(g)||(h.add(g),q=Oj.bind(null,e,k,g),k.then(q,q)),p.effectTag|=4096,p.expirationTime=b;break a}}while(null!==(p=p.return));h=Error((pb(g.type)||"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+qb(g))}S!==jj&&(S=ij),h=Ai(h,g),p=f;do{switch(p.tag){case 3:k=h;p.effectTag|=4096,p.expirationTime=b,yg(p,Xi(p,k,b));break a;case 1:k=h;var w=p.type,ub=p.stateNode;if(0==(64&p.effectTag)&&("function"==typeof w.getDerivedStateFromError||null!==ub&&"function"==typeof ub.componentDidCatch&&(null===aj||!aj.has(ub)))){p.effectTag|=4096,p.expirationTime=b,yg(p,$i(p,k,b));break a}}}while(null!==(p=p.return))}X=Pj(X)}catch(Xc){b=Xc;continue}break}while(1)}function Fj(){var a=cj.current;return cj.current=sh,null===a?sh:a}function Ag(a,b){a<lj&&2<a&&(lj=a),null!==b&&a<mj&&2<a&&(mj=a,nj=b)}function Bg(a){wi<a&&(wi=a)}function Qj(a){var b=Rj(a.alternate,a,U);return a.memoizedProps=a.pendingProps,null===b&&(b=Pj(a)),dj.current=null,b}function Pj(a){X=a;do{var b=X.alternate;if(a=X.return,0==(2048&X.effectTag)){if(b=function(a,b,c){var d=b.pendingProps;switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return null;case 1:return L(b.type)&&Df(),null;case 3:return eh(),H(K),H(J),(c=b.stateNode).pendingContext&&(c.context=c.pendingContext,c.pendingContext=null),null!==a&&null!==a.child||!Wh(b)||(b.effectTag|=4),null;case 5:gh(b),c=ch(bh.current);var e=b.type;if(null!==a&&null!=b.stateNode)pi(a,b,e,d,c),a.ref!==b.ref&&(b.effectTag|=128);else{if(!d){if(null===b.stateNode)throw Error(u(166));return null}if(a=ch($g.current),Wh(b)){var g,h,d=b.stateNode,e=b.type,f=b.memoizedProps;switch(d[Md]=b,d[Nd]=f,e){case"iframe":case"object":case"embed":F("load",d);break;case"video":case"audio":for(a=0;a<ac.length;a++)F(ac[a],d);break;case"source":F("error",d);break;case"img":case"image":case"link":F("error",d),F("load",d);break;case"form":F("reset",d),F("submit",d);break;case"details":F("toggle",d);break;case"input":Ab(d,f),F("invalid",d),rd(c,"onChange");break;case"select":d._wrapperState={wasMultiple:!!f.multiple},F("invalid",d),rd(c,"onChange");break;case"textarea":Jb(d,f),F("invalid",d),rd(c,"onChange")}for(g in od(e,f),a=null,f)f.hasOwnProperty(g)&&(h=f[g],"children"===g?"string"==typeof h?d.textContent!==h&&(a=["children",h]):"number"==typeof h&&d.textContent!==""+h&&(a=["children",""+h]):va.hasOwnProperty(g)&&null!=h&&rd(c,g));switch(e){case"input":xb(d),Eb(d,f,!0);break;case"textarea":xb(d),Lb(d);break;case"select":case"option":break;default:"function"==typeof f.onClick&&(d.onclick=sd)}c=a,null!==(b.updateQueue=c)&&(b.effectTag|=4)}else{switch(g=9===c.nodeType?c:c.ownerDocument,(a=a===qd?Nb(e):a)===qd?"script"===e?((a=g.createElement("div")).innerHTML="<script><\/script>",a=a.removeChild(a.firstChild)):"string"==typeof d.is?a=g.createElement(e,{is:d.is}):(a=g.createElement(e),"select"===e&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,e),a[Md]=b,a[Nd]=d,ni(a,b),b.stateNode=a,g=pd(e,d),e){case"iframe":case"object":case"embed":F("load",a),h=d;break;case"video":case"audio":for(h=0;h<ac.length;h++)F(ac[h],a);h=d;break;case"source":F("error",a),h=d;break;case"img":case"image":case"link":F("error",a),F("load",a),h=d;break;case"form":F("reset",a),F("submit",a),h=d;break;case"details":F("toggle",a),h=d;break;case"input":Ab(a,d),h=zb(a,d),F("invalid",a),rd(c,"onChange");break;case"option":h=Gb(a,d);break;case"select":a._wrapperState={wasMultiple:!!d.multiple},h=n({},d,{value:void 0}),F("invalid",a),rd(c,"onChange");break;case"textarea":Jb(a,d),h=Ib(a,d),F("invalid",a),rd(c,"onChange");break;default:h=d}od(e,h);var l,k=h;for(f in k)k.hasOwnProperty(f)&&(l=k[f],"style"===f?md(a,l):"dangerouslySetInnerHTML"===f?null!=(l=l?l.__html:void 0)&&Qb(a,l):"children"===f?"string"==typeof l?"textarea"===e&&""===l||Rb(a,l):"number"==typeof l&&Rb(a,""+l):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(va.hasOwnProperty(f)?null!=l&&rd(c,f):null!=l&&Xa(a,f,l,g)));switch(e){case"input":xb(a),Eb(a,d,!1);break;case"textarea":xb(a),Lb(a);break;case"option":null!=d.value&&a.setAttribute("value",""+rb(d.value));break;case"select":a.multiple=!!d.multiple,null!=(c=d.value)?Hb(a,!!d.multiple,c,!1):null!=d.defaultValue&&Hb(a,!!d.multiple,d.defaultValue,!0);break;default:"function"==typeof h.onClick&&(a.onclick=sd)}Fd(e,d)&&(b.effectTag|=4)}null!==b.ref&&(b.effectTag|=128)}return null;case 6:if(a&&null!=b.stateNode)qi(0,b,a.memoizedProps,d);else{if("string"!=typeof d&&null===b.stateNode)throw Error(u(166));c=ch(bh.current),ch($g.current),Wh(b)?(c=b.stateNode,d=b.memoizedProps,c[Md]=b,c.nodeValue!==d&&(b.effectTag|=4)):((c=(9===c.nodeType?c:c.ownerDocument).createTextNode(d))[Md]=b).stateNode=c}return null;case 13:return(H(M),d=b.memoizedState,0!=(64&b.effectTag))?(b.expirationTime=c,b):(c=null!==d,d=!1,null===a?void 0!==b.memoizedProps.fallback&&Wh(b):(d=null!==(e=a.memoizedState),c||null===e||null!==(e=a.child.sibling)&&(null!==(f=b.firstEffect)?(b.firstEffect=e).nextEffect=f:(b.firstEffect=b.lastEffect=e).nextEffect=null,e.effectTag=8)),c&&!d&&0!=(2&b.mode)&&(null===a&&!0!==b.memoizedProps.unstable_avoidThisFallback||0!=(1&M.current)?S===ti&&(S=ui):(S!==ti&&S!==ui||(S=vi),0!==wi&&null!==T&&(xi(T,U),yi(T,wi)))),(c||d)&&(b.effectTag|=4),null);case 4:return eh(),null;case 10:return og(b),null;case 17:return L(b.type)&&Df(),null;case 19:if(H(M),null===(d=b.memoizedState))return null;if(e=0!=(64&b.effectTag),null===(f=d.rendering)){if(e)ri(d,!1);else if(S!==ti||null!==a&&0!=(64&a.effectTag))for(f=b.child;null!==f;){if(null!==(a=hh(f))){for(b.effectTag|=64,ri(d,!1),null!==(e=a.updateQueue)&&(b.updateQueue=e,b.effectTag|=4),null===d.lastEffect&&(b.firstEffect=null),b.lastEffect=d.lastEffect,d=b.child;null!==d;)f=c,(e=d).effectTag&=2,e.nextEffect=null,e.firstEffect=null,(e.lastEffect=null)===(a=e.alternate)?(e.childExpirationTime=0,e.expirationTime=f,e.child=null,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null):(e.childExpirationTime=a.childExpirationTime,e.expirationTime=a.expirationTime,e.child=a.child,e.memoizedProps=a.memoizedProps,e.memoizedState=a.memoizedState,e.updateQueue=a.updateQueue,f=a.dependencies,e.dependencies=null===f?null:{expirationTime:f.expirationTime,firstContext:f.firstContext,responders:f.responders}),d=d.sibling;return I(M,1&M.current|2),b.child}f=f.sibling}}else{if(!e)if(null!==(a=hh(f))){if(b.effectTag|=64,e=!0,null!==(c=a.updateQueue)&&(b.updateQueue=c,b.effectTag|=4),ri(d,!0),null===d.tail&&"hidden"===d.tailMode&&!f.alternate)return null!==(b=b.lastEffect=d.lastEffect)&&(b.nextEffect=null),null}else 2*$f()-d.renderingStartTime>d.tailExpiration&&1<c&&(b.effectTag|=64,ri(d,!(e=!0)),b.expirationTime=b.childExpirationTime=c-1);d.isBackwards?(f.sibling=b.child,b.child=f):(null!==(c=d.last)?c.sibling=f:b.child=f,d.last=f)}return null!==d.tail?(0===d.tailExpiration&&(d.tailExpiration=$f()+500),c=d.tail,d.rendering=c,d.tail=c.sibling,d.lastEffect=b.lastEffect,d.renderingStartTime=$f(),c.sibling=null,b=M.current,I(M,e?1&b|2:1&b),c):null}throw Error(u(156,b.tag))}(b,X,U),1===U||1!==X.childExpirationTime){for(var c=0,d=X.child;null!==d;){var e=d.expirationTime,f=d.childExpirationTime;(c=c<e?e:c)<f&&(c=f),d=d.sibling}X.childExpirationTime=c}if(null!==b)return b;null!==a&&0==(2048&a.effectTag)&&(null===a.firstEffect&&(a.firstEffect=X.firstEffect),null!==X.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=X.firstEffect),a.lastEffect=X.lastEffect),1<X.effectTag)&&(null!==a.lastEffect?a.lastEffect.nextEffect=X:a.firstEffect=X,a.lastEffect=X)}else{if(null!==(b=function(a){switch(a.tag){case 1:L(a.type)&&Df();var b=a.effectTag;return 4096&b?(a.effectTag=-4097&b|64,a):null;case 3:if(eh(),H(K),H(J),0!=(64&(b=a.effectTag)))throw Error(u(285));return a.effectTag=-4097&b|64,a;case 5:return gh(a),null;case 13:return H(M),4096&(b=a.effectTag)?(a.effectTag=-4097&b|64,a):null;case 19:return H(M),null;case 4:return eh(),null;case 10:return og(a),null;default:return null}}(X)))return b.effectTag&=2047,b;null!==a&&(a.firstEffect=a.lastEffect=null,a.effectTag|=2048)}if(null!==(b=X.sibling))return b}while(null!==(X=a));return S===ti&&(S=jj),null}function Ij(a){var b=a.expirationTime;return(a=a.childExpirationTime)<b?b:a}function Jj(a){var b=ag();return cg(99,function(a,b){for(;Dj(),null!==rj;);if((W&(fj|gj))!==V)throw Error(u(327));var c=a.finishedWork,d=a.finishedExpirationTime;if(null!==c){if(a.finishedWork=null,a.finishedExpirationTime=0,c===a.current)throw Error(u(177));a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90,a.nextKnownPendingLevel=0;var e=Ij(c);if(a.firstPendingTime=e,d<=a.lastSuspendedTime?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:d<=a.firstSuspendedTime&&(a.firstSuspendedTime=d-1),d<=a.lastPingedTime&&(a.lastPingedTime=0),d<=a.lastExpiredTime&&(a.lastExpiredTime=0),a===T&&(X=T=null,U=0),null!==(e=1<c.effectTag?null!==c.lastEffect?(c.lastEffect.nextEffect=c).firstEffect:c:c.firstEffect)){var f=W,g=(W|=gj,dj.current=null,Dd=fd,xd());if(yd(g)){if("selectionStart"in g)var h={start:g.selectionStart,end:g.selectionEnd};else a:{var k=(h=(h=g.ownerDocument)&&h.defaultView||window).getSelection&&h.getSelection();if(k&&0!==k.rangeCount){h=k.anchorNode;var l=k.anchorOffset,m=k.focusNode;k=k.focusOffset;try{h.nodeType,m.nodeType}catch(wb){h=null;break a}var A,p=0,x=-1,z=-1,ca=0,D=0,t=g,y=null;b:for(;;){for(;t!==h||0!==l&&3!==t.nodeType||(x=p+l),t!==m||0!==k&&3!==t.nodeType||(z=p+k),3===t.nodeType&&(p+=t.nodeValue.length),null!==(A=t.firstChild);)y=t,t=A;for(;;){if(t===g)break b;if(y===h&&++ca===l&&(x=p),y===m&&++D===k&&(z=p),null!==(A=t.nextSibling))break;y=(t=y).parentNode}t=A}h=-1===x||-1===z?null:{start:x,end:z}}else h=null}h=h||{start:0,end:0}}else h=null;fd=!(Ed={activeElementDetached:null,focusedElem:g,selectionRange:h}),Y=e;do{try{!function(){for(;null!==Y;){var a=Y.effectTag;0!=(256&a)&&function(a,b){switch(b.tag){case 0:case 11:case 15:case 22:return;case 1:var c,d;return 256&b.effectTag&&null!==a&&(c=a.memoizedProps,d=a.memoizedState,b=(a=b.stateNode).getSnapshotBeforeUpdate(b.elementType===b.type?c:ig(b.type,c),d),a.__reactInternalSnapshotBeforeUpdate=b);case 3:case 5:case 6:case 4:case 17:return}throw Error(u(163))}(Y.alternate,Y),0==(512&a)||qj||(qj=!0,dg(97,function(){return Dj(),null})),Y=Y.nextEffect}}()}catch(wb){if(null===Y)throw Error(u(330));Ei(Y,wb),Y=Y.nextEffect}}while(null!==Y);Y=e;do{try{for(g=a,h=b;null!==Y;){var B,w,q=Y.effectTag;switch(16&q&&Rb(Y.stateNode,""),128&q&&null!==(B=Y.alternate)&&null!==(w=B.ref)&&("function"==typeof w?w(null):w.current=null),1038&q){case 2:Pi(Y),Y.effectTag&=-3;break;case 6:Pi(Y),Y.effectTag&=-3,Si(Y.alternate,Y);break;case 1024:Y.effectTag&=-1025;break;case 1028:Y.effectTag&=-1025,Si(Y.alternate,Y);break;case 4:Si(Y.alternate,Y);break;case 8:Mi(g,l=Y,h),function Ni(a){var b=a.alternate;a.return=null,a.child=null,a.memoizedState=null,a.updateQueue=null,a.dependencies=null,a.alternate=null,a.firstEffect=null,a.lastEffect=null,a.pendingProps=null,a.memoizedProps=null,(a.stateNode=null)!==b&&Ni(b)}(l)}Y=Y.nextEffect}}catch(wb){if(null===Y)throw Error(u(330));Ei(Y,wb),Y=Y.nextEffect}}while(null!==Y);if(w=Ed,B=xd(),q=w.focusedElem,h=w.selectionRange,B!==q&&q&&q.ownerDocument&&function wd(a,b){return!(!a||!b)&&(a===b||(!a||3!==a.nodeType)&&(b&&3===b.nodeType?wd(a,b.parentNode):"contains"in a?a.contains(b):!!a.compareDocumentPosition&&!!(16&a.compareDocumentPosition(b))))}(q.ownerDocument.documentElement,q)){null!==h&&yd(q)&&(B=h.start,void 0===(w=h.end)&&(w=B),"selectionStart"in q?(q.selectionStart=B,q.selectionEnd=Math.min(w,q.value.length)):(w=(B=q.ownerDocument||document)&&B.defaultView||window).getSelection&&(w=w.getSelection(),l=q.textContent.length,g=Math.min(h.start,l),h=void 0===h.end?g:Math.min(h.end,l),!w.extend&&h<g&&(l=h,h=g,g=l),l=vd(q,g),m=vd(q,h),l)&&m&&(1!==w.rangeCount||w.anchorNode!==l.node||w.anchorOffset!==l.offset||w.focusNode!==m.node||w.focusOffset!==m.offset)&&((B=B.createRange()).setStart(l.node,l.offset),w.removeAllRanges(),h<g?(w.addRange(B),w.extend(m.node,m.offset)):(B.setEnd(m.node,m.offset),w.addRange(B)))),B=[];for(w=q;w=w.parentNode;)1===w.nodeType&&B.push({element:w,left:w.scrollLeft,top:w.scrollTop});for("function"==typeof q.focus&&q.focus(),q=0;q<B.length;q++)(w=B[q]).element.scrollLeft=w.left,w.element.scrollTop=w.top}fd=!!Dd,Ed=Dd=null,a.current=c,Y=e;do{try{for(q=a;null!==Y;){var vb,Xc,ub=Y.effectTag;36&ub&&function(a,b,c){switch(c.tag){case 0:case 11:case 15:case 22:return Ii(3,c);case 1:var d;return a=c.stateNode,4&c.effectTag&&(null===b?a.componentDidMount():(d=c.elementType===c.type?b.memoizedProps:ig(c.type,b.memoizedProps),a.componentDidUpdate(d,b.memoizedState,a.__reactInternalSnapshotBeforeUpdate))),null!==(b=c.updateQueue)&&Cg(0,b,a);case 3:if(null!==(b=c.updateQueue)){if((a=null)!==c.child)switch(c.child.tag){case 5:case 1:a=c.child.stateNode}Cg(0,b,a)}return;case 5:return a=c.stateNode,null===b&&4&c.effectTag&&Fd(c.type,c.memoizedProps)&&a.focus();case 6:case 4:case 12:return;case 13:return null===c.memoizedState&&null!==(c=c.alternate)&&null!==(c=c.memoizedState)&&null!==(c=c.dehydrated)&&Vc(c);case 19:case 17:case 20:case 21:return}throw Error(u(163))}(q,Y.alternate,Y),128&ub&&(B=void 0,null!==(vb=Y.ref))&&(Xc=Y.stateNode,Y.tag,B=Xc,"function"==typeof vb?vb(B):vb.current=B),Y=Y.nextEffect}}catch(wb){if(null===Y)throw Error(u(330));Ei(Y,wb),Y=Y.nextEffect}}while(null!==Y);Y=null,Vf(),W=f}else a.current=c;if(qj)qj=!1,rj=a,sj=b;else for(Y=e;null!==Y;)b=Y.nextEffect,Y.nextEffect=null,Y=b;if(0===(b=a.firstPendingTime)&&(aj=null),1073741823===b?a===vj?uj++:(uj=0,vj=a):uj=0,"function"==typeof Uj&&Uj(c.stateNode,d),Z(a),Yi)throw Yi=!1,a=Zi,Zi=null,a;(W&ej)===V&&gg()}return null}.bind(null,a,b)),null}function Dj(){var a;if(90!==sj)return a=97<sj?97:sj,sj=90,cg(a,Vj)}function Vj(){if(null===rj)return!1;var a=rj;if(rj=null,(W&(fj|gj))!==V)throw Error(u(331));var b=W;for(W|=gj,a=a.current.firstEffect;null!==a;){try{var c=a;if(0!=(512&c.effectTag))switch(c.tag){case 0:case 11:case 15:case 22:Hi(5,c),Ii(5,c)}}catch(d){if(null===a)throw Error(u(330));Ei(a,d)}c=a.nextEffect,a.nextEffect=null,a=c}return W=b,gg(),!0}function Wj(a,b,c){xg(a,b=Xi(a,b=Ai(c,b),1073741823)),null!==(a=xj(a,1073741823))&&Z(a)}function Ei(a,b){if(3===a.tag)Wj(a,a,b);else for(var c=a.return;null!==c;){if(3===c.tag){Wj(c,a,b);break}if(1===c.tag){var d=c.stateNode;if("function"==typeof c.type.getDerivedStateFromError||"function"==typeof d.componentDidCatch&&(null===aj||!aj.has(d))){xg(c,a=$i(c,a=Ai(b,a),1073741823)),null!==(c=xj(c,1073741823))&&Z(c);break}}c=c.return}}function Oj(a,b,c){var d=a.pingCache;null!==d&&d.delete(b),T===a&&U===c?S===vi||S===ui&&1073741823===lj&&$f()-Ti<pj?Ej(a,U):oj=!0:!Aj(a,c)||0!==(b=a.lastPingedTime)&&b<c||(a.lastPingedTime=c,Z(a))}var Rj=function(a,b,c){var d=b.expirationTime;if(null!==a){var e=b.pendingProps;if(a.memoizedProps!==e||K.current)rg=!0;else{if(d<c){switch(rg=!1,b.tag){case 3:hi(b),Xh();break;case 5:if(fh(b),4&b.mode&&1!==c&&e.hidden)return b.expirationTime=b.childExpirationTime=1,null;break;case 1:L(b.type)&&Gf(b);break;case 4:dh(b,b.stateNode.containerInfo);break;case 10:d=b.memoizedProps.value,e=b.type._context,I(jg,e._currentValue),e._currentValue=d;break;case 13:if(null!==b.memoizedState)return 0!==(d=b.child.childExpirationTime)&&c<=d?ji(a,b,c):(I(M,1&M.current),null!==(b=$h(a,b,c))?b.sibling:null);I(M,1&M.current);break;case 19:if(d=b.childExpirationTime>=c,0!=(64&a.effectTag)){if(d)return mi(a,b,c);b.effectTag|=64}if(null!==(e=b.memoizedState)&&(e.rendering=null,e.tail=null),I(M,M.current),!d)return null}return $h(a,b,c)}rg=!1}}else rg=!1;switch(b.expirationTime=0,b.tag){case 2:d=b.type;return null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),a=b.pendingProps,e=Cf(b,J.current),qg(b,c),e=oh(null,b,d,a,e,c),b.effectTag|=1,b="object"==typeof e&&null!==e&&"function"==typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=null,L(d)?(f=!0,Gf(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ug(b),"function"==typeof(g=d.getDerivedStateFromProps)&&Fg(b,0,g,a),e.updater=Jg,Ng((b.stateNode=e)._reactInternalFiber=b,d,a,c),gi(null,b,d,!0,f,c)):(b.tag=0,R(null,b,e,c),b.child);case 16:a:{if(e=b.elementType,null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),a=b.pendingProps,!function(a){var b;-1===a._status&&(a._status=0,b=(b=a._ctor)(),(a._result=b).then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)}))}(e),1!==e._status)throw e._result;switch(e=e._result,b.type=e,f=b.tag=function(a){if("function"==typeof a)return bi(a)?1:0;if(null!=a){if((a=a.$$typeof)===gb)return 11;if(a===jb)return 14}return 2}(e),a=ig(e,a),f){case 0:b=di(null,b,e,a,c);break a;case 1:b=fi(null,b,e,a,c);break a;case 11:b=Zh(null,b,e,a,c);break a;case 14:b=ai(null,b,e,ig(e.type,a),d,c);break a}throw Error(u(306,e,""))}return b;case 0:return d=b.type,e=b.pendingProps,di(a,b,d,e=b.elementType===d?e:ig(d,e),c);case 1:return d=b.type,e=b.pendingProps,fi(a,b,d,e=b.elementType===d?e:ig(d,e),c);case 3:if(hi(b),d=b.updateQueue,null===a||null===d)throw Error(u(282));if(d=b.pendingProps,e=null!==(e=b.memoizedState)?e.element:null,vg(a,b),zg(b,d,null,c),(d=b.memoizedState.element)===e)Xh(),b=$h(a,b,c);else{if((e=b.stateNode.hydrate)&&(Ph=Jd(b.stateNode.containerInfo.firstChild),Oh=b,e=Qh=!0),e)for(c=Yg(b,null,d,c),b.child=c;c;)c.effectTag=-3&c.effectTag|1024,c=c.sibling;else R(a,b,d,c),Xh();b=b.child}return b;case 5:return fh(b),null===a&&Uh(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Gd(d,e)?g=null:null!==f&&Gd(d,f)&&(b.effectTag|=16),ei(a,b),b=4&b.mode&&1!==c&&e.hidden?(b.expirationTime=b.childExpirationTime=1,null):(R(a,b,g,c),b.child);case 6:return null===a&&Uh(b),null;case 13:return ji(a,b,c);case 4:return dh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Xg(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,Zh(a,b,d,e=b.elementType===d?e:ig(d,e),c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context,e=b.pendingProps,g=b.memoizedProps;var f=e.value,h=b.type._context;if(I(jg,h._currentValue),h._currentValue=f,null!==g)if(h=g.value,0===(f=$e(h,f)?0:0|("function"==typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823))){if(g.children===e.children&&!K.current){b=$h(a,b,c);break a}}else for(null!==(h=b.child)&&(h.return=b);null!==h;){var k=h.dependencies;if(null!==k)for(var g=h.child,l=k.firstContext;null!==l;){if(l.context===d&&0!=(l.observedBits&f)){1===h.tag&&((l=wg(c,null)).tag=2,xg(h,l)),h.expirationTime<c&&(h.expirationTime=c),null!==(l=h.alternate)&&l.expirationTime<c&&(l.expirationTime=c),pg(h.return,c),k.expirationTime<c&&(k.expirationTime=c);break}l=l.next}else g=10===h.tag&&h.type===b.type?null:h.child;if(null!==g)g.return=h;else for(g=h;null!==g;){if(g===b){g=null;break}if(null!==(h=g.sibling)){h.return=g.return,g=h;break}g=g.return}h=g}R(a,b,e.children,c),b=b.child}return b;case 9:return e=b.type,d=(f=b.pendingProps).children,qg(b,c),d=d(e=sg(e,f.unstable_observedBits)),b.effectTag|=1,R(a,b,d,c),b.child;case 14:return f=ig(e=b.type,b.pendingProps),ai(a,b,e,f=ig(e.type,f),d,c);case 15:return ci(a,b,b.type,b.pendingProps,d,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),b.tag=1,L(d)?(a=!0,Gf(b)):a=!1,qg(b,c),Lg(b,d,e),Ng(b,d,e,c),gi(null,b,d,!0,a,c);case 19:return mi(a,b,c)}throw Error(u(156,b.tag))},Uj=null,Li=null;function Zj(a,b,c,d){this.tag=a,this.key=c,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=b,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=d,this.effectTag=0,this.lastEffect=this.firstEffect=this.nextEffect=null,this.childExpirationTime=this.expirationTime=0,this.alternate=null}function Sh(a,b,c,d){return new Zj(a,b,c,d)}function bi(a){return(a=a.prototype)&&a.isReactComponent}function Sg(a,b){var c=a.alternate;return null===c?((c=Sh(a.tag,b,a.key,a.mode)).elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,(c.alternate=a).alternate=c):(c.pendingProps=b,c.effectTag=0,c.nextEffect=null,c.firstEffect=null,c.lastEffect=null),c.childExpirationTime=a.childExpirationTime,c.expirationTime=a.expirationTime,c.child=a.child,c.memoizedProps=a.memoizedProps,c.memoizedState=a.memoizedState,c.updateQueue=a.updateQueue,b=a.dependencies,c.dependencies=null===b?null:{expirationTime:b.expirationTime,firstContext:b.firstContext,responders:b.responders},c.sibling=a.sibling,c.index=a.index,c.ref=a.ref,c}function Ug(a,b,c,d,e,f){var g=2;if("function"==typeof(d=a))bi(a)&&(g=1);else if("string"==typeof a)g=5;else a:switch(a){case ab:return Wg(c.children,e,f,b);case fb:g=8,e|=7;break;case bb:g=8,e|=1;break;case cb:return(a=Sh(12,c,b,8|e)).elementType=cb,a.type=cb,a.expirationTime=f,a;case hb:return(a=Sh(13,c,b,e)).type=hb,a.elementType=hb,a.expirationTime=f,a;case ib:return(a=Sh(19,c,b,e)).elementType=ib,a.expirationTime=f,a;default:if("object"==typeof a&&null!==a)switch(a.$$typeof){case db:g=10;break a;case eb:g=9;break a;case gb:g=11;break a;case jb:g=14;break a;case kb:g=16,d=null;break a;case lb:g=22;break a}throw Error(u(130,null==a?a:typeof a,""))}return(b=Sh(g,c,b,e)).elementType=a,b.type=d,b.expirationTime=f,b}function Wg(a,b,c,d){return(a=Sh(7,a,d,b)).expirationTime=c,a}function Tg(a,b,c){return(a=Sh(6,a,null,b)).expirationTime=c,a}function Vg(a,b,c){return(b=Sh(4,null!==a.children?a.children:[],a.key,b)).expirationTime=c,b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},b}function ak(a,b,c){this.tag=b,this.current=null,this.containerInfo=a,this.pingCache=this.pendingChildren=null,this.finishedExpirationTime=0,this.finishedWork=null,this.timeoutHandle=-1,this.pendingContext=this.context=null,this.hydrate=c,this.callbackNode=null,this.callbackPriority=90,this.lastExpiredTime=this.lastPingedTime=this.nextKnownPendingLevel=this.lastSuspendedTime=this.firstSuspendedTime=this.firstPendingTime=0}function Aj(a,b){var c=a.firstSuspendedTime;return a=a.lastSuspendedTime,0!==c&&b<=c&&a<=b}function xi(a,b){var c=a.firstSuspendedTime,d=a.lastSuspendedTime;c<b&&(a.firstSuspendedTime=b),(b<d||0===c)&&(a.lastSuspendedTime=b),b<=a.lastPingedTime&&(a.lastPingedTime=0),b<=a.lastExpiredTime&&(a.lastExpiredTime=0)}function yi(a,b){b>a.firstPendingTime&&(a.firstPendingTime=b);var c=a.firstSuspendedTime;0!==c&&(c<=b?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:b>=a.lastSuspendedTime&&(a.lastSuspendedTime=b+1),b>a.nextKnownPendingLevel)&&(a.nextKnownPendingLevel=b)}function Cj(a,b){var c=a.lastExpiredTime;(0===c||b<c)&&(a.lastExpiredTime=b)}function bk(a,b,c,d){var e=b.current,f=Gg(),g=Dg.suspense,f=Hg(f,e,g);a:if(c){b:{if(dc(c=c._reactInternalFiber)!==c||1!==c.tag)throw Error(u(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(L(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}}while(null!==(h=h.return));throw Error(u(171))}if(1===c.tag){var k=c.type;if(L(k)){c=Ff(c,k,h);break a}}c=h}else c=Af;null===b.context?b.context=c:b.pendingContext=c,(b=wg(f,g)).payload={element:a},null!==(d=void 0===d?null:d)&&(b.callback=d),xg(e,b),Ig(e,f)}function ck(a){return(a=a.current).child?(a.child.tag,a.child.stateNode):null}function dk(a,b){null!==(a=a.memoizedState)&&null!==a.dehydrated&&a.retryTime<b&&(a.retryTime=b)}function ek(a,b){dk(a,b),(a=a.alternate)&&dk(a,b)}function fk(a,b,c){var d=new ak(a,b,c=null!=c&&!0===c.hydrate),e=Sh(3,null,null,2===b?7:1===b?3:0);(d.current=e).stateNode=d,ug(e),a[Od]=d.current,c&&0!==b&&function(b){var c=cc(b);Hc.forEach(function(a){uc(a,b,c)}),Ic.forEach(function(a){uc(a,b,c)})}(9===a.nodeType?a:a.ownerDocument),this._internalRoot=d}function gk(a){return a&&(1===a.nodeType||9===a.nodeType||11===a.nodeType||8===a.nodeType&&" react-mount-point-unstable "===a.nodeValue)}function ik(a,b,c,d,e){var h,k,g,f=c._reactRootContainer;return f?(g=f._internalRoot,"function"==typeof e&&(h=e,e=function(){var a=ck(g);h.call(a)}),bk(b,g,a,e)):(g=(c._reactRootContainer=function(a,b){if(!(b=b?b:!(!(b=a?9===a.nodeType?a.documentElement:a.firstChild:null)||1!==b.nodeType||!b.hasAttribute("data-reactroot"))))for(var c;c=a.lastChild;)a.removeChild(c);return new fk(a,0,b?{hydrate:!0}:void 0)}(c,d))._internalRoot,"function"==typeof e&&(k=e,e=function(){var a=ck(g);k.call(a)}),Nj(function(){bk(b,g,a,e)})),ck(g)}function kk(a,b){if(gk(b))return function(a,b,c,argument_3){return{$$typeof:$a,key:null==(argument_3=3<arguments.length&&void 0!==argument_3?argument_3:null)?null:""+argument_3,children:a,containerInfo:b,implementation:c}}(a,b,null,2<arguments.length&&void 0!==arguments[2]?arguments[2]:null);throw Error(u(200))}fk.prototype.render=function(a){bk(a,this._internalRoot,null,null)},fk.prototype.unmount=function(){var a=this._internalRoot,b=a.containerInfo;bk(null,a,null,function(){b[Od]=null})},wc=function(a){var b;13===a.tag&&(Ig(a,b=hg(Gg(),150,100)),ek(a,b))},xc=function(a){13===a.tag&&(Ig(a,3),ek(a,3))},yc=function(a){var b;13===a.tag&&(Ig(a,b=Hg(Gg(),a,null)),ek(a,b))},za=function(a,b,c){switch(b){case"input":if(Cb(a,c),b=c.name,"radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;for(c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]'),b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Qd(d);if(!e)throw Error(u(90));yb(d),Cb(d,e)}}}break;case"textarea":Kb(a,c);break;case"select":null!=(b=c.value)&&Hb(a,!!c.multiple,b,!1)}},Fa=Mj,Ga=function(a,b,c,d,e){var f=W;W|=4;try{return cg(98,a.bind(null,b,c,d,e))}finally{(W=f)===V&&gg()}};Ia=function(a,b){var c=W;W|=2;try{return a(b)}finally{(W=c)===V&&gg()}},Ye={Events:[Nc,Pd,Qd,xa,ta,Xd,function(a){jc(a,Wd)},Da,Ea,id,mc,Dj,{current:!(Ha=function(){var a;(W&(1|fj|gj))===V&&(null!==tj&&(a=tj,tj=null,a.forEach(function(a,c){Cj(c,a),Z(c)}),gg()),Dj())})}]};!function(a){var b=a.findFiberByHostInstance;!function(a){if("undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!b.isDisabled&&b.supportsFiber)try{var c=b.inject(a);Uj=function(a){try{b.onCommitFiberRoot(c,a,void 0,64==(64&a.current.effectTag))}catch(e){}},Li=function(a){try{b.onCommitFiberUnmount(c,a)}catch(e){}}}catch(d){}}(n({},a,{overrideHookState:null,overrideProps:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Wa.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){return null===(a=hc(a))?null:a.stateNode},findFiberByHostInstance:function(a){return b?b(a):null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null}))}({findFiberByHostInstance:tc,bundleType:0,version:"16.14.0",rendererPackageName:"react-dom"}),exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Ye,exports.createPortal=kk,exports.findDOMNode=function(a){if(null==a)return null;if(1!==a.nodeType){var b=a._reactInternalFiber;if(void 0===b){if("function"==typeof a.render)throw Error(u(188));throw Error(u(268,Object.keys(a)))}a=null===(a=hc(b))?null:a.stateNode}return a},exports.flushSync=function(a,b){if((W&(fj|gj))!==V)throw Error(u(187));var c=W;W|=1;try{return cg(99,a.bind(null,b))}finally{W=c,gg()}},exports.hydrate=function(a,b,c){if(gk(b))return ik(null,a,b,!0,c);throw Error(u(200))},exports.render=function(a,b,c){if(gk(b))return ik(null,a,b,!1,c);throw Error(u(200))},exports.unmountComponentAtNode=function(a){if(gk(a))return!!a._reactRootContainer&&(Nj(function(){ik(null,null,a,!1,function(){a._reactRootContainer=null,a[Od]=null})}),!0);throw Error(u(40))},exports.unstable_batchedUpdates=Mj,exports.unstable_createPortal=function(a,b){return kk(a,b,2<arguments.length&&void 0!==arguments[2]?arguments[2]:null)},exports.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!gk(c))throw Error(u(200));if(null==a||void 0===a._reactInternalFiber)throw Error(u(38));return ik(a,b,c,!1,d)},exports.version="16.14.0"},{"object-assign":1032,react:1427,scheduler:1442}],1382:[function(require,module,exports){"use strict";!function checkDCE(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)}catch(err){console.error(err)}}(),module.exports=require("./cjs/react-dom.production.min.js")},{"./cjs/react-dom.development.js":1380,"./cjs/react-dom.production.min.js":1381}],1383:[function(require,module,exports){!function(process){!function(){"use strict";function typeOf(object){if("object"==typeof object&&null!==object){var $$typeof=object.$$typeof;switch($$typeof){case REACT_ELEMENT_TYPE:var type=object.type;switch(type){case REACT_ASYNC_MODE_TYPE:case REACT_CONCURRENT_MODE_TYPE:case REACT_FRAGMENT_TYPE:case REACT_PROFILER_TYPE:case REACT_STRICT_MODE_TYPE:case REACT_SUSPENSE_TYPE:return type;default:var $$typeofType=type&&type.$$typeof;switch($$typeofType){case REACT_CONTEXT_TYPE:case REACT_FORWARD_REF_TYPE:case REACT_LAZY_TYPE:case REACT_MEMO_TYPE:case REACT_PROVIDER_TYPE:return $$typeofType;default:return $$typeof}}case REACT_PORTAL_TYPE:return $$typeof}}}function isConcurrentMode(object){return typeOf(object)===REACT_CONCURRENT_MODE_TYPE}var hasSymbol,REACT_ELEMENT_TYPE,REACT_PORTAL_TYPE,REACT_FRAGMENT_TYPE,REACT_STRICT_MODE_TYPE,REACT_PROFILER_TYPE,REACT_PROVIDER_TYPE,REACT_CONTEXT_TYPE,REACT_ASYNC_MODE_TYPE,REACT_CONCURRENT_MODE_TYPE,REACT_FORWARD_REF_TYPE,REACT_SUSPENSE_TYPE,REACT_SUSPENSE_LIST_TYPE,REACT_MEMO_TYPE,REACT_LAZY_TYPE,REACT_BLOCK_TYPE,REACT_FUNDAMENTAL_TYPE,REACT_RESPONDER_TYPE,REACT_SCOPE_TYPE,ContextConsumer,ContextProvider,Element,ForwardRef,Fragment,Lazy,Memo,Portal,Profiler,StrictMode,Suspense,hasWarnedAboutDeprecatedIsAsyncMode;"production"!==process.env.NODE_ENV&&(hasSymbol="function"==typeof Symbol&&Symbol.for,REACT_ELEMENT_TYPE=hasSymbol?Symbol.for("react.element"):60103,REACT_PORTAL_TYPE=hasSymbol?Symbol.for("react.portal"):60106,REACT_FRAGMENT_TYPE=hasSymbol?Symbol.for("react.fragment"):60107,REACT_STRICT_MODE_TYPE=hasSymbol?Symbol.for("react.strict_mode"):60108,REACT_PROFILER_TYPE=hasSymbol?Symbol.for("react.profiler"):60114,REACT_PROVIDER_TYPE=hasSymbol?Symbol.for("react.provider"):60109,REACT_CONTEXT_TYPE=hasSymbol?Symbol.for("react.context"):60110,REACT_ASYNC_MODE_TYPE=hasSymbol?Symbol.for("react.async_mode"):60111,REACT_CONCURRENT_MODE_TYPE=hasSymbol?Symbol.for("react.concurrent_mode"):60111,REACT_FORWARD_REF_TYPE=hasSymbol?Symbol.for("react.forward_ref"):60112,REACT_SUSPENSE_TYPE=hasSymbol?Symbol.for("react.suspense"):60113,REACT_SUSPENSE_LIST_TYPE=hasSymbol?Symbol.for("react.suspense_list"):60120,REACT_MEMO_TYPE=hasSymbol?Symbol.for("react.memo"):60115,REACT_LAZY_TYPE=hasSymbol?Symbol.for("react.lazy"):60116,REACT_BLOCK_TYPE=hasSymbol?Symbol.for("react.block"):60121,REACT_FUNDAMENTAL_TYPE=hasSymbol?Symbol.for("react.fundamental"):60117,REACT_RESPONDER_TYPE=hasSymbol?Symbol.for("react.responder"):60118,REACT_SCOPE_TYPE=hasSymbol?Symbol.for("react.scope"):60119,hasSymbol=REACT_CONCURRENT_MODE_TYPE,ContextConsumer=REACT_CONTEXT_TYPE,ContextProvider=REACT_PROVIDER_TYPE,Element=REACT_ELEMENT_TYPE,ForwardRef=REACT_FORWARD_REF_TYPE,Fragment=REACT_FRAGMENT_TYPE,Lazy=REACT_LAZY_TYPE,Memo=REACT_MEMO_TYPE,Portal=REACT_PORTAL_TYPE,Profiler=REACT_PROFILER_TYPE,StrictMode=REACT_STRICT_MODE_TYPE,Suspense=REACT_SUSPENSE_TYPE,hasWarnedAboutDeprecatedIsAsyncMode=!1,exports.AsyncMode=REACT_ASYNC_MODE_TYPE,exports.ConcurrentMode=hasSymbol,exports.ContextConsumer=ContextConsumer,exports.ContextProvider=ContextProvider,exports.Element=Element,exports.ForwardRef=ForwardRef,exports.Fragment=Fragment,exports.Lazy=Lazy,exports.Memo=Memo,exports.Portal=Portal,exports.Profiler=Profiler,exports.StrictMode=StrictMode,exports.Suspense=Suspense,exports.isAsyncMode=function(object){return hasWarnedAboutDeprecatedIsAsyncMode||(hasWarnedAboutDeprecatedIsAsyncMode=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),isConcurrentMode(object)||typeOf(object)===REACT_ASYNC_MODE_TYPE},exports.isConcurrentMode=isConcurrentMode,exports.isContextConsumer=function(object){return typeOf(object)===REACT_CONTEXT_TYPE},exports.isContextProvider=function(object){return typeOf(object)===REACT_PROVIDER_TYPE},exports.isElement=function(object){return"object"==typeof object&&null!==object&&object.$$typeof===REACT_ELEMENT_TYPE},exports.isForwardRef=function(object){return typeOf(object)===REACT_FORWARD_REF_TYPE},exports.isFragment=function(object){return typeOf(object)===REACT_FRAGMENT_TYPE},exports.isLazy=function(object){return typeOf(object)===REACT_LAZY_TYPE},exports.isMemo=function(object){return typeOf(object)===REACT_MEMO_TYPE},exports.isPortal=function(object){return typeOf(object)===REACT_PORTAL_TYPE},exports.isProfiler=function(object){return typeOf(object)===REACT_PROFILER_TYPE},exports.isStrictMode=function(object){return typeOf(object)===REACT_STRICT_MODE_TYPE},exports.isSuspense=function(object){return typeOf(object)===REACT_SUSPENSE_TYPE},exports.isValidElementType=function(type){return"string"==typeof type||"function"==typeof type||type===REACT_FRAGMENT_TYPE||type===REACT_CONCURRENT_MODE_TYPE||type===REACT_PROFILER_TYPE||type===REACT_STRICT_MODE_TYPE||type===REACT_SUSPENSE_TYPE||type===REACT_SUSPENSE_LIST_TYPE||"object"==typeof type&&null!==type&&(type.$$typeof===REACT_LAZY_TYPE||type.$$typeof===REACT_MEMO_TYPE||type.$$typeof===REACT_PROVIDER_TYPE||type.$$typeof===REACT_CONTEXT_TYPE||type.$$typeof===REACT_FORWARD_REF_TYPE||type.$$typeof===REACT_FUNDAMENTAL_TYPE||type.$$typeof===REACT_RESPONDER_TYPE||type.$$typeof===REACT_SCOPE_TYPE||type.$$typeof===REACT_BLOCK_TYPE)},exports.typeOf=typeOf)}.call(this)}.call(this,require("_process"))},{_process:1042}],1384:[function(require,module,exports){"use strict";var b="function"==typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;function z(a){if("object"==typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l,exports.ConcurrentMode=m,exports.ContextConsumer=k,exports.ContextProvider=h,exports.Element=c,exports.ForwardRef=n,exports.Fragment=e,exports.Lazy=t,exports.Memo=r,exports.Portal=d,exports.Profiler=g,exports.StrictMode=f,exports.Suspense=p,exports.isAsyncMode=function(a){return A(a)||z(a)===l},exports.isConcurrentMode=A,exports.isContextConsumer=function(a){return z(a)===k},exports.isContextProvider=function(a){return z(a)===h},exports.isElement=function(a){return"object"==typeof a&&null!==a&&a.$$typeof===c},exports.isForwardRef=function(a){return z(a)===n},exports.isFragment=function(a){return z(a)===e},exports.isLazy=function(a){return z(a)===t},exports.isMemo=function(a){return z(a)===r},exports.isPortal=function(a){return z(a)===d},exports.isProfiler=function(a){return z(a)===g},exports.isStrictMode=function(a){return z(a)===f},exports.isSuspense=function(a){return z(a)===p},exports.isValidElementType=function(a){return"string"==typeof a||"function"==typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"==typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)},exports.typeOf=z},{}],1385:[function(require,module,exports){!function(process){!function(){"use strict";"production"===process.env.NODE_ENV?module.exports=require("./cjs/react-is.production.min.js"):module.exports=require("./cjs/react-is.development.js")}.call(this)}.call(this,require("_process"))},{"./cjs/react-is.development.js":1383,"./cjs/react-is.production.min.js":1384,_process:1042}],1386:[function(require,module,exports){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_inheritsLoose2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=exports.ManagerReferenceNodeSetterContext=exports.ManagerReferenceNodeContext=void 0,_interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"))),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),React=_interopRequireWildcard(require("react")),_interopRequireWildcard=_interopRequireDefault(require("@hypnosphi/create-react-context")),ManagerReferenceNodeContext=(0,_interopRequireWildcard.default)(),ManagerReferenceNodeSetterContext=(exports.ManagerReferenceNodeContext=ManagerReferenceNodeContext,(0,_interopRequireWildcard.default)()),_interopRequireDefault=(exports.ManagerReferenceNodeSetterContext=ManagerReferenceNodeSetterContext,function(_React$Component){function Manager(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=_React$Component.call.apply(_React$Component,[this].concat(args))||this,(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"referenceNode",void 0),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"setReferenceNode",function(newReferenceNode){newReferenceNode&&_this.referenceNode!==newReferenceNode&&(_this.referenceNode=newReferenceNode,_this.forceUpdate())}),_this}(0,_inheritsLoose2.default)(Manager,_React$Component);var _proto=Manager.prototype;return _proto.componentWillUnmount=function(){this.referenceNode=null},_proto.render=function(){return React.createElement(ManagerReferenceNodeContext.Provider,{value:this.referenceNode},React.createElement(ManagerReferenceNodeSetterContext.Provider,{value:this.setReferenceNode},this.props.children))},Manager}(React.Component));exports.default=_interopRequireDefault},{"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/inheritsLoose":12,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@hypnosphi/create-react-context":33,react:1427}],1387:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectWithoutPropertiesLoose2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(_ref){var referenceElement=_ref.referenceElement,props=(0,_objectWithoutPropertiesLoose2.default)(_ref,["referenceElement"]);return React.createElement(_Manager.ManagerReferenceNodeContext.Consumer,null,function(referenceNode){return React.createElement(InnerPopper,(0,_extends2.default)({referenceElement:void 0!==referenceElement?referenceElement:referenceNode},props))})},exports.placements=exports.InnerPopper=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_inheritsLoose2=_interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_deepEqual=_interopRequireDefault(require("deep-equal")),React=_interopRequireWildcard(require("react")),_popper=_interopRequireDefault(require("popper.js")),_Manager=require("./Manager"),_utils=require("./utils"),initialStyle={position:"absolute",top:0,left:0,opacity:0,pointerEvents:"none"},initialArrowStyle={},InnerPopper=function(_React$Component){function InnerPopper(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=_React$Component.call.apply(_React$Component,[this].concat(args))||this,(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"state",{data:void 0,placement:void 0}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"popperInstance",void 0),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"popperNode",null),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"arrowNode",null),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"setPopperNode",function(popperNode){popperNode&&_this.popperNode!==popperNode&&((0,_utils.setRef)(_this.props.innerRef,popperNode),_this.popperNode=popperNode,_this.updatePopperInstance())}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"setArrowNode",function(arrowNode){_this.arrowNode=arrowNode}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"updateStateModifier",{enabled:!0,order:900,fn:function(data){var placement=data.placement;return _this.setState({data:data,placement:placement}),data}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"getOptions",function(){return{placement:_this.props.placement,eventsEnabled:_this.props.eventsEnabled,positionFixed:_this.props.positionFixed,modifiers:(0,_extends2.default)({},_this.props.modifiers,{arrow:(0,_extends2.default)({},_this.props.modifiers&&_this.props.modifiers.arrow,{enabled:!!_this.arrowNode,element:_this.arrowNode}),applyStyle:{enabled:!1},updateStateModifier:_this.updateStateModifier})}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"getPopperStyle",function(){return _this.popperNode&&_this.state.data?(0,_extends2.default)({position:_this.state.data.offsets.popper.position},_this.state.data.styles):initialStyle}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"getPopperPlacement",function(){return _this.state.data?_this.state.placement:void 0}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"getArrowStyle",function(){return _this.arrowNode&&_this.state.data?_this.state.data.arrowStyles:initialArrowStyle}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"getOutOfBoundariesState",function(){return _this.state.data?_this.state.data.hide:void 0}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"destroyPopperInstance",function(){_this.popperInstance&&(_this.popperInstance.destroy(),_this.popperInstance=null)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"updatePopperInstance",function(){_this.destroyPopperInstance();var popperNode=(0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)).popperNode,referenceElement=_this.props.referenceElement;referenceElement&&popperNode&&(_this.popperInstance=new _popper.default(referenceElement,popperNode,_this.getOptions()))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"scheduleUpdate",function(){_this.popperInstance&&_this.popperInstance.scheduleUpdate()}),_this}(0,_inheritsLoose2.default)(InnerPopper,_React$Component);var _proto=InnerPopper.prototype;return _proto.componentDidUpdate=function(prevProps,prevState){this.props.placement===prevProps.placement&&this.props.referenceElement===prevProps.referenceElement&&this.props.positionFixed===prevProps.positionFixed&&(0,_deepEqual.default)(this.props.modifiers,prevProps.modifiers,{strict:!0})?this.props.eventsEnabled!==prevProps.eventsEnabled&&this.popperInstance&&(this.props.eventsEnabled?this.popperInstance.enableEventListeners():this.popperInstance.disableEventListeners()):("development"===process.env.NODE_ENV&&this.props.modifiers!==prevProps.modifiers&&null!=this.props.modifiers&&null!=prevProps.modifiers&&(0,_utils.shallowEqual)(this.props.modifiers,prevProps.modifiers)&&console.warn("'modifiers' prop reference updated even though all values appear the same.\nConsider memoizing the 'modifiers' object to avoid needless rendering."),this.updatePopperInstance()),prevState.placement!==this.state.placement&&this.scheduleUpdate()},_proto.componentWillUnmount=function(){(0,_utils.setRef)(this.props.innerRef,null),this.destroyPopperInstance()},_proto.render=function(){return(0,_utils.unwrapArray)(this.props.children)({ref:this.setPopperNode,style:this.getPopperStyle(),placement:this.getPopperPlacement(),outOfBoundaries:this.getOutOfBoundariesState(),scheduleUpdate:this.scheduleUpdate,arrowProps:{ref:this.setArrowNode,style:this.getArrowStyle()}})},InnerPopper}(React.Component),_interopRequireWildcard=(exports.InnerPopper=InnerPopper,(0,_defineProperty2.default)(InnerPopper,"defaultProps",{placement:"bottom",eventsEnabled:!0,referenceElement:void 0,positionFixed:!1}),_popper.default.placements);exports.placements=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"./Manager":1386,"./utils":1390,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/inheritsLoose":12,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectWithoutPropertiesLoose":22,_process:1042,"deep-equal":638,"popper.js":1041,react:1427}],1388:[function(require,module,exports){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(props){return React.createElement(_Manager.ManagerReferenceNodeSetterContext.Consumer,null,function(setReferenceNode){return React.createElement(InnerReference,(0,_extends2.default)({setReferenceNode:setReferenceNode},props))})},_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_inheritsLoose2=_interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),React=_interopRequireWildcard(require("react")),_warning=_interopRequireDefault(require("warning")),_Manager=require("./Manager"),_utils=require("./utils"),InnerReference=function(_React$Component){function InnerReference(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=_React$Component.call.apply(_React$Component,[this].concat(args))||this,(0,_defineProperty2.default)((0,_assertThisInitialized2.default)((0,_assertThisInitialized2.default)(_this)),"refHandler",function(node){(0,_utils.setRef)(_this.props.innerRef,node),(0,_utils.safeInvoke)(_this.props.setReferenceNode,node)}),_this}(0,_inheritsLoose2.default)(InnerReference,_React$Component);var _proto=InnerReference.prototype;return _proto.componentWillUnmount=function(){(0,_utils.setRef)(this.props.innerRef,null)},_proto.render=function(){return(0,_warning.default)(Boolean(this.props.setReferenceNode),"`Reference` should not be used outside of a `Manager` component."),(0,_utils.unwrapArray)(this.props.children)({ref:this.refHandler})},InnerReference}(React.Component)},{"./Manager":1386,"./utils":1390,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/inheritsLoose":12,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,react:1427,warning:1702}],1389:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_Popper=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"Popper",{enumerable:!0,get:function(){return _Popper.default}}),Object.defineProperty(exports,"placements",{enumerable:!0,get:function(){return _Popper.placements}}),Object.defineProperty(exports,"Manager",{enumerable:!0,get:function(){return _Manager.default}}),Object.defineProperty(exports,"Reference",{enumerable:!0,get:function(){return _Reference.default}}),_interopRequireWildcard(require("./Popper"))),_Manager=_interopRequireDefault(require("./Manager")),_Reference=_interopRequireDefault(require("./Reference"))},{"./Manager":1386,"./Popper":1387,"./Reference":1388,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14}],1390:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setRef=exports.shallowEqual=exports.safeInvoke=exports.unwrapArray=void 0;function safeInvoke(fn){if("function"==typeof fn){for(var _len=arguments.length,args=new Array(1<_len?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];return fn.apply(void 0,args)}}exports.unwrapArray=function(arg){return Array.isArray(arg)?arg[0]:arg},exports.safeInvoke=safeInvoke,exports.shallowEqual=function(objA,objB){var aKeys=Object.keys(objA),bKeys=Object.keys(objB);if(bKeys.length!==aKeys.length)return!1;for(var i=0;i<bKeys.length;i++){var key=aKeys[i];if(objA[key]!==objB[key])return!1}return!0};exports.setRef=function(ref,node){if("function"==typeof ref)return safeInvoke(ref,node);null!=ref&&(ref.current=node)}},{}],1391:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default;exports.__esModule=!0,exports.default=exports.ReactReduxContext=void 0;_interopRequireDefault=_interopRequireDefault(require("react")).default.createContext(null),require=exports.ReactReduxContext=_interopRequireDefault;exports.default=require},{"@babel/runtime/helpers/interopRequireDefault":13,react:1427}],1392:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard").default,_react=(exports.__esModule=!0,exports.default=void 0,_interopRequireWildcard(require("react"))),_Context=(_interopRequireDefault(require("prop-types")),require("./Context")),_Subscription=require("../utils/Subscription"),_useIsomorphicLayoutEffect=require("../utils/useIsomorphicLayoutEffect");function Provider(_ref){var store=_ref.store,context=_ref.context,_ref=_ref.children,contextValue=(0,_react.useMemo)(function(){var subscription=(0,_Subscription.createSubscription)(store);return{store:store,subscription:subscription}},[store]),previousState=(0,_react.useMemo)(function(){return store.getState()},[store]),context=((0,_useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function(){var subscription=contextValue.subscription;return subscription.onStateChange=subscription.notifyNestedSubs,subscription.trySubscribe(),previousState!==store.getState()&&subscription.notifyNestedSubs(),function(){subscription.tryUnsubscribe(),subscription.onStateChange=null}},[contextValue,previousState]),context||_Context.ReactReduxContext);return _react.default.createElement(context.Provider,{value:contextValue},_ref)}exports.default=Provider},{"../utils/Subscription":1407,"../utils/useIsomorphicLayoutEffect":1413,"./Context":1391,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"prop-types":1046,react:1427}],1393:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard").default,_extends2=(exports.__esModule=!0,exports.default=function(selectorFactory,_ref){void 0===_ref&&(_ref={});var _ref2$getDisplayName=_ref.getDisplayName,getDisplayName=void 0===_ref2$getDisplayName?function(name){return"ConnectAdvanced("+name+")"}:_ref2$getDisplayName,_ref2$getDisplayName=_ref.methodName,methodName=void 0===_ref2$getDisplayName?"connectAdvanced":_ref2$getDisplayName,_ref2$getDisplayName=_ref.renderCountProp,renderCountProp=void 0===_ref2$getDisplayName?void 0:_ref2$getDisplayName,_ref2$getDisplayName=_ref.shouldHandleStateChanges,shouldHandleStateChanges=void 0===_ref2$getDisplayName||_ref2$getDisplayName,_ref2$getDisplayName=_ref.storeKey,storeKey=void 0===_ref2$getDisplayName?"store":_ref2$getDisplayName,_ref2$getDisplayName=(_ref.withRef,_ref.forwardRef),forwardRef=void 0!==_ref2$getDisplayName&&_ref2$getDisplayName,_ref2$getDisplayName=_ref.context,_ref2$getDisplayName=void 0===_ref2$getDisplayName?_Context.ReactReduxContext:_ref2$getDisplayName,connectOptions=(0,_objectWithoutPropertiesLoose2.default)(_ref,_excluded);var Context=_ref2$getDisplayName;return function(WrappedComponent){var wrappedComponentName=WrappedComponent.displayName||WrappedComponent.name||"Component",displayName=getDisplayName(wrappedComponentName),selectorFactoryOptions=(0,_extends2.default)({},connectOptions,{getDisplayName:getDisplayName,methodName:methodName,renderCountProp:renderCountProp,shouldHandleStateChanges:shouldHandleStateChanges,storeKey:storeKey,displayName:displayName,wrappedComponentName:wrappedComponentName,WrappedComponent:WrappedComponent}),wrappedComponentName=connectOptions.pure;var usePureOnlyMemo=wrappedComponentName?_react.useMemo:function(callback){return callback()};function ConnectFunction(props){var _useMemo=(0,_react.useMemo)(function(){var reactReduxForwardedRef=props.reactReduxForwardedRef,wrapperProps=(0,_objectWithoutPropertiesLoose2.default)(props,_excluded2);return[props.context,reactReduxForwardedRef,wrapperProps]},[props]),propsContext=_useMemo[0],reactReduxForwardedRef=_useMemo[1],wrapperProps=_useMemo[2],ContextToUse=(0,_react.useMemo)(function(){return propsContext&&propsContext.Consumer&&(0,_reactIs.isContextConsumer)(_react.default.createElement(propsContext.Consumer,null))?propsContext:Context},[propsContext,Context]),contextValue=(0,_react.useContext)(ContextToUse),didStoreComeFromProps=Boolean(props.store)&&Boolean(props.store.getState)&&Boolean(props.store.dispatch),store=(Boolean(contextValue)&&Boolean(contextValue.store),(didStoreComeFromProps?props:contextValue).store),childPropsSelector=(0,_react.useMemo)(function(){return function(store){return selectorFactory(store.dispatch,selectorFactoryOptions)}(store)},[store]),_useMemo=(0,_react.useMemo)(function(){var subscription,notifyNestedSubs;return shouldHandleStateChanges?(notifyNestedSubs=(subscription=(0,_Subscription.createSubscription)(store,didStoreComeFromProps?null:contextValue.subscription)).notifyNestedSubs.bind(subscription),[subscription,notifyNestedSubs]):NO_SUBSCRIPTION_ARRAY},[store,didStoreComeFromProps,contextValue]),subscription=_useMemo[0],_useMemo=_useMemo[1],overriddenContextValue=(0,_react.useMemo)(function(){return didStoreComeFromProps?contextValue:(0,_extends2.default)({},contextValue,{subscription:subscription})},[didStoreComeFromProps,contextValue,subscription]),_useReducer=(0,_react.useReducer)(storeStateUpdatesReducer,EMPTY_ARRAY,initStateUpdates),previousStateUpdateResult=_useReducer[0][0],_useReducer=_useReducer[1];if(previousStateUpdateResult&&previousStateUpdateResult.error)throw previousStateUpdateResult.error;var lastChildProps=(0,_react.useRef)(),lastWrapperProps=(0,_react.useRef)(wrapperProps),childPropsFromStoreUpdate=(0,_react.useRef)(),renderIsScheduled=(0,_react.useRef)(!1),actualChildProps=usePureOnlyMemo(function(){return childPropsFromStoreUpdate.current&&wrapperProps===lastWrapperProps.current?childPropsFromStoreUpdate.current:childPropsSelector(store.getState(),wrapperProps)},[store,previousStateUpdateResult,wrapperProps]),renderedWrappedComponent=(useIsomorphicLayoutEffectWithArgs(captureWrapperProps,[lastWrapperProps,lastChildProps,renderIsScheduled,wrapperProps,actualChildProps,childPropsFromStoreUpdate,_useMemo]),useIsomorphicLayoutEffectWithArgs(subscribeUpdates,[shouldHandleStateChanges,store,subscription,childPropsSelector,lastWrapperProps,lastChildProps,renderIsScheduled,childPropsFromStoreUpdate,_useMemo,_useReducer],[store,subscription,childPropsSelector]),(0,_react.useMemo)(function(){return _react.default.createElement(WrappedComponent,(0,_extends2.default)({},actualChildProps,{ref:reactReduxForwardedRef}))},[reactReduxForwardedRef,WrappedComponent,actualChildProps]));return(0,_react.useMemo)(function(){return shouldHandleStateChanges?_react.default.createElement(ContextToUse.Provider,{value:overriddenContextValue},renderedWrappedComponent):renderedWrappedComponent},[ContextToUse,renderedWrappedComponent,overriddenContextValue])}var Connect=wrappedComponentName?_react.default.memo(ConnectFunction):ConnectFunction;return Connect.WrappedComponent=WrappedComponent,Connect.displayName=ConnectFunction.displayName=displayName,forwardRef?((wrappedComponentName=_react.default.forwardRef(function(props,ref){return _react.default.createElement(Connect,(0,_extends2.default)({},props,{reactReduxForwardedRef:ref}))})).displayName=displayName,wrappedComponentName.WrappedComponent=WrappedComponent,(0,_hoistNonReactStatics.default)(wrappedComponentName,WrappedComponent)):(0,_hoistNonReactStatics.default)(Connect,WrappedComponent)}},_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectWithoutPropertiesLoose2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")),_hoistNonReactStatics=_interopRequireDefault(require("hoist-non-react-statics")),_react=_interopRequireWildcard(require("react")),_reactIs=require("react-is"),_Subscription=require("../utils/Subscription"),_useIsomorphicLayoutEffect=require("../utils/useIsomorphicLayoutEffect"),_Context=require("./Context"),_excluded=["getDisplayName","methodName","renderCountProp","shouldHandleStateChanges","storeKey","withRef","forwardRef","context"],_excluded2=["reactReduxForwardedRef"],EMPTY_ARRAY=[],NO_SUBSCRIPTION_ARRAY=[null,null];function storeStateUpdatesReducer(state,action){state=state[1];return[action.payload,state+1]}function useIsomorphicLayoutEffectWithArgs(effectFunc,effectArgs,dependencies){(0,_useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function(){return effectFunc.apply(void 0,effectArgs)},dependencies)}function captureWrapperProps(lastWrapperProps,lastChildProps,renderIsScheduled,wrapperProps,actualChildProps,childPropsFromStoreUpdate,notifyNestedSubs){lastWrapperProps.current=wrapperProps,lastChildProps.current=actualChildProps,renderIsScheduled.current=!1,childPropsFromStoreUpdate.current&&(childPropsFromStoreUpdate.current=null,notifyNestedSubs())}function subscribeUpdates(shouldHandleStateChanges,store,subscription,childPropsSelector,lastWrapperProps,lastChildProps,renderIsScheduled,childPropsFromStoreUpdate,notifyNestedSubs,forceComponentUpdateDispatch){var didUnsubscribe,lastThrownError;if(shouldHandleStateChanges)return didUnsubscribe=!1,lastThrownError=null,subscription.onStateChange=shouldHandleStateChanges=function(){if(!didUnsubscribe){var newChildProps,error,latestStoreState=store.getState();try{newChildProps=childPropsSelector(latestStoreState,lastWrapperProps.current)}catch(e){lastThrownError=error=e}error||(lastThrownError=null),newChildProps===lastChildProps.current?renderIsScheduled.current||notifyNestedSubs():(lastChildProps.current=newChildProps,childPropsFromStoreUpdate.current=newChildProps,renderIsScheduled.current=!0,forceComponentUpdateDispatch({type:"STORE_UPDATED",payload:{error:error}}))}},subscription.trySubscribe(),shouldHandleStateChanges(),function(){if(didUnsubscribe=!0,subscription.tryUnsubscribe(),subscription.onStateChange=null,lastThrownError)throw lastThrownError}}var initStateUpdates=function(){return[null,0]}},{"../utils/Subscription":1407,"../utils/useIsomorphicLayoutEffect":1413,"./Context":1391,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectWithoutPropertiesLoose":22,"hoist-non-react-statics":654,react:1427,"react-is":1418}],1394:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_extends2=(exports.__esModule=!0,exports.createConnect=createConnect,exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectWithoutPropertiesLoose2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")),_connectAdvanced=_interopRequireDefault(require("../components/connectAdvanced")),_shallowEqual=_interopRequireDefault(require("../utils/shallowEqual")),_mapDispatchToProps=_interopRequireDefault(require("./mapDispatchToProps")),_mapStateToProps=_interopRequireDefault(require("./mapStateToProps")),_mergeProps=_interopRequireDefault(require("./mergeProps")),_selectorFactory=_interopRequireDefault(require("./selectorFactory")),_excluded=["pure","areStatesEqual","areOwnPropsEqual","areStatePropsEqual","areMergedPropsEqual"];function match(arg,factories,name){for(var i=factories.length-1;0<=i;i--){var result=factories[i](arg);if(result)return result}return function(dispatch,options){throw new Error("Invalid value of type "+typeof arg+" for "+name+" argument when connecting component "+options.wrappedComponentName+".")}}function strictEqual(a,b){return a===b}function createConnect(_temp){var _temp=void 0===_temp?{}:_temp,_ref$connectHOC=_temp.connectHOC,connectHOC=void 0===_ref$connectHOC?_connectAdvanced.default:_ref$connectHOC,_ref$connectHOC=_temp.mapStateToPropsFactories,mapStateToPropsFactories=void 0===_ref$connectHOC?_mapStateToProps.default:_ref$connectHOC,_ref$connectHOC=_temp.mapDispatchToPropsFactories,mapDispatchToPropsFactories=void 0===_ref$connectHOC?_mapDispatchToProps.default:_ref$connectHOC,_ref$connectHOC=_temp.mergePropsFactories,mergePropsFactories=void 0===_ref$connectHOC?_mergeProps.default:_ref$connectHOC,_ref$connectHOC=_temp.selectorFactory,selectorFactory=void 0===_ref$connectHOC?_selectorFactory.default:_ref$connectHOC;return function(mapStateToProps,mapDispatchToProps,mergeProps,_ref2){var _ref2=_ref2=void 0===_ref2?{}:_ref2,_ref3$pure=_ref2.pure,_ref3$pure=void 0===_ref3$pure||_ref3$pure,_ref3$areStatesEqual=_ref2.areStatesEqual,_ref3$areStatesEqual=void 0===_ref3$areStatesEqual?strictEqual:_ref3$areStatesEqual,_ref3$areOwnPropsEqua=_ref2.areOwnPropsEqual,_ref3$areOwnPropsEqua=void 0===_ref3$areOwnPropsEqua?_shallowEqual.default:_ref3$areOwnPropsEqua,_ref3$areStatePropsEq=_ref2.areStatePropsEqual,_ref3$areStatePropsEq=void 0===_ref3$areStatePropsEq?_shallowEqual.default:_ref3$areStatePropsEq,_ref3$areMergedPropsE=_ref2.areMergedPropsEqual,_ref3$areMergedPropsE=void 0===_ref3$areMergedPropsE?_shallowEqual.default:_ref3$areMergedPropsE,_ref2=(0,_objectWithoutPropertiesLoose2.default)(_ref2,_excluded),initMapStateToProps=match(mapStateToProps,mapStateToPropsFactories,"mapStateToProps"),mapDispatchToProps=match(mapDispatchToProps,mapDispatchToPropsFactories,"mapDispatchToProps"),mergeProps=match(mergeProps,mergePropsFactories,"mergeProps");return connectHOC(selectorFactory,(0,_extends2.default)({methodName:"connect",getDisplayName:function(name){return"Connect("+name+")"},shouldHandleStateChanges:Boolean(mapStateToProps),initMapStateToProps:initMapStateToProps,initMapDispatchToProps:mapDispatchToProps,initMergeProps:mergeProps,pure:_ref3$pure,areStatesEqual:_ref3$areStatesEqual,areOwnPropsEqual:_ref3$areOwnPropsEqua,areStatePropsEqual:_ref3$areStatePropsEq,areMergedPropsEqual:_ref3$areMergedPropsE},_ref2))}}exports.default=createConnect()},{"../components/connectAdvanced":1393,"../utils/shallowEqual":1412,"./mapDispatchToProps":1395,"./mapStateToProps":1396,"./mergeProps":1397,"./selectorFactory":1398,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectWithoutPropertiesLoose":22}],1395:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_bindActionCreators=(exports.__esModule=!0,exports.default=void 0,exports.whenMapDispatchToPropsIsFunction=whenMapDispatchToPropsIsFunction,exports.whenMapDispatchToPropsIsMissing=whenMapDispatchToPropsIsMissing,exports.whenMapDispatchToPropsIsObject=whenMapDispatchToPropsIsObject,_interopRequireDefault(require("../utils/bindActionCreators"))),_wrapMapToProps=require("./wrapMapToProps");function whenMapDispatchToPropsIsFunction(mapDispatchToProps){return"function"==typeof mapDispatchToProps?(0,_wrapMapToProps.wrapMapToPropsFunc)(mapDispatchToProps,"mapDispatchToProps"):void 0}function whenMapDispatchToPropsIsMissing(mapDispatchToProps){return mapDispatchToProps?void 0:(0,_wrapMapToProps.wrapMapToPropsConstant)(function(dispatch){return{dispatch:dispatch}})}function whenMapDispatchToPropsIsObject(mapDispatchToProps){return mapDispatchToProps&&"object"==typeof mapDispatchToProps?(0,_wrapMapToProps.wrapMapToPropsConstant)(function(dispatch){return(0,_bindActionCreators.default)(mapDispatchToProps,dispatch)}):void 0}exports.default=[whenMapDispatchToPropsIsFunction,whenMapDispatchToPropsIsMissing,whenMapDispatchToPropsIsObject]},{"../utils/bindActionCreators":1409,"./wrapMapToProps":1400,"@babel/runtime/helpers/interopRequireDefault":13}],1396:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.default=void 0,exports.whenMapStateToPropsIsFunction=whenMapStateToPropsIsFunction,exports.whenMapStateToPropsIsMissing=whenMapStateToPropsIsMissing;var _wrapMapToProps=require("./wrapMapToProps");function whenMapStateToPropsIsFunction(mapStateToProps){return"function"==typeof mapStateToProps?(0,_wrapMapToProps.wrapMapToPropsFunc)(mapStateToProps,"mapStateToProps"):void 0}function whenMapStateToPropsIsMissing(mapStateToProps){return mapStateToProps?void 0:(0,_wrapMapToProps.wrapMapToPropsConstant)(function(){return{}})}exports.default=[whenMapStateToPropsIsFunction,whenMapStateToPropsIsMissing]},{"./wrapMapToProps":1400}],1397:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_extends2=(exports.__esModule=!0,exports.default=void 0,exports.defaultMergeProps=defaultMergeProps,exports.whenMergePropsIsFunction=whenMergePropsIsFunction,exports.whenMergePropsIsOmitted=whenMergePropsIsOmitted,exports.wrapMergePropsFunc=wrapMergePropsFunc,_interopRequireDefault(require("@babel/runtime/helpers/extends")));_interopRequireDefault(require("../utils/verifyPlainObject"));function defaultMergeProps(stateProps,dispatchProps,ownProps){return(0,_extends2.default)({},ownProps,stateProps,dispatchProps)}function wrapMergePropsFunc(mergeProps){return function(dispatch,_ref){_ref.displayName;var mergedProps,pure=_ref.pure,areMergedPropsEqual=_ref.areMergedPropsEqual,hasRunOnce=!1;return function(stateProps,dispatchProps,ownProps){stateProps=mergeProps(stateProps,dispatchProps,ownProps);return hasRunOnce?pure&&areMergedPropsEqual(stateProps,mergedProps)||(mergedProps=stateProps):(hasRunOnce=!0,mergedProps=stateProps),mergedProps}}}function whenMergePropsIsFunction(mergeProps){return"function"==typeof mergeProps?wrapMergePropsFunc(mergeProps):void 0}function whenMergePropsIsOmitted(mergeProps){return mergeProps?void 0:function(){return defaultMergeProps}}exports.default=[whenMergePropsIsFunction,whenMergePropsIsOmitted]},{"../utils/verifyPlainObject":1414,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13}],1398:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_objectWithoutPropertiesLoose2=(exports.__esModule=!0,exports.default=function(dispatch,_ref2){var initMapStateToProps=_ref2.initMapStateToProps,initMapDispatchToProps=_ref2.initMapDispatchToProps,initMergeProps=_ref2.initMergeProps,_ref2=(0,_objectWithoutPropertiesLoose2.default)(_ref2,_excluded),initMapStateToProps=initMapStateToProps(dispatch,_ref2),initMapDispatchToProps=initMapDispatchToProps(dispatch,_ref2),initMergeProps=initMergeProps(dispatch,_ref2);return(_ref2.pure?pureFinalPropsSelectorFactory:impureFinalPropsSelectorFactory)(initMapStateToProps,initMapDispatchToProps,initMergeProps,dispatch,_ref2)},exports.impureFinalPropsSelectorFactory=impureFinalPropsSelectorFactory,exports.pureFinalPropsSelectorFactory=pureFinalPropsSelectorFactory,_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"))),_excluded=(_interopRequireDefault(require("./verifySubselectors")),["initMapStateToProps","initMapDispatchToProps","initMergeProps"]);function impureFinalPropsSelectorFactory(mapStateToProps,mapDispatchToProps,mergeProps,dispatch){return function(state,ownProps){return mergeProps(mapStateToProps(state,ownProps),mapDispatchToProps(dispatch,ownProps),ownProps)}}function pureFinalPropsSelectorFactory(mapStateToProps,mapDispatchToProps,mergeProps,dispatch,_ref){var state,ownProps,stateProps,dispatchProps,mergedProps,areStatesEqual=_ref.areStatesEqual,areOwnPropsEqual=_ref.areOwnPropsEqual,areStatePropsEqual=_ref.areStatePropsEqual,hasRunAtLeastOnce=!1;function handleSubsequentCalls(nextState,nextOwnProps){var propsChanged=!areOwnPropsEqual(nextOwnProps,ownProps),stateChanged=!areStatesEqual(nextState,state,nextOwnProps,ownProps);return state=nextState,ownProps=nextOwnProps,propsChanged&&stateChanged?(stateProps=mapStateToProps(state,ownProps),mapDispatchToProps.dependsOnOwnProps&&(dispatchProps=mapDispatchToProps(dispatch,ownProps)),mergedProps=mergeProps(stateProps,dispatchProps,ownProps)):propsChanged?(mapStateToProps.dependsOnOwnProps&&(stateProps=mapStateToProps(state,ownProps)),mapDispatchToProps.dependsOnOwnProps&&(dispatchProps=mapDispatchToProps(dispatch,ownProps)),mergedProps=mergeProps(stateProps,dispatchProps,ownProps)):stateChanged?(nextState=mapStateToProps(state,ownProps),nextOwnProps=!areStatePropsEqual(nextState,stateProps),stateProps=nextState,mergedProps=nextOwnProps?mergeProps(stateProps,dispatchProps,ownProps):mergedProps):mergedProps}return function(nextState,nextOwnProps){return hasRunAtLeastOnce?handleSubsequentCalls(nextState,nextOwnProps):(stateProps=mapStateToProps(state=nextState,ownProps=nextOwnProps),dispatchProps=mapDispatchToProps(dispatch,ownProps),mergedProps=mergeProps(stateProps,dispatchProps,ownProps),hasRunAtLeastOnce=!0,mergedProps)}}},{"./verifySubselectors":1399,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectWithoutPropertiesLoose":22}],1399:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_warning=(exports.__esModule=!0,exports.default=function(mapStateToProps,mapDispatchToProps,mergeProps,displayName){verify(mapStateToProps,"mapStateToProps",displayName),verify(mapDispatchToProps,"mapDispatchToProps",displayName),verify(mergeProps,"mergeProps",displayName)},_interopRequireDefault(require("../utils/warning")));function verify(selector,methodName,displayName){if(!selector)throw new Error("Unexpected value for "+methodName+" in "+displayName+".");"mapStateToProps"!==methodName&&"mapDispatchToProps"!==methodName||Object.prototype.hasOwnProperty.call(selector,"dependsOnOwnProps")||(0,_warning.default)("The selector for "+methodName+" of "+displayName+" did not specify a value for dependsOnOwnProps.")}},{"../utils/warning":1415,"@babel/runtime/helpers/interopRequireDefault":13}],1400:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default;exports.__esModule=!0,exports.getDependsOnOwnProps=getDependsOnOwnProps,exports.wrapMapToPropsConstant=function(getConstant){return function(dispatch,options){var constant=getConstant(dispatch,options);function constantSelector(){return constant}return constantSelector.dependsOnOwnProps=!1,constantSelector}},exports.wrapMapToPropsFunc=function(mapToProps,methodName){return function(dispatch,_ref){_ref.displayName;var proxy=function(stateOrDispatch,ownProps){return proxy.dependsOnOwnProps?proxy.mapToProps(stateOrDispatch,ownProps):proxy.mapToProps(stateOrDispatch)};return proxy.dependsOnOwnProps=!0,proxy.mapToProps=function(stateOrDispatch,ownProps){proxy.mapToProps=mapToProps,proxy.dependsOnOwnProps=getDependsOnOwnProps(mapToProps);var props=proxy(stateOrDispatch,ownProps);return"function"==typeof props&&(proxy.mapToProps=props,proxy.dependsOnOwnProps=getDependsOnOwnProps(props),props=proxy(stateOrDispatch,ownProps)),props},proxy}},_interopRequireDefault(require("../utils/verifyPlainObject"));function getDependsOnOwnProps(mapToProps){return null!==mapToProps.dependsOnOwnProps&&void 0!==mapToProps.dependsOnOwnProps?Boolean(mapToProps.dependsOnOwnProps):1!==mapToProps.length}},{"../utils/verifyPlainObject":1414,"@babel/runtime/helpers/interopRequireDefault":13}],1401:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_Provider=(exports.__esModule=!0,_interopRequireDefault(require("./components/Provider"))),_Provider=(exports.Provider=_Provider.default,_interopRequireDefault(require("./components/connectAdvanced"))),_Provider=(exports.connectAdvanced=_Provider.default,require("./components/Context")),_Provider=(exports.ReactReduxContext=_Provider.ReactReduxContext,_interopRequireDefault(require("./connect/connect"))),_Provider=(exports.connect=_Provider.default,require("./hooks/useDispatch")),_Provider=(exports.useDispatch=_Provider.useDispatch,exports.createDispatchHook=_Provider.createDispatchHook,require("./hooks/useSelector")),_Provider=(exports.useSelector=_Provider.useSelector,exports.createSelectorHook=_Provider.createSelectorHook,require("./hooks/useStore")),_Provider=(exports.useStore=_Provider.useStore,exports.createStoreHook=_Provider.createStoreHook,_interopRequireDefault(require("./utils/shallowEqual")));exports.shallowEqual=_Provider.default},{"./components/Context":1391,"./components/Provider":1392,"./components/connectAdvanced":1393,"./connect/connect":1394,"./hooks/useDispatch":1402,"./hooks/useSelector":1404,"./hooks/useStore":1405,"./utils/shallowEqual":1412,"@babel/runtime/helpers/interopRequireDefault":13}],1402:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.createDispatchHook=createDispatchHook,exports.useDispatch=void 0;var _Context=require("../components/Context"),_useStore=require("./useStore");function createDispatchHook(context){var useStore=(context=void 0===context?_Context.ReactReduxContext:context)===_Context.ReactReduxContext?_useStore.useStore:(0,_useStore.createStoreHook)(context);return function(){return useStore().dispatch}}exports.useDispatch=createDispatchHook()},{"../components/Context":1391,"./useStore":1405}],1403:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.useReduxContext=function(){var contextValue=(0,_react.useContext)(_Context.ReactReduxContext);return contextValue};var _react=require("react"),_Context=require("../components/Context")},{"../components/Context":1391,react:1427}],1404:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.createSelectorHook=createSelectorHook,exports.useSelector=void 0;var _react=require("react"),_useReduxContext2=require("./useReduxContext"),_Subscription=require("../utils/Subscription"),_useIsomorphicLayoutEffect=require("../utils/useIsomorphicLayoutEffect"),_Context=require("../components/Context"),refEquality=function(a,b){return a===b};function createSelectorHook(context){var useReduxContext=(context=void 0===context?_Context.ReactReduxContext:context)===_Context.ReactReduxContext?_useReduxContext2.useReduxContext:function(){return(0,_react.useContext)(context)};return function(selector,equalityFn){void 0===equalityFn&&(equalityFn=refEquality);var _useReduxContext=useReduxContext(),selector=function(selector,equalityFn,store,contextSub){var newSelectedState,selectedState,forceRender=(0,_react.useReducer)(function(s){return s+1},0)[1],subscription=(0,_react.useMemo)(function(){return(0,_Subscription.createSubscription)(store,contextSub)},[store,contextSub]),latestSubscriptionCallbackError=(0,_react.useRef)(),latestSelector=(0,_react.useRef)(),latestStoreState=(0,_react.useRef)(),latestSelectedState=(0,_react.useRef)(),storeState=store.getState();try{selectedState=selector===latestSelector.current&&storeState===latestStoreState.current&&!latestSubscriptionCallbackError.current||(newSelectedState=selector(storeState),void 0!==latestSelectedState.current&&equalityFn(newSelectedState,latestSelectedState.current))?latestSelectedState.current:newSelectedState}catch(err){throw latestSubscriptionCallbackError.current&&(err.message+="\nThe error may be correlated with this previous error:\n"+latestSubscriptionCallbackError.current.stack+"\n\n"),err}return(0,_useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function(){latestSelector.current=selector,latestStoreState.current=storeState,latestSelectedState.current=selectedState,latestSubscriptionCallbackError.current=void 0}),(0,_useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function(){function checkForUpdates(){try{var newStoreState=store.getState();if(newStoreState===latestStoreState.current)return;var _newSelectedState=latestSelector.current(newStoreState);if(equalityFn(_newSelectedState,latestSelectedState.current))return;latestSelectedState.current=_newSelectedState,latestStoreState.current=newStoreState}catch(err){latestSubscriptionCallbackError.current=err}forceRender()}return subscription.onStateChange=checkForUpdates,subscription.trySubscribe(),checkForUpdates(),function(){return subscription.tryUnsubscribe()}},[store,subscription]),selectedState}(selector,equalityFn,_useReduxContext.store,_useReduxContext.subscription);return(0,_react.useDebugValue)(selector),selector}}exports.useSelector=createSelectorHook()},{"../components/Context":1391,"../utils/Subscription":1407,"../utils/useIsomorphicLayoutEffect":1413,"./useReduxContext":1403,react:1427}],1405:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.createStoreHook=createStoreHook,exports.useStore=void 0;var _react=require("react"),_Context=require("../components/Context"),_useReduxContext2=require("./useReduxContext");function createStoreHook(context){var useReduxContext=(context=void 0===context?_Context.ReactReduxContext:context)===_Context.ReactReduxContext?_useReduxContext2.useReduxContext:function(){return(0,_react.useContext)(context)};return function(){return useReduxContext().store}}exports.useStore=createStoreHook()},{"../components/Context":1391,"./useReduxContext":1403,react:1427}],1406:[function(require,module,exports){"use strict";var _exportNames={batch:exports.__esModule=!0},_exports=require("./exports"),_reactBatchedUpdates=(Object.keys(_exports).forEach(function(key){"default"===key||"__esModule"===key||Object.prototype.hasOwnProperty.call(_exportNames,key)||key in exports&&exports[key]===_exports[key]||(exports[key]=_exports[key])}),require("./utils/reactBatchedUpdates"));exports.batch=_reactBatchedUpdates.unstable_batchedUpdates,(0,require("./utils/batch").setBatch)(_reactBatchedUpdates.unstable_batchedUpdates)},{"./exports":1401,"./utils/batch":1408,"./utils/reactBatchedUpdates":1411}],1407:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.createSubscription=function(store,parentSub){var unsubscribe,listeners=nullListeners;function handleChangeWrapper(){subscription.onStateChange&&subscription.onStateChange()}function trySubscribe(){var batch,first,last;unsubscribe||(unsubscribe=parentSub?parentSub.addNestedSub(handleChangeWrapper):store.subscribe(handleChangeWrapper),batch=(0,_batch.getBatch)(),last=first=null,listeners={clear:function(){last=first=null},notify:function(){batch(function(){for(var listener=first;listener;)listener.callback(),listener=listener.next})},get:function(){for(var listeners=[],listener=first;listener;)listeners.push(listener),listener=listener.next;return listeners},subscribe:function(callback){var isSubscribed=!0,listener=last={callback:callback,next:null,prev:last};return listener.prev?listener.prev.next=listener:first=listener,function(){isSubscribed&&null!==first&&(isSubscribed=!1,listener.next?listener.next.prev=listener.prev:last=listener.prev,listener.prev?listener.prev.next=listener.next:first=listener.next)}}})}var subscription={addNestedSub:function(listener){return trySubscribe(),listeners.subscribe(listener)},notifyNestedSubs:function(){listeners.notify()},handleChangeWrapper:handleChangeWrapper,isSubscribed:function(){return Boolean(unsubscribe)},trySubscribe:trySubscribe,tryUnsubscribe:function(){unsubscribe&&(unsubscribe(),unsubscribe=void 0,listeners.clear(),listeners=nullListeners)},getListeners:function(){return listeners}};return subscription};var _batch=require("./batch");var nullListeners={notify:function(){},get:function(){return[]}}},{"./batch":1408}],1408:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.setBatch=exports.getBatch=void 0;var batch=function(callback){callback()};exports.setBatch=function(newBatch){return batch=newBatch};exports.getBatch=function(){return batch}},{}],1409:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.default=function(actionCreators,dispatch){var key,boundActionCreators={};for(key in actionCreators)!function(key){var actionCreator=actionCreators[key];"function"==typeof actionCreator&&(boundActionCreators[key]=function(){return dispatch(actionCreator.apply(void 0,arguments))})}(key);return boundActionCreators}},{}],1410:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.default=function(obj){if("object"!=typeof obj||null===obj)return!1;obj=Object.getPrototypeOf(obj);if(null===obj)return!0;var baseProto=obj;for(;null!==Object.getPrototypeOf(baseProto);)baseProto=Object.getPrototypeOf(baseProto);return obj===baseProto}},{}],1411:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.unstable_batchedUpdates=void 0;require=require("react-dom");exports.unstable_batchedUpdates=require.unstable_batchedUpdates},{"react-dom":1382}],1412:[function(require,module,exports){"use strict";function is(x,y){return x===y?0!==x||0!==y||1/x==1/y:x!=x&&y!=y}exports.__esModule=!0,exports.default=function(objA,objB){if(!is(objA,objB)){if("object"!=typeof objA||null===objA||"object"!=typeof objB||null===objB)return!1;var keysA=Object.keys(objA),keysB=Object.keys(objB);if(keysA.length!==keysB.length)return!1;for(var i=0;i<keysA.length;i++)if(!Object.prototype.hasOwnProperty.call(objB,keysA[i])||!is(objA[keysA[i]],objB[keysA[i]]))return!1}return!0}},{}],1413:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.useIsomorphicLayoutEffect=void 0;require=require("react"),require="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement?require.useLayoutEffect:require.useEffect;exports.useIsomorphicLayoutEffect=require},{react:1427}],1414:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault").default,_isPlainObject=(exports.__esModule=!0,exports.default=function(value,displayName,methodName){(0,_isPlainObject.default)(value)||(0,_warning.default)(methodName+"() in "+displayName+" must return a plain object. Instead received "+value+".")},_interopRequireDefault(require("./isPlainObject"))),_warning=_interopRequireDefault(require("./warning"))},{"./isPlainObject":1410,"./warning":1415,"@babel/runtime/helpers/interopRequireDefault":13}],1415:[function(require,module,exports){"use strict";exports.__esModule=!0,exports.default=function(message){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(message);try{throw new Error(message)}catch(e){}}},{}],1416:[function(require,module,exports){!function(process){!function(){"use strict";function typeOf(object){if("object"==typeof object&&null!==object){var $$typeof=object.$$typeof;switch($$typeof){case REACT_ELEMENT_TYPE:var type=object.type;switch(type){case REACT_FRAGMENT_TYPE:case REACT_PROFILER_TYPE:case REACT_STRICT_MODE_TYPE:case REACT_SUSPENSE_TYPE:case REACT_SUSPENSE_LIST_TYPE:return type;default:var $$typeofType=type&&type.$$typeof;switch($$typeofType){case REACT_CONTEXT_TYPE:case REACT_FORWARD_REF_TYPE:case REACT_LAZY_TYPE:case REACT_MEMO_TYPE:case REACT_PROVIDER_TYPE:return $$typeofType;default:return $$typeof}}case REACT_PORTAL_TYPE:return $$typeof}}}var REACT_ELEMENT_TYPE,REACT_PORTAL_TYPE,REACT_FRAGMENT_TYPE,REACT_STRICT_MODE_TYPE,REACT_PROFILER_TYPE,REACT_PROVIDER_TYPE,REACT_CONTEXT_TYPE,REACT_FORWARD_REF_TYPE,REACT_SUSPENSE_TYPE,REACT_SUSPENSE_LIST_TYPE,REACT_MEMO_TYPE,REACT_LAZY_TYPE,REACT_BLOCK_TYPE,REACT_SERVER_BLOCK_TYPE,REACT_FUNDAMENTAL_TYPE,REACT_DEBUG_TRACING_MODE_TYPE,REACT_LEGACY_HIDDEN_TYPE,symbolFor,ContextProvider,Element,ForwardRef,Fragment,Lazy,Memo,Portal,Profiler,StrictMode,Suspense,hasWarnedAboutDeprecatedIsAsyncMode,hasWarnedAboutDeprecatedIsConcurrentMode;"production"!==process.env.NODE_ENV&&(REACT_ELEMENT_TYPE=60103,REACT_PORTAL_TYPE=60106,REACT_FRAGMENT_TYPE=60107,REACT_STRICT_MODE_TYPE=60108,REACT_PROFILER_TYPE=60114,REACT_PROVIDER_TYPE=60109,REACT_CONTEXT_TYPE=60110,REACT_FORWARD_REF_TYPE=60112,REACT_SUSPENSE_TYPE=60113,REACT_SUSPENSE_LIST_TYPE=60120,REACT_MEMO_TYPE=60115,REACT_LAZY_TYPE=60116,REACT_BLOCK_TYPE=60121,REACT_SERVER_BLOCK_TYPE=60122,REACT_FUNDAMENTAL_TYPE=60117,REACT_DEBUG_TRACING_MODE_TYPE=60129,REACT_LEGACY_HIDDEN_TYPE=60131,"function"==typeof Symbol&&Symbol.for&&(REACT_ELEMENT_TYPE=(symbolFor=Symbol.for)("react.element"),REACT_PORTAL_TYPE=symbolFor("react.portal"),REACT_FRAGMENT_TYPE=symbolFor("react.fragment"),REACT_STRICT_MODE_TYPE=symbolFor("react.strict_mode"),REACT_PROFILER_TYPE=symbolFor("react.profiler"),REACT_PROVIDER_TYPE=symbolFor("react.provider"),REACT_CONTEXT_TYPE=symbolFor("react.context"),REACT_FORWARD_REF_TYPE=symbolFor("react.forward_ref"),REACT_SUSPENSE_TYPE=symbolFor("react.suspense"),REACT_SUSPENSE_LIST_TYPE=symbolFor("react.suspense_list"),REACT_MEMO_TYPE=symbolFor("react.memo"),REACT_LAZY_TYPE=symbolFor("react.lazy"),REACT_BLOCK_TYPE=symbolFor("react.block"),REACT_SERVER_BLOCK_TYPE=symbolFor("react.server.block"),REACT_FUNDAMENTAL_TYPE=symbolFor("react.fundamental"),symbolFor("react.scope"),symbolFor("react.opaque.id"),REACT_DEBUG_TRACING_MODE_TYPE=symbolFor("react.debug_trace_mode"),symbolFor("react.offscreen"),REACT_LEGACY_HIDDEN_TYPE=symbolFor("react.legacy_hidden")),symbolFor=REACT_CONTEXT_TYPE,ContextProvider=REACT_PROVIDER_TYPE,Element=REACT_ELEMENT_TYPE,ForwardRef=REACT_FORWARD_REF_TYPE,Fragment=REACT_FRAGMENT_TYPE,Lazy=REACT_LAZY_TYPE,Memo=REACT_MEMO_TYPE,Portal=REACT_PORTAL_TYPE,Profiler=REACT_PROFILER_TYPE,StrictMode=REACT_STRICT_MODE_TYPE,Suspense=REACT_SUSPENSE_TYPE,hasWarnedAboutDeprecatedIsConcurrentMode=hasWarnedAboutDeprecatedIsAsyncMode=!1,exports.ContextConsumer=symbolFor,exports.ContextProvider=ContextProvider,exports.Element=Element,exports.ForwardRef=ForwardRef,exports.Fragment=Fragment,exports.Lazy=Lazy,exports.Memo=Memo,exports.Portal=Portal,exports.Profiler=Profiler,exports.StrictMode=StrictMode,exports.Suspense=Suspense,exports.isAsyncMode=function(object){return hasWarnedAboutDeprecatedIsAsyncMode||(hasWarnedAboutDeprecatedIsAsyncMode=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 18+.")),!1},exports.isConcurrentMode=function(object){return hasWarnedAboutDeprecatedIsConcurrentMode||(hasWarnedAboutDeprecatedIsConcurrentMode=!0,console.warn("The ReactIs.isConcurrentMode() alias has been deprecated, and will be removed in React 18+.")),!1},exports.isContextConsumer=function(object){return typeOf(object)===REACT_CONTEXT_TYPE},exports.isContextProvider=function(object){return typeOf(object)===REACT_PROVIDER_TYPE},exports.isElement=function(object){return"object"==typeof object&&null!==object&&object.$$typeof===REACT_ELEMENT_TYPE},exports.isForwardRef=function(object){return typeOf(object)===REACT_FORWARD_REF_TYPE},exports.isFragment=function(object){return typeOf(object)===REACT_FRAGMENT_TYPE},exports.isLazy=function(object){return typeOf(object)===REACT_LAZY_TYPE},exports.isMemo=function(object){return typeOf(object)===REACT_MEMO_TYPE},exports.isPortal=function(object){return typeOf(object)===REACT_PORTAL_TYPE},exports.isProfiler=function(object){return typeOf(object)===REACT_PROFILER_TYPE},exports.isStrictMode=function(object){return typeOf(object)===REACT_STRICT_MODE_TYPE},exports.isSuspense=function(object){return typeOf(object)===REACT_SUSPENSE_TYPE},exports.isValidElementType=function(type){return"string"==typeof type||"function"==typeof type||type===REACT_FRAGMENT_TYPE||type===REACT_PROFILER_TYPE||type===REACT_DEBUG_TRACING_MODE_TYPE||type===REACT_STRICT_MODE_TYPE||type===REACT_SUSPENSE_TYPE||type===REACT_SUSPENSE_LIST_TYPE||type===REACT_LEGACY_HIDDEN_TYPE||"object"==typeof type&&null!==type&&(type.$$typeof===REACT_LAZY_TYPE||type.$$typeof===REACT_MEMO_TYPE||type.$$typeof===REACT_PROVIDER_TYPE||type.$$typeof===REACT_CONTEXT_TYPE||type.$$typeof===REACT_FORWARD_REF_TYPE||type.$$typeof===REACT_FUNDAMENTAL_TYPE||type.$$typeof===REACT_BLOCK_TYPE||type[0]===REACT_SERVER_BLOCK_TYPE)},exports.typeOf=typeOf)}.call(this)}.call(this,require("_process"))},{_process:1042}],1417:[function(require,module,exports){"use strict";var b=60103,c=60106,d=60107,e=60108,f=60114,g=60109,h=60110,k=60112,l=60113,m=60120,n=60115,p=60116,q=60121,r=60122,u=60117,v=60129,w=60131;function y(a){if("object"==typeof a&&null!==a){var t=a.$$typeof;switch(t){case b:switch(a=a.type){case d:case f:case e:case l:case m:return a;default:switch(a=a&&a.$$typeof){case h:case k:case p:case n:case g:return a;default:return t}}case c:return t}}}"function"==typeof Symbol&&Symbol.for&&(b=(x=Symbol.for)("react.element"),c=x("react.portal"),d=x("react.fragment"),e=x("react.strict_mode"),f=x("react.profiler"),g=x("react.provider"),h=x("react.context"),k=x("react.forward_ref"),l=x("react.suspense"),m=x("react.suspense_list"),n=x("react.memo"),p=x("react.lazy"),q=x("react.block"),r=x("react.server.block"),u=x("react.fundamental"),v=x("react.debug_trace_mode"),w=x("react.legacy_hidden"));var x=g,A=b,B=k,C=d,D=p,E=n,F=c,G=f,H=e,I=l;exports.ContextConsumer=h,exports.ContextProvider=x,exports.Element=A,exports.ForwardRef=B,exports.Fragment=C,exports.Lazy=D,exports.Memo=E,exports.Portal=F,exports.Profiler=G,exports.StrictMode=H,exports.Suspense=I,exports.isAsyncMode=function(){return!1},exports.isConcurrentMode=function(){return!1},exports.isContextConsumer=function(a){return y(a)===h},exports.isContextProvider=function(a){return y(a)===g},exports.isElement=function(a){return"object"==typeof a&&null!==a&&a.$$typeof===b},exports.isForwardRef=function(a){return y(a)===k},exports.isFragment=function(a){return y(a)===d},exports.isLazy=function(a){return y(a)===p},exports.isMemo=function(a){return y(a)===n},exports.isPortal=function(a){return y(a)===c},exports.isProfiler=function(a){return y(a)===f},exports.isStrictMode=function(a){return y(a)===e},exports.isSuspense=function(a){return y(a)===l},exports.isValidElementType=function(a){return"string"==typeof a||"function"==typeof a||a===d||a===f||a===v||a===e||a===l||a===m||a===w||"object"==typeof a&&null!==a&&(a.$$typeof===p||a.$$typeof===n||a.$$typeof===g||a.$$typeof===h||a.$$typeof===k||a.$$typeof===u||a.$$typeof===q||a[0]===r)},exports.typeOf=y},{}],1418:[function(require,module,exports){arguments[4][1385][0].apply(exports,arguments)},{"./cjs/react-is.development.js":1416,"./cjs/react-is.production.min.js":1417,_process:1042,dup:1385}],1419:[function(require,module,exports){"use strict";function _interopDefault(ex){return ex&&"object"==typeof ex&&"default"in ex?ex.default:ex}var reactRouter=require("react-router"),React=_interopDefault(require("react")),history=require("history"),PropTypes=_interopDefault(require("prop-types")),warning=_interopDefault(require("tiny-warning")),invariant=_interopDefault(require("tiny-invariant"));function _extends(){return(_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var key,source=arguments[i];for(key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target}).apply(this,arguments)}function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),_setPrototypeOf(subClass.prototype.constructor=subClass,superClass)}function _setPrototypeOf(o,p){return(_setPrototypeOf=Object.setPrototypeOf||function(o,p){return o.__proto__=p,o})(o,p)}function _objectWithoutPropertiesLoose(source,excluded){if(null==source)return{};for(var key,target={},sourceKeys=Object.keys(source),i=0;i<sourceKeys.length;i++)key=sourceKeys[i],0<=excluded.indexOf(key)||(target[key]=source[key]);return target}function resolveToLocation(to,currentLocation){return"function"==typeof to?to(currentLocation):to}function normalizeToLocation(to,currentLocation){return"string"==typeof to?history.createLocation(to,null,null,currentLocation):to}function forwardRefShim(C){return C}var require=function(_React$Component){function BrowserRouter(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_this=_React$Component.call.apply(_React$Component,[this].concat(args))||this).history=history.createBrowserHistory(_this.props),_this}return _inheritsLoose(BrowserRouter,_React$Component),BrowserRouter.prototype.render=function(){return React.createElement(reactRouter.Router,{history:this.history,children:this.props.children})},BrowserRouter}(React.Component),HashRouter=(require.propTypes={basename:PropTypes.string,children:PropTypes.node,forceRefresh:PropTypes.bool,getUserConfirmation:PropTypes.func,keyLength:PropTypes.number},require.prototype.componentDidMount=function(){warning(!this.props.history,"<BrowserRouter> ignores the history prop. To use a custom history, use `import { Router }` instead of `import { BrowserRouter as Router }`.")},function(_React$Component){function HashRouter(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_this=_React$Component.call.apply(_React$Component,[this].concat(args))||this).history=history.createHashHistory(_this.props),_this}return _inheritsLoose(HashRouter,_React$Component),HashRouter.prototype.render=function(){return React.createElement(reactRouter.Router,{history:this.history,children:this.props.children})},HashRouter}(React.Component)),forwardRef=(HashRouter.propTypes={basename:PropTypes.string,children:PropTypes.node,getUserConfirmation:PropTypes.func,hashType:PropTypes.oneOf(["hashbang","noslash","slash"])},HashRouter.prototype.componentDidMount=function(){warning(!this.props.history,"<HashRouter> ignores the history prop. To use a custom history, use `import { Router }` instead of `import { HashRouter as Router }`.")},React.forwardRef);function forwardRefShim$1(C){return C}var LinkAnchor=(forwardRef=void 0===forwardRef?forwardRefShim:forwardRef)(function(_ref,forwardedRef){var innerRef=_ref.innerRef,navigate=_ref.navigate,_onClick=_ref.onClick,_ref=_objectWithoutPropertiesLoose(_ref,["innerRef","navigate","onClick"]),target=_ref.target,_ref=_extends({},_ref,{onClick:function(event){try{_onClick&&_onClick(event)}catch(ex){throw event.preventDefault(),ex}event.defaultPrevented||0!==event.button||target&&"_self"!==target||function(event){return event.metaKey||event.altKey||event.ctrlKey||event.shiftKey}(event)||(event.preventDefault(),navigate())}});return _ref.ref=forwardRefShim!==forwardRef&&forwardedRef||innerRef,React.createElement("a",_ref)}),Link=(LinkAnchor.displayName="LinkAnchor",forwardRef(function(_ref2,forwardedRef){var _ref2$component=_ref2.component,component=void 0===_ref2$component?LinkAnchor:_ref2$component,replace=_ref2.replace,to=_ref2.to,innerRef=_ref2.innerRef,rest=_objectWithoutPropertiesLoose(_ref2,["component","replace","to","innerRef"]);return React.createElement(reactRouter.__RouterContext.Consumer,null,function(context){context||invariant(!1,"You should not use <Link> outside a <Router>");var history$1=context.history,location=normalizeToLocation(resolveToLocation(to,context.location),context.location),location=location?history$1.createHref(location):"",location=_extends({},rest,{href:location,navigate:function(){var location=resolveToLocation(to,context.location),isDuplicateNavigation=history.createPath(context.location)===history.createPath(normalizeToLocation(location));(replace||isDuplicateNavigation?history$1.replace:history$1.push)(location)}});return forwardRefShim!==forwardRef?location.ref=forwardedRef||innerRef:location.innerRef=innerRef,React.createElement(component,location)})})),toType=PropTypes.oneOfType([PropTypes.string,PropTypes.object,PropTypes.func]),refType=PropTypes.oneOfType([PropTypes.string,PropTypes.func,PropTypes.shape({current:PropTypes.any})]),forwardRef$1=(Link.displayName="Link",Link.propTypes={innerRef:refType,onClick:PropTypes.func,replace:PropTypes.bool,target:PropTypes.string,to:toType.isRequired},React.forwardRef);refType=(forwardRef$1=void 0===forwardRef$1?forwardRefShim$1:forwardRef$1)(function(_ref,forwardedRef){var _ref$ariaCurrent=_ref["aria-current"],ariaCurrent=void 0===_ref$ariaCurrent?"page":_ref$ariaCurrent,_ref$ariaCurrent=_ref.activeClassName,activeClassName=void 0===_ref$ariaCurrent?"active":_ref$ariaCurrent,activeStyle=_ref.activeStyle,classNameProp=_ref.className,exact=_ref.exact,isActiveProp=_ref.isActive,locationProp=_ref.location,sensitive=_ref.sensitive,strict=_ref.strict,styleProp=_ref.style,to=_ref.to,innerRef=_ref.innerRef,rest=_objectWithoutPropertiesLoose(_ref,["aria-current","activeClassName","activeStyle","className","exact","isActive","location","sensitive","strict","style","to","innerRef"]);return React.createElement(reactRouter.__RouterContext.Consumer,null,function(context){context||invariant(!1,"You should not use <NavLink> outside a <Router>");var context=locationProp||context.location,toLocation=normalizeToLocation(resolveToLocation(to,context),context),path=toLocation.pathname,path=path&&path.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1"),path=path?reactRouter.matchPath(context.pathname,{path:path,exact:exact,sensitive:sensitive,strict:strict}):null,context=!!(isActiveProp?isActiveProp(path,context):path),path="function"==typeof classNameProp?classNameProp(context):classNameProp,style="function"==typeof styleProp?styleProp(context):styleProp,context=(context&&(path=function(){for(var _len=arguments.length,classnames=new Array(_len),_key=0;_key<_len;_key++)classnames[_key]=arguments[_key];return classnames.filter(function(i){return i}).join(" ")}(path,activeClassName),style=_extends({},style,activeStyle)),_extends({"aria-current":context&&ariaCurrent||null,className:path,style:style,to:toLocation},rest));return forwardRefShim$1!==forwardRef$1?context.ref=forwardedRef||innerRef:context.innerRef=innerRef,React.createElement(Link,context)})}),refType.displayName="NavLink",toType=PropTypes.oneOf(["page","step","location","date","time","true","false"]);refType.propTypes=_extends({},Link.propTypes,{"aria-current":toType,activeClassName:PropTypes.string,activeStyle:PropTypes.object,className:PropTypes.oneOfType([PropTypes.string,PropTypes.func]),exact:PropTypes.bool,isActive:PropTypes.func,location:PropTypes.object,sensitive:PropTypes.bool,strict:PropTypes.bool,style:PropTypes.oneOfType([PropTypes.object,PropTypes.func])}),Object.defineProperty(exports,"MemoryRouter",{enumerable:!0,get:function(){return reactRouter.MemoryRouter}}),Object.defineProperty(exports,"Prompt",{enumerable:!0,get:function(){return reactRouter.Prompt}}),Object.defineProperty(exports,"Redirect",{enumerable:!0,get:function(){return reactRouter.Redirect}}),Object.defineProperty(exports,"Route",{enumerable:!0,get:function(){return reactRouter.Route}}),Object.defineProperty(exports,"Router",{enumerable:!0,get:function(){return reactRouter.Router}}),Object.defineProperty(exports,"StaticRouter",{enumerable:!0,get:function(){return reactRouter.StaticRouter}}),Object.defineProperty(exports,"Switch",{enumerable:!0,get:function(){return reactRouter.Switch}}),Object.defineProperty(exports,"generatePath",{enumerable:!0,get:function(){return reactRouter.generatePath}}),Object.defineProperty(exports,"matchPath",{enumerable:!0,get:function(){return reactRouter.matchPath}}),Object.defineProperty(exports,"useHistory",{enumerable:!0,get:function(){return reactRouter.useHistory}}),Object.defineProperty(exports,"useLocation",{enumerable:!0,get:function(){return reactRouter.useLocation}}),Object.defineProperty(exports,"useParams",{enumerable:!0,get:function(){return reactRouter.useParams}}),Object.defineProperty(exports,"useRouteMatch",{enumerable:!0,get:function(){return reactRouter.useRouteMatch}}),Object.defineProperty(exports,"withRouter",{enumerable:!0,get:function(){return reactRouter.withRouter}}),exports.BrowserRouter=require,exports.HashRouter=HashRouter,exports.Link=Link,exports.NavLink=refType},{history:653,"prop-types":1046,react:1427,"react-router":1424,"tiny-invariant":1696,"tiny-warning":1697}],1420:[function(require,module,exports){"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var reactRouter=require("react-router"),React=_interopDefault(require("react")),history=require("history"),invariant=(require("prop-types"),require("tiny-warning"),_interopDefault(require("tiny-invariant")));function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o,r=arguments[t];for(o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e}).apply(this,arguments)}function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),_setPrototypeOf(e.prototype.constructor=e,t)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function _objectWithoutPropertiesLoose(e,t){if(null==e)return{};for(var r,n={},a=Object.keys(e),o=0;o<a.length;o++)r=a[o],0<=t.indexOf(r)||(n[r]=e[r]);return n}function resolveToLocation(e,t){return"function"==typeof e?e(t):e}function normalizeToLocation(e,t){return"string"==typeof e?history.createLocation(e,null,null,t):e}function forwardRefShim(e){return e}_inheritsLoose(e,n=React.Component),e.prototype.render=function(){return React.createElement(reactRouter.Router,{history:this.history,children:this.props.children})};var n,require=e,HashRouter=function(n){function e(){for(var e,t=arguments.length,r=new Array(t),o=0;o<t;o++)r[o]=arguments[o];return(e=n.call.apply(n,[this].concat(r))||this).history=history.createHashHistory(e.props),e}return _inheritsLoose(e,n),e.prototype.render=function(){return React.createElement(reactRouter.Router,{history:this.history,children:this.props.children})},e}(React.Component),forwardRef=React.forwardRef;function e(){for(var e,t=arguments.length,r=new Array(t),o=0;o<t;o++)r[o]=arguments[o];return(e=n.call.apply(n,[this].concat(r))||this).history=history.createBrowserHistory(e.props),e}function forwardRefShim$1(e){return e}var LinkAnchor=(forwardRef=void 0===forwardRef?forwardRefShim:forwardRef)(function(e,t){var r=e.innerRef,o=e.navigate,n=e.onClick,e=_objectWithoutPropertiesLoose(e,["innerRef","navigate","onClick"]),i=e.target,e=_extends({},e,{onClick:function(t){try{n&&n(t)}catch(e){throw t.preventDefault(),e}var e;t.defaultPrevented||0!==t.button||i&&"_self"!==i||(e=t).metaKey||e.altKey||e.ctrlKey||e.shiftKey||(t.preventDefault(),o())}});return e.ref=forwardRefShim!==forwardRef&&t||r,React.createElement("a",e)}),Link=forwardRef(function(e,a){var t=e.component,i=void 0===t?LinkAnchor:t,c=e.replace,u=e.to,f=e.innerRef,s=_objectWithoutPropertiesLoose(e,["component","replace","to","innerRef"]);return React.createElement(reactRouter.__RouterContext.Consumer,null,function(r){r||invariant(!1);var o=r.history,e=normalizeToLocation(resolveToLocation(u,r.location),r.location),e=e?o.createHref(e):"",e=_extends({},s,{href:e,navigate:function(){var e=resolveToLocation(u,r.location),t=history.createPath(r.location)===history.createPath(normalizeToLocation(e));(c||t?o.replace:o.push)(e)}});return forwardRefShim!==forwardRef?e.ref=a||f:e.innerRef=f,React.createElement(i,e)})}),forwardRef$1=React.forwardRef;var NavLink=(forwardRef$1=void 0===forwardRef$1?forwardRefShim$1:forwardRef$1)(function(e,s){var t=e["aria-current"],l=void 0===t?"page":t,t=e.activeClassName,p=void 0===t?"active":t,R=e.activeStyle,h=e.className,y=e.exact,d=e.isActive,m=e.location,v=e.sensitive,b=e.strict,P=e.style,w=e.to,x=e.innerRef,g=_objectWithoutPropertiesLoose(e,["aria-current","activeClassName","activeStyle","className","exact","isActive","location","sensitive","strict","style","to","innerRef"]);return React.createElement(reactRouter.__RouterContext.Consumer,null,function(e){e||invariant(!1);var e=m||e.location,r=normalizeToLocation(resolveToLocation(w,e),e),o=r.pathname,o=o&&o.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1"),o=o?reactRouter.matchPath(e.pathname,{path:o,exact:y,sensitive:v,strict:b}):null,e=!!(d?d(o,e):o),o="function"==typeof h?h(e):h,u="function"==typeof P?P(e):P,e=(e&&(o=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.filter(function(e){return e}).join(" ")}(o,p),u=_extends({},u,R)),_extends({"aria-current":e&&l||null,className:o,style:u,to:r},g));return forwardRefShim$1!==forwardRef$1?e.ref=s||x:e.innerRef=x,React.createElement(Link,e)})});Object.defineProperty(exports,"MemoryRouter",{enumerable:!0,get:function(){return reactRouter.MemoryRouter}}),Object.defineProperty(exports,"Prompt",{enumerable:!0,get:function(){return reactRouter.Prompt}}),Object.defineProperty(exports,"Redirect",{enumerable:!0,get:function(){return reactRouter.Redirect}}),Object.defineProperty(exports,"Route",{enumerable:!0,get:function(){return reactRouter.Route}}),Object.defineProperty(exports,"Router",{enumerable:!0,get:function(){return reactRouter.Router}}),Object.defineProperty(exports,"StaticRouter",{enumerable:!0,get:function(){return reactRouter.StaticRouter}}),Object.defineProperty(exports,"Switch",{enumerable:!0,get:function(){return reactRouter.Switch}}),Object.defineProperty(exports,"generatePath",{enumerable:!0,get:function(){return reactRouter.generatePath}}),Object.defineProperty(exports,"matchPath",{enumerable:!0,get:function(){return reactRouter.matchPath}}),Object.defineProperty(exports,"useHistory",{enumerable:!0,get:function(){return reactRouter.useHistory}}),Object.defineProperty(exports,"useLocation",{enumerable:!0,get:function(){return reactRouter.useLocation}}),Object.defineProperty(exports,"useParams",{enumerable:!0,get:function(){return reactRouter.useParams}}),Object.defineProperty(exports,"useRouteMatch",{enumerable:!0,get:function(){return reactRouter.useRouteMatch}}),Object.defineProperty(exports,"withRouter",{enumerable:!0,get:function(){return reactRouter.withRouter}}),exports.BrowserRouter=require,exports.HashRouter=HashRouter,exports.Link=Link,exports.NavLink=NavLink},{history:653,"prop-types":1046,react:1427,"react-router":1424,"tiny-invariant":1696,"tiny-warning":1697}],1421:[function(require,module,exports){"use strict";module.exports=require("./cjs/react-router-dom.min.js")},{"./cjs/react-router-dom.js":1419,"./cjs/react-router-dom.min.js":1420}],1422:[function(require,module,exports){!function(global){!function(){"use strict";function _interopDefault(ex){return ex&&"object"==typeof ex&&"default"in ex?ex.default:ex}var React=_interopDefault(require("react")),PropTypes=_interopDefault(require("prop-types")),history=require("history"),warning=_interopDefault(require("tiny-warning")),invariant=_interopDefault(require("tiny-invariant")),pathToRegexp=_interopDefault(require("path-to-regexp")),reactIs=require("react-is"),hoistStatics=_interopDefault(require("hoist-non-react-statics"));function _extends(){return(_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var key,source=arguments[i];for(key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target}).apply(this,arguments)}function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),_setPrototypeOf(subClass.prototype.constructor=subClass,superClass)}function _setPrototypeOf(o,p){return(_setPrototypeOf=Object.setPrototypeOf||function(o,p){return o.__proto__=p,o})(o,p)}function _objectWithoutPropertiesLoose(source,excluded){if(null==source)return{};for(var key,target={},sourceKeys=Object.keys(source),i=0;i<sourceKeys.length;i++)key=sourceKeys[i],0<=excluded.indexOf(key)||(target[key]=source[key]);return target}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:{};function createNamedContext(name){var context=createContext();return context.displayName=name,context}var createContext=React.createContext||function(defaultValue,calculateChangedBits){var _Consumer$contextType,contextProp="__create-react-context-"+(commonjsGlobal[key="__global_unique_id__"]=(commonjsGlobal[key]||0)+1)+"__",key=function(_React$Component){function Provider(){for(var _this,value,handlers,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_this=_React$Component.call.apply(_React$Component,[this].concat(args))||this).emitter=(value=_this.props.value,handlers=[],{on:function(handler){handlers.push(handler)},off:function(handler){handlers=handlers.filter(function(h){return h!==handler})},get:function(){return value},set:function(newValue,changedBits){value=newValue,handlers.forEach(function(handler){return handler(value,changedBits)})}}),_this}_inheritsLoose(Provider,_React$Component);var _proto=Provider.prototype;return _proto.getChildContext=function(){var _ref={};return _ref[contextProp]=this.emitter,_ref},_proto.componentWillReceiveProps=function(nextProps){var oldValue,newValue,x,y;this.props.value!==nextProps.value&&(oldValue=this.props.value,newValue=nextProps.value,(x=oldValue)===(y=newValue)?0===x&&1/x!=1/y:x==x||y==y)&&(x="function"==typeof calculateChangedBits?calculateChangedBits(oldValue,newValue):1073741823,warning((1073741823&x)===x,"calculateChangedBits: Expected the return value to be a 31-bit integer. Instead received: "+x),0!==(x|=0))&&this.emitter.set(nextProps.value,x)},_proto.render=function(){return this.props.children},Provider}(React.Component),_Provider$childContex=(key.childContextTypes=((_Provider$childContex={})[contextProp]=PropTypes.object.isRequired,_Provider$childContex),function(_React$Component2){function Consumer(){for(var _this2,_len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];return(_this2=_React$Component2.call.apply(_React$Component2,[this].concat(args))||this).observedBits=void 0,_this2.state={value:_this2.getValue()},_this2.onUpdate=function(newValue,changedBits){0!=((0|_this2.observedBits)&changedBits)&&_this2.setState({value:_this2.getValue()})},_this2}_inheritsLoose(Consumer,_React$Component2);var _proto2=Consumer.prototype;return _proto2.componentWillReceiveProps=function(nextProps){nextProps=nextProps.observedBits;this.observedBits=null==nextProps?1073741823:nextProps},_proto2.componentDidMount=function(){this.context[contextProp]&&this.context[contextProp].on(this.onUpdate);var observedBits=this.props.observedBits;this.observedBits=null==observedBits?1073741823:observedBits},_proto2.componentWillUnmount=function(){this.context[contextProp]&&this.context[contextProp].off(this.onUpdate)},_proto2.getValue=function(){return this.context[contextProp]?this.context[contextProp].get():defaultValue},_proto2.render=function(){return children=this.props.children,(Array.isArray(children)?children[0]:children)(this.state.value);var children},Consumer}(React.Component));return _Provider$childContex.contextTypes=((_Consumer$contextType={})[contextProp]=PropTypes.object,_Consumer$contextType),{Provider:key,Consumer:_Provider$childContex}},historyContext=createNamedContext("Router-History"),context=createNamedContext("Router"),Router=function(_React$Component){function Router(props){var _this=_React$Component.call(this,props)||this;return _this.state={location:props.history.location},_this._isMounted=!1,_this._pendingLocation=null,props.staticContext||(_this.unlisten=props.history.listen(function(location){_this._pendingLocation=location})),_this}_inheritsLoose(Router,_React$Component),Router.computeRootMatch=function(pathname){return{path:"/",url:"/",params:{},isExact:"/"===pathname}};var _proto=Router.prototype;return _proto.componentDidMount=function(){var _this2=this;this._isMounted=!0,this.unlisten&&this.unlisten(),this.props.staticContext||(this.unlisten=this.props.history.listen(function(location){_this2._isMounted&&_this2.setState({location:location})})),this._pendingLocation&&this.setState({location:this._pendingLocation})},_proto.componentWillUnmount=function(){this.unlisten&&(this.unlisten(),this._isMounted=!1,this._pendingLocation=null)},_proto.render=function(){return React.createElement(context.Provider,{value:{history:this.props.history,location:this.state.location,match:Router.computeRootMatch(this.state.location.pathname),staticContext:this.props.staticContext}},React.createElement(historyContext.Provider,{children:this.props.children||null,value:this.props.history}))},Router}(React.Component),MemoryRouter=(Router.propTypes={children:PropTypes.node,history:PropTypes.object.isRequired,staticContext:PropTypes.object},Router.prototype.componentDidUpdate=function(prevProps){warning(prevProps.history===this.props.history,"You cannot change <Router history>")},function(_React$Component){function MemoryRouter(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_this=_React$Component.call.apply(_React$Component,[this].concat(args))||this).history=history.createMemoryHistory(_this.props),_this}return _inheritsLoose(MemoryRouter,_React$Component),MemoryRouter.prototype.render=function(){return React.createElement(Router,{history:this.history,children:this.props.children})},MemoryRouter}(React.Component)),Lifecycle=(MemoryRouter.propTypes={initialEntries:PropTypes.array,initialIndex:PropTypes.number,getUserConfirmation:PropTypes.func,keyLength:PropTypes.number,children:PropTypes.node},MemoryRouter.prototype.componentDidMount=function(){warning(!this.props.history,"<MemoryRouter> ignores the history prop. To use a custom history, use `import { Router }` instead of `import { MemoryRouter as Router }`.")},function(_React$Component){function Lifecycle(){return _React$Component.apply(this,arguments)||this}_inheritsLoose(Lifecycle,_React$Component);var _proto=Lifecycle.prototype;return _proto.componentDidMount=function(){this.props.onMount&&this.props.onMount.call(this,this)},_proto.componentDidUpdate=function(prevProps){this.props.onUpdate&&this.props.onUpdate.call(this,this,prevProps)},_proto.componentWillUnmount=function(){this.props.onUnmount&&this.props.onUnmount.call(this,this)},_proto.render=function(){return null},Lifecycle}(React.Component));function Prompt(_ref){var message=_ref.message,_ref=_ref.when,when=void 0===_ref||_ref;return React.createElement(context.Consumer,null,function(context){var method;return context||invariant(!1,"You should not use <Prompt> outside a <Router>"),!when||context.staticContext?null:(method=context.history.block,React.createElement(Lifecycle,{onMount:function(self){self.release=method(message)},onUpdate:function(self,prevProps){prevProps.message!==message&&(self.release(),self.release=method(message))},onUnmount:function(self){self.release()},message:message}))})}var messageType=PropTypes.oneOfType([PropTypes.func,PropTypes.string]),cache=(Prompt.propTypes={when:PropTypes.bool,message:messageType.isRequired},{}),cacheLimit=1e4,cacheCount=0;function generatePath(path,params){return void 0===params&&(params={}),"/"===(path=void 0===path?"/":path)?path:function(path){var generator;return cache[path]||(generator=pathToRegexp.compile(path),cacheCount<cacheLimit&&(cache[path]=generator,cacheCount++),generator)}(path)(params,{pretty:!0})}function Redirect(_ref){var computedMatch=_ref.computedMatch,to=_ref.to,_ref=_ref.push,push=void 0!==_ref&&_ref;return React.createElement(context.Consumer,null,function(context){context||invariant(!1,"You should not use <Redirect> outside a <Router>");var history$1=context.history,context=context.staticContext,method=push?history$1.push:history$1.replace,location=history.createLocation(computedMatch?"string"==typeof to?generatePath(to,computedMatch.params):_extends({},to,{pathname:generatePath(to.pathname,computedMatch.params)}):to);return context?(method(location),null):React.createElement(Lifecycle,{onMount:function(){method(location)},onUpdate:function(self,prevProps){prevProps=history.createLocation(prevProps.to);history.locationsAreEqual(prevProps,_extends({},location,{key:prevProps.key}))||method(location)},to:to})})}Redirect.propTypes={push:PropTypes.bool,from:PropTypes.string,to:PropTypes.oneOfType([PropTypes.string,PropTypes.object]).isRequired};var cache$1={},cacheLimit$1=1e4,cacheCount$1=0;function matchPath(pathname,options){var options=options="string"!=typeof(options=void 0===options?{}:options)&&!Array.isArray(options)?options:{path:options},path=options.path,_options$exact=options.exact,exact=void 0!==_options$exact&&_options$exact,_options$exact=options.strict,strict=void 0!==_options$exact&&_options$exact,_options$exact=options.sensitive,sensitive=void 0!==_options$exact&&_options$exact;return[].concat(path).reduce(function(matched,path){var url,values,regexp;return path||""===path?matched||(regexp=(matched=function(path,options){var keys,cacheKey=""+options.end+options.strict+options.sensitive;return(cacheKey=cache$1[cacheKey]||(cache$1[cacheKey]={}))[path]||(options={regexp:pathToRegexp(path,keys=[],options),keys:keys},cacheCount$1<cacheLimit$1&&(cacheKey[path]=options,cacheCount$1++),options)}(path,{end:exact,strict:strict,sensitive:sensitive})).regexp,matched=matched.keys,!(regexp=regexp.exec(pathname))||(url=regexp[0],values=regexp.slice(1),regexp=pathname===url,exact&&!regexp)?null:{path:path,url:"/"===path&&""===url?"/":url,isExact:regexp,params:matched.reduce(function(memo,key,index){return memo[key.name]=values[index],memo},{})}):null},null)}function isEmptyChildren(children){return 0===React.Children.count(children)}function evalChildrenDev(children,props,path){children=children(props);return warning(void 0!==children,"You returned `undefined` from the `children` function of <Route"+(path?' path="'+path+'"':"")+">, but you should have returned a React element or `null`"),children||null}messageType=function(_React$Component){function Route(){return _React$Component.apply(this,arguments)||this}return _inheritsLoose(Route,_React$Component),Route.prototype.render=function(){var _this=this;return React.createElement(context.Consumer,null,function(context$1){context$1||invariant(!1,"You should not use <Route> outside a <Router>");var location=_this.props.location||context$1.location,location=_extends({},context$1,{location:location,match:_this.props.computedMatch||(_this.props.path?matchPath(location.pathname,_this.props):context$1.match)}),context$1=_this.props,children=context$1.children,component=context$1.component,context$1=context$1.render;return Array.isArray(children)&&isEmptyChildren(children)&&(children=null),React.createElement(context.Provider,{value:location},location.match?children?"function"==typeof children?evalChildrenDev(children,location,_this.props.path):children:component?React.createElement(component,location):context$1?context$1(location):null:"function"==typeof children?evalChildrenDev(children,location,_this.props.path):null)})},Route}(React.Component);function addLeadingSlash(path){return"/"===path.charAt(0)?path:"/"+path}function createURL(location){return"string"==typeof location?location:history.createPath(location)}function staticHandler(methodName){return function(){invariant(!1,"You cannot %s with <StaticRouter>",methodName)}}function noop(){}messageType.propTypes={children:PropTypes.oneOfType([PropTypes.func,PropTypes.node]),component:function(props,propName){if(props[propName]&&!reactIs.isValidElementType(props[propName]))return new Error("Invalid prop 'component' supplied to 'Route': the prop is not a valid React component")},exact:PropTypes.bool,location:PropTypes.object,path:PropTypes.oneOfType([PropTypes.string,PropTypes.arrayOf(PropTypes.string)]),render:PropTypes.func,sensitive:PropTypes.bool,strict:PropTypes.bool},messageType.prototype.componentDidMount=function(){warning(!(this.props.children&&!isEmptyChildren(this.props.children)&&this.props.component),"You should not use <Route component> and <Route children> in the same route; <Route component> will be ignored"),warning(!(this.props.children&&!isEmptyChildren(this.props.children)&&this.props.render),"You should not use <Route render> and <Route children> in the same route; <Route render> will be ignored"),warning(!(this.props.component&&this.props.render),"You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored")},messageType.prototype.componentDidUpdate=function(prevProps){warning(!(this.props.location&&!prevProps.location),'<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.'),warning(!(!this.props.location&&prevProps.location),'<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.')};var StaticRouter=function(_React$Component){function StaticRouter(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_this=_React$Component.call.apply(_React$Component,[this].concat(args))||this).handlePush=function(location){return _this.navigateTo(location,"PUSH")},_this.handleReplace=function(location){return _this.navigateTo(location,"REPLACE")},_this.handleListen=function(){return noop},_this.handleBlock=function(){return noop},_this}_inheritsLoose(StaticRouter,_React$Component);var _proto=StaticRouter.prototype;return _proto.navigateTo=function(location,action){var _this$props=this.props,_this$props$basename=_this$props.basename,_this$props$basename=void 0===_this$props$basename?"":_this$props$basename,_this$props=_this$props.context,_this$props=void 0===_this$props?{}:_this$props;_this$props.action=action,_this$props.location=function(basename,location){return basename?_extends({},location,{pathname:addLeadingSlash(basename)+location.pathname}):location}(_this$props$basename,history.createLocation(location)),_this$props.url=createURL(_this$props.location)},_proto.render=function(){var _this$props2=this.props,_this$props2$basename=_this$props2.basename,basename=void 0===_this$props2$basename?"":_this$props2$basename,_this$props2$basename=_this$props2.context,_this$props2$basename=void 0===_this$props2$basename?{}:_this$props2$basename,_this$props2$location=_this$props2.location,_this$props2$location=void 0===_this$props2$location?"/":_this$props2$location,_this$props2=_objectWithoutPropertiesLoose(_this$props2,["basename","context","location"]),_this$props2$location={createHref:function(path){return addLeadingSlash(basename+createURL(path))},action:"POP",location:function(basename,location){return!basename||(basename=addLeadingSlash(basename),0!==location.pathname.indexOf(basename))?location:_extends({},location,{pathname:location.pathname.substr(basename.length)})}(basename,history.createLocation(_this$props2$location)),push:this.handlePush,replace:this.handleReplace,go:staticHandler("go"),goBack:staticHandler("goBack"),goForward:staticHandler("goForward"),listen:this.handleListen,block:this.handleBlock};return React.createElement(Router,_extends({},_this$props2,{history:_this$props2$location,staticContext:_this$props2$basename}))},StaticRouter}(React.Component),Switch=(StaticRouter.propTypes={basename:PropTypes.string,context:PropTypes.object,location:PropTypes.oneOfType([PropTypes.string,PropTypes.object])},StaticRouter.prototype.componentDidMount=function(){warning(!this.props.history,"<StaticRouter> ignores the history prop. To use a custom history, use `import { Router }` instead of `import { StaticRouter as Router }`.")},function(_React$Component){function Switch(){return _React$Component.apply(this,arguments)||this}return _inheritsLoose(Switch,_React$Component),Switch.prototype.render=function(){var _this=this;return React.createElement(context.Consumer,null,function(context){context||invariant(!1,"You should not use <Switch> outside a <Router>");var element,match,location=_this.props.location||context.location;return React.Children.forEach(_this.props.children,function(child){var path;null==match&&React.isValidElement(child)&&(path=(element=child).props.path||child.props.from,match=path?matchPath(location.pathname,_extends({},child.props,{path:path})):context.match)}),match?React.cloneElement(element,{location:location,computedMatch:match}):null})},Switch}(React.Component));Switch.propTypes={children:PropTypes.node,location:PropTypes.object},Switch.prototype.componentDidUpdate=function(prevProps){warning(!(this.props.location&&!prevProps.location),'<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.'),warning(!(!this.props.location&&prevProps.location),'<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.')};var useContext=React.useContext;function useLocation(){return"function"!=typeof useContext&&invariant(!1,"You must use React >= 16.8 in order to use useLocation()"),useContext(context).location}if("undefined"!=typeof window){var initialBuildName,global$1=window,key="__react_router_build__",buildNames={cjs:"CommonJS",esm:"ES modules",umd:"UMD"};if(global$1[key]&&"cjs"!==global$1[key])throw initialBuildName=buildNames[global$1[key]],new Error("You are loading the "+buildNames.cjs+" build of React Router on a page that is already running the "+initialBuildName+" build, so things won't work right.");global$1[key]="cjs"}exports.MemoryRouter=MemoryRouter,exports.Prompt=Prompt,exports.Redirect=Redirect,exports.Route=messageType,exports.Router=Router,exports.StaticRouter=StaticRouter,exports.Switch=Switch,exports.__HistoryContext=historyContext,exports.__RouterContext=context,exports.generatePath=generatePath,exports.matchPath=matchPath,exports.useHistory=function(){return"function"!=typeof useContext&&invariant(!1,"You must use React >= 16.8 in order to use useHistory()"),useContext(historyContext)},exports.useLocation=useLocation,exports.useParams=function(){"function"!=typeof useContext&&invariant(!1,"You must use React >= 16.8 in order to use useParams()");var match=useContext(context).match;return match?match.params:{}},exports.useRouteMatch=function(path){"function"!=typeof useContext&&invariant(!1,"You must use React >= 16.8 in order to use useRouteMatch()");var location=useLocation(),match=useContext(context).match;return path?matchPath(location.pathname,path):match},exports.withRouter=function(Component){function C(props){var wrappedComponentRef=props.wrappedComponentRef,remainingProps=_objectWithoutPropertiesLoose(props,["wrappedComponentRef"]);return React.createElement(context.Consumer,null,function(context){return context||invariant(!1,"You should not use <"+displayName+" /> outside a <Router>"),React.createElement(Component,_extends({},remainingProps,context,{ref:wrappedComponentRef}))})}var displayName="withRouter("+(Component.displayName||Component.name)+")";return C.displayName=displayName,C.WrappedComponent=Component,C.propTypes={wrappedComponentRef:PropTypes.oneOfType([PropTypes.string,PropTypes.func,PropTypes.object])},hoistStatics(C,Component)}}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{history:653,"hoist-non-react-statics":654,"path-to-regexp":1040,"prop-types":1046,react:1427,"react-is":1385,"tiny-invariant":1696,"tiny-warning":1697}],1423:[function(require,module,exports){!function(global){!function(){"use strict";function _interopDefault(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var React=_interopDefault(require("react")),PropTypes=_interopDefault(require("prop-types")),history=require("history"),invariant=(require("tiny-warning"),_interopDefault(require("tiny-invariant"))),pathToRegexp=_interopDefault(require("path-to-regexp")),hoistStatics=(require("react-is"),_interopDefault(require("hoist-non-react-statics")));function _extends(){return(_extends=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var o,n=arguments[e];for(o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t}).apply(this,arguments)}function _inheritsLoose(t,e){t.prototype=Object.create(e.prototype),_setPrototypeOf(t.prototype.constructor=t,e)}function _setPrototypeOf(t,e){return(_setPrototypeOf=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function _objectWithoutPropertiesLoose(t,e){if(null==t)return{};for(var n,r={},i=Object.keys(t),o=0;o<i.length;o++)n=i[o],0<=e.indexOf(n)||(r[n]=t[n]);return r}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:{};function createNamedContext(t){var e=createContext();return e.displayName=t,e}var n,createContext=React.createContext||function(n,i){var e,o="__create-react-context-"+function(){var t="__global_unique_id__";return commonjsGlobal[t]=(commonjsGlobal[t]||0)+1}()+"__",r=function(r){function t(){for(var t,e=arguments.length,n=new Array(e),o=0;o<e;o++)n[o]=arguments[o];return(t=r.call.apply(r,[this].concat(n))||this).emitter=function(n){var o=[];return{on:function(t){o.push(t)},off:function(e){o=o.filter(function(t){return t!==e})},get:function(){return n},set:function(t,e){n=t,o.forEach(function(t){return t(n,e)})}}}(t.props.value),t}_inheritsLoose(t,r);var e=t.prototype;return e.getChildContext=function(){var t;return(t={})[o]=this.emitter,t},e.componentWillReceiveProps=function(t){var n,o;this.props.value===t.value||function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}(n=this.props.value,o=t.value)||(n="function"==typeof i?i(n,o):1073741823,0==(n|=0))||this.emitter.set(t.value,n)},e.render=function(){return this.props.children},t}(React.Component),t=(r.childContextTypes=((t={})[o]=PropTypes.object.isRequired,t),function(r){function t(){for(var n,t=arguments.length,e=new Array(t),o=0;o<t;o++)e[o]=arguments[o];return(n=r.call.apply(r,[this].concat(e))||this).observedBits=void 0,n.state={value:n.getValue()},n.onUpdate=function(t,e){0!=((0|n.observedBits)&e)&&n.setState({value:n.getValue()})},n}_inheritsLoose(t,r);var e=t.prototype;return e.componentWillReceiveProps=function(t){t=t.observedBits;this.observedBits=null==t?1073741823:t},e.componentDidMount=function(){this.context[o]&&this.context[o].on(this.onUpdate);var t=this.props.observedBits;this.observedBits=null==t?1073741823:t},e.componentWillUnmount=function(){this.context[o]&&this.context[o].off(this.onUpdate)},e.getValue=function(){return this.context[o]?this.context[o].get():n},e.render=function(){return t=this.props.children,(Array.isArray(t)?t[0]:t)(this.state.value);var t},t}(React.Component));return t.contextTypes=((e={})[o]=PropTypes.object,e),{Provider:r,Consumer:t}},historyContext=createNamedContext("Router-History"),context=createNamedContext("Router"),Router=(_inheritsLoose(t,n=React.Component),t.computeRootMatch=function(t){return{path:"/",url:"/",params:{},isExact:"/"===t}},(e=t.prototype).componentDidMount=function(){var e=this;this._isMounted=!0,this.unlisten&&this.unlisten(),this.props.staticContext||(this.unlisten=this.props.history.listen(function(t){e._isMounted&&e.setState({location:t})})),this._pendingLocation&&this.setState({location:this._pendingLocation})},e.componentWillUnmount=function(){this.unlisten&&(this.unlisten(),this._isMounted=!1,this._pendingLocation=null)},e.render=function(){return React.createElement(context.Provider,{value:{history:this.props.history,location:this.state.location,match:t.computeRootMatch(this.state.location.pathname),staticContext:this.props.staticContext}},React.createElement(historyContext.Provider,{children:this.props.children||null,value:this.props.history}))},t),e=function(r){function t(){for(var t,e=arguments.length,n=new Array(e),o=0;o<e;o++)n[o]=arguments[o];return(t=r.call.apply(r,[this].concat(n))||this).history=history.createMemoryHistory(t.props),t}return _inheritsLoose(t,r),t.prototype.render=function(){return React.createElement(Router,{history:this.history,children:this.props.children})},t}(React.Component),Lifecycle=function(t){function e(){return t.apply(this,arguments)||this}_inheritsLoose(e,t);var n=e.prototype;return n.componentDidMount=function(){this.props.onMount&&this.props.onMount.call(this,this)},n.componentDidUpdate=function(t){this.props.onUpdate&&this.props.onUpdate.call(this,this,t)},n.componentWillUnmount=function(){this.props.onUnmount&&this.props.onUnmount.call(this,this)},n.render=function(){return null},e}(React.Component);function t(t){var e;return(e=n.call(this,t)||this).state={location:t.history.location},e._isMounted=!1,e._pendingLocation=null,t.staticContext||(e.unlisten=t.history.listen(function(t){e._pendingLocation=t})),e}var cache={},cacheLimit=1e4,cacheCount=0;function generatePath(t,e){return void 0===e&&(e={}),"/"===(t=void 0===t?"/":t)?t:function(t){var e;return cache[t]||(e=pathToRegexp.compile(t),cacheCount<cacheLimit&&(cache[t]=e,cacheCount++),e)}(t)(e,{pretty:!0})}var cache$1={},cacheLimit$1=1e4,cacheCount$1=0;function matchPath(u,t){var t=t="string"!=typeof(t=void 0===t?{}:t)&&!Array.isArray(t)?t:{path:t},n=t.path,o=t.exact,p=void 0!==o&&o,o=t.strict,h=void 0!==o&&o,o=t.sensitive,l=void 0!==o&&o;return[].concat(n).reduce(function(t,e){var a,c,o;return e||""===e?t||(o=(t=function(t,e){var r,n=""+e.end+e.strict+e.sensitive;return(n=cache$1[n]||(cache$1[n]={}))[t]||(e={regexp:pathToRegexp(t,r=[],e),keys:r},cacheCount$1<cacheLimit$1&&(n[t]=e,cacheCount$1++),e)}(e,{end:p,strict:h,sensitive:l})).regexp,t=t.keys,!(o=o.exec(u))||(a=o[0],c=o.slice(1),o=u===a,p&&!o)?null:{path:e,url:"/"===e&&""===a?"/":a,isExact:o,params:t.reduce(function(t,e,n){return t[e.name]=c[n],t},{})}):null},null)}var Route=function(t){function e(){return t.apply(this,arguments)||this}return _inheritsLoose(e,t),e.prototype.render=function(){var c=this;return React.createElement(context.Consumer,null,function(t){t||invariant(!1);var e=c.props.location||t.location,e=_extends({},t,{location:e,match:c.props.computedMatch||(c.props.path?matchPath(e.pathname,c.props):t.match)}),t=c.props,r=t.children,i=t.component,t=t.render;return Array.isArray(r)&&function(t){return 0===React.Children.count(t)}(r)&&(r=null),React.createElement(context.Provider,{value:e},e.match?r?"function"==typeof r?r(e):r:i?React.createElement(i,e):t?t(e):null:"function"==typeof r?r(e):null)})},e}(React.Component);function addLeadingSlash(t){return"/"===t.charAt(0)?t:"/"+t}function createURL(t){return"string"==typeof t?t:history.createPath(t)}function staticHandler(){return function(){invariant(!1)}}function noop(){}var StaticRouter=function(r){function t(){for(var e,t=arguments.length,n=new Array(t),o=0;o<t;o++)n[o]=arguments[o];return(e=r.call.apply(r,[this].concat(n))||this).handlePush=function(t){return e.navigateTo(t,"PUSH")},e.handleReplace=function(t){return e.navigateTo(t,"REPLACE")},e.handleListen=function(){return noop},e.handleBlock=function(){return noop},e}_inheritsLoose(t,r);var e=t.prototype;return e.navigateTo=function(t,e){var n=this.props,o=n.basename,o=void 0===o?"":o,n=n.context,n=void 0===n?{}:n;n.action=e,n.location=function(t,e){return t?_extends({},e,{pathname:addLeadingSlash(t)+e.pathname}):e}(o,history.createLocation(t)),n.url=createURL(n.location)},e.render=function(){var t=this.props,e=t.basename,n=void 0===e?"":e,e=t.context,e=void 0===e?{}:e,i=t.location,i=void 0===i?"/":i,t=_objectWithoutPropertiesLoose(t,["basename","context","location"]),i={createHref:function(t){return addLeadingSlash(n+createURL(t))},action:"POP",location:function(t,e){return!t||(t=addLeadingSlash(t),0!==e.pathname.indexOf(t))?e:_extends({},e,{pathname:e.pathname.substr(t.length)})}(n,history.createLocation(i)),push:this.handlePush,replace:this.handleReplace,go:staticHandler(),goBack:staticHandler(),goForward:staticHandler(),listen:this.handleListen,block:this.handleBlock};return React.createElement(Router,_extends({},t,{history:i,staticContext:e}))},t}(React.Component),Switch=function(t){function e(){return t.apply(this,arguments)||this}return _inheritsLoose(e,t),e.prototype.render=function(){var t=this;return React.createElement(context.Consumer,null,function(n){n||invariant(!1);var o,r,i=t.props.location||n.location;return React.Children.forEach(t.props.children,function(t){var e;null==r&&React.isValidElement(t)&&(e=(o=t).props.path||t.props.from,r=e?matchPath(i.pathname,_extends({},t.props,{path:e})):n.match)}),r?React.cloneElement(o,{location:i,computedMatch:r}):null})},e}(React.Component);var useContext=React.useContext;function useLocation(){return useContext(context).location}exports.MemoryRouter=e,exports.Prompt=function(t){var o=t.message,r=void 0===(t=t.when)||t;return React.createElement(context.Consumer,null,function(t){var n;return t||invariant(!1),!r||t.staticContext?null:(n=t.history.block,React.createElement(Lifecycle,{onMount:function(t){t.release=n(o)},onUpdate:function(t,e){e.message!==o&&(t.release(),t.release=n(o))},onUnmount:function(t){t.release()},message:o}))})},exports.Redirect=function(t){var i=t.computedMatch,a=t.to,c=void 0!==(t=t.push)&&t;return React.createElement(context.Consumer,null,function(t){t||invariant(!1);var e=t.history,t=t.staticContext,o=c?e.push:e.replace,r=history.createLocation(i?"string"==typeof a?generatePath(a,i.params):_extends({},a,{pathname:generatePath(a.pathname,i.params)}):a);return t?(o(r),null):React.createElement(Lifecycle,{onMount:function(){o(r)},onUpdate:function(t,e){e=history.createLocation(e.to);history.locationsAreEqual(e,_extends({},r,{key:e.key}))||o(r)},to:a})})},exports.Route=Route,exports.Router=Router,exports.StaticRouter=StaticRouter,exports.Switch=Switch,exports.__HistoryContext=historyContext,exports.__RouterContext=context,exports.generatePath=generatePath,exports.matchPath=matchPath,exports.useHistory=function(){return useContext(historyContext)},exports.useLocation=useLocation,exports.useParams=function(){var t=useContext(context).match;return t?t.params:{}},exports.useRouteMatch=function(t){var e=useLocation(),n=useContext(context).match;return t?matchPath(e.pathname,t):n},exports.withRouter=function(o){function t(t){var e=t.wrappedComponentRef,n=_objectWithoutPropertiesLoose(t,["wrappedComponentRef"]);return React.createElement(context.Consumer,null,function(t){return t||invariant(!1),React.createElement(o,_extends({},n,t,{ref:e}))})}var e="withRouter("+(o.displayName||o.name)+")";return t.displayName=e,t.WrappedComponent=o,hoistStatics(t,o)}}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{history:653,"hoist-non-react-statics":654,"path-to-regexp":1040,"prop-types":1046,react:1427,"react-is":1385,"tiny-invariant":1696,"tiny-warning":1697}],1424:[function(require,module,exports){"use strict";module.exports=require("./cjs/react-router.min.js")},{"./cjs/react-router.js":1422,"./cjs/react-router.min.js":1423}],1425:[function(require,module,exports){},{"object-assign":1032,"prop-types/checkPropTypes":1043}],1426:[function(require,module,exports){"use strict";var l=require("object-assign"),require="function"==typeof Symbol&&Symbol.for,p=require?Symbol.for("react.element"):60103,q=require?Symbol.for("react.portal"):60106,r=require?Symbol.for("react.fragment"):60107,t=require?Symbol.for("react.strict_mode"):60108,u=require?Symbol.for("react.profiler"):60114,v=require?Symbol.for("react.provider"):60109,w=require?Symbol.for("react.context"):60110,x=require?Symbol.for("react.forward_ref"):60112,y=require?Symbol.for("react.suspense"):60113,z=require?Symbol.for("react.memo"):60115,A=require?Symbol.for("react.lazy"):60116,B="function"==typeof Symbol&&Symbol.iterator;function C(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var D={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E={};function F(a,b,c){this.props=a,this.context=b,this.refs=E,this.updater=c||D}function G(){}function H(a,b,c){this.props=a,this.context=b,this.refs=E,this.updater=c||D}F.prototype.isReactComponent={},F.prototype.setState=function(a,b){if("object"!=typeof a&&"function"!=typeof a&&null!=a)throw Error(C(85));this.updater.enqueueSetState(this,a,b,"setState")},F.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")},G.prototype=F.prototype;var require=H.prototype=new G,J=(require.constructor=H,l(require,F.prototype),require.isPureReactComponent=!0,{current:null}),K=Object.prototype.hasOwnProperty,L={key:!0,ref:!0,__self:!0,__source:!0};function M(a,b,c){var e,d={},g=null,k=null;if(null!=b)for(e in void 0!==b.ref&&(k=b.ref),void 0!==b.key&&(g=""+b.key),b)K.call(b,e)&&!L.hasOwnProperty(e)&&(d[e]=b[e]);var f=arguments.length-2;if(1===f)d.children=c;else if(1<f){for(var h=Array(f),m=0;m<f;m++)h[m]=arguments[m+2];d.children=h}if(a&&a.defaultProps)for(e in f=a.defaultProps)void 0===d[e]&&(d[e]=f[e]);return{$$typeof:p,type:a,key:g,ref:k,props:d,_owner:J.current}}function O(a){return"object"==typeof a&&null!==a&&a.$$typeof===p}var P=/\/+/g,Q=[];function R(a,b,c,e){var d;return Q.length?((d=Q.pop()).result=a,d.keyPrefix=b,d.func=c,d.context=e,d.count=0,d):{result:a,keyPrefix:b,func:c,context:e,count:0}}function S(a){a.result=null,a.keyPrefix=null,a.func=null,a.context=null,a.count=0,Q.length<10&&Q.push(a)}function V(a,b,c){return null==a?0:function T(a,b,c,e){var g=!1;if(null===(a="undefined"!=(d=typeof a)&&"boolean"!==d?a:null))g=!0;else switch(d){case"string":case"number":g=!0;break;case"object":switch(a.$$typeof){case p:case q:g=!0}}if(g)return c(e,a,""===b?"."+U(a,0):b),1;if(g=0,b=""===b?".":b+":",Array.isArray(a))for(var k=0;k<a.length;k++){var d,f=b+U(d=a[k],k);g+=T(d,f,c,e)}else if("function"==typeof(f=null!==a&&"object"==typeof a&&"function"==typeof(f=B&&a[B]||a["@@iterator"])?f:null))for(a=f.call(a),k=0;!(d=a.next()).done;)g+=T(d=d.value,f=b+U(d,k++),c,e);else if("object"===d)throw c=""+a,Error(C(31,"[object Object]"===c?"object with keys {"+Object.keys(a).join(", ")+"}":c,""));return g}(a,"",b,c)}function U(a,b){return"object"==typeof a&&null!==a&&null!=a.key?function(a){var b={"=":"=0",":":"=2"};return"$"+(""+a).replace(/[=:]/g,function(a){return b[a]})}(a.key):b.toString(36)}function W(a,b){a.func.call(a.context,b,a.count++)}function aa(a,b,c){var e=a.result,d=a.keyPrefix;a=a.func.call(a.context,b,a.count++),Array.isArray(a)?X(a,e,c,function(a){return a}):null!=a&&(O(a)&&(a=function(a,b){return{$$typeof:p,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}(a,d+(!a.key||b&&b.key===a.key?"":(""+a.key).replace(P,"$&/")+"/")+c)),e.push(a))}function X(a,b,c,e,d){var g="";V(a,aa,b=R(b,g=null!=c?(""+c).replace(P,"$&/")+"/":g,e,d)),S(b)}var Y={current:null};function Z(){var a=Y.current;if(null===a)throw Error(C(321));return a}require={ReactCurrentDispatcher:Y,ReactCurrentBatchConfig:{suspense:null},ReactCurrentOwner:J,IsSomeRendererActing:{current:!1},assign:l};exports.Children={map:function(a,b,c){return null==a||X(a,a=[],null,b,c),a},forEach:function(a,b,c){if(null==a)return a;V(a,W,b=R(null,null,b,c)),S(b)},count:function(a){return V(a,function(){return null},null)},toArray:function(a){var b=[];return X(a,b,null,function(a){return a}),b},only:function(a){if(O(a))return a;throw Error(C(143))}},exports.Component=F,exports.Fragment=r,exports.Profiler=u,exports.PureComponent=H,exports.StrictMode=t,exports.Suspense=y,exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=require,exports.cloneElement=function(a,b,c){if(null==a)throw Error(C(267,a));var e=l({},a.props),d=a.key,g=a.ref,k=a._owner;if(null!=b)for(h in void 0!==b.ref&&(g=b.ref,k=J.current),void 0!==b.key&&(d=""+b.key),a.type&&a.type.defaultProps&&(f=a.type.defaultProps),b)K.call(b,h)&&!L.hasOwnProperty(h)&&(e[h]=(void 0===b[h]&&void 0!==f?f:b)[h]);var h=arguments.length-2;if(1===h)e.children=c;else if(1<h){for(var f=Array(h),m=0;m<h;m++)f[m]=arguments[m+2];e.children=f}return{$$typeof:p,type:a.type,key:d,ref:g,props:e,_owner:k}},exports.createContext=function(a,b){return(a={$$typeof:w,_calculateChangedBits:b=void 0===b?null:b,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null}).Provider={$$typeof:v,_context:a},a.Consumer=a},exports.createElement=M,exports.createFactory=function(a){var b=M.bind(null,a);return b.type=a,b},exports.createRef=function(){return{current:null}},exports.forwardRef=function(a){return{$$typeof:x,render:a}},exports.isValidElement=O,exports.lazy=function(a){return{$$typeof:A,_ctor:a,_status:-1,_result:null}},exports.memo=function(a,b){return{$$typeof:z,type:a,compare:void 0===b?null:b}},exports.useCallback=function(a,b){return Z().useCallback(a,b)},exports.useContext=function(a,b){return Z().useContext(a,b)},exports.useDebugValue=function(){},exports.useEffect=function(a,b){return Z().useEffect(a,b)},exports.useImperativeHandle=function(a,b,c){return Z().useImperativeHandle(a,b,c)},exports.useLayoutEffect=function(a,b){return Z().useLayoutEffect(a,b)},exports.useMemo=function(a,b){return Z().useMemo(a,b)},exports.useReducer=function(a,b,c){return Z().useReducer(a,b,c)},exports.useRef=function(a){return Z().useRef(a)},exports.useState=function(a){return Z().useState(a)},exports.version="16.14.0"},{"object-assign":1032}],1427:[function(require,module,exports){"use strict";module.exports=require("./cjs/react.production.min.js")},{"./cjs/react.development.js":1425,"./cjs/react.production.min.js":1426}],1428:[function(require,module,exports){"use strict";function createThunkMiddleware(extraArgument){return function(_ref){var dispatch=_ref.dispatch,getState=_ref.getState;return function(next){return function(action){return"function"==typeof action?action(dispatch,getState,extraArgument):next(action)}}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var thunk=createThunkMiddleware();thunk.withExtraArgument=createThunkMiddleware,exports.default=thunk},{}],1429:[function(require,module,exports){!function(process){!function(){"use strict";function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var _objectSpread__default=_interopDefaultLegacy(require("@babel/runtime/helpers/objectSpread2"));function formatProdErrorMessage(code){return"Minified Redux error #"+code+"; visit https://redux.js.org/Errors?code="+code+" for the full message or use the non-minified dev environment for full errors. "}function randomString(){return Math.random().toString(36).substring(7).split("").join(".")}var $$observable="function"==typeof Symbol&&Symbol.observable||"@@observable",ActionTypes={INIT:"@@redux/INIT"+randomString(),REPLACE:"@@redux/REPLACE"+randomString(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+randomString()}};function isPlainObject(obj){if("object"==typeof obj&&null!==obj){for(var proto=obj;null!==Object.getPrototypeOf(proto);)proto=Object.getPrototypeOf(proto);return Object.getPrototypeOf(obj)===proto}}function miniKindOf(val){if(void 0===val)return"undefined";if(null===val)return"null";var type=typeof val;switch(type){case"boolean":case"string":case"number":case"symbol":case"function":return type}if(Array.isArray(val))return"array";if(function(val){return val instanceof Date||"function"==typeof val.toDateString&&"function"==typeof val.getDate&&"function"==typeof val.setDate}(val))return"date";if(function(val){return val instanceof Error||"string"==typeof val.message&&val.constructor&&"number"==typeof val.constructor.stackTraceLimit}(val))return"error";var constructorName=function(val){return"function"==typeof val.constructor?val.constructor.name:null}(val);switch(constructorName){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return constructorName}return type.slice(8,-1).toLowerCase().replace(/\s/g,"")}function kindOf(val){var typeOfVal=typeof val;return typeOfVal="production"!==process.env.NODE_ENV?miniKindOf(val):typeOfVal}function createStore(reducer,preloadedState,enhancer){if("function"==typeof preloadedState&&"function"==typeof enhancer||"function"==typeof enhancer&&"function"==typeof arguments[3])throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(0):"It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof preloadedState&&void 0===enhancer&&(enhancer=preloadedState,preloadedState=void 0),void 0!==enhancer){if("function"!=typeof enhancer)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(1):"Expected the enhancer to be a function. Instead, received: '"+kindOf(enhancer)+"'");return enhancer(createStore)(reducer,preloadedState)}if("function"!=typeof reducer)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(2):"Expected the root reducer to be a function. Instead, received: '"+kindOf(reducer)+"'");var currentReducer=reducer,currentState=preloadedState,currentListeners=[],nextListeners=currentListeners,isDispatching=!1;function ensureCanMutateNextListeners(){nextListeners===currentListeners&&(nextListeners=currentListeners.slice())}function getState(){if(isDispatching)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(3):"You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return currentState}function subscribe(listener){if("function"!=typeof listener)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(4):"Expected the listener to be a function. Instead, received: '"+kindOf(listener)+"'");if(isDispatching)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(5):"You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");var isSubscribed=!0;return ensureCanMutateNextListeners(),nextListeners.push(listener),function(){if(isSubscribed){if(isDispatching)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(6):"You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");isSubscribed=!1,ensureCanMutateNextListeners();var index=nextListeners.indexOf(listener);nextListeners.splice(index,1),currentListeners=null}}}function dispatch(action){if(!isPlainObject(action))throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(7):"Actions must be plain objects. Instead, the actual type was: '"+kindOf(action)+"'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.");if(void 0===action.type)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(8):'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if(isDispatching)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(9):"Reducers may not dispatch actions.");try{isDispatching=!0,currentState=currentReducer(currentState,action)}finally{isDispatching=!1}for(var listeners=currentListeners=nextListeners,i=0;i<listeners.length;i++)(0,listeners[i])();return action}return dispatch({type:ActionTypes.INIT}),(enhancer={dispatch:dispatch,subscribe:subscribe,getState:getState,replaceReducer:function(nextReducer){if("function"!=typeof nextReducer)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(10):"Expected the nextReducer to be a function. Instead, received: '"+kindOf(nextReducer));currentReducer=nextReducer,dispatch({type:ActionTypes.REPLACE})}})[$$observable]=function(){var outerSubscribe=subscribe,_ref={subscribe:function(observer){if("object"!=typeof observer||null===observer)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(11):"Expected the observer to be an object. Instead, received: '"+kindOf(observer)+"'");function observeState(){observer.next&&observer.next(getState())}return observeState(),{unsubscribe:outerSubscribe(observeState)}}};return _ref[$$observable]=function(){return this},_ref},enhancer}var legacy_createStore=createStore;function warning(message){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(message);try{throw new Error(message)}catch(e){}}function bindActionCreator(actionCreator,dispatch){return function(){return dispatch(actionCreator.apply(this,arguments))}}function compose(){for(var _len=arguments.length,funcs=new Array(_len),_key=0;_key<_len;_key++)funcs[_key]=arguments[_key];return 0===funcs.length?function(arg){return arg}:1===funcs.length?funcs[0]:funcs.reduce(function(a,b){return function(){return a(b.apply(void 0,arguments))}})}exports.__DO_NOT_USE__ActionTypes=ActionTypes,exports.applyMiddleware=function(){for(var _len=arguments.length,middlewares=new Array(_len),_key=0;_key<_len;_key++)middlewares[_key]=arguments[_key];return function(createStore){return function(){var store=createStore.apply(void 0,arguments),_dispatch=function(){throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(15):"Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},middlewareAPI={getState:store.getState,dispatch:function(){return _dispatch.apply(void 0,arguments)}},chain=middlewares.map(function(middleware){return middleware(middlewareAPI)}),_dispatch=compose.apply(void 0,chain)(store.dispatch);return _objectSpread__default.default(_objectSpread__default.default({},store),{},{dispatch:_dispatch})}}},exports.bindActionCreators=function(actionCreators,dispatch){if("function"==typeof actionCreators)return bindActionCreator(actionCreators,dispatch);if("object"!=typeof actionCreators||null===actionCreators)throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(16):"bindActionCreators expected an object or a function, but instead received: '"+kindOf(actionCreators)+'\'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');var key,boundActionCreators={};for(key in actionCreators){var actionCreator=actionCreators[key];"function"==typeof actionCreator&&(boundActionCreators[key]=bindActionCreator(actionCreator,dispatch))}return boundActionCreators},exports.combineReducers=function(reducers){for(var reducerKeys=Object.keys(reducers),finalReducers={},i=0;i<reducerKeys.length;i++){var key=reducerKeys[i];"production"!==process.env.NODE_ENV&&void 0===reducers[key]&&warning('No reducer provided for key "'+key+'"'),"function"==typeof reducers[key]&&(finalReducers[key]=reducers[key])}var unexpectedKeyCache,shapeAssertionError,finalReducerKeys=Object.keys(finalReducers);"production"!==process.env.NODE_ENV&&(unexpectedKeyCache={});try{!function(reducers){Object.keys(reducers).forEach(function(key){var reducer=reducers[key];if(void 0===reducer(void 0,{type:ActionTypes.INIT}))throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(12):'The slice reducer for key "'+key+"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.");if(void 0===reducer(void 0,{type:ActionTypes.PROBE_UNKNOWN_ACTION()}))throw new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(13):'The slice reducer for key "'+key+"\" returned undefined when probed with a random type. Don't try to handle '"+ActionTypes.INIT+'\' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.')})}(finalReducers)}catch(e){shapeAssertionError=e}return function(state,action){if(void 0===state&&(state={}),shapeAssertionError)throw shapeAssertionError;"production"!==process.env.NODE_ENV&&(warningMessage=function(inputState,reducers,action,unexpectedKeyCache){var unexpectedKeys,reducerKeys=Object.keys(reducers),argumentName=action&&action.type===ActionTypes.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";return 0===reducerKeys.length?"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.":isPlainObject(inputState)?((unexpectedKeys=Object.keys(inputState).filter(function(key){return!reducers.hasOwnProperty(key)&&!unexpectedKeyCache[key]})).forEach(function(key){unexpectedKeyCache[key]=!0}),(!action||action.type!==ActionTypes.REPLACE)&&0<unexpectedKeys.length?"Unexpected "+(1<unexpectedKeys.length?"keys":"key")+' "'+unexpectedKeys.join('", "')+'" found in '+argumentName+'. Expected to find one of the known reducer keys instead: "'+reducerKeys.join('", "')+'". Unexpected keys will be ignored.':void 0):"The "+argumentName+' has unexpected type of "'+kindOf(inputState)+'". Expected argument to be an object with the following keys: "'+reducerKeys.join('", "')+'"'}(state,finalReducers,action,unexpectedKeyCache))&&warning(warningMessage);for(var warningMessage,hasChanged=!1,nextState={},_i=0;_i<finalReducerKeys.length;_i++){var actionType,_key=finalReducerKeys[_i],reducer=finalReducers[_key],previousStateForKey=state[_key],reducer=reducer(previousStateForKey,action);if(void 0===reducer)throw actionType=action&&action.type,new Error("production"===process.env.NODE_ENV?formatProdErrorMessage(14):"When called with an action of type "+(actionType?'"'+String(actionType)+'"':"(unknown type)")+', the slice reducer for key "'+_key+'" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.');nextState[_key]=reducer,hasChanged=hasChanged||reducer!==previousStateForKey}return(hasChanged=hasChanged||finalReducerKeys.length!==Object.keys(state).length)?nextState:state}},exports.compose=compose,exports.createStore=createStore,exports.legacy_createStore=legacy_createStore}.call(this)}.call(this,require("_process"))},{"@babel/runtime/helpers/objectSpread2":20,_process:1042}],1430:[function(require,module,exports){module=function(exports){"use strict";var undefined,Op=Object.prototype,hasOwn=Op.hasOwnProperty,defineProperty=Object.defineProperty||function(obj,key,desc){obj[key]=desc.value},$Symbol="function"==typeof Symbol?Symbol:{},iteratorSymbol=$Symbol.iterator||"@@iterator",asyncIteratorSymbol=$Symbol.asyncIterator||"@@asyncIterator",toStringTagSymbol=$Symbol.toStringTag||"@@toStringTag";function define(obj,key,value){return Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}),obj[key]}try{define({},"")}catch(err){define=function(obj,key,value){return obj[key]=value}}function wrap(innerFn,outerFn,self,tryLocsList){outerFn=outerFn&&outerFn.prototype instanceof Generator?outerFn:Generator,outerFn=Object.create(outerFn.prototype),tryLocsList=new Context(tryLocsList||[]);return defineProperty(outerFn,"_invoke",{value:function(innerFn,self,context){var state=GenStateSuspendedStart;return function(method,arg){if(state===GenStateExecuting)throw new Error("Generator is already running");if(state===GenStateCompleted){if("throw"===method)throw arg;return doneResult()}for(context.method=method,context.arg=arg;;){var delegate=context.delegate;if(delegate){delegate=function maybeInvokeDelegate(delegate,context){var methodName=context.method;var method=delegate.iterator[methodName];if(method===undefined)return context.delegate=null,"throw"===methodName&&delegate.iterator.return&&(context.method="return",context.arg=undefined,maybeInvokeDelegate(delegate,context),"throw"===context.method)||"return"!==methodName&&(context.method="throw",context.arg=new TypeError("The iterator does not provide a '"+methodName+"' method")),ContinueSentinel;methodName=tryCatch(method,delegate.iterator,context.arg);if("throw"===methodName.type)return context.method="throw",context.arg=methodName.arg,context.delegate=null,ContinueSentinel;method=methodName.arg;if(!method)return context.method="throw",context.arg=new TypeError("iterator result is not an object"),context.delegate=null,ContinueSentinel;{if(!method.done)return method;context[delegate.resultName]=method.value,context.next=delegate.nextLoc,"return"!==context.method&&(context.method="next",context.arg=undefined)}context.delegate=null;return ContinueSentinel}(delegate,context);if(delegate){if(delegate===ContinueSentinel)continue;return delegate}}if("next"===context.method)context.sent=context._sent=context.arg;else if("throw"===context.method){if(state===GenStateSuspendedStart)throw state=GenStateCompleted,context.arg;context.dispatchException(context.arg)}else"return"===context.method&&context.abrupt("return",context.arg);state=GenStateExecuting;delegate=tryCatch(innerFn,self,context);if("normal"===delegate.type){if(state=context.done?GenStateCompleted:GenStateSuspendedYield,delegate.arg!==ContinueSentinel)return{value:delegate.arg,done:context.done}}else"throw"===delegate.type&&(state=GenStateCompleted,context.method="throw",context.arg=delegate.arg)}}}(innerFn,self,tryLocsList)}),outerFn}function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}exports.wrap=wrap;var GenStateSuspendedStart="suspendedStart",GenStateSuspendedYield="suspendedYield",GenStateExecuting="executing",GenStateCompleted="completed",ContinueSentinel={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var $Symbol={},getProto=(define($Symbol,iteratorSymbol,function(){return this}),Object.getPrototypeOf),getProto=getProto&&getProto(getProto(values([]))),Gp=(getProto&&getProto!==Op&&hasOwn.call(getProto,iteratorSymbol)&&($Symbol=getProto),GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create($Symbol));function defineIteratorMethods(prototype){["next","throw","return"].forEach(function(method){define(prototype,method,function(arg){return this._invoke(method,arg)})})}function AsyncIterator(generator,PromiseImpl){var previousPromise;defineProperty(this,"_invoke",{value:function(method,arg){function callInvokeWithMethodAndArg(){return new PromiseImpl(function(resolve,reject){!function invoke(method,arg,resolve,reject){var result,method=tryCatch(generator[method],generator,arg);if("throw"!==method.type)return(arg=(result=method.arg).value)&&"object"==typeof arg&&hasOwn.call(arg,"__await")?PromiseImpl.resolve(arg.__await).then(function(value){invoke("next",value,resolve,reject)},function(err){invoke("throw",err,resolve,reject)}):PromiseImpl.resolve(arg).then(function(unwrapped){result.value=unwrapped,resolve(result)},function(error){return invoke("throw",error,resolve,reject)});reject(method.arg)}(method,arg,resolve,reject)})}return previousPromise=previousPromise?previousPromise.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}})}function pushTryEntry(locs){var entry={tryLoc:locs[0]};1 in locs&&(entry.catchLoc=locs[1]),2 in locs&&(entry.finallyLoc=locs[2],entry.afterLoc=locs[3]),this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal",delete record.arg,entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}],tryLocsList.forEach(pushTryEntry,this),this.reset(!0)}function values(iterable){if(iterable){var i,iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod)return iteratorMethod.call(iterable);if("function"==typeof iterable.next)return iterable;if(!isNaN(iterable.length))return i=-1,(iteratorMethod=function next(){for(;++i<iterable.length;)if(hasOwn.call(iterable,i))return next.value=iterable[i],next.done=!1,next;return next.value=undefined,next.done=!0,next}).next=iteratorMethod}return{next:doneResult}}function doneResult(){return{value:undefined,done:!0}}return defineProperty(Gp,"constructor",{value:GeneratorFunction.prototype=GeneratorFunctionPrototype,configurable:!0}),defineProperty(GeneratorFunctionPrototype,"constructor",{value:GeneratorFunction,configurable:!0}),GeneratorFunction.displayName=define(GeneratorFunctionPrototype,toStringTagSymbol,"GeneratorFunction"),exports.isGeneratorFunction=function(genFun){genFun="function"==typeof genFun&&genFun.constructor;return!!genFun&&(genFun===GeneratorFunction||"GeneratorFunction"===(genFun.displayName||genFun.name))},exports.mark=function(genFun){return Object.setPrototypeOf?Object.setPrototypeOf(genFun,GeneratorFunctionPrototype):(genFun.__proto__=GeneratorFunctionPrototype,define(genFun,toStringTagSymbol,"GeneratorFunction")),genFun.prototype=Object.create(Gp),genFun},exports.awrap=function(arg){return{__await:arg}},defineIteratorMethods(AsyncIterator.prototype),define(AsyncIterator.prototype,asyncIteratorSymbol,function(){return this}),exports.AsyncIterator=AsyncIterator,exports.async=function(innerFn,outerFn,self,tryLocsList,PromiseImpl){void 0===PromiseImpl&&(PromiseImpl=Promise);var iter=new AsyncIterator(wrap(innerFn,outerFn,self,tryLocsList),PromiseImpl);return exports.isGeneratorFunction(outerFn)?iter:iter.next().then(function(result){return result.done?result.value:iter.next()})},defineIteratorMethods(Gp),define(Gp,toStringTagSymbol,"Generator"),define(Gp,iteratorSymbol,function(){return this}),define(Gp,"toString",function(){return"[object Generator]"}),exports.keys=function(val){var key,object=Object(val),keys=[];for(key in object)keys.push(key);return keys.reverse(),function next(){for(;keys.length;){var key=keys.pop();if(key in object)return next.value=key,next.done=!1,next}return next.done=!0,next}},exports.values=values,Context.prototype={constructor:Context,reset:function(skipTempReset){if(this.prev=0,this.next=0,this.sent=this._sent=undefined,this.done=!1,this.delegate=null,this.method="next",this.arg=undefined,this.tryEntries.forEach(resetTryEntry),!skipTempReset)for(var name in this)"t"===name.charAt(0)&&hasOwn.call(this,name)&&!isNaN(+name.slice(1))&&(this[name]=undefined)},stop:function(){this.done=!0;var rootRecord=this.tryEntries[0].completion;if("throw"===rootRecord.type)throw rootRecord.arg;return this.rval},dispatchException:function(exception){if(this.done)throw exception;var context=this;function handle(loc,caught){return record.type="throw",record.arg=exception,context.next=loc,caught&&(context.method="next",context.arg=undefined),!!caught}for(var i=this.tryEntries.length-1;0<=i;--i){var entry=this.tryEntries[i],record=entry.completion;if("root"===entry.tryLoc)return handle("end");if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc"),hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc)return handle(entry.catchLoc,!0);if(this.prev<entry.finallyLoc)return handle(entry.finallyLoc)}else if(hasCatch){if(this.prev<entry.catchLoc)return handle(entry.catchLoc,!0)}else{if(!hasFinally)throw new Error("try statement without catch or finally");if(this.prev<entry.finallyLoc)return handle(entry.finallyLoc)}}}},abrupt:function(type,arg){for(var i=this.tryEntries.length-1;0<=i;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev<entry.finallyLoc){var finallyEntry=entry;break}}var record=(finallyEntry=finallyEntry&&("break"===type||"continue"===type)&&finallyEntry.tryLoc<=arg&&arg<=finallyEntry.finallyLoc?null:finallyEntry)?finallyEntry.completion:{};return record.type=type,record.arg=arg,finallyEntry?(this.method="next",this.next=finallyEntry.finallyLoc,ContinueSentinel):this.complete(record)},complete:function(record,afterLoc){if("throw"===record.type)throw record.arg;return"break"===record.type||"continue"===record.type?this.next=record.arg:"return"===record.type?(this.rval=this.arg=record.arg,this.method="return",this.next="end"):"normal"===record.type&&afterLoc&&(this.next=afterLoc),ContinueSentinel},finish:function(finallyLoc){for(var i=this.tryEntries.length-1;0<=i;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc)return this.complete(entry.completion,entry.afterLoc),resetTryEntry(entry),ContinueSentinel}},catch:function(tryLoc){for(var i=this.tryEntries.length-1;0<=i;--i){var record,thrown,entry=this.tryEntries[i];if(entry.tryLoc===tryLoc)return"throw"===(record=entry.completion).type&&(thrown=record.arg,resetTryEntry(entry)),thrown}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){return this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc},"next"===this.method&&(this.arg=undefined),ContinueSentinel}},exports}("object"==typeof module?module.exports:{});try{regeneratorRuntime=module}catch(accidentalStrictMode){"object"==typeof globalThis?globalThis.regeneratorRuntime=module:Function("r","regeneratorRuntime = r")(module)}},{}],1431:[function(require,module,exports){"use strict";var require=require("functions-have-names").functionsHaveConfigurableNames(),$Object=Object,$TypeError=TypeError;module.exports=function(){if(null!=this&&this!==$Object(this))throw new $TypeError("RegExp.prototype.flags getter called on non-object");var result="";return this.hasIndices&&(result+="d"),this.global&&(result+="g"),this.ignoreCase&&(result+="i"),this.multiline&&(result+="m"),this.dotAll&&(result+="s"),this.unicode&&(result+="u"),this.sticky&&(result+="y"),result},require&&Object.defineProperty&&Object.defineProperty(module.exports,"name",{value:"get flags"})},{"functions-have-names":643}],1432:[function(require,module,exports){"use strict";var define=require("define-properties"),callBind=require("call-bind"),implementation=require("./implementation"),getPolyfill=require("./polyfill"),require=require("./shim"),callBind=callBind(getPolyfill());define(callBind,{getPolyfill:getPolyfill,implementation:implementation,shim:require}),module.exports=callBind},{"./implementation":1431,"./polyfill":1433,"./shim":1434,"call-bind":115,"define-properties":639}],1433:[function(require,module,exports){"use strict";var implementation=require("./implementation"),supportsDescriptors=require("define-properties").supportsDescriptors,$gOPD=Object.getOwnPropertyDescriptor;module.exports=function(){if(supportsDescriptors&&"gim"===/a/gim.flags){var descriptor=$gOPD(RegExp.prototype,"flags");if(descriptor&&"function"==typeof descriptor.get&&"boolean"==typeof RegExp.prototype.dotAll&&"boolean"==typeof RegExp.prototype.hasIndices){var calls="",o={};if(Object.defineProperty(o,"hasIndices",{get:function(){calls+="d"}}),Object.defineProperty(o,"sticky",{get:function(){calls+="y"}}),"dy"===calls)return descriptor.get}}return implementation}},{"./implementation":1431,"define-properties":639}],1434:[function(require,module,exports){"use strict";var supportsDescriptors=require("define-properties").supportsDescriptors,getPolyfill=require("./polyfill"),gOPD=Object.getOwnPropertyDescriptor,defineProperty=Object.defineProperty,TypeErr=TypeError,getProto=Object.getPrototypeOf,regex=/a/;module.exports=function(){var polyfill,proto,descriptor;if(supportsDescriptors&&getProto)return polyfill=getPolyfill(),proto=getProto(regex),(descriptor=gOPD(proto,"flags"))&&descriptor.get===polyfill||defineProperty(proto,"flags",{configurable:!0,enumerable:!1,get:polyfill}),polyfill;throw new TypeErr("RegExp.prototype.flags requires a true ES5 environment that supports property descriptors")}},{"./polyfill":1433,"define-properties":639}],1435:[function(require,module,exports){"use strict";function isAbsolute(pathname){return"/"===pathname.charAt(0)}function spliceOne(list,index){for(var i=index,k=i+1,n=list.length;k<n;i+=1,k+=1)list[i]=list[k];list.pop()}module.exports=function(to,from){void 0===from&&(from="");var toParts=to&&to.split("/")||[],fromParts=from&&from.split("/")||[],isToAbs=to&&isAbsolute(to),from=from&&isAbsolute(from),isToAbs=isToAbs||from;if(to&&isAbsolute(to)?fromParts=toParts:toParts.length&&(fromParts.pop(),fromParts=fromParts.concat(toParts)),!fromParts.length)return"/";to=!!fromParts.length&&("."===(from=fromParts[fromParts.length-1])||".."===from||""===from);for(var up=0,i=fromParts.length;0<=i;i--){var part=fromParts[i];"."===part?spliceOne(fromParts,i):".."===part?(spliceOne(fromParts,i),up++):up&&(spliceOne(fromParts,i),up--)}if(!isToAbs)for(;up--;)fromParts.unshift("..");return!isToAbs||""===fromParts[0]||fromParts[0]&&isAbsolute(fromParts[0])||fromParts.unshift(""),toParts=fromParts.join("/"),to&&"/"!==toParts.substr(-1)&&(toParts+="/"),toParts}},{}],1436:[function(require,module,exports){"use strict";function isAbsolute(e){return"/"===e.charAt(0)}function spliceOne(e,t){for(var s=t,n=s+1,i=e.length;n<i;s+=1,n+=1)e[s]=e[n];e.pop()}module.exports=function(e,t){void 0===t&&(t="");var n=e&&e.split("/")||[],i=t&&t.split("/")||[],l=e&&isAbsolute(e),t=t&&isAbsolute(t),l=l||t;if(e&&isAbsolute(e)?i=n:n.length&&(i.pop(),i=i.concat(n)),!i.length)return"/";e=!!i.length&&("."===(t=i[i.length-1])||".."===t||""===t);for(var a=0,c=i.length;0<=c;c--){var f=i[c];"."===f?spliceOne(i,c):".."===f?(spliceOne(i,c),a++):a&&(spliceOne(i,c),a--)}if(!l)for(;a--;)i.unshift("..");return!l||""===i[0]||i[0]&&isAbsolute(i[0])||i.unshift(""),n=i.join("/"),e&&"/"!==n.substr(-1)&&(n+="/"),n}},{}],1437:[function(require,module,exports){!function(process){!function(){"use strict";"production"===process.env.NODE_ENV?module.exports=require("./cjs/resolve-pathname.min.js"):module.exports=require("./cjs/resolve-pathname.js")}.call(this)}.call(this,require("_process"))},{"./cjs/resolve-pathname.js":1435,"./cjs/resolve-pathname.min.js":1436,_process:1042}],1438:[function(require,module,exports){},{}],1439:[function(require,module,exports){"use strict";var b=0;exports.__interactionsRef=null,exports.__subscriberRef=null,exports.unstable_clear=function(a){return a()},exports.unstable_getCurrent=function(){return null},exports.unstable_getThreadID=function(){return++b},exports.unstable_subscribe=function(){},exports.unstable_trace=function(a,d,c){return c()},exports.unstable_unsubscribe=function(){},exports.unstable_wrap=function(a){return a}},{}],1440:[function(require,module,exports){},{}],1441:[function(require,module,exports){"use strict";var f,g,h,p,q,t,u,w,x,y,z,B,C,D,E,F,G,k,l,I;function J(a,b){var c=a.length;for(a.push(b);;){var d=c-1>>>1,e=a[d];if(!(void 0!==e&&0<K(e,b)))break;a[d]=b,a[c]=e,c=d}}function L(a){return void 0===(a=a[0])?null:a}function M(a){var b=a[0];if(void 0!==b){var c=a.pop();if(c!==b){a[0]=c;for(var d=0,e=a.length;d<e;){var m=2*(d+1)-1,n=a[m],v=1+m,r=a[v];if(void 0!==n&&K(n,c)<0)d=void 0!==r&&K(r,n)<0?(a[d]=r,a[v]=c,v):(a[d]=n,a[m]=c,m);else{if(!(void 0!==r&&K(r,c)<0))break;a[d]=r,a[v]=c,d=v}}}}}function K(a,b){var c=a.sortIndex-b.sortIndex;return 0!=c?c:a.id-b.id}"undefined"==typeof window||"function"!=typeof MessageChannel?(q=p=null,t=function(){if(null!==p)try{var a=exports.unstable_now();p(!0,a),p=null}catch(b){throw setTimeout(t,0),b}},u=Date.now(),exports.unstable_now=function(){return Date.now()-u},f=function(a){null!==p?setTimeout(f,0,a):(p=a,setTimeout(t,0))},g=function(a,b){q=setTimeout(a,b)},h=function(){clearTimeout(q)},k=function(){return!1},l=exports.unstable_forceFrameRate=function(){}):(w=window.performance,x=window.Date,y=window.setTimeout,z=window.clearTimeout,"undefined"!=typeof console&&(A=window.cancelAnimationFrame,"function"!=typeof window.requestAnimationFrame&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),"function"!=typeof A)&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),"object"==typeof w&&"function"==typeof w.now?exports.unstable_now=function(){return w.now()}:(B=x.now(),exports.unstable_now=function(){return x.now()-B}),C=!1,D=null,E=-1,F=5,G=0,k=function(){return exports.unstable_now()>=G},l=function(){},exports.unstable_forceFrameRate=function(a){a<0||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing framerates higher than 125 fps is not unsupported"):F=0<a?Math.floor(1e3/a):5},A=new MessageChannel,I=A.port2,A.port1.onmessage=function(){if(null!==D){var a=exports.unstable_now();G=a+F;try{D(!0,a)?I.postMessage(null):(C=!1,D=null)}catch(b){throw I.postMessage(null),b}}else C=!1},f=function(a){D=a,C||(C=!0,I.postMessage(null))},g=function(a,b){E=y(function(){a(exports.unstable_now())},b)},h=function(){z(E),E=-1});var N=[],O=[],P=1,Q=null,R=3,S=!1,T=!1,U=!1;function V(a){for(var b=L(O);null!==b;){if(null===b.callback)M(O);else{if(!(b.startTime<=a))break;M(O),b.sortIndex=b.expirationTime,J(N,b)}b=L(O)}}function W(a){var b;U=!1,V(a),T||(null!==L(N)?(T=!0,f(X)):null!==(b=L(O))&&g(W,b.startTime-a))}function X(a,b){T=!1,U&&(U=!1,h()),S=!0;var c=R;try{for(V(b),Q=L(N);null!==Q&&(!(Q.expirationTime>b)||a&&!k());){var e,d=Q.callback;null!==d?(Q.callback=null,R=Q.priorityLevel,e=d(Q.expirationTime<=b),b=exports.unstable_now(),"function"==typeof e?Q.callback=e:Q===L(N)&&M(N),V(b)):M(N),Q=L(N)}var n,m=null!==Q||(null!==(n=L(O))&&g(W,n.startTime-b),!1);return m}finally{Q=null,R=c,S=!1}}function Y(a){switch(a){case 1:return-1;case 2:return 250;case 5:return 1073741823;case 4:return 1e4;default:return 5e3}}var A=l;exports.unstable_IdlePriority=5,exports.unstable_ImmediatePriority=1,exports.unstable_LowPriority=4,exports.unstable_NormalPriority=3,exports.unstable_Profiling=null,exports.unstable_UserBlockingPriority=2,exports.unstable_cancelCallback=function(a){a.callback=null},exports.unstable_continueExecution=function(){T||S||(T=!0,f(X))},exports.unstable_getCurrentPriorityLevel=function(){return R},exports.unstable_getFirstCallbackNode=function(){return L(N)},exports.unstable_next=function(a){switch(R){case 1:case 2:case 3:var b=3;break;default:b=R}var c=R;R=b;try{return a()}finally{R=c}},exports.unstable_pauseExecution=function(){},exports.unstable_requestPaint=A,exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=R;R=a;try{return b()}finally{R=c}},exports.unstable_scheduleCallback=function(a,b,c){var e,d=exports.unstable_now();return"object"==typeof c&&null!==c?(e="number"==typeof(e=c.delay)&&0<e?d+e:d,c="number"==typeof c.timeout?c.timeout:Y(a)):(c=Y(a),e=d),a={id:P++,callback:b,priorityLevel:a,startTime:e,expirationTime:c=e+c,sortIndex:-1},d<e?(a.sortIndex=e,J(O,a),null===L(N)&&a===L(O)&&(U?h():U=!0,g(W,e-d))):(a.sortIndex=c,J(N,a),T||S||(T=!0,f(X))),a},exports.unstable_shouldYield=function(){var a=exports.unstable_now(),b=(V(a),L(N));return b!==Q&&null!==Q&&null!==b&&null!==b.callback&&b.startTime<=a&&b.expirationTime<Q.expirationTime||k()},exports.unstable_wrapCallback=function(a){var b=R;return function(){var c=R;R=b;try{return a.apply(this,arguments)}finally{R=c}}}},{}],1442:[function(require,module,exports){"use strict";module.exports=require("./cjs/scheduler.production.min.js")},{"./cjs/scheduler.development.js":1440,"./cjs/scheduler.production.min.js":1441}],1443:[function(require,module,exports){"use strict";module.exports=require("./cjs/scheduler-tracing.production.min.js")},{"./cjs/scheduler-tracing.development.js":1438,"./cjs/scheduler-tracing.production.min.js":1439}],1444:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_has2=_interopRequireDefault(require("lodash/has")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Button=_interopRequireDefault(require("../../elements/Button")),_Modal=_interopRequireDefault(require("../../modules/Modal")),_interopRequireWildcard=function(_Component){function Confirm(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Confirm);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Confirm)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleCancel",function(e){(0,_invoke2.default)(_this.props,"onCancel",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleCancelOverrides",function(predefinedProps){return{onClick:function(e,buttonProps){(0,_invoke2.default)(predefinedProps,"onClick",e,buttonProps),_this.handleCancel(e)}}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleConfirmOverrides",function(predefinedProps){return{onClick:function(e,buttonProps){(0,_invoke2.default)(predefinedProps,"onClick",e,buttonProps),(0,_invoke2.default)(_this.props,"onConfirm",e,_this.props)}}}),_this}return(0,_inherits2.default)(Confirm,_Component),(0,_createClass2.default)(Confirm,[{key:"render",value:function(){var _this$props=this.props,cancelButton=_this$props.cancelButton,confirmButton=_this$props.confirmButton,content=_this$props.content,header=_this$props.header,open=_this$props.open,_this$props=_this$props.size,rest=(0,_lib.getUnhandledProps)(Confirm,this.props),openProp={};return(0,_has2.default)(this.props,"open")&&(openProp.open=open),_react.default.createElement(_Modal.default,(0,_extends2.default)({},rest,openProp,{size:_this$props,onClose:this.handleCancel}),_Modal.default.Header.create(header,{autoGenerateKey:!1}),_Modal.default.Content.create(content,{autoGenerateKey:!1}),_react.default.createElement(_Modal.default.Actions,null,_Button.default.create(cancelButton,{autoGenerateKey:!1,overrideProps:this.handleCancelOverrides}),_Button.default.create(confirmButton,{autoGenerateKey:!1,defaultProps:{primary:!0},overrideProps:this.handleConfirmOverrides})))}}]),Confirm}(_react.Component);(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{cancelButton:"Cancel",confirmButton:"OK",content:"Are you sure?",size:"small"}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["cancelButton","confirmButton","content","header","onCancel","onConfirm","open","size"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{cancelButton:_lib.customPropTypes.itemShorthand,confirmButton:_lib.customPropTypes.itemShorthand,content:_lib.customPropTypes.itemShorthand,header:_lib.customPropTypes.itemShorthand,onCancel:_propTypes.default.func,onConfirm:_propTypes.default.func,open:_propTypes.default.bool,size:_propTypes.default.oneOf(["mini","tiny","small","large","fullscreen"])}:{},exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../elements/Button":1514,"../../lib":1588,"../../modules/Modal":1620,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/has":951,"lodash/invoke":959,"prop-types":1046,react:1427}],1445:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Confirm=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Confirm.default}}),_interopRequireDefault(require("./Confirm")))},{"./Confirm":1444,"@babel/runtime/helpers/interopRequireDefault":13}],1446:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_classCallCheck2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"))),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_propTypes=_interopRequireDefault(require("prop-types")),_react=require("react"),_lib=require("../../lib"),_getNodeRefFromProps=_interopRequireDefault(require("./lib/getNodeRefFromProps")),_handleClassNamesChange=_interopRequireDefault(require("./lib/handleClassNamesChange")),nodeRegistry=new(_interopRequireDefault(require("./lib/NodeRegistry")).default),_interopRequireDefault=function(_Component){function MountNode(){return(0,_classCallCheck2.default)(this,MountNode),(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(MountNode).apply(this,arguments))}return(0,_inherits2.default)(MountNode,_Component),(0,_createClass2.default)(MountNode,[{key:"shouldComponentUpdate",value:function(_ref){return _ref.className!==this.props.className}},{key:"componentDidMount",value:function(){var nodeRef=(0,_getNodeRefFromProps.default)(this.props);nodeRegistry.add(nodeRef,this),nodeRegistry.emit(nodeRef,_handleClassNamesChange.default)}},{key:"componentDidUpdate",value:function(){nodeRegistry.emit((0,_getNodeRefFromProps.default)(this.props),_handleClassNamesChange.default)}},{key:"componentWillUnmount",value:function(){var nodeRef=(0,_getNodeRefFromProps.default)(this.props);nodeRegistry.del(nodeRef,this),nodeRegistry.emit(nodeRef,_handleClassNamesChange.default)}},{key:"render",value:function(){return null}}]),MountNode}(_react.Component);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["className","node"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{className:_propTypes.default.string,node:_propTypes.default.oneOfType([_lib.customPropTypes.domNode,_lib.customPropTypes.refObject])}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./lib/NodeRegistry":1448,"./lib/getNodeRefFromProps":1451,"./lib/handleClassNamesChange":1452,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"prop-types":1046,react:1427}],1447:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_MountNode=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _MountNode.default}}),_interopRequireDefault(require("./MountNode")))},{"./MountNode":1446,"@babel/runtime/helpers/interopRequireDefault":13}],1448:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_classCallCheck2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"))),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));exports.default=function NodeRegistry(){var _this=this;(0,_classCallCheck2.default)(this,NodeRegistry),(0,_defineProperty2.default)(this,"add",function(nodeRef,component){_this.nodes.has(nodeRef)?_this.nodes.get(nodeRef).add(component):_this.nodes.set(nodeRef,new Set([component]))}),(0,_defineProperty2.default)(this,"del",function(nodeRef,component){var set;_this.nodes.has(nodeRef)&&(1===(set=_this.nodes.get(nodeRef)).size?_this.nodes.delete(nodeRef):set.delete(component))}),(0,_defineProperty2.default)(this,"emit",function(nodeRef,callback){callback(nodeRef,_this.nodes.get(nodeRef))}),this.nodes=new Map}},{"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":13}],1449:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_uniq2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("lodash/fp/uniq"))),_identity2=_interopRequireDefault(require("lodash/fp/identity")),_filter2=_interopRequireDefault(require("lodash/fp/filter")),_split2=_interopRequireDefault(require("lodash/fp/split")),_flatMap2=_interopRequireDefault(require("lodash/fp/flatMap")),_map2=_interopRequireDefault(require("lodash/fp/map")),_toArray2=_interopRequireDefault(require("lodash/fp/toArray")),_interopRequireDefault=(0,_interopRequireDefault(require("lodash/fp/flow")).default)(_toArray2.default,(0,_map2.default)("props.className"),(0,_flatMap2.default)((0,_split2.default)(/\s+/)),(0,_filter2.default)(_identity2.default),_uniq2.default);exports.default=_interopRequireDefault},{"@babel/runtime/helpers/interopRequireDefault":13,"lodash/fp/filter":929,"lodash/fp/flatMap":930,"lodash/fp/flow":931,"lodash/fp/identity":932,"lodash/fp/map":938,"lodash/fp/split":944,"lodash/fp/toArray":947,"lodash/fp/uniq":949}],1450:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_difference2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("lodash/difference")));exports.default=function(prevClassNames,currentClassNames){return[(0,_difference2.default)(currentClassNames,prevClassNames),(0,_difference2.default)(prevClassNames,currentClassNames)]}},{"@babel/runtime/helpers/interopRequireDefault":13,"lodash/difference":908}],1451:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_isNil2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("lodash/isNil"))),_reactComponentRef=require("@stardust-ui/react-component-ref"),_lib=require("../../../lib");exports.default=function(props){props=props.node;if((0,_lib.isBrowser)())return(0,_reactComponentRef.isRefObject)(props)?props:(0,_isNil2.default)(props)?(0,_reactComponentRef.toRefObject)(document.body):(0,_reactComponentRef.toRefObject)(props)}},{"../../../lib":1588,"@babel/runtime/helpers/interopRequireDefault":13,"@stardust-ui/react-component-ref":107,"lodash/isNil":972}],1452:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_slicedToArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"))),_forEach2=_interopRequireDefault(require("lodash/forEach")),_computeClassNames=_interopRequireDefault(require("./computeClassNames")),_computeClassNamesDifference=_interopRequireDefault(require("./computeClassNamesDifference")),prevClassNames=new Map;exports.default=function(nodeRef,components){var components=(0,_computeClassNames.default)(components),_computeClassNamesDif=(0,_computeClassNamesDifference.default)(prevClassNames.get(nodeRef),components),_computeClassNamesDif=(0,_slicedToArray2.default)(_computeClassNamesDif,2),forAdd=_computeClassNamesDif[0],_computeClassNamesDif=_computeClassNamesDif[1];nodeRef.current&&((0,_forEach2.default)(forAdd,function(className){return nodeRef.current.classList.add(className)}),(0,_forEach2.default)(_computeClassNamesDif,function(className){return nodeRef.current.classList.remove(className)})),prevClassNames.set(nodeRef,components)}},{"./computeClassNames":1449,"./computeClassNamesDifference":1450,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/slicedToArray":25,"lodash/forEach":921}],1453:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_map2=_interopRequireDefault(require("lodash/map")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Menu=_interopRequireDefault(require("../../collections/Menu")),_PaginationItem=_interopRequireDefault(require("./PaginationItem")),_interopRequireDefault=function(_Component){function Pagination(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Pagination);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Pagination)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleItemClick",function(e,_ref){_ref=_ref.value;+_this.state.activePage!=+_ref&&(_this.trySetState({activePage:_ref}),(0,_invoke2.default)(_this.props,"onPageChange",e,(0,_objectSpread2.default)({},_this.props,{activePage:_ref})))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleItemOverrides",function(active,type,value){return function(predefinedProps){return{active:active,type:type,key:"".concat(type,"-").concat(value),onClick:function(e,itemProps){(0,_invoke2.default)(predefinedProps,"onClick",e,itemProps),"ellipsisItem"!==itemProps.type&&_this.handleItemClick(e,itemProps)}}}}),_this}return(0,_inherits2.default)(Pagination,_Component),(0,_createClass2.default)(Pagination,[{key:"render",value:function(){var _this2=this,_this$props=this.props,ariaLabel=_this$props["aria-label"],boundaryRange=_this$props.boundaryRange,disabled=_this$props.disabled,ellipsisItem=_this$props.ellipsisItem,siblingRange=_this$props.siblingRange,_this$props=_this$props.totalPages,activePage=this.state.activePage,activePage=(0,_lib.createPaginationItems)({activePage:activePage,boundaryRange:boundaryRange,hideEllipsis:(0,_isNil2.default)(ellipsisItem),siblingRange:siblingRange,totalPages:_this$props}),boundaryRange=(0,_lib.getUnhandledProps)(Pagination,this.props);return _react.default.createElement(_Menu.default,(0,_extends2.default)({},boundaryRange,{"aria-label":ariaLabel,pagination:!0,role:"navigation"}),(0,_map2.default)(activePage,function(_ref2){var active=_ref2.active,type=_ref2.type,_ref2=_ref2.value;return _PaginationItem.default.create(_this2.props[type],{defaultProps:{content:_ref2,disabled:disabled,value:_ref2},overrideProps:_this2.handleItemOverrides(active,type,_ref2)})}))}}]),Pagination}(_lib.AutoControlledComponent);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"autoControlledProps",["activePage"]),(0,_defineProperty2.default)(_interopRequireDefault,"defaultProps",{"aria-label":"Pagination Navigation",boundaryRange:1,ellipsisItem:"...",firstItem:{"aria-label":"First item",content:"«"},lastItem:{"aria-label":"Last item",content:"»"},nextItem:{"aria-label":"Next item",content:"⟩"},pageItem:{},prevItem:{"aria-label":"Previous item",content:"⟨"},siblingRange:1}),(0,_defineProperty2.default)(_interopRequireDefault,"Item",_PaginationItem.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["activePage","aria-label","boundaryRange","defaultActivePage","disabled","ellipsisItem","firstItem","lastItem","nextItem","onPageChange","pageItem","prevItem","siblingRange","totalPages"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{"aria-label":_propTypes.default.string,defaultActivePage:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),activePage:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),boundaryRange:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),disabled:_propTypes.default.bool,ellipsisItem:_lib.customPropTypes.itemShorthand,firstItem:_lib.customPropTypes.itemShorthand,lastItem:_lib.customPropTypes.itemShorthand,nextItem:_lib.customPropTypes.itemShorthand,pageItem:_lib.customPropTypes.itemShorthand,prevItem:_lib.customPropTypes.itemShorthand,onPageChange:_propTypes.default.func,siblingRange:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),totalPages:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]).isRequired}:{}}.call(this)}.call(this,require("_process"))},{"../../collections/Menu":1495,"../../lib":1588,"./PaginationItem":1454,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/invoke":959,"lodash/isNil":972,"lodash/map":989,"prop-types":1046,react:1427}],1454:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_classCallCheck2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"))),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_keyboardKey=_interopRequireDefault(require("keyboard-key")),_propTypes=_interopRequireDefault(require("prop-types")),_react=require("react"),_lib=require("../../lib"),_MenuItem=_interopRequireDefault(require("../../collections/Menu/MenuItem")),_interopRequireDefault=function(_Component){function PaginationItem(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,PaginationItem);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(PaginationItem)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleKeyDown",function(e){(0,_invoke2.default)(_this.props,"onKeyDown",e,_this.props),_keyboardKey.default.getCode(e)===_keyboardKey.default.Enter&&(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleOverrides",function(){return{onClick:_this.handleClick,onKeyDown:_this.handleKeyDown}}),_this}return(0,_inherits2.default)(PaginationItem,_Component),(0,_createClass2.default)(PaginationItem,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,_this$props=_this$props.type,_this$props=this.props.disabled||"ellipsisItem"===_this$props;return _MenuItem.default.create(this.props,{defaultProps:{active:active,"aria-current":active,"aria-disabled":_this$props,disabled:_this$props,onClick:this.handleClick,onKeyDown:this.handleKeyDown,tabIndex:_this$props?-1:0},overrideProps:this.handleOverrides})}}]),PaginationItem}(_react.Component);(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["active","disabled","onClick","onKeyDown","type"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{active:_propTypes.default.bool,disabled:_propTypes.default.bool,onClick:_propTypes.default.func,onKeyDown:_propTypes.default.func,type:_propTypes.default.oneOf(["ellipsisItem","firstItem","prevItem","pageItem","nextItem","lastItem"])}:{},_interopRequireDefault.create=(0,_lib.createShorthandFactory)(_interopRequireDefault,function(content){return{content:content}}),exports.default=_interopRequireDefault}.call(this)}.call(this,require("_process"))},{"../../collections/Menu/MenuItem":1493,"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"keyboard-key":662,"lodash/invoke":959,"prop-types":1046,react:1427}],1455:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Pagination=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Pagination.default}}),_interopRequireDefault(require("./Pagination")))},{"./Pagination":1453,"@babel/runtime/helpers/interopRequireDefault":13}],1456:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectSpread2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectSpread"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_eventStack=_interopRequireDefault(require("@semantic-ui-react/event-stack")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_keyboardKey=_interopRequireDefault(require("keyboard-key")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_PortalInner=_interopRequireDefault(require("./PortalInner")),_interopRequireWildcard=function(_Component){function Portal(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Portal);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Portal)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"contentRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"triggerRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"latestDocumentMouseDownEvent",null),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleDocumentMouseDown",function(e){_this.latestDocumentMouseDownEvent=e}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleDocumentClick",function(e){var closeOnDocumentClick=_this.props.closeOnDocumentClick,currentMouseDownEvent=_this.latestDocumentMouseDownEvent;_this.latestDocumentMouseDownEvent=null,!_this.contentRef.current||(0,_lib.doesNodeContainClick)(_this.triggerRef.current,e)||currentMouseDownEvent&&(0,_lib.doesNodeContainClick)(_this.contentRef.current,currentMouseDownEvent)||(0,_lib.doesNodeContainClick)(_this.contentRef.current,e)||closeOnDocumentClick&&_this.close(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleEscape",function(e){_this.props.closeOnEscape&&_keyboardKey.default.getCode(e)===_keyboardKey.default.Escape&&_this.close(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handlePortalMouseLeave",function(e){var _this$props=_this.props,closeOnPortalMouseLeave=_this$props.closeOnPortalMouseLeave,_this$props=_this$props.mouseLeaveDelay;closeOnPortalMouseLeave&&e.target===_this.contentRef.current&&(_this.mouseLeaveTimer=_this.closeWithTimeout(e,_this$props))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handlePortalMouseEnter",function(){_this.props.closeOnPortalMouseLeave&&clearTimeout(_this.mouseLeaveTimer)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTriggerBlur",function(e){for(var _this$props2=_this.props,trigger=_this$props2.trigger,_this$props2=_this$props2.closeOnTriggerBlur,_len2=arguments.length,rest=new Array(1<_len2?_len2-1:0),_key2=1;_key2<_len2;_key2++)rest[_key2-1]=arguments[_key2];_invoke2.default.apply(void 0,[trigger,"props.onBlur",e].concat(rest));trigger=e.relatedTarget||document.activeElement,trigger=(0,_invoke2.default)(_this.contentRef.current,"contains",trigger);_this$props2&&!trigger&&_this.close(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTriggerClick",function(e){for(var _this$props3=_this.props,trigger=_this$props3.trigger,closeOnTriggerClick=_this$props3.closeOnTriggerClick,_this$props3=_this$props3.openOnTriggerClick,open=_this.state.open,_len3=arguments.length,rest=new Array(1<_len3?_len3-1:0),_key3=1;_key3<_len3;_key3++)rest[_key3-1]=arguments[_key3];_invoke2.default.apply(void 0,[trigger,"props.onClick",e].concat(rest)),open&&closeOnTriggerClick?_this.close(e):!open&&_this$props3&&_this.open(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTriggerFocus",function(e){for(var _this$props4=_this.props,trigger=_this$props4.trigger,_this$props4=_this$props4.openOnTriggerFocus,_len4=arguments.length,rest=new Array(1<_len4?_len4-1:0),_key4=1;_key4<_len4;_key4++)rest[_key4-1]=arguments[_key4];_invoke2.default.apply(void 0,[trigger,"props.onFocus",e].concat(rest)),_this$props4&&_this.open(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTriggerMouseLeave",function(e){clearTimeout(_this.mouseEnterTimer);for(var _this$props5=_this.props,trigger=_this$props5.trigger,closeOnTriggerMouseLeave=_this$props5.closeOnTriggerMouseLeave,_this$props5=_this$props5.mouseLeaveDelay,_len5=arguments.length,rest=new Array(1<_len5?_len5-1:0),_key5=1;_key5<_len5;_key5++)rest[_key5-1]=arguments[_key5];_invoke2.default.apply(void 0,[trigger,"props.onMouseLeave",e].concat(rest)),closeOnTriggerMouseLeave&&(_this.mouseLeaveTimer=_this.closeWithTimeout(e,_this$props5))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTriggerMouseEnter",function(e){clearTimeout(_this.mouseLeaveTimer);for(var _this$props6=_this.props,trigger=_this$props6.trigger,mouseEnterDelay=_this$props6.mouseEnterDelay,_this$props6=_this$props6.openOnTriggerMouseEnter,_len6=arguments.length,rest=new Array(1<_len6?_len6-1:0),_key6=1;_key6<_len6;_key6++)rest[_key6-1]=arguments[_key6];_invoke2.default.apply(void 0,[trigger,"props.onMouseEnter",e].concat(rest)),_this$props6&&(_this.mouseEnterTimer=_this.openWithTimeout(e,mouseEnterDelay))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"open",function(e){var onOpen=_this.props.onOpen;onOpen&&onOpen(e,_this.props),_this.trySetState({open:!0})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"openWithTimeout",function(e,delay){var eventClone=(0,_objectSpread2.default)({},e);return setTimeout(function(){return _this.open(eventClone)},delay||0)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"close",function(e){var onClose=_this.props.onClose;onClose&&onClose(e,_this.props),_this.trySetState({open:!1})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"closeWithTimeout",function(e,delay){var eventClone=(0,_objectSpread2.default)({},e);return setTimeout(function(){return _this.close(eventClone)},delay||0)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleMount",function(){(0,_invoke2.default)(_this.props,"onMount",null,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleUnmount",function(){(0,_invoke2.default)(_this.props,"onUnmount",null,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTriggerRef",function(c){_this.triggerRef.current=c,(0,_reactComponentRef.handleRef)(_this.props.triggerRef,c)}),_this}return(0,_inherits2.default)(Portal,_Component),(0,_createClass2.default)(Portal,[{key:"componentWillUnmount",value:function(){clearTimeout(this.mouseEnterTimer),clearTimeout(this.mouseLeaveTimer)}},{key:"render",value:function(){var _this$props7=this.props,children=_this$props7.children,eventPool=_this$props7.eventPool,mountNode=_this$props7.mountNode,_this$props7=_this$props7.trigger,open=this.state.open;return _react.default.createElement(_react.Fragment,null,open&&_react.default.createElement(_react.Fragment,null,_react.default.createElement(_PortalInner.default,{innerRef:this.contentRef,mountNode:mountNode,onMount:this.handleMount,onUnmount:this.handleUnmount},children),_react.default.createElement(_eventStack.default,{name:"mouseleave",on:this.handlePortalMouseLeave,pool:eventPool,target:this.contentRef}),_react.default.createElement(_eventStack.default,{name:"mouseenter",on:this.handlePortalMouseEnter,pool:eventPool,target:this.contentRef}),_react.default.createElement(_eventStack.default,{name:"mousedown",on:this.handleDocumentMouseDown,pool:eventPool}),_react.default.createElement(_eventStack.default,{name:"click",on:this.handleDocumentClick,pool:eventPool}),_react.default.createElement(_eventStack.default,{name:"keydown",on:this.handleEscape,pool:eventPool})),_this$props7&&_react.default.createElement(_reactComponentRef.Ref,{innerRef:this.handleTriggerRef},(0,_react.cloneElement)(_this$props7,{onBlur:this.handleTriggerBlur,onClick:this.handleTriggerClick,onFocus:this.handleTriggerFocus,onMouseLeave:this.handleTriggerMouseLeave,onMouseEnter:this.handleTriggerMouseEnter})))}}]),Portal}(_lib.AutoControlledComponent);(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{closeOnDocumentClick:!0,closeOnEscape:!0,eventPool:"default",openOnTriggerClick:!0}),(0,_defineProperty2.default)(_interopRequireWildcard,"autoControlledProps",["open"]),(0,_defineProperty2.default)(_interopRequireWildcard,"Inner",_PortalInner.default),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["children","closeOnDocumentClick","closeOnEscape","closeOnPortalMouseLeave","closeOnTriggerBlur","closeOnTriggerClick","closeOnTriggerMouseLeave","defaultOpen","eventPool","mountNode","mouseEnterDelay","mouseLeaveDelay","onClose","onMount","onOpen","onUnmount","open","openOnTriggerClick","openOnTriggerFocus","openOnTriggerMouseEnter","trigger","triggerRef"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{children:_propTypes.default.node.isRequired,closeOnDocumentClick:_propTypes.default.bool,closeOnEscape:_propTypes.default.bool,closeOnPortalMouseLeave:_propTypes.default.bool,closeOnTriggerBlur:_propTypes.default.bool,closeOnTriggerClick:_propTypes.default.bool,closeOnTriggerMouseLeave:_propTypes.default.bool,defaultOpen:_propTypes.default.bool,eventPool:_propTypes.default.string,mountNode:_propTypes.default.any,mouseEnterDelay:_propTypes.default.number,mouseLeaveDelay:_propTypes.default.number,onClose:_propTypes.default.func,onMount:_propTypes.default.func,onOpen:_propTypes.default.func,onUnmount:_propTypes.default.func,open:_propTypes.default.bool,openOnTriggerClick:_propTypes.default.bool,openOnTriggerFocus:_propTypes.default.bool,openOnTriggerMouseEnter:_propTypes.default.bool,trigger:_propTypes.default.node,triggerRef:_lib.customPropTypes.ref}:{},exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./PortalInner":1457,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@semantic-ui-react/event-stack":36,"@stardust-ui/react-component-ref":107,_process:1042,"keyboard-key":662,"lodash/invoke":959,"prop-types":1046,react:1427}],1457:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_classCallCheck2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"))),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_reactDom=require("react-dom"),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function PortalInner(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,PortalInner);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(PortalInner)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleRef",function(c){(0,_reactComponentRef.handleRef)(_this.props.innerRef,c)}),_this}return(0,_inherits2.default)(PortalInner,_Component),(0,_createClass2.default)(PortalInner,[{key:"componentDidMount",value:function(){(0,_invoke2.default)(this.props,"onMount",null,this.props)}},{key:"componentWillUnmount",value:function(){(0,_invoke2.default)(this.props,"onUnmount",null,this.props)}},{key:"render",value:function(){var children,_this$props;return(0,_lib.isBrowser)()?(children=(_this$props=this.props).children,_this$props=void 0===(_this$props=_this$props.mountNode)?document.body:_this$props,(0,_reactDom.createPortal)(_react.default.createElement(_reactComponentRef.Ref,{innerRef:this.handleRef},children),_this$props)):null}}]),PortalInner}(_react.Component);(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["children","innerRef","mountNode","onMount","onUnmount"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{children:_interopRequireDefault.default.node.isRequired,innerRef:_lib.customPropTypes.ref,mountNode:_interopRequireDefault.default.any,onMount:_interopRequireDefault.default.func,onUnmount:_interopRequireDefault.default.func}:{},exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,"@stardust-ui/react-component-ref":107,_process:1042,"lodash/invoke":959,"prop-types":1046,react:1427,"react-dom":1382}],1458:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Portal=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Portal.default}}),_interopRequireDefault(require("./Portal")))},{"./Portal":1456,"@babel/runtime/helpers/interopRequireDefault":13}],1459:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Checkbox=_interopRequireDefault(require("../../modules/Checkbox"));function Radio(props){var slider=props.slider,toggle=props.toggle,type=props.type,props=(0,_lib.getUnhandledProps)(Radio,props);return _react.default.createElement(_Checkbox.default,(0,_extends2.default)({},props,{type:type,radio:!(slider||toggle)||void 0,slider:slider,toggle:toggle}))}Radio.handledProps=["slider","toggle","type"],Radio.propTypes="production"!==process.env.NODE_ENV?{slider:_Checkbox.default.propTypes.slider,toggle:_Checkbox.default.propTypes.toggle,type:_Checkbox.default.propTypes.type}:{},Radio.defaultProps={type:"radio"},exports.default=Radio}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../../modules/Checkbox":1601,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,react:1427}],1460:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Radio=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Radio.default}}),_interopRequireDefault(require("./Radio")))},{"./Radio":1459,"@babel/runtime/helpers/interopRequireDefault":13}],1461:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectSpread2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectSpread"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_isVisible=_interopRequireDefault(require("./lib/isVisible")),_interopRequireWildcard=function(_Component){function Responsive(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Responsive);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Responsive)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"state",{visible:!0}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleResize",function(e){_this.ticking||(_this.ticking=!0,_this.frameId=requestAnimationFrame(function(){return _this.handleUpdate(e)}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleUpdate",function(e){_this.ticking=!1;var visible=_this.state.visible,width=(0,_invoke2.default)(_this.props,"getWidth"),nextVisible=(0,_isVisible.default)(width,_this.props);visible!==nextVisible&&_this.setState({visible:nextVisible}),(0,_invoke2.default)(_this.props,"onUpdate",e,(0,_objectSpread2.default)({},_this.props,{width:width}))}),_this}return(0,_inherits2.default)(Responsive,_Component),(0,_createClass2.default)(Responsive,[{key:"componentDidMount",value:function(){var fireOnMount=this.props.fireOnMount;_lib.eventStack.sub("resize",this.handleResize,{target:"window"}),fireOnMount&&this.handleUpdate()}},{key:"componentWillUnmount",value:function(){_lib.eventStack.unsub("resize",this.handleResize,{target:"window"}),cancelAnimationFrame(this.frameId)}},{key:"render",value:function(){var children=this.props.children,visible=this.state.visible,ElementType=(0,_lib.getElementType)(Responsive,this.props),rest=(0,_lib.getUnhandledProps)(Responsive,this.props);return visible?_react.default.createElement(ElementType,rest,children):null}}],[{key:"getDerivedStateFromProps",value:function(props){var width=(0,_invoke2.default)(props,"getWidth");return{visible:(0,_isVisible.default)(width,props)}}}]),Responsive}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{getWidth:function(){return(0,_lib.isBrowser)()?window.innerWidth:0}}),(0,_defineProperty2.default)(_interopRequireWildcard,"onlyMobile",{minWidth:320,maxWidth:767}),(0,_defineProperty2.default)(_interopRequireWildcard,"onlyTablet",{minWidth:768,maxWidth:991}),(0,_defineProperty2.default)(_interopRequireWildcard,"onlyComputer",{minWidth:992}),(0,_defineProperty2.default)(_interopRequireWildcard,"onlyLargeScreen",{minWidth:1200,maxWidth:1919}),(0,_defineProperty2.default)(_interopRequireWildcard,"onlyWidescreen",{minWidth:1920}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["as","children","fireOnMount","getWidth","maxWidth","minWidth","onUpdate"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,fireOnMount:_propTypes.default.bool,getWidth:_propTypes.default.func,maxWidth:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),minWidth:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),onUpdate:_propTypes.default.func}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./lib/isVisible":1463,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/invoke":959,"prop-types":1046,react:1427}],1462:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Responsive=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Responsive.default}}),_interopRequireDefault(require("./Responsive")))},{"./Responsive":1461,"@babel/runtime/helpers/interopRequireDefault":13}],1463:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_isNil2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("lodash/isNil")));exports.default=function(width,_ref){var maxWidth=_ref.maxWidth;return function(width,minWidth){return!!(0,_isNil2.default)(minWidth)||minWidth<=width}(width,_ref.minWidth)&&function(width,maxWidth){return!!(0,_isNil2.default)(maxWidth)||width<=maxWidth}(width,maxWidth)}},{"@babel/runtime/helpers/interopRequireDefault":13,"lodash/isNil":972}],1464:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_Dropdown=_interopRequireDefault(require("../../modules/Dropdown"));function Select(props){return _react.default.createElement(_Dropdown.default,(0,_extends2.default)({},props,{selection:!0}))}Select.handledProps=["options"],Select.propTypes="production"!==process.env.NODE_ENV?{options:_propTypes.default.arrayOf(_propTypes.default.shape(_Dropdown.default.Item.propTypes)).isRequired}:{},Select.Divider=_Dropdown.default.Divider,Select.Header=_Dropdown.default.Header,Select.Item=_Dropdown.default.Item,Select.Menu=_Dropdown.default.Menu,exports.default=Select}.call(this)}.call(this,require("_process"))},{"../../modules/Dropdown":1612,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1465:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Select=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Select.default}}),_interopRequireDefault(require("./Select")))},{"./Select":1464,"@babel/runtime/helpers/interopRequireDefault":13}],1466:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_get2=_interopRequireDefault(require("lodash/get")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function TextArea(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,TextArea);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(TextArea)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"ref",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"focus",function(){return _this.ref.current.focus()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleChange",function(e){var value=(0,_get2.default)(e,"target.value");(0,_invoke2.default)(_this.props,"onChange",e,(0,_objectSpread2.default)({},_this.props,{value:value}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleInput",function(e){var value=(0,_get2.default)(e,"target.value");(0,_invoke2.default)(_this.props,"onInput",e,(0,_objectSpread2.default)({},_this.props,{value:value}))}),_this}return(0,_inherits2.default)(TextArea,_Component),(0,_createClass2.default)(TextArea,[{key:"render",value:function(){var _this$props=this.props,rows=_this$props.rows,_this$props=_this$props.value,rest=(0,_lib.getUnhandledProps)(TextArea,this.props),ElementType=(0,_lib.getElementType)(TextArea,this.props);return _react.default.createElement(_reactComponentRef.Ref,{innerRef:this.ref},_react.default.createElement(ElementType,(0,_extends2.default)({},rest,{onChange:this.handleChange,onInput:this.handleInput,rows:rows,value:_this$props})))}}]),TextArea}(_react.Component);(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{as:"textarea",rows:3}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["as","onChange","onInput","rows","value"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,onChange:_interopRequireDefault.default.func,onInput:_interopRequireDefault.default.func,rows:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string]),value:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string])}:{},exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@stardust-ui/react-component-ref":107,_process:1042,"lodash/get":950,"lodash/invoke":959,"prop-types":1046,react:1427}],1467:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_TextArea=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _TextArea.default}}),_interopRequireDefault(require("./TextArea")))},{"./TextArea":1466,"@babel/runtime/helpers/interopRequireDefault":13}],1468:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_Portal=_interopRequireDefault(require("../Portal")),_Transition=_interopRequireDefault(require("../../modules/Transition")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function TransitionablePortal(props){var _this;return(0,_classCallCheck2.default)(this,TransitionablePortal),_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(TransitionablePortal).call(this,props)),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handlePortalClose",function(){_this.setState({portalOpen:!1})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handlePortalOpen",function(){_this.setState({portalOpen:!0})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTransitionHide",function(nothing,data){var portalOpen=_this.state.portalOpen;_this.setState({transitionVisible:!1}),(0,_invoke2.default)(_this.props,"onClose",null,(0,_objectSpread2.default)({},data,{portalOpen:!1,transitionVisible:!1})),(0,_invoke2.default)(_this.props,"onHide",null,(0,_objectSpread2.default)({},data,{portalOpen:portalOpen,transitionVisible:!1}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTransitionStart",function(nothing,data){var portalOpen=_this.state.portalOpen,transitionVisible=data.status===_Transition.default.ENTERING;(0,_invoke2.default)(_this.props,"onStart",null,(0,_objectSpread2.default)({},data,{portalOpen:portalOpen,transitionVisible:transitionVisible})),transitionVisible&&(_this.setState({transitionVisible:transitionVisible}),(0,_invoke2.default)(_this.props,"onOpen",null,(0,_objectSpread2.default)({},data,{transitionVisible:transitionVisible,portalOpen:!0})))}),_this.state={portalOpen:props.open},_this}return(0,_inherits2.default)(TransitionablePortal,_Component),(0,_createClass2.default)(TransitionablePortal,[{key:"UNSAFE_componentWillReceiveProps",value:function(_ref){_ref=_ref.open;this.setState({portalOpen:_ref})}},{key:"render",value:function(){var _this$props=this.props,children=_this$props.children,_this$props=_this$props.transition,_this$state=this.state,portalOpen=_this$state.portalOpen,_this$state=_this$state.transitionVisible,_this$state=portalOpen||_this$state,rest=(0,_lib.getUnhandledProps)(TransitionablePortal,this.props);return _react.default.createElement(_Portal.default,(0,_extends2.default)({},rest,{open:_this$state,onOpen:this.handlePortalOpen,onClose:this.handlePortalClose}),_react.default.createElement(_Transition.default,(0,_extends2.default)({},_this$props,{transitionOnMount:!0,onStart:this.handleTransitionStart,onHide:this.handleTransitionHide,visible:portalOpen}),children))}}]),TransitionablePortal}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{transition:{animation:"scale",duration:400}}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["children","onClose","onHide","onOpen","onStart","open","transition"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{children:_propTypes.default.node.isRequired,onClose:_propTypes.default.func,onHide:_propTypes.default.func,onOpen:_propTypes.default.func,onStart:_propTypes.default.func,open:_propTypes.default.bool,transition:_propTypes.default.object}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../../modules/Transition":1650,"../Portal":1458,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/invoke":959,"prop-types":1046,react:1427}],1469:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_TransitionablePortal=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _TransitionablePortal.default}}),_interopRequireDefault(require("./TransitionablePortal")))},{"./TransitionablePortal":1468,"@babel/runtime/helpers/interopRequireDefault":13}],1470:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_slicedToArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_forEach2=_interopRequireDefault(require("lodash/forEach")),_without2=_interopRequireDefault(require("lodash/without")),_includes2=_interopRequireDefault(require("lodash/includes")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function Visibility(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Visibility);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Visibility)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"calculations",{bottomPassed:!1,bottomVisible:!1,fits:!1,passing:!1,offScreen:!1,onScreen:!1,topPassed:!1,topVisible:!1}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"firedCallbacks",[]),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"ref",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"fire",function(_ref,value){var callback=_ref.callback,_ref=_ref.name,_this$props=_this.props,continuous=_this$props.continuous,_this$props=_this$props.once,matchesDirection=_this.calculations[value]!==(2<arguments.length&&void 0!==arguments[2]&&arguments[2]),continuous=continuous||_this.calculations[value]!==_this.oldCalculations[value];matchesDirection&&continuous&&_this.execute(callback,_ref),_this$props||(_this.firedCallbacks=(0,_without2.default)(_this.firedCallbacks,_ref))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleUpdate",function(){_this.ticking||(_this.ticking=!0,_this.frameId=requestAnimationFrame(_this.update))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"update",function(){var onBottomPassedReverse,onBottomVisibleReverse,onPassing,onPassingReverse,onTopPassed,onTopPassedReverse,onTopVisible,onTopVisibleReverse,onOffScreen,onOnScreen,_this$props2,onBottomPassed,onBottomVisible;_this.mounted&&(_this.ticking=!1,_this.oldCalculations=_this.calculations,_this.calculations=_this.computeCalculations(),_this.pageYOffset=_this.getPageYOffset(),onBottomPassed=(_this$props2=_this.props).onBottomPassed,onBottomPassedReverse=_this$props2.onBottomPassedReverse,onBottomVisible=_this$props2.onBottomVisible,onBottomVisibleReverse=_this$props2.onBottomVisibleReverse,onPassing=_this$props2.onPassing,onPassingReverse=_this$props2.onPassingReverse,onTopPassed=_this$props2.onTopPassed,onTopPassedReverse=_this$props2.onTopPassedReverse,onTopVisible=_this$props2.onTopVisible,onTopVisibleReverse=_this$props2.onTopVisibleReverse,onOffScreen=_this$props2.onOffScreen,onOnScreen=_this$props2.onOnScreen,_this$props2=_this$props2.updateOn,onBottomPassed={bottomPassed:{callback:onBottomPassed,name:"onBottomPassed"},bottomVisible:{callback:onBottomVisible,name:"onBottomVisible"},passing:{callback:onPassing,name:"onPassing"},offScreen:{callback:onOffScreen,name:"onOffScreen"},onScreen:{callback:onOnScreen,name:"onOnScreen"},topPassed:{callback:onTopPassed,name:"onTopPassed"},topVisible:{callback:onTopVisible,name:"onTopVisible"}},onBottomVisible={bottomPassed:{callback:onBottomPassedReverse,name:"onBottomPassedReverse"},bottomVisible:{callback:onBottomVisibleReverse,name:"onBottomVisibleReverse"},passing:{callback:onPassingReverse,name:"onPassingReverse"},topPassed:{callback:onTopPassedReverse,name:"onTopPassedReverse"},topVisible:{callback:onTopVisibleReverse,name:"onTopVisibleReverse"}},(0,_invoke2.default)(_this.props,"onUpdate",null,(0,_objectSpread2.default)({},_this.props,{calculations:_this.calculations})),_this.fireOnPassed(),(0,_forEach2.default)(onBottomVisible,function(data,value){return _this.fire(data,value,!0)}),(0,_forEach2.default)(onBottomPassed,function(data,value){return _this.fire(data,value)}),"repaint"===_this$props2)&&_this.handleUpdate()}),_this}return(0,_inherits2.default)(Visibility,_Component),(0,_createClass2.default)(Visibility,[{key:"UNSAFE_componentWillReceiveProps",value:function(_ref2){var continuous=_ref2.continuous,once=_ref2.once,context=_ref2.context,_ref2=_ref2.updateOn;continuous===this.props.continuous&&once===this.props.once&&_ref2===this.props.updateOn||(this.firedCallbacks=[]),context===this.props.context&&_ref2===this.props.updateOn||(this.unattachHandlers(this.props.context),this.attachHandlers(context,_ref2))}},{key:"componentDidMount",value:function(){var context,fireOnMount,_this$props3;this.mounted=!0,(0,_lib.isBrowser)()&&(context=(_this$props3=this.props).context,fireOnMount=_this$props3.fireOnMount,_this$props3=_this$props3.updateOn,this.pageYOffset=this.getPageYOffset(),this.attachHandlers(context,_this$props3),fireOnMount)&&this.update()}},{key:"componentWillUnmount",value:function(){var context=this.props.context;this.unattachHandlers(context),this.mounted=!1}},{key:"attachHandlers",value:function(context,updateOn){"events"===updateOn?context&&(_lib.eventStack.sub("resize",this.handleUpdate,{target:context}),_lib.eventStack.sub("scroll",this.handleUpdate,{target:context})):this.handleUpdate()}},{key:"unattachHandlers",value:function(context){context&&(_lib.eventStack.unsub("resize",this.handleUpdate,{target:context}),_lib.eventStack.unsub("scroll",this.handleUpdate,{target:context})),this.frameId&&cancelAnimationFrame(this.frameId)}},{key:"execute",value:function(callback,name){var continuous=this.props.continuous;!callback||!continuous&&(0,_includes2.default)(this.firedCallbacks,name)||(callback(null,(0,_objectSpread2.default)({},this.props,{calculations:this.calculations})),this.firedCallbacks.push(name))}},{key:"fireOnPassed",value:function(){var _this2=this,_this$calculations=this.calculations,percentagePassed=_this$calculations.percentagePassed,pixelsPassed=_this$calculations.pixelsPassed,_this$calculations=this.props.onPassed;(0,_forEach2.default)(_this$calculations,function(callback,passed){var pixelsValue=Number(passed);(pixelsValue&&pixelsValue<=pixelsPassed||(pixelsValue="".concat(passed).match(/^(\d+)%$/))&&Number(pixelsValue[1])/100<=percentagePassed)&&_this2.execute(callback,passed)})}},{key:"computeCalculations",value:function(){var offset=this.props.offset,_this$ref$current$get=this.ref.current.getBoundingClientRect(),bottom=_this$ref$current$get.bottom,height=_this$ref$current$get.height,top=_this$ref$current$get.top,_this$ref$current$get=_this$ref$current$get.width,offset=(0,_lib.normalizeOffset)(offset),offset=(0,_slicedToArray2.default)(offset,2),topOffset=offset[0],offset=offset[1],direction=this.getPageYOffset()>this.pageYOffset?"down":"up",topPassed=top<topOffset,bottomPassed=bottom<offset,pixelsPassed=bottomPassed?0:Math.max(-1*top,0),offset=offset<=bottom&&bottom<=window.innerHeight,bottom=topOffset<=top&&top<=window.innerHeight,topOffset=(bottom||topPassed)&&!bottomPassed;return{bottomPassed:bottomPassed,bottomVisible:offset,direction:direction,fits:bottom&&offset,height:height,passing:topPassed&&!bottomPassed,percentagePassed:pixelsPassed/height,pixelsPassed:pixelsPassed,offScreen:!topOffset,onScreen:topOffset,topPassed:topPassed,topVisible:bottom,width:_this$ref$current$get}}},{key:"getPageYOffset",value:function(){var context=this.props.context;return context?context===window?window.pageYOffset:context.scrollTop:0}},{key:"render",value:function(){var children=this.props.children,ElementType=(0,_lib.getElementType)(Visibility,this.props),rest=(0,_lib.getUnhandledProps)(Visibility,this.props);return _react.default.createElement(_reactComponentRef.Ref,{innerRef:this.ref},_react.default.createElement(ElementType,rest,children))}}]),Visibility}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{context:(0,_lib.isBrowser)()?window:null,continuous:!1,offset:[0,0],once:!0,updateOn:"events"}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["as","children","context","continuous","fireOnMount","offset","onBottomPassed","onBottomPassedReverse","onBottomVisible","onBottomVisibleReverse","onOffScreen","onOnScreen","onPassed","onPassing","onPassingReverse","onTopPassed","onTopPassedReverse","onTopVisible","onTopVisibleReverse","onUpdate","once","updateOn"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,children:_interopRequireDefault.default.node,context:_interopRequireDefault.default.object,continuous:_interopRequireDefault.default.bool,fireOnMount:_interopRequireDefault.default.bool,onBottomPassed:_interopRequireDefault.default.func,onBottomPassedReverse:_interopRequireDefault.default.func,onBottomVisible:_interopRequireDefault.default.func,onBottomVisibleReverse:_interopRequireDefault.default.func,offset:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string,_interopRequireDefault.default.arrayOf(_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string]))]),once:_interopRequireDefault.default.bool,onPassed:_interopRequireDefault.default.object,onPassing:_interopRequireDefault.default.func,onPassingReverse:_interopRequireDefault.default.func,onOffScreen:_interopRequireDefault.default.func,onOnScreen:_interopRequireDefault.default.func,onTopPassed:_interopRequireDefault.default.func,onTopPassedReverse:_interopRequireDefault.default.func,onTopVisible:_interopRequireDefault.default.func,onTopVisibleReverse:_interopRequireDefault.default.func,onUpdate:_interopRequireDefault.default.func,updateOn:_interopRequireDefault.default.oneOf(["events","repaint"])}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@babel/runtime/helpers/slicedToArray":25,"@stardust-ui/react-component-ref":107,_process:1042,"lodash/forEach":921,"lodash/includes":956,"lodash/invoke":959,"lodash/without":1028,"prop-types":1046,react:1427}],1471:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Visibility=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Visibility.default}}),_interopRequireDefault(require("./Visibility")))},{"./Visibility":1470,"@babel/runtime/helpers/interopRequireDefault":13}],1472:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_each2=_interopRequireDefault(require("lodash/each")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_BreadcrumbDivider=_interopRequireDefault(require("./BreadcrumbDivider")),_BreadcrumbSection=_interopRequireDefault(require("./BreadcrumbSection"));function Breadcrumb(props){var childElements,children=props.children,className=props.className,divider=props.divider,icon=props.icon,sections=props.sections,size=props.size,size=(0,_classnames.default)("ui",size,"breadcrumb",className),className=(0,_lib.getUnhandledProps)(Breadcrumb,props),props=(0,_lib.getElementType)(Breadcrumb,props);return _lib.childrenUtils.isNil(children)?(childElements=[],(0,_each2.default)(sections,function(section,index){var breadcrumbElement=_BreadcrumbSection.default.create(section);childElements.push(breadcrumbElement),index!==sections.length-1&&(index="".concat(breadcrumbElement.key,"_divider")||JSON.stringify(section),childElements.push(_BreadcrumbDivider.default.create({content:divider,icon:icon,key:index})))}),_react.default.createElement(props,(0,_extends2.default)({},className,{className:size}),childElements)):_react.default.createElement(props,(0,_extends2.default)({},className,{className:size}),children)}Breadcrumb.handledProps=["as","children","className","divider","icon","sections","size"],Breadcrumb.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,divider:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["icon"]),_lib.customPropTypes.contentShorthand]),icon:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["divider"]),_lib.customPropTypes.itemShorthand]),sections:_lib.customPropTypes.collectionShorthand,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium"))}:{},Breadcrumb.Divider=_BreadcrumbDivider.default,Breadcrumb.Section=_BreadcrumbSection.default,exports.default=Breadcrumb}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./BreadcrumbDivider":1473,"./BreadcrumbSection":1474,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/each":910,"lodash/without":1028,"prop-types":1046,react:1427}],1473:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon"));function BreadcrumbDivider(props){var children=props.children,className=props.className,content=props.content,icon=props.icon,className=(0,_classnames.default)("divider",className),rest=(0,_lib.getUnhandledProps)(BreadcrumbDivider,props),props=(0,_lib.getElementType)(BreadcrumbDivider,props);return(0,_isNil2.default)(icon)?(0,_isNil2.default)(content)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?"/":children):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),content):_Icon.default.create(icon,{defaultProps:(0,_objectSpread2.default)({},rest,{className:className}),autoGenerateKey:!1})}BreadcrumbDivider.handledProps=["as","children","className","content","icon"],BreadcrumbDivider.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,icon:_lib.customPropTypes.itemShorthand}:{},BreadcrumbDivider.create=(0,_lib.createShorthandFactory)(BreadcrumbDivider,function(icon){return{icon:icon}}),exports.default=BreadcrumbDivider}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,_process:1042,classnames:116,"lodash/isNil":972,"prop-types":1046,react:1427}],1474:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function BreadcrumbSection(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,BreadcrumbSection);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(BreadcrumbSection)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeElementType",function(){var _this$props=_this.props,link=_this$props.link,_this$props=_this$props.onClick;if(link||_this$props)return"a"}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){return(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),_this}return(0,_inherits2.default)(BreadcrumbSection,_Component),(0,_createClass2.default)(BreadcrumbSection,[{key:"render",value:function(){var _this$props2=this.props,active=_this$props2.active,children=_this$props2.children,className=_this$props2.className,content=_this$props2.content,_this$props2=_this$props2.href,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),"section",className),className=(0,_lib.getUnhandledProps)(BreadcrumbSection,this.props),ElementType=(0,_lib.getElementType)(BreadcrumbSection,this.props,this.computeElementType);return _react.default.createElement(ElementType,(0,_extends2.default)({},className,{className:active,href:_this$props2,onClick:this.handleClick}),_lib.childrenUtils.isNil(children)?content:children)}}]),BreadcrumbSection}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","children","className","content","href","link","onClick"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,active:_interopRequireDefault.default.bool,children:_interopRequireDefault.default.node,className:_interopRequireDefault.default.string,content:_lib.customPropTypes.contentShorthand,href:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["link"]),_interopRequireDefault.default.string]),link:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["href"]),_interopRequireDefault.default.bool]),onClick:_interopRequireDefault.default.func}:{},_interopRequireWildcard.create=(0,_lib.createShorthandFactory)(_interopRequireWildcard,function(content){return{content:content,link:!0}})}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"prop-types":1046,react:1427}],1475:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Breadcrumb=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Breadcrumb.default}}),_interopRequireDefault(require("./Breadcrumb")))},{"./Breadcrumb":1472,"@babel/runtime/helpers/interopRequireDefault":13}],1476:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=_interopRequireDefault(require("./FormButton")),_FormCheckbox=_interopRequireDefault(require("./FormCheckbox")),_FormDropdown=_interopRequireDefault(require("./FormDropdown")),_FormField=_interopRequireDefault(require("./FormField")),_FormGroup=_interopRequireDefault(require("./FormGroup")),_FormInput=_interopRequireDefault(require("./FormInput")),_FormRadio=_interopRequireDefault(require("./FormRadio")),_FormSelect=_interopRequireDefault(require("./FormSelect")),_interopRequireDefault=_interopRequireDefault(require("./FormTextArea")),Form=function(_Component){function Form(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Form);for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Form)).call.apply(_getPrototypeOf2,[this].concat(_args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleSubmit",function(e){"string"!=typeof _this.props.action&&(0,_invoke2.default)(e,"preventDefault");for(var _len2=arguments.length,args=new Array(1<_len2?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];_invoke2.default.apply(void 0,[_this.props,"onSubmit",e,_this.props].concat(args))}),_this}return(0,_inherits2.default)(Form,_Component),(0,_createClass2.default)(Form,[{key:"render",value:function(){var _this$props=this.props,action=_this$props.action,children=_this$props.children,className=_this$props.className,error=_this$props.error,inverted=_this$props.inverted,loading=_this$props.loading,reply=_this$props.reply,size=_this$props.size,success=_this$props.success,unstackable=_this$props.unstackable,warning=_this$props.warning,_this$props=_this$props.widths,size=(0,_classnames.default)("ui",size,(0,_lib.useKeyOnly)(error,"error"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(loading,"loading"),(0,_lib.useKeyOnly)(reply,"reply"),(0,_lib.useKeyOnly)(success,"success"),(0,_lib.useKeyOnly)(unstackable,"unstackable"),(0,_lib.useKeyOnly)(warning,"warning"),(0,_lib.useWidthProp)(_this$props,null,!0),"form",className),error=(0,_lib.getUnhandledProps)(Form,this.props),inverted=(0,_lib.getElementType)(Form,this.props);return _react.default.createElement(inverted,(0,_extends2.default)({},error,{action:action,className:size,onSubmit:this.handleSubmit}),children)}}]),Form}(_react.Component);(0,_defineProperty2.default)(Form,"defaultProps",{as:"form"}),(0,_defineProperty2.default)(Form,"Field",_FormField.default),(0,_defineProperty2.default)(Form,"Button",_interopRequireWildcard.default),(0,_defineProperty2.default)(Form,"Checkbox",_FormCheckbox.default),(0,_defineProperty2.default)(Form,"Dropdown",_FormDropdown.default),(0,_defineProperty2.default)(Form,"Group",_FormGroup.default),(0,_defineProperty2.default)(Form,"Input",_FormInput.default),(0,_defineProperty2.default)(Form,"Radio",_FormRadio.default),(0,_defineProperty2.default)(Form,"Select",_FormSelect.default),(0,_defineProperty2.default)(Form,"TextArea",_interopRequireDefault.default),(0,_defineProperty2.default)(Form,"handledProps",["action","as","children","className","error","inverted","loading","onSubmit","reply","size","success","unstackable","warning","widths"]),Form.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,action:_propTypes.default.string,children:_propTypes.default.node,className:_propTypes.default.string,error:_propTypes.default.bool,inverted:_propTypes.default.bool,loading:_propTypes.default.bool,onSubmit:_propTypes.default.func,reply:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium")),success:_propTypes.default.bool,unstackable:_propTypes.default.bool,warning:_propTypes.default.bool,widths:_propTypes.default.oneOf(["equal"])}:{},exports.default=Form}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./FormButton":1477,"./FormCheckbox":1478,"./FormDropdown":1479,"./FormField":1480,"./FormGroup":1481,"./FormInput":1482,"./FormRadio":1483,"./FormSelect":1484,"./FormTextArea":1485,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/without":1028,"prop-types":1046,react:1427}],1477:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Button=_interopRequireDefault(require("../../elements/Button")),_interopRequireDefault=_interopRequireDefault(require("./FormField"));function FormButton(props){var control=props.control,rest=(0,_lib.getUnhandledProps)(FormButton,props),props=(0,_lib.getElementType)(FormButton,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{control:control}))}FormButton.handledProps=["as","control"],FormButton.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,control:_interopRequireDefault.default.propTypes.control}:{},FormButton.defaultProps={as:_interopRequireDefault.default,control:_Button.default},exports.default=FormButton}.call(this)}.call(this,require("_process"))},{"../../elements/Button":1514,"../../lib":1588,"./FormField":1480,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1478:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Checkbox=_interopRequireDefault(require("../../modules/Checkbox")),_interopRequireDefault=_interopRequireDefault(require("./FormField"));function FormCheckbox(props){var control=props.control,rest=(0,_lib.getUnhandledProps)(FormCheckbox,props),props=(0,_lib.getElementType)(FormCheckbox,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{control:control}))}FormCheckbox.handledProps=["as","control"],FormCheckbox.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,control:_interopRequireDefault.default.propTypes.control}:{},FormCheckbox.defaultProps={as:_interopRequireDefault.default,control:_Checkbox.default},exports.default=FormCheckbox}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../../modules/Checkbox":1601,"./FormField":1480,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1479:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Dropdown=_interopRequireDefault(require("../../modules/Dropdown")),_interopRequireDefault=_interopRequireDefault(require("./FormField"));function FormDropdown(props){var control=props.control,rest=(0,_lib.getUnhandledProps)(FormDropdown,props),props=(0,_lib.getElementType)(FormDropdown,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{control:control}))}FormDropdown.handledProps=["as","control"],FormDropdown.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,control:_interopRequireDefault.default.propTypes.control}:{},FormDropdown.defaultProps={as:_interopRequireDefault.default,control:_Dropdown.default},exports.default=FormDropdown}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../../modules/Dropdown":1612,"./FormField":1480,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1480:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectSpread2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectSpread"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_get2=_interopRequireDefault(require("lodash/get")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Label=_interopRequireDefault(require("../../elements/Label")),_Checkbox=_interopRequireDefault(require("../../modules/Checkbox")),_Radio=_interopRequireDefault(require("../../addons/Radio"));function FormField(props){var children=props.children,className=props.className,content=props.content,control=props.control,disabled=props.disabled,error=props.error,inline=props.inline,label=props.label,required=props.required,type=props.type,width=props.width,id=props.id,inline=(0,_classnames.default)((0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(error,"error"),(0,_lib.useKeyOnly)(inline,"inline"),(0,_lib.useKeyOnly)(required,"required"),(0,_lib.useWidthProp)(width,"wide"),"field",className),width=(0,_lib.getUnhandledProps)(FormField,props),className=(0,_lib.getElementType)(FormField,props),props=(0,_get2.default)(error,"pointing","above"),errorLabel=_Label.default.create(error,{autoGenerateKey:!1,defaultProps:{prompt:!0,pointing:props,id:id?"".concat(id,"-error-message"):void 0,role:"alert","aria-atomic":!0}}),errorLabelBefore=("below"===props||"right"===props)&&errorLabel,props=("above"===props||"left"===props)&&errorLabel;return(0,_isNil2.default)(control)?(0,_isNil2.default)(label)?_react.default.createElement(className,(0,_extends2.default)({},width,{className:inline}),_lib.childrenUtils.isNil(children)?content:children):_react.default.createElement(className,(0,_extends2.default)({},width,{className:inline}),errorLabelBefore,(0,_lib.createHTMLLabel)(label,{autoGenerateKey:!1}),props):(errorLabel={"aria-describedby":id&&error?"".concat(id,"-error-message"):null,"aria-invalid":void 0!==error||void 0},error=(0,_objectSpread2.default)({},width,{content:content,children:children,disabled:disabled,required:required,type:type,id:id}),"input"!==control||"checkbox"!==type&&"radio"!==type?control===_Checkbox.default||control===_Radio.default?_react.default.createElement(className,{className:inline},errorLabelBefore,(0,_react.createElement)(control,(0,_objectSpread2.default)({},errorLabel,error,{label:label})),props):_react.default.createElement(className,{className:inline},(0,_lib.createHTMLLabel)(label,{defaultProps:{htmlFor:id},autoGenerateKey:!1}),errorLabelBefore,(0,_react.createElement)(control,(0,_objectSpread2.default)({},errorLabel,error)),props):_react.default.createElement(className,{className:inline},_react.default.createElement("label",null,errorLabelBefore,(0,_react.createElement)(control,(0,_objectSpread2.default)({},errorLabel,error))," ",label,props)))}FormField.handledProps=["as","children","className","content","control","disabled","error","id","inline","label","required","type","width"],FormField.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,control:_lib.customPropTypes.some([_propTypes.default.func,_propTypes.default.oneOf(["button","input","select","textarea"])]),disabled:_propTypes.default.bool,error:_propTypes.default.oneOfType([_propTypes.default.bool,_lib.customPropTypes.itemShorthand]),id:_propTypes.default.string,inline:_propTypes.default.bool,label:_propTypes.default.oneOfType([_propTypes.default.node,_propTypes.default.object]),required:_propTypes.default.bool,type:_lib.customPropTypes.every([_lib.customPropTypes.demand(["control"])]),width:_propTypes.default.oneOf(_lib.SUI.WIDTHS)}:{},exports.default=FormField}.call(this)}.call(this,require("_process"))},{"../../addons/Radio":1460,"../../elements/Label":1536,"../../lib":1588,"../../modules/Checkbox":1601,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,_process:1042,classnames:116,"lodash/get":950,"lodash/isNil":972,"prop-types":1046,react:1427}],1481:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function FormGroup(props){var children=props.children,className=props.className,grouped=props.grouped,inline=props.inline,unstackable=props.unstackable,widths=props.widths,grouped=(0,_classnames.default)((0,_lib.useKeyOnly)(grouped,"grouped"),(0,_lib.useKeyOnly)(inline,"inline"),(0,_lib.useKeyOnly)(unstackable,"unstackable"),(0,_lib.useWidthProp)(widths,null,!0),"fields",className),inline=(0,_lib.getUnhandledProps)(FormGroup,props),unstackable=(0,_lib.getElementType)(FormGroup,props);return _react.default.createElement(unstackable,(0,_extends2.default)({},inline,{className:grouped}),children)}FormGroup.handledProps=["as","children","className","grouped","inline","unstackable","widths"],FormGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,grouped:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["inline"]),_propTypes.default.bool]),inline:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["grouped"]),_propTypes.default.bool]),unstackable:_propTypes.default.bool,widths:_propTypes.default.oneOf([].concat((0,_toConsumableArray2.default)(_lib.SUI.WIDTHS),["equal"]))}:{},exports.default=FormGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/toConsumableArray":27,_process:1042,classnames:116,"prop-types":1046,react:1427}],1482:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Input=_interopRequireDefault(require("../../elements/Input")),_interopRequireDefault=_interopRequireDefault(require("./FormField"));function FormInput(props){var control=props.control,rest=(0,_lib.getUnhandledProps)(FormInput,props),props=(0,_lib.getElementType)(FormInput,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{control:control}))}FormInput.handledProps=["as","control"],FormInput.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,control:_interopRequireDefault.default.propTypes.control}:{},FormInput.defaultProps={as:_interopRequireDefault.default,control:_Input.default},exports.default=FormInput}.call(this)}.call(this,require("_process"))},{"../../elements/Input":1532,"../../lib":1588,"./FormField":1480,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1483:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Radio=_interopRequireDefault(require("../../addons/Radio")),_interopRequireDefault=_interopRequireDefault(require("./FormField"));function FormRadio(props){var control=props.control,rest=(0,_lib.getUnhandledProps)(FormRadio,props),props=(0,_lib.getElementType)(FormRadio,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{control:control}))}FormRadio.handledProps=["as","control"],FormRadio.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,control:_interopRequireDefault.default.propTypes.control}:{},FormRadio.defaultProps={as:_interopRequireDefault.default,control:_Radio.default},exports.default=FormRadio}.call(this)}.call(this,require("_process"))},{"../../addons/Radio":1460,"../../lib":1588,"./FormField":1480,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1484:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Select=_interopRequireDefault(require("../../addons/Select")),_Dropdown=_interopRequireDefault(require("../../modules/Dropdown")),_interopRequireDefault=_interopRequireDefault(require("./FormField"));function FormSelect(props){var control=props.control,options=props.options,rest=(0,_lib.getUnhandledProps)(FormSelect,props),props=(0,_lib.getElementType)(FormSelect,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{control:control,options:options}))}FormSelect.handledProps=["as","control","options"],FormSelect.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,control:_interopRequireDefault.default.propTypes.control,options:_propTypes.default.arrayOf(_propTypes.default.shape(_Dropdown.default.Item.propTypes)).isRequired}:{},FormSelect.defaultProps={as:_interopRequireDefault.default,control:_Select.default},exports.default=FormSelect}.call(this)}.call(this,require("_process"))},{"../../addons/Select":1465,"../../lib":1588,"../../modules/Dropdown":1612,"./FormField":1480,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1485:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_TextArea=_interopRequireDefault(require("../../addons/TextArea")),_interopRequireDefault=_interopRequireDefault(require("./FormField"));function FormTextArea(props){var control=props.control,rest=(0,_lib.getUnhandledProps)(FormTextArea,props),props=(0,_lib.getElementType)(FormTextArea,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{control:control}))}FormTextArea.handledProps=["as","control"],FormTextArea.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,control:_interopRequireDefault.default.propTypes.control}:{},FormTextArea.defaultProps={as:_interopRequireDefault.default,control:_TextArea.default},exports.default=FormTextArea}.call(this)}.call(this,require("_process"))},{"../../addons/TextArea":1467,"../../lib":1588,"./FormField":1480,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1486:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Form=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Form.default}}),_interopRequireDefault(require("./Form")))},{"./Form":1476,"@babel/runtime/helpers/interopRequireDefault":13}],1487:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_GridColumn=_interopRequireDefault(require("./GridColumn")),_interopRequireDefault=_interopRequireDefault(require("./GridRow"));function Grid(props){var celled=props.celled,centered=props.centered,children=props.children,className=props.className,columns=props.columns,container=props.container,divided=props.divided,doubling=props.doubling,inverted=props.inverted,padded=props.padded,relaxed=props.relaxed,reversed=props.reversed,stackable=props.stackable,stretched=props.stretched,textAlign=props.textAlign,verticalAlign=props.verticalAlign,centered=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(centered,"centered"),(0,_lib.useKeyOnly)(container,"container"),(0,_lib.useKeyOnly)(doubling,"doubling"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(stackable,"stackable"),(0,_lib.useKeyOnly)(stretched,"stretched"),(0,_lib.useKeyOrValueAndKey)(celled,"celled"),(0,_lib.useKeyOrValueAndKey)(divided,"divided"),(0,_lib.useKeyOrValueAndKey)(padded,"padded"),(0,_lib.useKeyOrValueAndKey)(relaxed,"relaxed"),(0,_lib.useMultipleProp)(reversed,"reversed"),(0,_lib.useTextAlignProp)(textAlign),(0,_lib.useVerticalAlignProp)(verticalAlign),(0,_lib.useWidthProp)(columns,"column",!0),"grid",className),container=(0,_lib.getUnhandledProps)(Grid,props),doubling=(0,_lib.getElementType)(Grid,props);return _react.default.createElement(doubling,(0,_extends2.default)({},container,{className:centered}),children)}Grid.handledProps=["as","celled","centered","children","className","columns","container","divided","doubling","inverted","padded","relaxed","reversed","stackable","stretched","textAlign","verticalAlign"],Grid.Column=_GridColumn.default,Grid.Row=_interopRequireDefault.default,Grid.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,celled:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["internally"])]),centered:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,columns:_propTypes.default.oneOf([].concat((0,_toConsumableArray2.default)(_lib.SUI.WIDTHS),["equal"])),container:_propTypes.default.bool,divided:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["vertically"])]),doubling:_propTypes.default.bool,inverted:_propTypes.default.bool,padded:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["horizontally","vertically"])]),relaxed:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["very"])]),reversed:_lib.customPropTypes.multipleProp(["computer","computer vertically","mobile","mobile vertically","tablet","tablet vertically"]),stackable:_propTypes.default.bool,stretched:_propTypes.default.bool,textAlign:_propTypes.default.oneOf(_lib.SUI.TEXT_ALIGNMENTS),verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS)}:{},exports.default=Grid}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./GridColumn":1488,"./GridRow":1489,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/toConsumableArray":27,_process:1042,classnames:116,"prop-types":1046,react:1427}],1488:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function GridColumn(props){var children=props.children,className=props.className,computer=props.computer,color=props.color,floated=props.floated,largeScreen=props.largeScreen,mobile=props.mobile,only=props.only,stretched=props.stretched,tablet=props.tablet,textAlign=props.textAlign,verticalAlign=props.verticalAlign,widescreen=props.widescreen,width=props.width,color=(0,_classnames.default)(color,(0,_lib.useKeyOnly)(stretched,"stretched"),(0,_lib.useMultipleProp)(only,"only"),(0,_lib.useTextAlignProp)(textAlign),(0,_lib.useValueAndKey)(floated,"floated"),(0,_lib.useVerticalAlignProp)(verticalAlign),(0,_lib.useWidthProp)(computer,"wide computer"),(0,_lib.useWidthProp)(largeScreen,"wide large screen"),(0,_lib.useWidthProp)(mobile,"wide mobile"),(0,_lib.useWidthProp)(tablet,"wide tablet"),(0,_lib.useWidthProp)(widescreen,"wide widescreen"),(0,_lib.useWidthProp)(width,"wide"),"column",className),stretched=(0,_lib.getUnhandledProps)(GridColumn,props),only=(0,_lib.getElementType)(GridColumn,props);return _react.default.createElement(only,(0,_extends2.default)({},stretched,{className:color}),children)}GridColumn.handledProps=["as","children","className","color","computer","floated","largeScreen","mobile","only","stretched","tablet","textAlign","verticalAlign","widescreen","width"],GridColumn.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),computer:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["width"]),_propTypes.default.oneOf(_lib.SUI.WIDTHS)]),floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),largeScreen:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["width"]),_propTypes.default.oneOf(_lib.SUI.WIDTHS)]),mobile:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["width"]),_propTypes.default.oneOf(_lib.SUI.WIDTHS)]),only:_lib.customPropTypes.multipleProp(_lib.SUI.VISIBILITY),stretched:_propTypes.default.bool,tablet:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["width"]),_propTypes.default.oneOf(_lib.SUI.WIDTHS)]),textAlign:_propTypes.default.oneOf(_lib.SUI.TEXT_ALIGNMENTS),verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS),widescreen:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["width"]),_propTypes.default.oneOf(_lib.SUI.WIDTHS)]),width:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["computer","largeScreen","mobile","tablet","widescreen"]),_propTypes.default.oneOf(_lib.SUI.WIDTHS)])}:{},GridColumn.create=(0,_lib.createShorthandFactory)(GridColumn,function(children){return{children:children}}),exports.default=GridColumn}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1489:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function GridRow(props){var centered=props.centered,children=props.children,className=props.className,color=props.color,columns=props.columns,divided=props.divided,only=props.only,reversed=props.reversed,stretched=props.stretched,textAlign=props.textAlign,verticalAlign=props.verticalAlign,color=(0,_classnames.default)(color,(0,_lib.useKeyOnly)(centered,"centered"),(0,_lib.useKeyOnly)(divided,"divided"),(0,_lib.useKeyOnly)(stretched,"stretched"),(0,_lib.useMultipleProp)(only,"only"),(0,_lib.useMultipleProp)(reversed,"reversed"),(0,_lib.useTextAlignProp)(textAlign),(0,_lib.useVerticalAlignProp)(verticalAlign),(0,_lib.useWidthProp)(columns,"column",!0),"row",className),centered=(0,_lib.getUnhandledProps)(GridRow,props),divided=(0,_lib.getElementType)(GridRow,props);return _react.default.createElement(divided,(0,_extends2.default)({},centered,{className:color}),children)}GridRow.handledProps=["as","centered","children","className","color","columns","divided","only","reversed","stretched","textAlign","verticalAlign"],GridRow.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,centered:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),columns:_propTypes.default.oneOf([].concat((0,_toConsumableArray2.default)(_lib.SUI.WIDTHS),["equal"])),divided:_propTypes.default.bool,only:_lib.customPropTypes.multipleProp(_lib.SUI.VISIBILITY),reversed:_lib.customPropTypes.multipleProp(["computer","computer vertically","mobile","mobile vertically","tablet","tablet vertically"]),stretched:_propTypes.default.bool,textAlign:_propTypes.default.oneOf(_lib.SUI.TEXT_ALIGNMENTS),verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS)}:{},exports.default=GridRow}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/toConsumableArray":27,_process:1042,classnames:116,"prop-types":1046,react:1427}],1490:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Grid=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Grid.default}}),_interopRequireDefault(require("./Grid")))},{"./Grid":1487,"@babel/runtime/helpers/interopRequireDefault":13}],1491:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_map2=_interopRequireDefault(require("lodash/map")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_MenuHeader=_interopRequireDefault(require("./MenuHeader")),_MenuItem=_interopRequireDefault(require("./MenuItem")),_interopRequireDefault=_interopRequireDefault(require("./MenuMenu")),Menu=function(_Component){function Menu(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Menu);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Menu)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleItemOverrides",function(predefinedProps){return{onClick:function(e,itemProps){var index=itemProps.index;_this.trySetState({activeIndex:index}),(0,_invoke2.default)(predefinedProps,"onClick",e,itemProps),(0,_invoke2.default)(_this.props,"onItemClick",e,itemProps)}}}),_this}return(0,_inherits2.default)(Menu,_Component),(0,_createClass2.default)(Menu,[{key:"renderItems",value:function(){var _this2=this,items=this.props.items,activeIndex=this.state.activeIndex;return(0,_map2.default)(items,function(item,index){return _MenuItem.default.create(item,{defaultProps:{active:parseInt(activeIndex,10)===index,index:index},overrideProps:_this2.handleItemOverrides})})}},{key:"render",value:function(){var _this$props=this.props,attached=_this$props.attached,borderless=_this$props.borderless,children=_this$props.children,className=_this$props.className,color=_this$props.color,compact=_this$props.compact,fixed=_this$props.fixed,floated=_this$props.floated,fluid=_this$props.fluid,icon=_this$props.icon,inverted=_this$props.inverted,pagination=_this$props.pagination,pointing=_this$props.pointing,secondary=_this$props.secondary,size=_this$props.size,stackable=_this$props.stackable,tabular=_this$props.tabular,text=_this$props.text,vertical=_this$props.vertical,_this$props=_this$props.widths,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(borderless,"borderless"),(0,_lib.useKeyOnly)(compact,"compact"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(pagination,"pagination"),(0,_lib.useKeyOnly)(pointing,"pointing"),(0,_lib.useKeyOnly)(secondary,"secondary"),(0,_lib.useKeyOnly)(stackable,"stackable"),(0,_lib.useKeyOnly)(text,"text"),(0,_lib.useKeyOnly)(vertical,"vertical"),(0,_lib.useKeyOrValueAndKey)(attached,"attached"),(0,_lib.useKeyOrValueAndKey)(floated,"floated"),(0,_lib.useKeyOrValueAndKey)(icon,"icon"),(0,_lib.useKeyOrValueAndKey)(tabular,"tabular"),(0,_lib.useValueAndKey)(fixed,"fixed"),(0,_lib.useWidthProp)(_this$props,"item"),className,"menu"),size=(0,_lib.getUnhandledProps)(Menu,this.props),borderless=(0,_lib.getElementType)(Menu,this.props);return _react.default.createElement(borderless,(0,_extends2.default)({},size,{className:color}),_lib.childrenUtils.isNil(children)?this.renderItems():children)}}]),Menu}(_lib.AutoControlledComponent);(0,_defineProperty2.default)(Menu,"autoControlledProps",["activeIndex"]),(0,_defineProperty2.default)(Menu,"Header",_MenuHeader.default),(0,_defineProperty2.default)(Menu,"Item",_MenuItem.default),(0,_defineProperty2.default)(Menu,"Menu",_interopRequireDefault.default),(0,_defineProperty2.default)(Menu,"handledProps",["activeIndex","as","attached","borderless","children","className","color","compact","defaultActiveIndex","fixed","floated","fluid","icon","inverted","items","onItemClick","pagination","pointing","secondary","size","stackable","tabular","text","vertical","widths"]),Menu.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,activeIndex:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),attached:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["top","bottom"])]),borderless:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),compact:_propTypes.default.bool,defaultActiveIndex:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),fixed:_propTypes.default.oneOf(["left","right","bottom","top"]),floated:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["right"])]),fluid:_propTypes.default.bool,icon:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["labeled"])]),inverted:_propTypes.default.bool,items:_lib.customPropTypes.collectionShorthand,onItemClick:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_propTypes.default.func]),pagination:_propTypes.default.bool,pointing:_propTypes.default.bool,secondary:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium","big")),stackable:_propTypes.default.bool,tabular:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["right"])]),text:_propTypes.default.bool,vertical:_propTypes.default.bool,widths:_propTypes.default.oneOf(_lib.SUI.WIDTHS)}:{},Menu.create=(0,_lib.createShorthandFactory)(Menu,function(items){return{items:items}}),exports.default=Menu}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./MenuHeader":1492,"./MenuItem":1493,"./MenuMenu":1494,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/map":989,"lodash/without":1028,"prop-types":1046,react:1427}],1492:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function MenuHeader(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("header",className),rest=(0,_lib.getUnhandledProps)(MenuHeader,props),props=(0,_lib.getElementType)(MenuHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}MenuHeader.handledProps=["as","children","className","content"],MenuHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=MenuHeader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1493:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_startCase2=_interopRequireDefault(require("lodash/startCase")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon")),_interopRequireWildcard=function(_Component){function MenuItem(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,MenuItem);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(MenuItem)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){_this.props.disabled||(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),_this}return(0,_inherits2.default)(MenuItem,_Component),(0,_createClass2.default)(MenuItem,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,children=_this$props.children,className=_this$props.className,color=_this$props.color,content=_this$props.content,disabled=_this$props.disabled,fitted=_this$props.fitted,header=_this$props.header,icon=_this$props.icon,link=_this$props.link,name=_this$props.name,onClick=_this$props.onClick,_this$props=_this$props.position,color=(0,_classnames.default)(color,_this$props,(0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(!0===icon||icon&&!(name||content),"icon"),(0,_lib.useKeyOnly)(header,"header"),(0,_lib.useKeyOnly)(link,"link"),(0,_lib.useKeyOrValueAndKey)(fitted,"fitted"),"item",className),_this$props=(0,_lib.getElementType)(MenuItem,this.props,function(){if(onClick)return"a"}),active=(0,_lib.getUnhandledProps)(MenuItem,this.props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(_this$props,(0,_extends2.default)({},active,{className:color,onClick:this.handleClick}),_Icon.default.create(icon,{autoGenerateKey:!1}),_lib.childrenUtils.isNil(content)?(0,_startCase2.default)(name):content):_react.default.createElement(_this$props,(0,_extends2.default)({},active,{className:color,onClick:this.handleClick}),children)}}]),MenuItem}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","children","className","color","content","disabled","fitted","header","icon","index","link","name","onClick","position"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),content:_lib.customPropTypes.contentShorthand,disabled:_propTypes.default.bool,fitted:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["horizontally","vertically"])]),header:_propTypes.default.bool,icon:_propTypes.default.oneOfType([_propTypes.default.bool,_lib.customPropTypes.itemShorthand]),index:_propTypes.default.number,link:_propTypes.default.bool,name:_propTypes.default.string,onClick:_propTypes.default.func,position:_propTypes.default.oneOf(["left","right"])}:{},_interopRequireWildcard.create=(0,_lib.createShorthandFactory)(_interopRequireWildcard,function(val){return{content:val,name:val}})}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/startCase":1008,"prop-types":1046,react:1427}],1494:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function MenuMenu(props){var children=props.children,className=props.className,content=props.content,position=props.position,position=(0,_classnames.default)(position,"menu",className),className=(0,_lib.getUnhandledProps)(MenuMenu,props),props=(0,_lib.getElementType)(MenuMenu,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:position}),_lib.childrenUtils.isNil(children)?content:children)}MenuMenu.handledProps=["as","children","className","content","position"],MenuMenu.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,position:_propTypes.default.oneOf(["left","right"])}:{},exports.default=MenuMenu}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1495:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Menu=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Menu.default}}),_interopRequireDefault(require("./Menu")))},{"./Menu":1491,"@babel/runtime/helpers/interopRequireDefault":13}],1496:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon")),_MessageContent=_interopRequireDefault(require("./MessageContent")),_MessageHeader=_interopRequireDefault(require("./MessageHeader")),_MessageList=_interopRequireDefault(require("./MessageList")),_interopRequireWildcard=_interopRequireDefault(require("./MessageItem")),_interopRequireDefault=function(_Component){function Message(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Message);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Message)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleDismiss",function(e){var onDismiss=_this.props.onDismiss;onDismiss&&onDismiss(e,_this.props)}),_this}return(0,_inherits2.default)(Message,_Component),(0,_createClass2.default)(Message,[{key:"render",value:function(){var _this$props=this.props,attached=_this$props.attached,children=_this$props.children,className=_this$props.className,color=_this$props.color,compact=_this$props.compact,content=_this$props.content,error=_this$props.error,floating=_this$props.floating,header=_this$props.header,hidden=_this$props.hidden,icon=_this$props.icon,info=_this$props.info,list=_this$props.list,negative=_this$props.negative,onDismiss=_this$props.onDismiss,positive=_this$props.positive,size=_this$props.size,success=_this$props.success,visible=_this$props.visible,_this$props=_this$props.warning,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(compact,"compact"),(0,_lib.useKeyOnly)(error,"error"),(0,_lib.useKeyOnly)(floating,"floating"),(0,_lib.useKeyOnly)(hidden,"hidden"),(0,_lib.useKeyOnly)(icon,"icon"),(0,_lib.useKeyOnly)(info,"info"),(0,_lib.useKeyOnly)(negative,"negative"),(0,_lib.useKeyOnly)(positive,"positive"),(0,_lib.useKeyOnly)(success,"success"),(0,_lib.useKeyOnly)(visible,"visible"),(0,_lib.useKeyOnly)(_this$props,"warning"),(0,_lib.useKeyOrValueAndKey)(attached,"attached"),"message",className),size=onDismiss&&_react.default.createElement(_Icon.default,{name:"close",onClick:this.handleDismiss}),compact=(0,_lib.getUnhandledProps)(Message,this.props),error=(0,_lib.getElementType)(Message,this.props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(error,(0,_extends2.default)({},compact,{className:color}),size,_Icon.default.create(icon,{autoGenerateKey:!1}),(!(0,_isNil2.default)(header)||!(0,_isNil2.default)(content)||!(0,_isNil2.default)(list))&&_react.default.createElement(_MessageContent.default,null,_MessageHeader.default.create(header,{autoGenerateKey:!1}),_MessageList.default.create(list,{autoGenerateKey:!1}),(0,_lib.createHTMLParagraph)(content,{autoGenerateKey:!1}))):_react.default.createElement(error,(0,_extends2.default)({},compact,{className:color}),size,children)}}]),Message}(_react.Component);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"Content",_MessageContent.default),(0,_defineProperty2.default)(_interopRequireDefault,"Header",_MessageHeader.default),(0,_defineProperty2.default)(_interopRequireDefault,"List",_MessageList.default),(0,_defineProperty2.default)(_interopRequireDefault,"Item",_interopRequireWildcard.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["as","attached","children","className","color","compact","content","error","floating","header","hidden","icon","info","list","negative","onDismiss","positive","size","success","visible","warning"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,attached:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["bottom","top"])]),children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),compact:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,error:_propTypes.default.bool,floating:_propTypes.default.bool,header:_lib.customPropTypes.itemShorthand,hidden:_propTypes.default.bool,icon:_propTypes.default.oneOfType([_lib.customPropTypes.itemShorthand,_propTypes.default.bool]),info:_propTypes.default.bool,list:_lib.customPropTypes.collectionShorthand,negative:_propTypes.default.bool,onDismiss:_propTypes.default.func,positive:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium")),success:_propTypes.default.bool,visible:_propTypes.default.bool,warning:_propTypes.default.bool}:{}}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"./MessageContent":1497,"./MessageHeader":1498,"./MessageItem":1499,"./MessageList":1500,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/isNil":972,"lodash/without":1028,"prop-types":1046,react:1427}],1497:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function MessageContent(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("content",className),rest=(0,_lib.getUnhandledProps)(MessageContent,props),props=(0,_lib.getElementType)(MessageContent,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}MessageContent.handledProps=["as","children","className","content"],MessageContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=MessageContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1498:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function MessageHeader(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("header",className),rest=(0,_lib.getUnhandledProps)(MessageHeader,props),props=(0,_lib.getElementType)(MessageHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}MessageHeader.handledProps=["as","children","className","content"],MessageHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},MessageHeader.create=(0,_lib.createShorthandFactory)(MessageHeader,function(val){return{content:val}}),exports.default=MessageHeader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1499:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function MessageItem(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("content",className),rest=(0,_lib.getUnhandledProps)(MessageItem,props),props=(0,_lib.getElementType)(MessageItem,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}MessageItem.handledProps=["as","children","className","content"],MessageItem.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},MessageItem.defaultProps={as:"li"},MessageItem.create=(0,_lib.createShorthandFactory)(MessageItem,function(content){return{content:content}}),exports.default=MessageItem}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1500:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_map2=_interopRequireDefault(require("lodash/map")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_MessageItem=_interopRequireDefault(require("./MessageItem"));function MessageList(props){var children=props.children,className=props.className,items=props.items,className=(0,_classnames.default)("list",className),rest=(0,_lib.getUnhandledProps)(MessageList,props),props=(0,_lib.getElementType)(MessageList,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?(0,_map2.default)(items,_MessageItem.default.create):children)}MessageList.handledProps=["as","children","className","items"],MessageList.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,items:_lib.customPropTypes.collectionShorthand}:{},MessageList.defaultProps={as:"ul"},MessageList.create=(0,_lib.createShorthandFactory)(MessageList,function(val){return{items:val}}),exports.default=MessageList}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./MessageItem":1499,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/map":989,"prop-types":1046,react:1427}],1501:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Message=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Message.default}}),_interopRequireDefault(require("./Message")))},{"./Message":1496,"@babel/runtime/helpers/interopRequireDefault":13}],1502:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_map2=_interopRequireDefault(require("lodash/map")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_TableBody=_interopRequireDefault(require("./TableBody")),_TableCell=_interopRequireDefault(require("./TableCell")),_TableFooter=_interopRequireDefault(require("./TableFooter")),_TableHeader=_interopRequireDefault(require("./TableHeader")),_TableHeaderCell=_interopRequireDefault(require("./TableHeaderCell")),_TableRow=_interopRequireDefault(require("./TableRow"));function Table(props){var headerShorthandOptions,attached=props.attached,basic=props.basic,celled=props.celled,children=props.children,className=props.className,collapsing=props.collapsing,color=props.color,columns=props.columns,compact=props.compact,definition=props.definition,fixed=props.fixed,footerRow=props.footerRow,headerRow=props.headerRow,headerRows=props.headerRows,inverted=props.inverted,padded=props.padded,renderBodyRow=props.renderBodyRow,selectable=props.selectable,singleLine=props.singleLine,size=props.size,sortable=props.sortable,stackable=props.stackable,striped=props.striped,structured=props.structured,tableData=props.tableData,textAlign=props.textAlign,unstackable=props.unstackable,verticalAlign=props.verticalAlign,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(celled,"celled"),(0,_lib.useKeyOnly)(collapsing,"collapsing"),(0,_lib.useKeyOnly)(definition,"definition"),(0,_lib.useKeyOnly)(fixed,"fixed"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(selectable,"selectable"),(0,_lib.useKeyOnly)(singleLine,"single line"),(0,_lib.useKeyOnly)(sortable,"sortable"),(0,_lib.useKeyOnly)(stackable,"stackable"),(0,_lib.useKeyOnly)(striped,"striped"),(0,_lib.useKeyOnly)(structured,"structured"),(0,_lib.useKeyOnly)(unstackable,"unstackable"),(0,_lib.useKeyOrValueAndKey)(attached,"attached"),(0,_lib.useKeyOrValueAndKey)(basic,"basic"),(0,_lib.useKeyOrValueAndKey)(compact,"compact"),(0,_lib.useKeyOrValueAndKey)(padded,"padded"),(0,_lib.useTextAlignProp)(textAlign),(0,_lib.useVerticalAlignProp)(verticalAlign),(0,_lib.useWidthProp)(columns,"column"),"table",className),size=(0,_lib.getUnhandledProps)(Table,props),celled=(0,_lib.getElementType)(Table,props);return _lib.childrenUtils.isNil(children)?(headerShorthandOptions={defaultProps:{cellAs:"th"}},collapsing=(headerRow||headerRows)&&_react.default.createElement(_TableHeader.default,null,_TableRow.default.create(headerRow,headerShorthandOptions),(0,_map2.default)(headerRows,function(data){return _TableRow.default.create(data,headerShorthandOptions)})),_react.default.createElement(celled,(0,_extends2.default)({},size,{className:color}),collapsing,_react.default.createElement(_TableBody.default,null,renderBodyRow&&(0,_map2.default)(tableData,function(data,index){return _TableRow.default.create(renderBodyRow(data,index))})),footerRow&&_react.default.createElement(_TableFooter.default,null,_TableRow.default.create(footerRow)))):_react.default.createElement(celled,(0,_extends2.default)({},size,{className:color}),children)}Table.handledProps=["as","attached","basic","celled","children","className","collapsing","color","columns","compact","definition","fixed","footerRow","headerRow","headerRows","inverted","padded","renderBodyRow","selectable","singleLine","size","sortable","stackable","striped","structured","tableData","textAlign","unstackable","verticalAlign"],Table.defaultProps={as:"table"},Table.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,attached:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["top","bottom"])]),basic:_propTypes.default.oneOfType([_propTypes.default.oneOf(["very"]),_propTypes.default.bool]),celled:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,collapsing:_propTypes.default.bool,color:_propTypes.default.oneOf(_lib.SUI.COLORS),columns:_propTypes.default.oneOf(_lib.SUI.WIDTHS),compact:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["very"])]),definition:_propTypes.default.bool,fixed:_propTypes.default.bool,footerRow:_lib.customPropTypes.itemShorthand,headerRow:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["headerRows"]),_lib.customPropTypes.itemShorthand]),headerRows:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["headerRow"]),_lib.customPropTypes.collectionShorthand]),inverted:_propTypes.default.bool,padded:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["very"])]),renderBodyRow:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_lib.customPropTypes.demand(["tableData"]),_propTypes.default.func]),selectable:_propTypes.default.bool,singleLine:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"mini","tiny","medium","big","huge","massive")),sortable:_propTypes.default.bool,stackable:_propTypes.default.bool,striped:_propTypes.default.bool,structured:_propTypes.default.bool,tableData:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_lib.customPropTypes.demand(["renderBodyRow"]),_propTypes.default.array]),textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified")),unstackable:_propTypes.default.bool,verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS)}:{},Table.Body=_TableBody.default,Table.Cell=_TableCell.default,Table.Footer=_TableFooter.default,Table.Header=_TableHeader.default,Table.HeaderCell=_TableHeaderCell.default,Table.Row=_TableRow.default,exports.default=Table}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./TableBody":1503,"./TableCell":1504,"./TableFooter":1505,"./TableHeader":1506,"./TableHeaderCell":1507,"./TableRow":1508,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/map":989,"lodash/without":1028,"prop-types":1046,react:1427}],1503:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function TableBody(props){var children=props.children,className=props.className,className=(0,_classnames.default)(className),rest=(0,_lib.getUnhandledProps)(TableBody,props),props=(0,_lib.getElementType)(TableBody,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}TableBody.handledProps=["as","children","className"],TableBody.defaultProps={as:"tbody"},TableBody.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string}:{},exports.default=TableBody}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1504:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon"));function TableCell(props){var active=props.active,children=props.children,className=props.className,collapsing=props.collapsing,content=props.content,disabled=props.disabled,error=props.error,icon=props.icon,negative=props.negative,positive=props.positive,selectable=props.selectable,singleLine=props.singleLine,textAlign=props.textAlign,verticalAlign=props.verticalAlign,warning=props.warning,width=props.width,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(collapsing,"collapsing"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(error,"error"),(0,_lib.useKeyOnly)(negative,"negative"),(0,_lib.useKeyOnly)(positive,"positive"),(0,_lib.useKeyOnly)(selectable,"selectable"),(0,_lib.useKeyOnly)(singleLine,"single line"),(0,_lib.useKeyOnly)(warning,"warning"),(0,_lib.useTextAlignProp)(textAlign),(0,_lib.useVerticalAlignProp)(verticalAlign),(0,_lib.useWidthProp)(width,"wide"),className),collapsing=(0,_lib.getUnhandledProps)(TableCell,props),disabled=(0,_lib.getElementType)(TableCell,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(disabled,(0,_extends2.default)({},collapsing,{className:active}),_Icon.default.create(icon),content):_react.default.createElement(disabled,(0,_extends2.default)({},collapsing,{className:active}),children)}TableCell.handledProps=["active","as","children","className","collapsing","content","disabled","error","icon","negative","positive","selectable","singleLine","textAlign","verticalAlign","warning","width"],TableCell.defaultProps={as:"td"},TableCell.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,collapsing:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,disabled:_propTypes.default.bool,error:_propTypes.default.bool,icon:_lib.customPropTypes.itemShorthand,negative:_propTypes.default.bool,positive:_propTypes.default.bool,selectable:_propTypes.default.bool,singleLine:_propTypes.default.bool,textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified")),verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS),warning:_propTypes.default.bool,width:_propTypes.default.oneOf(_lib.SUI.WIDTHS)}:{},TableCell.create=(0,_lib.createShorthandFactory)(TableCell,function(content){return{content:content}}),exports.default=TableCell}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1505:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_TableHeader=_interopRequireDefault(require("./TableHeader"));function TableFooter(props){var as=props.as,props=(0,_lib.getUnhandledProps)(TableFooter,props);return _react.default.createElement(_TableHeader.default,(0,_extends2.default)({},props,{as:as}))}TableFooter.handledProps=["as"],TableFooter.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType}:{},TableFooter.defaultProps={as:"tfoot"},exports.default=TableFooter}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./TableHeader":1506,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1506:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function TableHeader(props){var children=props.children,className=props.className,content=props.content,fullWidth=props.fullWidth,fullWidth=(0,_classnames.default)((0,_lib.useKeyOnly)(fullWidth,"full-width"),className),className=(0,_lib.getUnhandledProps)(TableHeader,props),props=(0,_lib.getElementType)(TableHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:fullWidth}),_lib.childrenUtils.isNil(children)?content:children)}TableHeader.handledProps=["as","children","className","content","fullWidth"],TableHeader.defaultProps={as:"thead"},TableHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,fullWidth:_propTypes.default.bool}:{},exports.default=TableHeader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1507:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_TableCell=_interopRequireDefault(require("./TableCell"));function TableHeaderCell(props){var as=props.as,className=props.className,sorted=props.sorted,sorted=(0,_classnames.default)((0,_lib.useValueAndKey)(sorted,"sorted"),className),className=(0,_lib.getUnhandledProps)(TableHeaderCell,props);return _react.default.createElement(_TableCell.default,(0,_extends2.default)({},className,{as:as,className:sorted}))}TableHeaderCell.handledProps=["as","className","sorted"],TableHeaderCell.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,className:_propTypes.default.string,sorted:_propTypes.default.oneOf(["ascending","descending"])}:{},TableHeaderCell.defaultProps={as:"th"},exports.default=TableHeaderCell}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./TableCell":1504,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1508:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_map2=_interopRequireDefault(require("lodash/map")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_TableCell=_interopRequireDefault(require("./TableCell"));function TableRow(props){var active=props.active,cellAs=props.cellAs,cells=props.cells,children=props.children,className=props.className,disabled=props.disabled,error=props.error,negative=props.negative,positive=props.positive,textAlign=props.textAlign,verticalAlign=props.verticalAlign,warning=props.warning,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(error,"error"),(0,_lib.useKeyOnly)(negative,"negative"),(0,_lib.useKeyOnly)(positive,"positive"),(0,_lib.useKeyOnly)(warning,"warning"),(0,_lib.useTextAlignProp)(textAlign),(0,_lib.useVerticalAlignProp)(verticalAlign),className),disabled=(0,_lib.getUnhandledProps)(TableRow,props),error=(0,_lib.getElementType)(TableRow,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(error,(0,_extends2.default)({},disabled,{className:active}),(0,_map2.default)(cells,function(cell){return _TableCell.default.create(cell,{defaultProps:{as:cellAs}})})):_react.default.createElement(error,(0,_extends2.default)({},disabled,{className:active}),children)}TableRow.handledProps=["active","as","cellAs","cells","children","className","disabled","error","negative","positive","textAlign","verticalAlign","warning"],TableRow.defaultProps={as:"tr",cellAs:"td"},TableRow.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,cellAs:_propTypes.default.elementType,cells:_lib.customPropTypes.collectionShorthand,children:_propTypes.default.node,className:_propTypes.default.string,disabled:_propTypes.default.bool,error:_propTypes.default.bool,negative:_propTypes.default.bool,positive:_propTypes.default.bool,textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified")),verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS),warning:_propTypes.default.bool}:{},TableRow.create=(0,_lib.createShorthandFactory)(TableRow,function(cells){return{cells:cells}}),exports.default=TableRow}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./TableCell":1504,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/map":989,"lodash/without":1028,"prop-types":1046,react:1427}],1509:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Table=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Table.default}}),_interopRequireDefault(require("./Table")))},{"./Table":1502,"@babel/runtime/helpers/interopRequireDefault":13}],1510:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../Icon/Icon")),_Label=_interopRequireDefault(require("../Label/Label")),_interopRequireWildcard=_interopRequireDefault(require("./ButtonContent")),_ButtonGroup=_interopRequireDefault(require("./ButtonGroup")),_interopRequireDefault=_interopRequireDefault(require("./ButtonOr")),Button=function(_Component){function Button(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Button);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Button)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"ref",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeElementType",function(){var _this$props=_this.props,attached=_this$props.attached,_this$props=_this$props.label;if(!(0,_isNil2.default)(attached)||!(0,_isNil2.default)(_this$props))return"div"}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeTabIndex",function(ElementType){var _this$props2=_this.props,disabled=_this$props2.disabled,_this$props2=_this$props2.tabIndex;return(0,_isNil2.default)(_this$props2)?disabled?-1:"div"===ElementType?0:void 0:_this$props2}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"focus",function(){return(0,_invoke2.default)(_this.ref.current,"focus")}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){_this.props.disabled?e.preventDefault():(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"hasIconClass",function(){var _this$props3=_this.props,labelPosition=_this$props3.labelPosition,children=_this$props3.children,content=_this$props3.content,_this$props3=_this$props3.icon;return!0===_this$props3||_this$props3&&(labelPosition||_lib.childrenUtils.isNil(children)&&(0,_isNil2.default)(content))}),_this}return(0,_inherits2.default)(Button,_Component),(0,_createClass2.default)(Button,[{key:"computeButtonAriaRole",value:function(ElementType){var role=this.props.role;return(0,_isNil2.default)(role)?"button"!==ElementType?"button":void 0:role}},{key:"render",value:function(){var _this$props4=this.props,active=_this$props4.active,animated=_this$props4.animated,attached=_this$props4.attached,basic=_this$props4.basic,children=_this$props4.children,circular=_this$props4.circular,className=_this$props4.className,color=_this$props4.color,compact=_this$props4.compact,content=_this$props4.content,disabled=_this$props4.disabled,floated=_this$props4.floated,fluid=_this$props4.fluid,icon=_this$props4.icon,inverted=_this$props4.inverted,label=_this$props4.label,labelPosition=_this$props4.labelPosition,loading=_this$props4.loading,negative=_this$props4.negative,positive=_this$props4.positive,primary=_this$props4.primary,secondary=_this$props4.secondary,size=_this$props4.size,_this$props4=_this$props4.toggle,color=(0,_classnames.default)(color,size,(0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(basic,"basic"),(0,_lib.useKeyOnly)(circular,"circular"),(0,_lib.useKeyOnly)(compact,"compact"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(this.hasIconClass(),"icon"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(loading,"loading"),(0,_lib.useKeyOnly)(negative,"negative"),(0,_lib.useKeyOnly)(positive,"positive"),(0,_lib.useKeyOnly)(primary,"primary"),(0,_lib.useKeyOnly)(secondary,"secondary"),(0,_lib.useKeyOnly)(_this$props4,"toggle"),(0,_lib.useKeyOrValueAndKey)(animated,"animated"),(0,_lib.useKeyOrValueAndKey)(attached,"attached")),size=(0,_classnames.default)((0,_lib.useKeyOrValueAndKey)(labelPosition||!!label,"labeled")),basic=(0,_classnames.default)((0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useValueAndKey)(floated,"floated")),circular=(0,_lib.getUnhandledProps)(Button,this.props),compact=(0,_lib.getElementType)(Button,this.props,this.computeElementType),fluid=this.computeTabIndex(compact);return(0,_isNil2.default)(label)?(inverted=(0,_classnames.default)("ui",color,basic,size,"button",className),loading=!_lib.childrenUtils.isNil(children),negative=this.computeButtonAriaRole(compact),_react.default.createElement(_reactComponentRef.Ref,{innerRef:this.ref},_react.default.createElement(compact,(0,_extends2.default)({},circular,{className:inverted,"aria-pressed":_this$props4?!!active:void 0,disabled:disabled&&"button"===compact||void 0,onClick:this.handleClick,role:negative,tabIndex:fluid}),loading&&children,!loading&&_Icon.default.create(icon,{autoGenerateKey:!1}),!loading&&content))):(positive=(0,_classnames.default)("ui",color,"button",className),primary=(0,_classnames.default)("ui",size,"button",className,basic),secondary=_Label.default.create(label,{defaultProps:{basic:!0,pointing:"left"===labelPosition?"right":"left"},autoGenerateKey:!1}),_react.default.createElement(compact,(0,_extends2.default)({},circular,{className:primary,onClick:this.handleClick}),"left"===labelPosition&&secondary,_react.default.createElement(_reactComponentRef.Ref,{innerRef:this.ref},_react.default.createElement("button",{className:positive,"aria-pressed":_this$props4?!!active:void 0,disabled:disabled,tabIndex:fluid},_Icon.default.create(icon,{autoGenerateKey:!1})," ",content)),("right"===labelPosition||!labelPosition)&&secondary))}}]),Button}(_react.Component);(0,_defineProperty2.default)(Button,"defaultProps",{as:"button"}),(0,_defineProperty2.default)(Button,"Content",_interopRequireWildcard.default),(0,_defineProperty2.default)(Button,"Group",_ButtonGroup.default),(0,_defineProperty2.default)(Button,"Or",_interopRequireDefault.default),(0,_defineProperty2.default)(Button,"handledProps",["active","animated","as","attached","basic","children","circular","className","color","compact","content","disabled","floated","fluid","icon","inverted","label","labelPosition","loading","negative","onClick","positive","primary","role","secondary","size","tabIndex","toggle"]),Button.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,animated:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["fade","vertical"])]),attached:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["left","right","top","bottom"])]),basic:_propTypes.default.bool,children:_lib.customPropTypes.every([_propTypes.default.node,_lib.customPropTypes.disallow(["label"]),_lib.customPropTypes.givenProps({icon:_propTypes.default.oneOfType([_propTypes.default.string.isRequired,_propTypes.default.object.isRequired,_propTypes.default.element.isRequired])},_lib.customPropTypes.disallow(["icon"]))]),circular:_propTypes.default.bool,className:_propTypes.default.string,color:_propTypes.default.oneOf([].concat((0,_toConsumableArray2.default)(_lib.SUI.COLORS),["facebook","google plus","instagram","linkedin","twitter","vk","youtube"])),compact:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,disabled:_propTypes.default.bool,floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),fluid:_propTypes.default.bool,icon:_lib.customPropTypes.some([_propTypes.default.bool,_propTypes.default.string,_propTypes.default.object,_propTypes.default.element]),inverted:_propTypes.default.bool,label:_lib.customPropTypes.some([_propTypes.default.string,_propTypes.default.object,_propTypes.default.element]),labelPosition:_propTypes.default.oneOf(["right","left"]),loading:_propTypes.default.bool,negative:_propTypes.default.bool,onClick:_propTypes.default.func,positive:_propTypes.default.bool,primary:_propTypes.default.bool,role:_propTypes.default.string,secondary:_propTypes.default.bool,size:_propTypes.default.oneOf(_lib.SUI.SIZES),tabIndex:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),toggle:_propTypes.default.bool}:{},Button.create=(0,_lib.createShorthandFactory)(Button,function(value){return{content:value}}),exports.default=Button}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../Icon/Icon":1525,"../Label/Label":1533,"./ButtonContent":1511,"./ButtonGroup":1512,"./ButtonOr":1513,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,"@babel/runtime/helpers/toConsumableArray":27,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"lodash/invoke":959,"lodash/isNil":972,"prop-types":1046,react:1427}],1511:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ButtonContent(props){var children=props.children,className=props.className,content=props.content,hidden=props.hidden,visible=props.visible,visible=(0,_classnames.default)((0,_lib.useKeyOnly)(visible,"visible"),(0,_lib.useKeyOnly)(hidden,"hidden"),"content",className),hidden=(0,_lib.getUnhandledProps)(ButtonContent,props),className=(0,_lib.getElementType)(ButtonContent,props);return _react.default.createElement(className,(0,_extends2.default)({},hidden,{className:visible}),_lib.childrenUtils.isNil(children)?content:children)}ButtonContent.handledProps=["as","children","className","content","hidden","visible"],ButtonContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,hidden:_propTypes.default.bool,visible:_propTypes.default.bool}:{},exports.default=ButtonContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1512:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_map2=_interopRequireDefault(require("lodash/map")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Button=_interopRequireDefault(require("./Button"));function ButtonGroup(props){var attached=props.attached,basic=props.basic,buttons=props.buttons,children=props.children,className=props.className,color=props.color,compact=props.compact,content=props.content,floated=props.floated,fluid=props.fluid,icon=props.icon,inverted=props.inverted,labeled=props.labeled,negative=props.negative,positive=props.positive,primary=props.primary,secondary=props.secondary,size=props.size,toggle=props.toggle,vertical=props.vertical,widths=props.widths,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(basic,"basic"),(0,_lib.useKeyOnly)(compact,"compact"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(icon,"icon"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(labeled,"labeled"),(0,_lib.useKeyOnly)(negative,"negative"),(0,_lib.useKeyOnly)(positive,"positive"),(0,_lib.useKeyOnly)(primary,"primary"),(0,_lib.useKeyOnly)(secondary,"secondary"),(0,_lib.useKeyOnly)(toggle,"toggle"),(0,_lib.useKeyOnly)(vertical,"vertical"),(0,_lib.useKeyOrValueAndKey)(attached,"attached"),(0,_lib.useValueAndKey)(floated,"floated"),(0,_lib.useWidthProp)(widths),"buttons",className),size=(0,_lib.getUnhandledProps)(ButtonGroup,props),basic=(0,_lib.getElementType)(ButtonGroup,props);return(0,_isNil2.default)(buttons)?_react.default.createElement(basic,(0,_extends2.default)({},size,{className:color}),_lib.childrenUtils.isNil(children)?content:children):_react.default.createElement(basic,(0,_extends2.default)({},size,{className:color}),(0,_map2.default)(buttons,function(button){return _Button.default.create(button)}))}ButtonGroup.handledProps=["as","attached","basic","buttons","children","className","color","compact","content","floated","fluid","icon","inverted","labeled","negative","positive","primary","secondary","size","toggle","vertical","widths"],ButtonGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,attached:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["left","right","top","bottom"])]),basic:_propTypes.default.bool,buttons:_lib.customPropTypes.collectionShorthand,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),compact:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),fluid:_propTypes.default.bool,icon:_propTypes.default.bool,inverted:_propTypes.default.bool,labeled:_propTypes.default.bool,negative:_propTypes.default.bool,positive:_propTypes.default.bool,primary:_propTypes.default.bool,secondary:_propTypes.default.bool,size:_propTypes.default.oneOf(_lib.SUI.SIZES),toggle:_propTypes.default.bool,vertical:_propTypes.default.bool,widths:_propTypes.default.oneOf(_lib.SUI.WIDTHS)}:{},exports.default=ButtonGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./Button":1510,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/isNil":972,"lodash/map":989,"prop-types":1046,react:1427}],1513:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ButtonOr(props){var className=props.className,text=props.text,className=(0,_classnames.default)("or",className),rest=(0,_lib.getUnhandledProps)(ButtonOr,props),props=(0,_lib.getElementType)(ButtonOr,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className,"data-text":text}))}ButtonOr.handledProps=["as","className","text"],ButtonOr.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,className:_propTypes.default.string,text:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string])}:{},exports.default=ButtonOr}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1514:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Button=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Button.default}}),_interopRequireDefault(require("./Button")))},{"./Button":1510,"@babel/runtime/helpers/interopRequireDefault":13}],1515:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function Container(props){var children=props.children,className=props.className,content=props.content,fluid=props.fluid,text=props.text,textAlign=props.textAlign,text=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(text,"text"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useTextAlignProp)(textAlign),"container",className),fluid=(0,_lib.getUnhandledProps)(Container,props),textAlign=(0,_lib.getElementType)(Container,props);return _react.default.createElement(textAlign,(0,_extends2.default)({},fluid,{className:text}),_lib.childrenUtils.isNil(children)?content:children)}Container.handledProps=["as","children","className","content","fluid","text","textAlign"],Container.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,fluid:_propTypes.default.bool,text:_propTypes.default.bool,textAlign:_propTypes.default.oneOf(_lib.SUI.TEXT_ALIGNMENTS)}:{},exports.default=Container}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1516:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Container=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Container.default}}),_interopRequireDefault(require("./Container")))},{"./Container":1515,"@babel/runtime/helpers/interopRequireDefault":13}],1517:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function Divider(props){var children=props.children,className=props.className,clearing=props.clearing,content=props.content,fitted=props.fitted,hidden=props.hidden,horizontal=props.horizontal,inverted=props.inverted,section=props.section,vertical=props.vertical,clearing=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(clearing,"clearing"),(0,_lib.useKeyOnly)(fitted,"fitted"),(0,_lib.useKeyOnly)(hidden,"hidden"),(0,_lib.useKeyOnly)(horizontal,"horizontal"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(section,"section"),(0,_lib.useKeyOnly)(vertical,"vertical"),"divider",className),fitted=(0,_lib.getUnhandledProps)(Divider,props),hidden=(0,_lib.getElementType)(Divider,props);return _react.default.createElement(hidden,(0,_extends2.default)({},fitted,{className:clearing}),_lib.childrenUtils.isNil(children)?content:children)}Divider.handledProps=["as","children","className","clearing","content","fitted","hidden","horizontal","inverted","section","vertical"],Divider.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,clearing:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,fitted:_propTypes.default.bool,hidden:_propTypes.default.bool,horizontal:_propTypes.default.bool,inverted:_propTypes.default.bool,section:_propTypes.default.bool,vertical:_propTypes.default.bool}:{},exports.default=Divider}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1518:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Divider=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Divider.default}}),_interopRequireDefault(require("./Divider")))},{"./Divider":1517,"@babel/runtime/helpers/interopRequireDefault":13}],1519:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=exports.names=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_classnames=_interopRequireDefault(require("classnames")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=["ad","andorra","ae","united arab emirates","uae","af","afghanistan","ag","antigua","ai","anguilla","al","albania","am","armenia","an","netherlands antilles","ao","angola","ar","argentina","as","american samoa","at","austria","au","australia","aw","aruba","ax","aland islands","az","azerbaijan","ba","bosnia","bb","barbados","bd","bangladesh","be","belgium","bf","burkina faso","bg","bulgaria","bh","bahrain","bi","burundi","bj","benin","bm","bermuda","bn","brunei","bo","bolivia","br","brazil","bs","bahamas","bt","bhutan","bv","bouvet island","bw","botswana","by","belarus","bz","belize","ca","canada","cc","cocos islands","cd","congo","cf","central african republic","cg","congo brazzaville","ch","switzerland","ci","cote divoire","ck","cook islands","cl","chile","cm","cameroon","cn","china","co","colombia","cr","costa rica","cs","cu","cuba","cv","cape verde","cx","christmas island","cy","cyprus","cz","czech republic","de","germany","dj","djibouti","dk","denmark","dm","dominica","do","dominican republic","dz","algeria","ec","ecuador","ee","estonia","eg","egypt","eh","western sahara","er","eritrea","es","spain","et","ethiopia","eu","european union","fi","finland","fj","fiji","fk","falkland islands","fm","micronesia","fo","faroe islands","fr","france","ga","gabon","gb","uk","united kingdom","gd","grenada","ge","georgia","gf","french guiana","gh","ghana","gi","gibraltar","gl","greenland","gm","gambia","gn","guinea","gp","guadeloupe","gq","equatorial guinea","gr","greece","gs","sandwich islands","gt","guatemala","gu","guam","gw","guinea-bissau","gy","guyana","hk","hong kong","hm","heard island","hn","honduras","hr","croatia","ht","haiti","hu","hungary","id","indonesia","ie","ireland","il","israel","in","india","io","indian ocean territory","iq","iraq","ir","iran","is","iceland","it","italy","jm","jamaica","jo","jordan","jp","japan","ke","kenya","kg","kyrgyzstan","kh","cambodia","ki","kiribati","km","comoros","kn","saint kitts and nevis","kp","north korea","kr","south korea","kw","kuwait","ky","cayman islands","kz","kazakhstan","la","laos","lb","lebanon","lc","saint lucia","li","liechtenstein","lk","sri lanka","lr","liberia","ls","lesotho","lt","lithuania","lu","luxembourg","lv","latvia","ly","libya","ma","morocco","mc","monaco","md","moldova","me","montenegro","mg","madagascar","mh","marshall islands","mk","macedonia","ml","mali","mm","myanmar","burma","mn","mongolia","mo","macau","mp","northern mariana islands","mq","martinique","mr","mauritania","ms","montserrat","mt","malta","mu","mauritius","mv","maldives","mw","malawi","mx","mexico","my","malaysia","mz","mozambique","na","namibia","nc","new caledonia","ne","niger","nf","norfolk island","ng","nigeria","ni","nicaragua","nl","netherlands","no","norway","np","nepal","nr","nauru","nu","niue","nz","new zealand","om","oman","pa","panama","pe","peru","pf","french polynesia","pg","new guinea","ph","philippines","pk","pakistan","pl","poland","pm","saint pierre","pn","pitcairn islands","pr","puerto rico","ps","palestine","pt","portugal","pw","palau","py","paraguay","qa","qatar","re","reunion","ro","romania","rs","serbia","ru","russia","rw","rwanda","sa","saudi arabia","sb","solomon islands","sc","seychelles","gb sct","scotland","sd","sudan","se","sweden","sg","singapore","sh","saint helena","si","slovenia","sj","svalbard","jan mayen","sk","slovakia","sl","sierra leone","sm","san marino","sn","senegal","so","somalia","sr","suriname","st","sao tome","sv","el salvador","sy","syria","sz","swaziland","tc","caicos islands","td","chad","tf","french territories","tg","togo","th","thailand","tj","tajikistan","tk","tokelau","tl","timorleste","tm","turkmenistan","tn","tunisia","to","tonga","tr","turkey","tt","trinidad","tv","tuvalu","tw","taiwan","tz","tanzania","ua","ukraine","ug","uganda","um","us minor islands","us","america","united states","uy","uruguay","uz","uzbekistan","va","vatican city","vc","saint vincent","ve","venezuela","vg","british virgin islands","vi","us virgin islands","vn","vietnam","vu","vanuatu","gb wls","wales","wf","wallis and futuna","ws","samoa","ye","yemen","yt","mayotte","za","south africa","zm","zambia","zw","zimbabwe"],Flag=(exports.names=_interopRequireWildcard,function(_PureComponent){function Flag(){return(0,_classCallCheck2.default)(this,Flag),(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Flag).apply(this,arguments))}return(0,_inherits2.default)(Flag,_PureComponent),(0,_createClass2.default)(Flag,[{key:"render",value:function(){var _this$props=this.props,className=_this$props.className,_this$props=_this$props.name,_this$props=(0,_classnames.default)(_this$props,"flag",className),className=(0,_lib.getUnhandledProps)(Flag,this.props),ElementType=(0,_lib.getElementType)(Flag,this.props);return _react.default.createElement(ElementType,(0,_extends2.default)({},className,{className:_this$props}))}}]),Flag}(_react.PureComponent));(0,_defineProperty2.default)(Flag,"defaultProps",{as:"i"}),(0,_defineProperty2.default)(Flag,"handledProps",["as","className","name"]),Flag.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,className:_interopRequireDefault.default.string,name:_lib.customPropTypes.suggest(_interopRequireWildcard)}:{},Flag.create=(0,_lib.createShorthandFactory)(Flag,function(value){return{name:value}}),exports.default=Flag}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"prop-types":1046,react:1427}],1520:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Flag=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Flag.default}}),_interopRequireDefault(require("./Flag")))},{"./Flag":1519,"@babel/runtime/helpers/interopRequireDefault":13}],1521:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../Icon")),_Image=_interopRequireDefault(require("../Image")),_HeaderSubheader=_interopRequireDefault(require("./HeaderSubheader")),_HeaderContent=_interopRequireDefault(require("./HeaderContent"));function Header(props){var attached=props.attached,block=props.block,children=props.children,className=props.className,color=props.color,content=props.content,disabled=props.disabled,dividing=props.dividing,floated=props.floated,icon=props.icon,image=props.image,inverted=props.inverted,size=props.size,sub=props.sub,subheader=props.subheader,textAlign=props.textAlign,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(block,"block"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(dividing,"dividing"),(0,_lib.useValueAndKey)(floated,"floated"),(0,_lib.useKeyOnly)(!0===icon,"icon"),(0,_lib.useKeyOnly)(!0===image,"image"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(sub,"sub"),(0,_lib.useKeyOrValueAndKey)(attached,"attached"),(0,_lib.useTextAlignProp)(textAlign),"header",className),size=(0,_lib.getUnhandledProps)(Header,props),block=(0,_lib.getElementType)(Header,props);return _lib.childrenUtils.isNil(children)?(disabled=_Icon.default.create(icon,{autoGenerateKey:!1}),dividing=_Image.default.create(image,{autoGenerateKey:!1}),floated=_HeaderSubheader.default.create(subheader,{autoGenerateKey:!1}),disabled||dividing?_react.default.createElement(block,(0,_extends2.default)({},size,{className:color}),disabled||dividing,(content||floated)&&_react.default.createElement(_HeaderContent.default,null,content,floated)):_react.default.createElement(block,(0,_extends2.default)({},size,{className:color}),content,floated)):_react.default.createElement(block,(0,_extends2.default)({},size,{className:color}),children)}Header.handledProps=["as","attached","block","children","className","color","content","disabled","dividing","floated","icon","image","inverted","size","sub","subheader","textAlign"],Header.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,attached:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["top","bottom"])]),block:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),content:_lib.customPropTypes.contentShorthand,disabled:_propTypes.default.bool,dividing:_propTypes.default.bool,floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),icon:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["image"]),_propTypes.default.oneOfType([_propTypes.default.bool,_lib.customPropTypes.itemShorthand])]),image:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["icon"]),_propTypes.default.oneOfType([_propTypes.default.bool,_lib.customPropTypes.itemShorthand])]),inverted:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"big","massive","mini")),sub:_propTypes.default.bool,subheader:_lib.customPropTypes.itemShorthand,textAlign:_propTypes.default.oneOf(_lib.SUI.TEXT_ALIGNMENTS)}:{},Header.Content=_HeaderContent.default,Header.Subheader=_HeaderSubheader.default,exports.default=Header}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../Icon":1527,"../Image":1530,"./HeaderContent":1522,"./HeaderSubheader":1523,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1522:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function HeaderContent(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("content",className),rest=(0,_lib.getUnhandledProps)(HeaderContent,props),props=(0,_lib.getElementType)(HeaderContent,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}HeaderContent.handledProps=["as","children","className","content"],HeaderContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=HeaderContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1523:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function HeaderSubheader(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("sub header",className),rest=(0,_lib.getUnhandledProps)(HeaderSubheader,props),props=(0,_lib.getElementType)(HeaderSubheader,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}HeaderSubheader.handledProps=["as","children","className","content"],HeaderSubheader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},HeaderSubheader.create=(0,_lib.createShorthandFactory)(HeaderSubheader,function(content){return{content:content}}),exports.default=HeaderSubheader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1524:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Header=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Header.default}}),_interopRequireDefault(require("./Header")))},{"./Header":1521,"@babel/runtime/helpers/interopRequireDefault":13}],1525:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=_interopRequireDefault(require("./IconGroup")),_interopRequireDefault=function(_PureComponent){function Icon(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Icon);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Icon)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){_this.props.disabled?e.preventDefault():(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),_this}return(0,_inherits2.default)(Icon,_PureComponent),(0,_createClass2.default)(Icon,[{key:"getIconAriaOptions",value:function(){var ariaOptions={},_this$props=this.props,ariaLabel=_this$props["aria-label"],_this$props=_this$props["aria-hidden"];return(0,_isNil2.default)(ariaLabel)?ariaOptions["aria-hidden"]="true":ariaOptions["aria-label"]=ariaLabel,(0,_isNil2.default)(_this$props)||(ariaOptions["aria-hidden"]=_this$props),ariaOptions}},{key:"render",value:function(){var _this$props2=this.props,bordered=_this$props2.bordered,circular=_this$props2.circular,className=_this$props2.className,color=_this$props2.color,corner=_this$props2.corner,disabled=_this$props2.disabled,fitted=_this$props2.fitted,flipped=_this$props2.flipped,inverted=_this$props2.inverted,link=_this$props2.link,loading=_this$props2.loading,name=_this$props2.name,rotated=_this$props2.rotated,_this$props2=_this$props2.size,color=(0,_classnames.default)(color,name,_this$props2,(0,_lib.useKeyOnly)(bordered,"bordered"),(0,_lib.useKeyOnly)(circular,"circular"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(fitted,"fitted"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(link,"link"),(0,_lib.useKeyOnly)(loading,"loading"),(0,_lib.useKeyOrValueAndKey)(corner,"corner"),(0,_lib.useValueAndKey)(flipped,"flipped"),(0,_lib.useValueAndKey)(rotated,"rotated"),"icon",className),name=(0,_lib.getUnhandledProps)(Icon,this.props),_this$props2=(0,_lib.getElementType)(Icon,this.props),bordered=this.getIconAriaOptions();return _react.default.createElement(_this$props2,(0,_extends2.default)({},name,bordered,{className:color,onClick:this.handleClick}))}}]),Icon}(_react.PureComponent);(0,_defineProperty2.default)(_interopRequireDefault,"defaultProps",{as:"i"}),(0,_defineProperty2.default)(_interopRequireDefault,"Group",_interopRequireWildcard.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["aria-hidden","aria-label","as","bordered","circular","className","color","corner","disabled","fitted","flipped","inverted","link","loading","name","rotated","size"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,bordered:_propTypes.default.bool,circular:_propTypes.default.bool,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),corner:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["top left","top right","bottom left","bottom right"])]),disabled:_propTypes.default.bool,fitted:_propTypes.default.bool,flipped:_propTypes.default.oneOf(["horizontally","vertically"]),inverted:_propTypes.default.bool,link:_propTypes.default.bool,loading:_propTypes.default.bool,name:_lib.customPropTypes.suggest(_lib.SUI.ALL_ICONS_IN_ALL_CONTEXTS),rotated:_propTypes.default.oneOf(["clockwise","counterclockwise"]),size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium")),"aria-hidden":_propTypes.default.string,"aria-label":_propTypes.default.string}:{},_interopRequireDefault.create=(0,_lib.createShorthandFactory)(_interopRequireDefault,function(value){return{name:value}}),exports.default=_interopRequireDefault}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./IconGroup":1526,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/isNil":972,"lodash/without":1028,"prop-types":1046,react:1427}],1526:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function IconGroup(props){var children=props.children,className=props.className,content=props.content,size=props.size,size=(0,_classnames.default)(size,"icons",className),className=(0,_lib.getUnhandledProps)(IconGroup,props),props=(0,_lib.getElementType)(IconGroup,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:size}),_lib.childrenUtils.isNil(children)?content:children)}IconGroup.handledProps=["as","children","className","content","size"],IconGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium"))}:{},IconGroup.defaultProps={as:"i"},exports.default=IconGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1527:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Icon=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Icon.default}}),_interopRequireDefault(require("./Icon")))},{"./Icon":1525,"@babel/runtime/helpers/interopRequireDefault":13}],1528:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Dimmer=_interopRequireDefault(require("../../modules/Dimmer")),_Label=_interopRequireDefault(require("../Label/Label")),_interopRequireDefault=_interopRequireDefault(require("./ImageGroup"));function Image(props){var avatar=props.avatar,bordered=props.bordered,centered=props.centered,children=props.children,circular=props.circular,className=props.className,content=props.content,dimmer=props.dimmer,disabled=props.disabled,floated=props.floated,fluid=props.fluid,hidden=props.hidden,href=props.href,inline=props.inline,label=props.label,rounded=props.rounded,size=props.size,spaced=props.spaced,verticalAlign=props.verticalAlign,wrapped=props.wrapped,ui=props.ui,ui=(0,_classnames.default)((0,_lib.useKeyOnly)(ui,"ui"),size,(0,_lib.useKeyOnly)(avatar,"avatar"),(0,_lib.useKeyOnly)(bordered,"bordered"),(0,_lib.useKeyOnly)(circular,"circular"),(0,_lib.useKeyOnly)(centered,"centered"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(hidden,"hidden"),(0,_lib.useKeyOnly)(inline,"inline"),(0,_lib.useKeyOnly)(rounded,"rounded"),(0,_lib.useKeyOrValueAndKey)(spaced,"spaced"),(0,_lib.useValueAndKey)(floated,"floated"),(0,_lib.useVerticalAlignProp)(verticalAlign,"aligned"),"image",className),size=(0,_lib.getUnhandledProps)(Image,props),avatar=(0,_lib.partitionHTMLProps)(size,{htmlProps:_lib.htmlImageProps}),bordered=(0,_slicedToArray2.default)(avatar,2),circular=bordered[0],centered=bordered[1],disabled=(0,_lib.getElementType)(Image,props,function(){if(!((0,_isNil2.default)(dimmer)&&(0,_isNil2.default)(label)&&(0,_isNil2.default)(wrapped)&&_lib.childrenUtils.isNil(children)))return"div"});return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?"img"===disabled?_react.default.createElement(disabled,(0,_extends2.default)({},centered,circular,{className:ui})):_react.default.createElement(disabled,(0,_extends2.default)({},centered,{className:ui,href:href}),_Dimmer.default.create(dimmer,{autoGenerateKey:!1}),_Label.default.create(label,{autoGenerateKey:!1}),_react.default.createElement("img",circular)):_react.default.createElement(disabled,(0,_extends2.default)({},size,{className:ui}),content):_react.default.createElement(disabled,(0,_extends2.default)({},size,{className:ui}),children)}Image.handledProps=["as","avatar","bordered","centered","children","circular","className","content","dimmer","disabled","floated","fluid","hidden","href","inline","label","rounded","size","spaced","ui","verticalAlign","wrapped"],Image.Group=_interopRequireDefault.default,Image.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,avatar:_propTypes.default.bool,bordered:_propTypes.default.bool,centered:_propTypes.default.bool,children:_propTypes.default.node,circular:_propTypes.default.bool,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,disabled:_propTypes.default.bool,dimmer:_lib.customPropTypes.itemShorthand,floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),fluid:_lib.customPropTypes.every([_propTypes.default.bool,_lib.customPropTypes.disallow(["size"])]),hidden:_propTypes.default.bool,href:_propTypes.default.string,inline:_propTypes.default.bool,label:_lib.customPropTypes.itemShorthand,rounded:_propTypes.default.bool,size:_propTypes.default.oneOf(_lib.SUI.SIZES),spaced:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["left","right"])]),ui:_propTypes.default.bool,verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS),wrapped:_propTypes.default.bool}:{},Image.defaultProps={as:"img",ui:!0},Image.create=(0,_lib.createShorthandFactory)(Image,function(value){return{src:value}}),exports.default=Image}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../../modules/Dimmer":1605,"../Label/Label":1533,"./ImageGroup":1529,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/slicedToArray":25,_process:1042,classnames:116,"lodash/isNil":972,"prop-types":1046,react:1427}],1529:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ImageGroup(props){var children=props.children,className=props.className,content=props.content,size=props.size,size=(0,_classnames.default)("ui",size,className,"images"),className=(0,_lib.getUnhandledProps)(ImageGroup,props),props=(0,_lib.getElementType)(ImageGroup,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:size}),_lib.childrenUtils.isNil(children)?content:children)}ImageGroup.handledProps=["as","children","className","content","size"],ImageGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,size:_propTypes.default.oneOf(_lib.SUI.SIZES)}:{},exports.default=ImageGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1530:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Image=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Image.default}}),_interopRequireDefault(require("./Image")))},{"./Image":1528,"@babel/runtime/helpers/interopRequireDefault":13}],1531:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_includes2=_interopRequireDefault(require("lodash/includes")),_map2=_interopRequireDefault(require("lodash/map")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_get2=_interopRequireDefault(require("lodash/get")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Button=_interopRequireDefault(require("../Button")),_Icon=_interopRequireDefault(require("../Icon")),_Label=_interopRequireDefault(require("../Label")),_interopRequireWildcard=function(_Component){function Input(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Input);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Input)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"inputRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeIcon",function(){var _this$props=_this.props,loading=_this$props.loading,_this$props=_this$props.icon;return(0,_isNil2.default)(_this$props)?loading?"spinner":void 0:_this$props}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeTabIndex",function(){var _this$props2=_this.props,disabled=_this$props2.disabled,_this$props2=_this$props2.tabIndex;return(0,_isNil2.default)(_this$props2)?disabled?-1:void 0:_this$props2}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"focus",function(){return _this.inputRef.current.focus()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"select",function(){return _this.inputRef.current.select()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleChange",function(e){var value=(0,_get2.default)(e,"target.value");(0,_invoke2.default)(_this.props,"onChange",e,(0,_objectSpread2.default)({},_this.props,{value:value}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleChildOverrides",function(child,defaultProps){return(0,_objectSpread2.default)({},defaultProps,child.props,{ref:function(c){(0,_reactComponentRef.handleRef)(child.ref,c),_this.inputRef.current=c}})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"partitionProps",function(){var _this$props3=_this.props,disabled=_this$props3.disabled,_this$props3=_this$props3.type,tabIndex=_this.computeTabIndex(),unhandled=(0,_lib.getUnhandledProps)(Input,_this.props),unhandled=(0,_lib.partitionHTMLProps)(unhandled),unhandled=(0,_slicedToArray2.default)(unhandled,2),htmlInputProps=unhandled[0],unhandled=unhandled[1];return[(0,_objectSpread2.default)({},htmlInputProps,{disabled:disabled,type:_this$props3,tabIndex:tabIndex,onChange:_this.handleChange,ref:_this.inputRef}),unhandled]}),_this}return(0,_inherits2.default)(Input,_Component),(0,_createClass2.default)(Input,[{key:"render",value:function(){var _this2=this,_this$props4=this.props,action=_this$props4.action,actionPosition=_this$props4.actionPosition,children=_this$props4.children,className=_this$props4.className,disabled=_this$props4.disabled,error=_this$props4.error,fluid=_this$props4.fluid,focus=_this$props4.focus,icon=_this$props4.icon,iconPosition=_this$props4.iconPosition,input=_this$props4.input,inverted=_this$props4.inverted,label=_this$props4.label,labelPosition=_this$props4.labelPosition,loading=_this$props4.loading,size=_this$props4.size,transparent=_this$props4.transparent,_this$props4=_this$props4.type,size=(0,_classnames.default)("ui",size,(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(error,"error"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(focus,"focus"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(loading,"loading"),(0,_lib.useKeyOnly)(transparent,"transparent"),(0,_lib.useValueAndKey)(actionPosition,"action")||(0,_lib.useKeyOnly)(action,"action"),(0,_lib.useValueAndKey)(iconPosition,"icon")||(0,_lib.useKeyOnly)(icon||loading,"icon"),(0,_lib.useValueAndKey)(labelPosition,"labeled")||(0,_lib.useKeyOnly)(label,"labeled"),"input",className),disabled=(0,_lib.getElementType)(Input,this.props),error=this.partitionProps(),fluid=(0,_slicedToArray2.default)(error,2),htmlInputProps=fluid[0],focus=fluid[1];return _lib.childrenUtils.isNil(children)?(inverted=_Button.default.create(action,{autoGenerateKey:!1}),transparent=_Label.default.create(label,{defaultProps:{className:(0,_classnames.default)("label",(0,_includes2.default)(labelPosition,"corner")&&labelPosition)},autoGenerateKey:!1}),_react.default.createElement(disabled,(0,_extends2.default)({},focus,{className:size}),"left"===actionPosition&&inverted,"right"!==labelPosition&&transparent,(0,_lib.createHTMLInput)(input||_this$props4,{defaultProps:htmlInputProps,autoGenerateKey:!1}),_Icon.default.create(this.computeIcon(),{autoGenerateKey:!1}),"left"!==actionPosition&&inverted,"right"===labelPosition&&transparent)):(iconPosition=(0,_map2.default)(_react.Children.toArray(children),function(child){return"input"!==child.type?child:(0,_react.cloneElement)(child,_this2.handleChildOverrides(child,htmlInputProps))}),_react.default.createElement(disabled,(0,_extends2.default)({},focus,{className:size}),iconPosition))}}]),Input}(_react.Component);(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{type:"text"}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["action","actionPosition","as","children","className","disabled","error","fluid","focus","icon","iconPosition","input","inverted","label","labelPosition","loading","onChange","size","tabIndex","transparent","type"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,action:_propTypes.default.oneOfType([_propTypes.default.bool,_lib.customPropTypes.itemShorthand]),actionPosition:_propTypes.default.oneOf(["left"]),children:_propTypes.default.node,className:_propTypes.default.string,disabled:_propTypes.default.bool,error:_propTypes.default.bool,fluid:_propTypes.default.bool,focus:_propTypes.default.bool,icon:_propTypes.default.oneOfType([_propTypes.default.bool,_lib.customPropTypes.itemShorthand]),iconPosition:_propTypes.default.oneOf(["left"]),input:_lib.customPropTypes.itemShorthand,inverted:_propTypes.default.bool,label:_lib.customPropTypes.itemShorthand,labelPosition:_propTypes.default.oneOf(["left","right","left corner","right corner"]),loading:_propTypes.default.bool,onChange:_propTypes.default.func,size:_propTypes.default.oneOf(["mini","small","large","big","huge","massive"]),tabIndex:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),transparent:_propTypes.default.bool,type:_propTypes.default.string}:{},_interopRequireWildcard.create=(0,_lib.createShorthandFactory)(_interopRequireWildcard,function(type){return{type:type}}),exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../Button":1514,"../Icon":1527,"../Label":1536,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@babel/runtime/helpers/slicedToArray":25,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"lodash/get":950,"lodash/includes":956,"lodash/invoke":959,"lodash/isNil":972,"lodash/map":989,"prop-types":1046,react:1427}],1532:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Input=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Input.default}}),_interopRequireDefault(require("./Input")))},{"./Input":1531,"@babel/runtime/helpers/interopRequireDefault":13}],1533:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_isUndefined2=_interopRequireDefault(require("lodash/isUndefined")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../Icon/Icon")),_Image=_interopRequireDefault(require("../Image/Image")),_LabelDetail=_interopRequireDefault(require("./LabelDetail")),_interopRequireWildcard=_interopRequireDefault(require("./LabelGroup")),_interopRequireDefault=function(_Component){function Label(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Label);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Label)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){var onClick=_this.props.onClick;onClick&&onClick(e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleIconOverrides",function(predefinedProps){return{onClick:function(e){(0,_invoke2.default)(predefinedProps,"onClick",e),(0,_invoke2.default)(_this.props,"onRemove",e,_this.props)}}}),_this}return(0,_inherits2.default)(Label,_Component),(0,_createClass2.default)(Label,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,attached=_this$props.attached,basic=_this$props.basic,children=_this$props.children,circular=_this$props.circular,className=_this$props.className,color=_this$props.color,content=_this$props.content,corner=_this$props.corner,detail=_this$props.detail,empty=_this$props.empty,floating=_this$props.floating,horizontal=_this$props.horizontal,icon=_this$props.icon,image=_this$props.image,onRemove=_this$props.onRemove,pointing=_this$props.pointing,prompt=_this$props.prompt,removeIcon=_this$props.removeIcon,ribbon=_this$props.ribbon,size=_this$props.size,_this$props=_this$props.tag,pointing=(!0===pointing?"pointing":("left"===pointing||"right"===pointing)&&"".concat(pointing," pointing"))||("above"===pointing||"below"===pointing)&&"pointing ".concat(pointing),color=(0,_classnames.default)("ui",color,pointing,size,(0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(basic,"basic"),(0,_lib.useKeyOnly)(circular,"circular"),(0,_lib.useKeyOnly)(empty,"empty"),(0,_lib.useKeyOnly)(floating,"floating"),(0,_lib.useKeyOnly)(horizontal,"horizontal"),(0,_lib.useKeyOnly)(!0===image,"image"),(0,_lib.useKeyOnly)(prompt,"prompt"),(0,_lib.useKeyOnly)(_this$props,"tag"),(0,_lib.useKeyOrValueAndKey)(corner,"corner"),(0,_lib.useKeyOrValueAndKey)(ribbon,"ribbon"),(0,_lib.useValueAndKey)(attached,"attached"),"label",className),pointing=(0,_lib.getUnhandledProps)(Label,this.props),size=(0,_lib.getElementType)(Label,this.props);return _lib.childrenUtils.isNil(children)?(active=(0,_isUndefined2.default)(removeIcon)?"delete":removeIcon,_react.default.createElement(size,(0,_extends2.default)({className:color,onClick:this.handleClick},pointing),_Icon.default.create(icon,{autoGenerateKey:!1}),"boolean"!=typeof image&&_Image.default.create(image,{autoGenerateKey:!1}),content,_LabelDetail.default.create(detail,{autoGenerateKey:!1}),onRemove&&_Icon.default.create(active,{autoGenerateKey:!1,overrideProps:this.handleIconOverrides}))):_react.default.createElement(size,(0,_extends2.default)({},pointing,{className:color,onClick:this.handleClick}),children)}}]),Label}(_react.Component);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"Detail",_LabelDetail.default),(0,_defineProperty2.default)(_interopRequireDefault,"Group",_interopRequireWildcard.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["active","as","attached","basic","children","circular","className","color","content","corner","detail","empty","floating","horizontal","icon","image","onClick","onRemove","pointing","prompt","removeIcon","ribbon","size","tag"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,attached:_propTypes.default.oneOf(["top","bottom","top right","top left","bottom left","bottom right"]),basic:_propTypes.default.bool,children:_propTypes.default.node,circular:_propTypes.default.bool,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),content:_lib.customPropTypes.contentShorthand,corner:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["left","right"])]),detail:_lib.customPropTypes.itemShorthand,empty:_lib.customPropTypes.every([_propTypes.default.bool,_lib.customPropTypes.demand(["circular"])]),floating:_propTypes.default.bool,horizontal:_propTypes.default.bool,icon:_lib.customPropTypes.itemShorthand,image:_propTypes.default.oneOfType([_propTypes.default.bool,_lib.customPropTypes.itemShorthand]),onClick:_propTypes.default.func,onRemove:_propTypes.default.func,pointing:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["above","below","left","right"])]),prompt:_propTypes.default.bool,removeIcon:_lib.customPropTypes.itemShorthand,ribbon:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["right"])]),size:_propTypes.default.oneOf(_lib.SUI.SIZES),tag:_propTypes.default.bool}:{},_interopRequireDefault.create=(0,_lib.createShorthandFactory)(_interopRequireDefault,function(value){return{content:value}})}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../Icon/Icon":1525,"../Image/Image":1528,"./LabelDetail":1534,"./LabelGroup":1535,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/isUndefined":982,"prop-types":1046,react:1427}],1534:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function LabelDetail(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("detail",className),rest=(0,_lib.getUnhandledProps)(LabelDetail,props),props=(0,_lib.getElementType)(LabelDetail,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}LabelDetail.handledProps=["as","children","className","content"],LabelDetail.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},LabelDetail.create=(0,_lib.createShorthandFactory)(LabelDetail,function(val){return{content:val}}),exports.default=LabelDetail}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1535:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function LabelGroup(props){var children=props.children,circular=props.circular,className=props.className,color=props.color,content=props.content,size=props.size,tag=props.tag,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(circular,"circular"),(0,_lib.useKeyOnly)(tag,"tag"),"labels",className),size=(0,_lib.getUnhandledProps)(LabelGroup,props),circular=(0,_lib.getElementType)(LabelGroup,props);return _react.default.createElement(circular,(0,_extends2.default)({},size,{className:color}),_lib.childrenUtils.isNil(children)?content:children)}LabelGroup.handledProps=["as","children","circular","className","color","content","size","tag"],LabelGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,circular:_propTypes.default.bool,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),content:_lib.customPropTypes.contentShorthand,size:_propTypes.default.oneOf(_lib.SUI.SIZES),tag:_propTypes.default.bool}:{},exports.default=LabelGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1536:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Label=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Label.default}}),_interopRequireDefault(require("./Label")))},{"./Label":1533,"@babel/runtime/helpers/interopRequireDefault":13}],1537:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_map2=_interopRequireDefault(require("lodash/map")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=_interopRequireDefault(require("./ListContent")),_ListDescription=_interopRequireDefault(require("./ListDescription")),_ListHeader=_interopRequireDefault(require("./ListHeader")),_ListIcon=_interopRequireDefault(require("./ListIcon")),_ListItem=_interopRequireDefault(require("./ListItem")),_interopRequireDefault=_interopRequireDefault(require("./ListList")),List=function(_Component){function List(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,List);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(List)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleItemOverrides",function(predefinedProps){return{onClick:function(e,itemProps){(0,_invoke2.default)(predefinedProps,"onClick",e,itemProps),(0,_invoke2.default)(_this.props,"onItemClick",e,itemProps)}}}),_this}return(0,_inherits2.default)(List,_Component),(0,_createClass2.default)(List,[{key:"render",value:function(){var _this2=this,_this$props=this.props,animated=_this$props.animated,bulleted=_this$props.bulleted,celled=_this$props.celled,children=_this$props.children,className=_this$props.className,content=_this$props.content,divided=_this$props.divided,floated=_this$props.floated,horizontal=_this$props.horizontal,inverted=_this$props.inverted,items=_this$props.items,link=_this$props.link,ordered=_this$props.ordered,relaxed=_this$props.relaxed,selection=_this$props.selection,size=_this$props.size,_this$props=_this$props.verticalAlign,size=(0,_classnames.default)("ui",size,(0,_lib.useKeyOnly)(animated,"animated"),(0,_lib.useKeyOnly)(bulleted,"bulleted"),(0,_lib.useKeyOnly)(celled,"celled"),(0,_lib.useKeyOnly)(divided,"divided"),(0,_lib.useKeyOnly)(horizontal,"horizontal"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(link,"link"),(0,_lib.useKeyOnly)(ordered,"ordered"),(0,_lib.useKeyOnly)(selection,"selection"),(0,_lib.useKeyOrValueAndKey)(relaxed,"relaxed"),(0,_lib.useValueAndKey)(floated,"floated"),(0,_lib.useVerticalAlignProp)(_this$props),"list",className),animated=(0,_lib.getUnhandledProps)(List,this.props),bulleted=(0,_lib.getElementType)(List,this.props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement(bulleted,(0,_extends2.default)({role:"list",className:size},animated),(0,_map2.default)(items,function(item){return _ListItem.default.create(item,{overrideProps:_this2.handleItemOverrides})})):_react.default.createElement(bulleted,(0,_extends2.default)({role:"list",className:size},animated),content):_react.default.createElement(bulleted,(0,_extends2.default)({role:"list",className:size},animated),children)}}]),List}(_react.Component);(0,_defineProperty2.default)(List,"Content",_interopRequireWildcard.default),(0,_defineProperty2.default)(List,"Description",_ListDescription.default),(0,_defineProperty2.default)(List,"Header",_ListHeader.default),(0,_defineProperty2.default)(List,"Icon",_ListIcon.default),(0,_defineProperty2.default)(List,"Item",_ListItem.default),(0,_defineProperty2.default)(List,"List",_interopRequireDefault.default),(0,_defineProperty2.default)(List,"handledProps",["animated","as","bulleted","celled","children","className","content","divided","floated","horizontal","inverted","items","link","onItemClick","ordered","relaxed","selection","size","verticalAlign"]),List.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,animated:_propTypes.default.bool,bulleted:_propTypes.default.bool,celled:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,divided:_propTypes.default.bool,floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),horizontal:_propTypes.default.bool,inverted:_propTypes.default.bool,items:_lib.customPropTypes.collectionShorthand,link:_propTypes.default.bool,onItemClick:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_propTypes.default.func]),ordered:_propTypes.default.bool,relaxed:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["very"])]),selection:_propTypes.default.bool,size:_propTypes.default.oneOf(_lib.SUI.SIZES),verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS)}:{},exports.default=List}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./ListContent":1538,"./ListDescription":1539,"./ListHeader":1540,"./ListIcon":1541,"./ListItem":1542,"./ListList":1543,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/map":989,"prop-types":1046,react:1427}],1538:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_ListDescription=_interopRequireDefault(require("./ListDescription")),_ListHeader=_interopRequireDefault(require("./ListHeader"));function ListContent(props){var children=props.children,className=props.className,content=props.content,description=props.description,floated=props.floated,header=props.header,verticalAlign=props.verticalAlign,floated=(0,_classnames.default)((0,_lib.useValueAndKey)(floated,"floated"),(0,_lib.useVerticalAlignProp)(verticalAlign),"content",className),verticalAlign=(0,_lib.getUnhandledProps)(ListContent,props),className=(0,_lib.getElementType)(ListContent,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(className,(0,_extends2.default)({},verticalAlign,{className:floated}),_ListHeader.default.create(header),_ListDescription.default.create(description),content):_react.default.createElement(className,(0,_extends2.default)({},verticalAlign,{className:floated}),children)}ListContent.handledProps=["as","children","className","content","description","floated","header","verticalAlign"],ListContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,description:_lib.customPropTypes.itemShorthand,floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),header:_lib.customPropTypes.itemShorthand,verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS)}:{},ListContent.create=(0,_lib.createShorthandFactory)(ListContent,function(content){return{content:content}}),exports.default=ListContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./ListDescription":1539,"./ListHeader":1540,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1539:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ListDescription(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)(className,"description"),rest=(0,_lib.getUnhandledProps)(ListDescription,props),props=(0,_lib.getElementType)(ListDescription,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ListDescription.handledProps=["as","children","className","content"],ListDescription.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},ListDescription.create=(0,_lib.createShorthandFactory)(ListDescription,function(content){return{content:content}}),exports.default=ListDescription}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1540:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ListHeader(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("header",className),rest=(0,_lib.getUnhandledProps)(ListHeader,props),props=(0,_lib.getElementType)(ListHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ListHeader.handledProps=["as","children","className","content"],ListHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},ListHeader.create=(0,_lib.createShorthandFactory)(ListHeader,function(content){return{content:content}}),exports.default=ListHeader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1541:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../Icon/Icon"));function ListIcon(props){var className=props.className,verticalAlign=props.verticalAlign,verticalAlign=(0,_classnames.default)((0,_lib.useVerticalAlignProp)(verticalAlign),className),className=(0,_lib.getUnhandledProps)(ListIcon,props);return _react.default.createElement(_Icon.default,(0,_extends2.default)({},className,{className:verticalAlign}))}ListIcon.handledProps=["className","verticalAlign"],ListIcon.propTypes="production"!==process.env.NODE_ENV?{className:_propTypes.default.string,verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS)}:{},ListIcon.create=(0,_lib.createShorthandFactory)(ListIcon,function(name){return{name:name}}),exports.default=ListIcon}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../Icon/Icon":1525,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1542:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_isPlainObject2=_interopRequireDefault(require("lodash/isPlainObject")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Image=_interopRequireDefault(require("../Image")),_ListContent=_interopRequireDefault(require("./ListContent")),_ListDescription=_interopRequireDefault(require("./ListDescription")),_ListHeader=_interopRequireDefault(require("./ListHeader")),_ListIcon=_interopRequireDefault(require("./ListIcon")),_interopRequireWildcard=function(_Component){function ListItem(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,ListItem);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(ListItem)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){_this.props.disabled||(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),_this}return(0,_inherits2.default)(ListItem,_Component),(0,_createClass2.default)(ListItem,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,children=_this$props.children,className=_this$props.className,content=_this$props.content,description=_this$props.description,disabled=_this$props.disabled,header=_this$props.header,icon=_this$props.icon,image=_this$props.image,_this$props=_this$props.value,ElementType=(0,_lib.getElementType)(ListItem,this.props),active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)("li"!==ElementType,"item"),className),disabled=(0,_lib.getUnhandledProps)(ListItem,this.props),className="li"===ElementType?{value:_this$props}:{"data-value":_this$props};return _lib.childrenUtils.isNil(children)?(_this$props=_ListIcon.default.create(icon,{autoGenerateKey:!1}),icon=_Image.default.create(image,{autoGenerateKey:!1}),!(0,_react.isValidElement)(content)&&(0,_isPlainObject2.default)(content)?_react.default.createElement(ElementType,(0,_extends2.default)({},className,{role:"listitem",className:active,onClick:this.handleClick},disabled),_this$props||icon,_ListContent.default.create(content,{autoGenerateKey:!1,defaultProps:{header:header,description:description}})):(image=_ListHeader.default.create(header,{autoGenerateKey:!1}),header=_ListDescription.default.create(description,{autoGenerateKey:!1}),_this$props||icon?_react.default.createElement(ElementType,(0,_extends2.default)({},className,{role:"listitem",className:active,onClick:this.handleClick},disabled),_this$props||icon,(content||image||header)&&_react.default.createElement(_ListContent.default,null,image,header,content)):_react.default.createElement(ElementType,(0,_extends2.default)({},className,{role:"listitem",className:active,onClick:this.handleClick},disabled),image,header,content))):_react.default.createElement(ElementType,(0,_extends2.default)({},className,{role:"listitem",className:active,onClick:this.handleClick},disabled),children)}}]),ListItem}(_react.Component);(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","children","className","content","description","disabled","header","icon","image","onClick","value"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.itemShorthand,description:_lib.customPropTypes.itemShorthand,disabled:_propTypes.default.bool,header:_lib.customPropTypes.itemShorthand,icon:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["image"]),_lib.customPropTypes.itemShorthand]),image:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["icon"]),_lib.customPropTypes.itemShorthand]),onClick:_propTypes.default.func,value:_propTypes.default.string}:{},_interopRequireWildcard.create=(0,_lib.createShorthandFactory)(_interopRequireWildcard,function(content){return{content:content}}),exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../Image":1530,"./ListContent":1538,"./ListDescription":1539,"./ListHeader":1540,"./ListIcon":1541,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/isPlainObject":976,"prop-types":1046,react:1427}],1543:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ListList(props){var children=props.children,className=props.className,content=props.content,rest=(0,_lib.getUnhandledProps)(ListList,props),props=(0,_lib.getElementType)(ListList,props),className=(0,_classnames.default)((0,_lib.useKeyOnly)("ul"!==props&&"ol"!==props,"list"),className);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ListList.handledProps=["as","children","className","content"],ListList.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=ListList}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1544:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_List=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _List.default}}),_interopRequireDefault(require("./List")))},{"./List":1537,"@babel/runtime/helpers/interopRequireDefault":13}],1545:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function Loader(props){var active=props.active,children=props.children,className=props.className,content=props.content,disabled=props.disabled,indeterminate=props.indeterminate,inline=props.inline,inverted=props.inverted,size=props.size,size=(0,_classnames.default)("ui",size,(0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(indeterminate,"indeterminate"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(children||content,"text"),(0,_lib.useKeyOrValueAndKey)(inline,"inline"),"loader",className),active=(0,_lib.getUnhandledProps)(Loader,props),disabled=(0,_lib.getElementType)(Loader,props);return _react.default.createElement(disabled,(0,_extends2.default)({},active,{className:size}),_lib.childrenUtils.isNil(children)?content:children)}Loader.handledProps=["active","as","children","className","content","disabled","indeterminate","inline","inverted","size"],Loader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,disabled:_propTypes.default.bool,indeterminate:_propTypes.default.bool,inline:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["centered"])]),inverted:_propTypes.default.bool,size:_propTypes.default.oneOf(_lib.SUI.SIZES)}:{},exports.default=Loader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1546:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Loader=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Loader.default}}),_interopRequireDefault(require("./Loader")))},{"./Loader":1545,"@babel/runtime/helpers/interopRequireDefault":13}],1547:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_PlaceholderHeader=_interopRequireDefault(require("./PlaceholderHeader")),_PlaceholderImage=_interopRequireDefault(require("./PlaceholderImage")),_PlaceholderLine=_interopRequireDefault(require("./PlaceholderLine")),_interopRequireDefault=_interopRequireDefault(require("./PlaceholderParagraph"));function Placeholder(props){var children=props.children,className=props.className,content=props.content,fluid=props.fluid,inverted=props.inverted,fluid=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(inverted,"inverted"),"placeholder",className),inverted=(0,_lib.getUnhandledProps)(Placeholder,props),className=(0,_lib.getElementType)(Placeholder,props);return _react.default.createElement(className,(0,_extends2.default)({},inverted,{className:fluid}),_lib.childrenUtils.isNil(children)?content:children)}Placeholder.handledProps=["as","children","className","content","fluid","inverted"],Placeholder.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,fluid:_propTypes.default.bool,inverted:_propTypes.default.bool}:{},Placeholder.Header=_PlaceholderHeader.default,Placeholder.Image=_PlaceholderImage.default,Placeholder.Line=_PlaceholderLine.default,Placeholder.Paragraph=_interopRequireDefault.default,exports.default=Placeholder}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./PlaceholderHeader":1548,"./PlaceholderImage":1549,"./PlaceholderLine":1550,"./PlaceholderParagraph":1551,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1548:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function PlaceholderHeader(props){var children=props.children,className=props.className,content=props.content,image=props.image,image=(0,_classnames.default)((0,_lib.useKeyOnly)(image,"image"),"header",className),className=(0,_lib.getUnhandledProps)(PlaceholderHeader,props),props=(0,_lib.getElementType)(PlaceholderHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:image}),_lib.childrenUtils.isNil(children)?content:children)}PlaceholderHeader.handledProps=["as","children","className","content","image"],PlaceholderHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,image:_propTypes.default.bool}:{},exports.default=PlaceholderHeader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1549:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function PlaceholderImage(props){var className=props.className,square=props.square,rectangular=props.rectangular,square=(0,_classnames.default)((0,_lib.useKeyOnly)(square,"square"),(0,_lib.useKeyOnly)(rectangular,"rectangular"),"image",className),rectangular=(0,_lib.getUnhandledProps)(PlaceholderImage,props),className=(0,_lib.getElementType)(PlaceholderImage,props);return _react.default.createElement(className,(0,_extends2.default)({},rectangular,{className:square}))}PlaceholderImage.handledProps=["as","className","rectangular","square"],PlaceholderImage.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,className:_propTypes.default.string,square:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["rectangular"]),_propTypes.default.bool]),rectangular:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["square"]),_propTypes.default.bool])}:{},exports.default=PlaceholderImage}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1550:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function PlaceholderLine(props){var className=props.className,length=props.length,length=(0,_classnames.default)("line",length,className),className=(0,_lib.getUnhandledProps)(PlaceholderLine,props),props=(0,_lib.getElementType)(PlaceholderLine,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:length}))}PlaceholderLine.handledProps=["as","className","length"],PlaceholderLine.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,className:_propTypes.default.string,length:_propTypes.default.oneOf(["full","very long","long","medium","short","very short"])}:{},exports.default=PlaceholderLine}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1551:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function PlaceholderParagraph(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("paragraph",className),rest=(0,_lib.getUnhandledProps)(PlaceholderParagraph,props),props=(0,_lib.getElementType)(PlaceholderParagraph,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}PlaceholderParagraph.handledProps=["as","children","className","content"],PlaceholderParagraph.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=PlaceholderParagraph}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1552:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Placeholder=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Placeholder.default}}),_interopRequireDefault(require("./Placeholder")))},{"./Placeholder":1547,"@babel/runtime/helpers/interopRequireDefault":13}],1553:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function Rail(props){var attached=props.attached,children=props.children,className=props.className,close=props.close,content=props.content,dividing=props.dividing,internal=props.internal,position=props.position,size=props.size,position=(0,_classnames.default)("ui",position,size,(0,_lib.useKeyOnly)(attached,"attached"),(0,_lib.useKeyOnly)(dividing,"dividing"),(0,_lib.useKeyOnly)(internal,"internal"),(0,_lib.useKeyOrValueAndKey)(close,"close"),"rail",className),size=(0,_lib.getUnhandledProps)(Rail,props),attached=(0,_lib.getElementType)(Rail,props);return _react.default.createElement(attached,(0,_extends2.default)({},size,{className:position}),_lib.childrenUtils.isNil(children)?content:children)}Rail.handledProps=["as","attached","children","className","close","content","dividing","internal","position","size"],Rail.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,attached:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,close:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["very"])]),content:_lib.customPropTypes.contentShorthand,dividing:_propTypes.default.bool,internal:_propTypes.default.bool,position:_propTypes.default.oneOf(_lib.SUI.FLOATS).isRequired,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium"))}:{},exports.default=Rail}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1554:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Rail=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Rail.default}}),_interopRequireDefault(require("./Rail")))},{"./Rail":1553,"@babel/runtime/helpers/interopRequireDefault":13}],1555:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_interopRequireDefault=_interopRequireDefault(require("./RevealContent"));function Reveal(props){var active=props.active,animated=props.animated,children=props.children,className=props.className,content=props.content,disabled=props.disabled,instant=props.instant,animated=(0,_classnames.default)("ui",animated,(0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(instant,"instant"),"reveal",className),active=(0,_lib.getUnhandledProps)(Reveal,props),disabled=(0,_lib.getElementType)(Reveal,props);return _react.default.createElement(disabled,(0,_extends2.default)({},active,{className:animated}),_lib.childrenUtils.isNil(children)?content:children)}Reveal.handledProps=["active","animated","as","children","className","content","disabled","instant"],Reveal.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,animated:_propTypes.default.oneOf(["fade","small fade","move","move right","move up","move down","rotate","rotate left"]),children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,disabled:_propTypes.default.bool,instant:_propTypes.default.bool}:{},Reveal.Content=_interopRequireDefault.default,exports.default=Reveal}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./RevealContent":1556,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1556:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function RevealContent(props){var children=props.children,className=props.className,content=props.content,hidden=props.hidden,visible=props.visible,hidden=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(hidden,"hidden"),(0,_lib.useKeyOnly)(visible,"visible"),"content",className),visible=(0,_lib.getUnhandledProps)(RevealContent,props),className=(0,_lib.getElementType)(RevealContent,props);return _react.default.createElement(className,(0,_extends2.default)({},visible,{className:hidden}),_lib.childrenUtils.isNil(children)?content:children)}RevealContent.handledProps=["as","children","className","content","hidden","visible"],RevealContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,hidden:_propTypes.default.bool,visible:_propTypes.default.bool}:{},exports.default=RevealContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1557:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Reveal=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Reveal.default}}),_interopRequireDefault(require("./Reveal")))},{"./Reveal":1555,"@babel/runtime/helpers/interopRequireDefault":13}],1558:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_SegmentGroup=_interopRequireDefault(require("./SegmentGroup")),_interopRequireDefault=_interopRequireDefault(require("./SegmentInline"));function Segment(props){var attached=props.attached,basic=props.basic,children=props.children,circular=props.circular,className=props.className,clearing=props.clearing,color=props.color,compact=props.compact,content=props.content,disabled=props.disabled,floated=props.floated,inverted=props.inverted,loading=props.loading,placeholder=props.placeholder,padded=props.padded,piled=props.piled,raised=props.raised,secondary=props.secondary,size=props.size,stacked=props.stacked,tertiary=props.tertiary,textAlign=props.textAlign,vertical=props.vertical,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(basic,"basic"),(0,_lib.useKeyOnly)(circular,"circular"),(0,_lib.useKeyOnly)(clearing,"clearing"),(0,_lib.useKeyOnly)(compact,"compact"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(loading,"loading"),(0,_lib.useKeyOnly)(placeholder,"placeholder"),(0,_lib.useKeyOnly)(piled,"piled"),(0,_lib.useKeyOnly)(raised,"raised"),(0,_lib.useKeyOnly)(secondary,"secondary"),(0,_lib.useKeyOnly)(stacked,"stacked"),(0,_lib.useKeyOnly)(tertiary,"tertiary"),(0,_lib.useKeyOnly)(vertical,"vertical"),(0,_lib.useKeyOrValueAndKey)(attached,"attached"),(0,_lib.useKeyOrValueAndKey)(padded,"padded"),(0,_lib.useTextAlignProp)(textAlign),(0,_lib.useValueAndKey)(floated,"floated"),"segment",className),size=(0,_lib.getUnhandledProps)(Segment,props),basic=(0,_lib.getElementType)(Segment,props);return _react.default.createElement(basic,(0,_extends2.default)({},size,{className:color}),_lib.childrenUtils.isNil(children)?content:children)}Segment.handledProps=["as","attached","basic","children","circular","className","clearing","color","compact","content","disabled","floated","inverted","loading","padded","piled","placeholder","raised","secondary","size","stacked","tertiary","textAlign","vertical"],Segment.Group=_SegmentGroup.default,Segment.Inline=_interopRequireDefault.default,Segment.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,attached:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["top","bottom"])]),basic:_propTypes.default.bool,children:_propTypes.default.node,circular:_propTypes.default.bool,className:_propTypes.default.string,clearing:_propTypes.default.bool,color:_propTypes.default.oneOf(_lib.SUI.COLORS),compact:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,disabled:_propTypes.default.bool,floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),inverted:_propTypes.default.bool,loading:_propTypes.default.bool,padded:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["very"])]),placeholder:_propTypes.default.bool,piled:_propTypes.default.bool,raised:_propTypes.default.bool,secondary:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium")),stacked:_propTypes.default.bool,tertiary:_propTypes.default.bool,textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified")),vertical:_propTypes.default.bool}:{},exports.default=Segment}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./SegmentGroup":1559,"./SegmentInline":1560,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1559:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function SegmentGroup(props){var children=props.children,className=props.className,compact=props.compact,content=props.content,horizontal=props.horizontal,piled=props.piled,raised=props.raised,size=props.size,stacked=props.stacked,size=(0,_classnames.default)("ui",size,(0,_lib.useKeyOnly)(compact,"compact"),(0,_lib.useKeyOnly)(horizontal,"horizontal"),(0,_lib.useKeyOnly)(piled,"piled"),(0,_lib.useKeyOnly)(raised,"raised"),(0,_lib.useKeyOnly)(stacked,"stacked"),"segments",className),compact=(0,_lib.getUnhandledProps)(SegmentGroup,props),horizontal=(0,_lib.getElementType)(SegmentGroup,props);return _react.default.createElement(horizontal,(0,_extends2.default)({},compact,{className:size}),_lib.childrenUtils.isNil(children)?content:children)}SegmentGroup.handledProps=["as","children","className","compact","content","horizontal","piled","raised","size","stacked"],SegmentGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,compact:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,horizontal:_propTypes.default.bool,piled:_propTypes.default.bool,raised:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium")),stacked:_propTypes.default.bool}:{},exports.default=SegmentGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1560:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function SegmentInline(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("inline",className),rest=(0,_lib.getUnhandledProps)(SegmentInline,props),props=(0,_lib.getElementType)(SegmentInline,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}SegmentInline.handledProps=["as","children","className","content"],SegmentInline.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=SegmentInline}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1561:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Segment=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Segment.default}}),_interopRequireDefault(require("./Segment")))},{"./Segment":1558,"@babel/runtime/helpers/interopRequireDefault":13}],1562:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../Icon")),_StepContent=_interopRequireDefault(require("./StepContent")),_interopRequireWildcard=_interopRequireDefault(require("./StepDescription")),_StepGroup=_interopRequireDefault(require("./StepGroup")),_interopRequireDefault=_interopRequireDefault(require("./StepTitle")),Step=function(_Component){function Step(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Step);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Step)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeElementType",function(){if(_this.props.onClick)return"a"}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){_this.props.disabled||(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),_this}return(0,_inherits2.default)(Step,_Component),(0,_createClass2.default)(Step,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,children=_this$props.children,className=_this$props.className,completed=_this$props.completed,content=_this$props.content,description=_this$props.description,disabled=_this$props.disabled,href=_this$props.href,icon=_this$props.icon,link=_this$props.link,_this$props=_this$props.title,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(completed,"completed"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(link,"link"),"step",className),completed=(0,_lib.getUnhandledProps)(Step,this.props),disabled=(0,_lib.getElementType)(Step,this.props,this.computeElementType);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement(disabled,(0,_extends2.default)({},completed,{className:active,href:href,onClick:this.handleClick}),_Icon.default.create(icon,{autoGenerateKey:!1}),_StepContent.default.create({description:description,title:_this$props},{autoGenerateKey:!1})):_react.default.createElement(disabled,(0,_extends2.default)({},completed,{className:active,href:href,onClick:this.handleClick}),content):_react.default.createElement(disabled,(0,_extends2.default)({},completed,{className:active,href:href,onClick:this.handleClick}),children)}}]),Step}(_react.Component);(0,_defineProperty2.default)(Step,"Content",_StepContent.default),(0,_defineProperty2.default)(Step,"Description",_interopRequireWildcard.default),(0,_defineProperty2.default)(Step,"Group",_StepGroup.default),(0,_defineProperty2.default)(Step,"Title",_interopRequireDefault.default),(0,_defineProperty2.default)(Step,"handledProps",["active","as","children","className","completed","content","description","disabled","href","icon","link","onClick","ordered","title"]),Step.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,completed:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,description:_lib.customPropTypes.itemShorthand,disabled:_propTypes.default.bool,href:_propTypes.default.string,icon:_lib.customPropTypes.itemShorthand,link:_propTypes.default.bool,onClick:_propTypes.default.func,ordered:_propTypes.default.bool,title:_lib.customPropTypes.itemShorthand}:{},Step.create=(0,_lib.createShorthandFactory)(Step,function(content){return{content:content}}),exports.default=Step}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"../Icon":1527,"./StepContent":1563,"./StepDescription":1564,"./StepGroup":1565,"./StepTitle":1566,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"prop-types":1046,react:1427}],1563:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_StepDescription=_interopRequireDefault(require("./StepDescription")),_StepTitle=_interopRequireDefault(require("./StepTitle"));function StepContent(props){var children=props.children,className=props.className,content=props.content,description=props.description,title=props.title,className=(0,_classnames.default)("content",className),rest=(0,_lib.getUnhandledProps)(StepContent,props),props=(0,_lib.getElementType)(StepContent,props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_StepTitle.default.create(title,{autoGenerateKey:!1}),_StepDescription.default.create(description,{autoGenerateKey:!1})):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),content):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}StepContent.handledProps=["as","children","className","content","description","title"],StepContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,description:_lib.customPropTypes.itemShorthand,title:_lib.customPropTypes.itemShorthand}:{},StepContent.create=(0,_lib.createShorthandFactory)(StepContent,function(content){return{content:content}}),exports.default=StepContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./StepDescription":1564,"./StepTitle":1566,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1564:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function StepDescription(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("description",className),rest=(0,_lib.getUnhandledProps)(StepDescription,props),props=(0,_lib.getElementType)(StepDescription,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}StepDescription.handledProps=["as","children","className","content"],StepDescription.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},StepDescription.create=(0,_lib.createShorthandFactory)(StepDescription,function(content){return{content:content}}),exports.default=StepDescription}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1565:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_values2=_interopRequireDefault(require("lodash/values")),_keys2=_interopRequireDefault(require("lodash/keys")),_without2=_interopRequireDefault(require("lodash/without")),_map2=_interopRequireDefault(require("lodash/map")),_pickBy2=_interopRequireDefault(require("lodash/pickBy")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Step=_interopRequireDefault(require("./Step")),_interopRequireDefault="production"!==process.env.NODE_ENV?(0,_pickBy2.default)(_lib.numberToWordMap,function(val,key){return key<=8}):{};function StepGroup(props){var attached=props.attached,children=props.children,className=props.className,content=props.content,fluid=props.fluid,items=props.items,ordered=props.ordered,size=props.size,stackable=props.stackable,unstackable=props.unstackable,vertical=props.vertical,widths=props.widths,size=(0,_classnames.default)("ui",size,(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(ordered,"ordered"),(0,_lib.useKeyOnly)(unstackable,"unstackable"),(0,_lib.useKeyOnly)(vertical,"vertical"),(0,_lib.useKeyOrValueAndKey)(attached,"attached"),(0,_lib.useValueAndKey)(stackable,"stackable"),(0,_lib.useWidthProp)(widths),"steps",className),fluid=(0,_lib.getUnhandledProps)(StepGroup,props),ordered=(0,_lib.getElementType)(StepGroup,props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement(ordered,(0,_extends2.default)({},fluid,{className:size}),(0,_map2.default)(items,function(item){return _Step.default.create(item)})):_react.default.createElement(ordered,(0,_extends2.default)({},fluid,{className:size}),content):_react.default.createElement(ordered,(0,_extends2.default)({},fluid,{className:size}),children)}StepGroup.handledProps=["as","attached","children","className","content","fluid","items","ordered","size","stackable","unstackable","vertical","widths"],StepGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,attached:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["top","bottom"])]),children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,fluid:_propTypes.default.bool,items:_lib.customPropTypes.collectionShorthand,ordered:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium")),stackable:_propTypes.default.oneOf(["tablet"]),unstackable:_propTypes.default.bool,vertical:_propTypes.default.bool,widths:_propTypes.default.oneOf([].concat((0,_toConsumableArray2.default)((0,_keys2.default)(_interopRequireDefault)),(0,_toConsumableArray2.default)((0,_keys2.default)(_interopRequireDefault).map(Number)),(0,_toConsumableArray2.default)((0,_values2.default)(_interopRequireDefault))))}:{},exports.default=StepGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./Step":1562,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/toConsumableArray":27,_process:1042,classnames:116,"lodash/keys":986,"lodash/map":989,"lodash/pickBy":997,"lodash/values":1027,"lodash/without":1028,"prop-types":1046,react:1427}],1566:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function StepTitle(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("title",className),rest=(0,_lib.getUnhandledProps)(StepTitle,props),props=(0,_lib.getElementType)(StepTitle,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}StepTitle.handledProps=["as","children","className","content"],StepTitle.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},StepTitle.create=(0,_lib.createShorthandFactory)(StepTitle,function(content){return{content:content}}),exports.default=StepTitle}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1567:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Step=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Step.default}}),_interopRequireDefault(require("./Step")))},{"./Step":1562,"@babel/runtime/helpers/interopRequireDefault":13}],1568:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_reactComponentRef=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"Ref",{enumerable:!0,get:function(){return _reactComponentRef.Ref}}),Object.defineProperty(exports,"Confirm",{enumerable:!0,get:function(){return _Confirm2.default}}),Object.defineProperty(exports,"MountNode",{enumerable:!0,get:function(){return _MountNode2.default}}),Object.defineProperty(exports,"Pagination",{enumerable:!0,get:function(){return _Pagination2.default}}),Object.defineProperty(exports,"PaginationItem",{enumerable:!0,get:function(){return _PaginationItem2.default}}),Object.defineProperty(exports,"Portal",{enumerable:!0,get:function(){return _Portal2.default}}),Object.defineProperty(exports,"PortalInner",{enumerable:!0,get:function(){return _PortalInner2.default}}),Object.defineProperty(exports,"Radio",{enumerable:!0,get:function(){return _Radio2.default}}),Object.defineProperty(exports,"Responsive",{enumerable:!0,get:function(){return _Responsive2.default}}),Object.defineProperty(exports,"Select",{enumerable:!0,get:function(){return _Select2.default}}),Object.defineProperty(exports,"TextArea",{enumerable:!0,get:function(){return _TextArea2.default}}),Object.defineProperty(exports,"TransitionablePortal",{enumerable:!0,get:function(){return _TransitionablePortal2.default}}),Object.defineProperty(exports,"Visibility",{enumerable:!0,get:function(){return _Visibility2.default}}),Object.defineProperty(exports,"Breadcrumb",{enumerable:!0,get:function(){return _Breadcrumb2.default}}),Object.defineProperty(exports,"BreadcrumbDivider",{enumerable:!0,get:function(){return _BreadcrumbDivider2.default}}),Object.defineProperty(exports,"BreadcrumbSection",{enumerable:!0,get:function(){return _BreadcrumbSection2.default}}),Object.defineProperty(exports,"Form",{enumerable:!0,get:function(){return _Form2.default}}),Object.defineProperty(exports,"FormButton",{enumerable:!0,get:function(){return _FormButton2.default}}),Object.defineProperty(exports,"FormCheckbox",{enumerable:!0,get:function(){return _FormCheckbox2.default}}),Object.defineProperty(exports,"FormDropdown",{enumerable:!0,get:function(){return _FormDropdown2.default}}),Object.defineProperty(exports,"FormField",{enumerable:!0,get:function(){return _FormField2.default}}),Object.defineProperty(exports,"FormGroup",{enumerable:!0,get:function(){return _FormGroup2.default}}),Object.defineProperty(exports,"FormInput",{enumerable:!0,get:function(){return _FormInput2.default}}),Object.defineProperty(exports,"FormRadio",{enumerable:!0,get:function(){return _FormRadio2.default}}),Object.defineProperty(exports,"FormSelect",{enumerable:!0,get:function(){return _FormSelect2.default}}),Object.defineProperty(exports,"FormTextArea",{enumerable:!0,get:function(){return _FormTextArea2.default}}),Object.defineProperty(exports,"Grid",{enumerable:!0,get:function(){return _Grid2.default}}),Object.defineProperty(exports,"GridColumn",{enumerable:!0,get:function(){return _GridColumn2.default}}),Object.defineProperty(exports,"GridRow",{enumerable:!0,get:function(){return _GridRow2.default}}),Object.defineProperty(exports,"Menu",{enumerable:!0,get:function(){return _Menu2.default}}),Object.defineProperty(exports,"MenuHeader",{enumerable:!0,get:function(){return _MenuHeader2.default}}),Object.defineProperty(exports,"MenuItem",{enumerable:!0,get:function(){return _MenuItem2.default}}),Object.defineProperty(exports,"MenuMenu",{enumerable:!0,get:function(){return _MenuMenu2.default}}),Object.defineProperty(exports,"Message",{enumerable:!0,get:function(){return _Message2.default}}),Object.defineProperty(exports,"MessageContent",{enumerable:!0,get:function(){return _MessageContent2.default}}),Object.defineProperty(exports,"MessageHeader",{enumerable:!0,get:function(){return _MessageHeader2.default}}),Object.defineProperty(exports,"MessageItem",{enumerable:!0,get:function(){return _MessageItem2.default}}),Object.defineProperty(exports,"MessageList",{enumerable:!0,get:function(){return _MessageList2.default}}),Object.defineProperty(exports,"Table",{enumerable:!0,get:function(){return _Table2.default}}),Object.defineProperty(exports,"TableBody",{enumerable:!0,get:function(){return _TableBody2.default}}),Object.defineProperty(exports,"TableCell",{enumerable:!0,get:function(){return _TableCell2.default}}),Object.defineProperty(exports,"TableFooter",{enumerable:!0,get:function(){return _TableFooter2.default}}),Object.defineProperty(exports,"TableHeader",{enumerable:!0,get:function(){return _TableHeader2.default}}),Object.defineProperty(exports,"TableHeaderCell",{enumerable:!0,get:function(){return _TableHeaderCell2.default}}),Object.defineProperty(exports,"TableRow",{enumerable:!0,get:function(){return _TableRow2.default}}),Object.defineProperty(exports,"Button",{enumerable:!0,get:function(){return _Button2.default}}),Object.defineProperty(exports,"ButtonContent",{enumerable:!0,get:function(){return _ButtonContent2.default}}),Object.defineProperty(exports,"ButtonGroup",{enumerable:!0,get:function(){return _ButtonGroup2.default}}),Object.defineProperty(exports,"ButtonOr",{enumerable:!0,get:function(){return _ButtonOr2.default}}),Object.defineProperty(exports,"Container",{enumerable:!0,get:function(){return _Container2.default}}),Object.defineProperty(exports,"Divider",{enumerable:!0,get:function(){return _Divider2.default}}),Object.defineProperty(exports,"Flag",{enumerable:!0,get:function(){return _Flag2.default}}),Object.defineProperty(exports,"Header",{enumerable:!0,get:function(){return _Header2.default}}),Object.defineProperty(exports,"HeaderContent",{enumerable:!0,get:function(){return _HeaderContent2.default}}),Object.defineProperty(exports,"HeaderSubheader",{enumerable:!0,get:function(){return _HeaderSubheader2.default}}),Object.defineProperty(exports,"Icon",{enumerable:!0,get:function(){return _Icon2.default}}),Object.defineProperty(exports,"IconGroup",{enumerable:!0,get:function(){return _IconGroup2.default}}),Object.defineProperty(exports,"Image",{enumerable:!0,get:function(){return _Image2.default}}),Object.defineProperty(exports,"ImageGroup",{enumerable:!0,get:function(){return _ImageGroup2.default}}),Object.defineProperty(exports,"Input",{enumerable:!0,get:function(){return _Input2.default}}),Object.defineProperty(exports,"Label",{enumerable:!0,get:function(){return _Label2.default}}),Object.defineProperty(exports,"LabelDetail",{enumerable:!0,get:function(){return _LabelDetail2.default}}),Object.defineProperty(exports,"LabelGroup",{enumerable:!0,get:function(){return _LabelGroup2.default}}),Object.defineProperty(exports,"List",{enumerable:!0,get:function(){return _List2.default}}),Object.defineProperty(exports,"ListContent",{enumerable:!0,get:function(){return _ListContent2.default}}),Object.defineProperty(exports,"ListDescription",{enumerable:!0,get:function(){return _ListDescription2.default}}),Object.defineProperty(exports,"ListHeader",{enumerable:!0,get:function(){return _ListHeader2.default}}),Object.defineProperty(exports,"ListIcon",{enumerable:!0,get:function(){return _ListIcon2.default}}),Object.defineProperty(exports,"ListItem",{enumerable:!0,get:function(){return _ListItem2.default}}),Object.defineProperty(exports,"ListList",{enumerable:!0,get:function(){return _ListList2.default}}),Object.defineProperty(exports,"Loader",{enumerable:!0,get:function(){return _Loader2.default}}),Object.defineProperty(exports,"Placeholder",{enumerable:!0,get:function(){return _Placeholder2.default}}),Object.defineProperty(exports,"PlaceholderHeader",{enumerable:!0,get:function(){return _PlaceholderHeader2.default}}),Object.defineProperty(exports,"PlaceholderImage",{enumerable:!0,get:function(){return _PlaceholderImage2.default}}),Object.defineProperty(exports,"PlaceholderLine",{enumerable:!0,get:function(){return _PlaceholderLine2.default}}),Object.defineProperty(exports,"PlaceholderParagraph",{enumerable:!0,get:function(){return _PlaceholderParagraph2.default}}),Object.defineProperty(exports,"Rail",{enumerable:!0,get:function(){return _Rail2.default}}),Object.defineProperty(exports,"Reveal",{enumerable:!0,get:function(){return _Reveal2.default}}),Object.defineProperty(exports,"RevealContent",{enumerable:!0,get:function(){return _RevealContent2.default}}),Object.defineProperty(exports,"Segment",{enumerable:!0,get:function(){return _Segment2.default}}),Object.defineProperty(exports,"SegmentGroup",{enumerable:!0,get:function(){return _SegmentGroup2.default}}),Object.defineProperty(exports,"SegmentInline",{enumerable:!0,get:function(){return _SegmentInline2.default}}),Object.defineProperty(exports,"Step",{enumerable:!0,get:function(){return _Step2.default}}),Object.defineProperty(exports,"StepContent",{enumerable:!0,get:function(){return _StepContent2.default}}),Object.defineProperty(exports,"StepDescription",{enumerable:!0,get:function(){return _StepDescription2.default}}),Object.defineProperty(exports,"StepGroup",{enumerable:!0,get:function(){return _StepGroup2.default}}),Object.defineProperty(exports,"StepTitle",{enumerable:!0,get:function(){return _StepTitle2.default}}),Object.defineProperty(exports,"Accordion",{enumerable:!0,get:function(){return _Accordion2.default}}),Object.defineProperty(exports,"AccordionAccordion",{enumerable:!0,get:function(){return _AccordionAccordion2.default}}),Object.defineProperty(exports,"AccordionContent",{enumerable:!0,get:function(){return _AccordionContent2.default}}),Object.defineProperty(exports,"AccordionPanel",{enumerable:!0,get:function(){return _AccordionPanel2.default}}),Object.defineProperty(exports,"AccordionTitle",{enumerable:!0,get:function(){return _AccordionTitle2.default}}),Object.defineProperty(exports,"Checkbox",{enumerable:!0,get:function(){return _Checkbox2.default}}),Object.defineProperty(exports,"Dimmer",{enumerable:!0,get:function(){return _Dimmer2.default}}),Object.defineProperty(exports,"DimmerDimmable",{enumerable:!0,get:function(){return _DimmerDimmable2.default}}),Object.defineProperty(exports,"DimmerInner",{enumerable:!0,get:function(){return _DimmerInner2.default}}),Object.defineProperty(exports,"Dropdown",{enumerable:!0,get:function(){return _Dropdown2.default}}),Object.defineProperty(exports,"DropdownDivider",{enumerable:!0,get:function(){return _DropdownDivider2.default}}),Object.defineProperty(exports,"DropdownHeader",{enumerable:!0,get:function(){return _DropdownHeader2.default}}),Object.defineProperty(exports,"DropdownItem",{enumerable:!0,get:function(){return _DropdownItem2.default}}),Object.defineProperty(exports,"DropdownMenu",{enumerable:!0,get:function(){return _DropdownMenu2.default}}),Object.defineProperty(exports,"DropdownSearchInput",{enumerable:!0,get:function(){return _DropdownSearchInput2.default}}),Object.defineProperty(exports,"Embed",{enumerable:!0,get:function(){return _Embed2.default}}),Object.defineProperty(exports,"Modal",{enumerable:!0,get:function(){return _Modal2.default}}),Object.defineProperty(exports,"ModalActions",{enumerable:!0,get:function(){return _ModalActions2.default}}),Object.defineProperty(exports,"ModalContent",{enumerable:!0,get:function(){return _ModalContent2.default}}),Object.defineProperty(exports,"ModalDescription",{enumerable:!0,get:function(){return _ModalDescription2.default}}),Object.defineProperty(exports,"ModalHeader",{enumerable:!0,get:function(){return _ModalHeader2.default}}),Object.defineProperty(exports,"Popup",{enumerable:!0,get:function(){return _Popup2.default}}),Object.defineProperty(exports,"PopupContent",{enumerable:!0,get:function(){return _PopupContent2.default}}),Object.defineProperty(exports,"PopupHeader",{enumerable:!0,get:function(){return _PopupHeader2.default}}),Object.defineProperty(exports,"Progress",{enumerable:!0,get:function(){return _Progress2.default}}),Object.defineProperty(exports,"Rating",{enumerable:!0,get:function(){return _Rating2.default}}),Object.defineProperty(exports,"RatingIcon",{enumerable:!0,get:function(){return _RatingIcon2.default}}),Object.defineProperty(exports,"Search",{enumerable:!0,get:function(){return _Search2.default}}),Object.defineProperty(exports,"SearchCategory",{enumerable:!0,get:function(){return _SearchCategory2.default}}),Object.defineProperty(exports,"SearchResult",{enumerable:!0,get:function(){return _SearchResult2.default}}),Object.defineProperty(exports,"SearchResults",{enumerable:!0,get:function(){return _SearchResults2.default}}),Object.defineProperty(exports,"Sidebar",{enumerable:!0,get:function(){return _Sidebar2.default}}),Object.defineProperty(exports,"SidebarPushable",{enumerable:!0,get:function(){return _SidebarPushable2.default}}),Object.defineProperty(exports,"SidebarPusher",{enumerable:!0,get:function(){return _SidebarPusher2.default}}),Object.defineProperty(exports,"Sticky",{enumerable:!0,get:function(){return _Sticky2.default}}),Object.defineProperty(exports,"Tab",{enumerable:!0,get:function(){return _Tab2.default}}),Object.defineProperty(exports,"TabPane",{enumerable:!0,get:function(){return _TabPane2.default}}),Object.defineProperty(exports,"Transition",{enumerable:!0,get:function(){return _Transition2.default}}),Object.defineProperty(exports,"TransitionGroup",{enumerable:!0,get:function(){return _TransitionGroup2.default}}),Object.defineProperty(exports,"Advertisement",{enumerable:!0,get:function(){return _Advertisement2.default}}),Object.defineProperty(exports,"Card",{enumerable:!0,get:function(){return _Card2.default}}),Object.defineProperty(exports,"CardContent",{enumerable:!0,get:function(){return _CardContent2.default}}),Object.defineProperty(exports,"CardDescription",{enumerable:!0,get:function(){return _CardDescription2.default}}),Object.defineProperty(exports,"CardGroup",{enumerable:!0,get:function(){return _CardGroup2.default}}),Object.defineProperty(exports,"CardHeader",{enumerable:!0,get:function(){return _CardHeader2.default}}),Object.defineProperty(exports,"CardMeta",{enumerable:!0,get:function(){return _CardMeta2.default}}),Object.defineProperty(exports,"Comment",{enumerable:!0,get:function(){return _Comment2.default}}),Object.defineProperty(exports,"CommentAction",{enumerable:!0,get:function(){return _CommentAction2.default}}),Object.defineProperty(exports,"CommentActions",{enumerable:!0,get:function(){return _CommentActions2.default}}),Object.defineProperty(exports,"CommentAuthor",{enumerable:!0,get:function(){return _CommentAuthor2.default}}),Object.defineProperty(exports,"CommentAvatar",{enumerable:!0,get:function(){return _CommentAvatar2.default}}),Object.defineProperty(exports,"CommentContent",{enumerable:!0,get:function(){return _CommentContent2.default}}),Object.defineProperty(exports,"CommentGroup",{enumerable:!0,get:function(){return _CommentGroup2.default}}),Object.defineProperty(exports,"CommentMetadata",{enumerable:!0,get:function(){return _CommentMetadata2.default}}),Object.defineProperty(exports,"CommentText",{enumerable:!0,get:function(){return _CommentText2.default}}),Object.defineProperty(exports,"Feed",{enumerable:!0,get:function(){return _Feed2.default}}),Object.defineProperty(exports,"FeedContent",{enumerable:!0,get:function(){return _FeedContent2.default}}),Object.defineProperty(exports,"FeedDate",{enumerable:!0,get:function(){return _FeedDate2.default}}),Object.defineProperty(exports,"FeedEvent",{enumerable:!0,get:function(){return _FeedEvent2.default}}),Object.defineProperty(exports,"FeedExtra",{enumerable:!0,get:function(){return _FeedExtra2.default}}),Object.defineProperty(exports,"FeedLabel",{enumerable:!0,get:function(){return _FeedLabel2.default}}),Object.defineProperty(exports,"FeedLike",{enumerable:!0,get:function(){return _FeedLike2.default}}),Object.defineProperty(exports,"FeedMeta",{enumerable:!0,get:function(){return _FeedMeta2.default}}),Object.defineProperty(exports,"FeedSummary",{enumerable:!0,get:function(){return _FeedSummary2.default}}),Object.defineProperty(exports,"FeedUser",{enumerable:!0,get:function(){return _FeedUser2.default}}),Object.defineProperty(exports,"Item",{enumerable:!0,get:function(){return _Item2.default}}),Object.defineProperty(exports,"ItemContent",{enumerable:!0,get:function(){return _ItemContent2.default}}),Object.defineProperty(exports,"ItemDescription",{enumerable:!0,get:function(){return _ItemDescription2.default}}),Object.defineProperty(exports,"ItemExtra",{enumerable:!0,get:function(){return _ItemExtra2.default}}),Object.defineProperty(exports,"ItemGroup",{enumerable:!0,get:function(){return _ItemGroup2.default}}),Object.defineProperty(exports,"ItemHeader",{enumerable:!0,get:function(){return _ItemHeader2.default}}),Object.defineProperty(exports,"ItemImage",{enumerable:!0,get:function(){return _ItemImage2.default}}),Object.defineProperty(exports,"ItemMeta",{enumerable:!0,get:function(){return _ItemMeta2.default}}),Object.defineProperty(exports,"Statistic",{enumerable:!0,get:function(){return _Statistic2.default}}),Object.defineProperty(exports,"StatisticGroup",{enumerable:!0,get:function(){return _StatisticGroup2.default}}),Object.defineProperty(exports,"StatisticLabel",{enumerable:!0,get:function(){return _StatisticLabel2.default}}),Object.defineProperty(exports,"StatisticValue",{enumerable:!0,get:function(){return _StatisticValue2.default}}),require("@stardust-ui/react-component-ref")),_Confirm2=_interopRequireDefault(require("./addons/Confirm")),_MountNode2=_interopRequireDefault(require("./addons/MountNode")),_Pagination2=_interopRequireDefault(require("./addons/Pagination")),_PaginationItem2=_interopRequireDefault(require("./addons/Pagination/PaginationItem")),_Portal2=_interopRequireDefault(require("./addons/Portal")),_PortalInner2=_interopRequireDefault(require("./addons/Portal/PortalInner")),_Radio2=_interopRequireDefault(require("./addons/Radio")),_Responsive2=_interopRequireDefault(require("./addons/Responsive")),_Select2=_interopRequireDefault(require("./addons/Select")),_TextArea2=_interopRequireDefault(require("./addons/TextArea")),_TransitionablePortal2=_interopRequireDefault(require("./addons/TransitionablePortal")),_Visibility2=_interopRequireDefault(require("./behaviors/Visibility")),_Breadcrumb2=_interopRequireDefault(require("./collections/Breadcrumb")),_BreadcrumbDivider2=_interopRequireDefault(require("./collections/Breadcrumb/BreadcrumbDivider")),_BreadcrumbSection2=_interopRequireDefault(require("./collections/Breadcrumb/BreadcrumbSection")),_Form2=_interopRequireDefault(require("./collections/Form")),_FormButton2=_interopRequireDefault(require("./collections/Form/FormButton")),_FormCheckbox2=_interopRequireDefault(require("./collections/Form/FormCheckbox")),_FormDropdown2=_interopRequireDefault(require("./collections/Form/FormDropdown")),_FormField2=_interopRequireDefault(require("./collections/Form/FormField")),_FormGroup2=_interopRequireDefault(require("./collections/Form/FormGroup")),_FormInput2=_interopRequireDefault(require("./collections/Form/FormInput")),_FormRadio2=_interopRequireDefault(require("./collections/Form/FormRadio")),_FormSelect2=_interopRequireDefault(require("./collections/Form/FormSelect")),_FormTextArea2=_interopRequireDefault(require("./collections/Form/FormTextArea")),_Grid2=_interopRequireDefault(require("./collections/Grid")),_GridColumn2=_interopRequireDefault(require("./collections/Grid/GridColumn")),_GridRow2=_interopRequireDefault(require("./collections/Grid/GridRow")),_Menu2=_interopRequireDefault(require("./collections/Menu")),_MenuHeader2=_interopRequireDefault(require("./collections/Menu/MenuHeader")),_MenuItem2=_interopRequireDefault(require("./collections/Menu/MenuItem")),_MenuMenu2=_interopRequireDefault(require("./collections/Menu/MenuMenu")),_Message2=_interopRequireDefault(require("./collections/Message")),_MessageContent2=_interopRequireDefault(require("./collections/Message/MessageContent")),_MessageHeader2=_interopRequireDefault(require("./collections/Message/MessageHeader")),_MessageItem2=_interopRequireDefault(require("./collections/Message/MessageItem")),_MessageList2=_interopRequireDefault(require("./collections/Message/MessageList")),_Table2=_interopRequireDefault(require("./collections/Table")),_TableBody2=_interopRequireDefault(require("./collections/Table/TableBody")),_TableCell2=_interopRequireDefault(require("./collections/Table/TableCell")),_TableFooter2=_interopRequireDefault(require("./collections/Table/TableFooter")),_TableHeader2=_interopRequireDefault(require("./collections/Table/TableHeader")),_TableHeaderCell2=_interopRequireDefault(require("./collections/Table/TableHeaderCell")),_TableRow2=_interopRequireDefault(require("./collections/Table/TableRow")),_Button2=_interopRequireDefault(require("./elements/Button/Button")),_ButtonContent2=_interopRequireDefault(require("./elements/Button/ButtonContent")),_ButtonGroup2=_interopRequireDefault(require("./elements/Button/ButtonGroup")),_ButtonOr2=_interopRequireDefault(require("./elements/Button/ButtonOr")),_Container2=_interopRequireDefault(require("./elements/Container")),_Divider2=_interopRequireDefault(require("./elements/Divider")),_Flag2=_interopRequireDefault(require("./elements/Flag")),_Header2=_interopRequireDefault(require("./elements/Header")),_HeaderContent2=_interopRequireDefault(require("./elements/Header/HeaderContent")),_HeaderSubheader2=_interopRequireDefault(require("./elements/Header/HeaderSubheader")),_Icon2=_interopRequireDefault(require("./elements/Icon")),_IconGroup2=_interopRequireDefault(require("./elements/Icon/IconGroup")),_Image2=_interopRequireDefault(require("./elements/Image")),_ImageGroup2=_interopRequireDefault(require("./elements/Image/ImageGroup")),_Input2=_interopRequireDefault(require("./elements/Input")),_Label2=_interopRequireDefault(require("./elements/Label")),_LabelDetail2=_interopRequireDefault(require("./elements/Label/LabelDetail")),_LabelGroup2=_interopRequireDefault(require("./elements/Label/LabelGroup")),_List2=_interopRequireDefault(require("./elements/List")),_ListContent2=_interopRequireDefault(require("./elements/List/ListContent")),_ListDescription2=_interopRequireDefault(require("./elements/List/ListDescription")),_ListHeader2=_interopRequireDefault(require("./elements/List/ListHeader")),_ListIcon2=_interopRequireDefault(require("./elements/List/ListIcon")),_ListItem2=_interopRequireDefault(require("./elements/List/ListItem")),_ListList2=_interopRequireDefault(require("./elements/List/ListList")),_Loader2=_interopRequireDefault(require("./elements/Loader")),_Placeholder2=_interopRequireDefault(require("./elements/Placeholder")),_PlaceholderHeader2=_interopRequireDefault(require("./elements/Placeholder/PlaceholderHeader")),_PlaceholderImage2=_interopRequireDefault(require("./elements/Placeholder/PlaceholderImage")),_PlaceholderLine2=_interopRequireDefault(require("./elements/Placeholder/PlaceholderLine")),_PlaceholderParagraph2=_interopRequireDefault(require("./elements/Placeholder/PlaceholderParagraph")),_Rail2=_interopRequireDefault(require("./elements/Rail")),_Reveal2=_interopRequireDefault(require("./elements/Reveal")),_RevealContent2=_interopRequireDefault(require("./elements/Reveal/RevealContent")),_Segment2=_interopRequireDefault(require("./elements/Segment")),_SegmentGroup2=_interopRequireDefault(require("./elements/Segment/SegmentGroup")),_SegmentInline2=_interopRequireDefault(require("./elements/Segment/SegmentInline")),_Step2=_interopRequireDefault(require("./elements/Step")),_StepContent2=_interopRequireDefault(require("./elements/Step/StepContent")),_StepDescription2=_interopRequireDefault(require("./elements/Step/StepDescription")),_StepGroup2=_interopRequireDefault(require("./elements/Step/StepGroup")),_StepTitle2=_interopRequireDefault(require("./elements/Step/StepTitle")),_Accordion2=_interopRequireDefault(require("./modules/Accordion/Accordion")),_AccordionAccordion2=_interopRequireDefault(require("./modules/Accordion/AccordionAccordion")),_AccordionContent2=_interopRequireDefault(require("./modules/Accordion/AccordionContent")),_AccordionPanel2=_interopRequireDefault(require("./modules/Accordion/AccordionPanel")),_AccordionTitle2=_interopRequireDefault(require("./modules/Accordion/AccordionTitle")),_Checkbox2=_interopRequireDefault(require("./modules/Checkbox")),_Dimmer2=_interopRequireDefault(require("./modules/Dimmer")),_DimmerDimmable2=_interopRequireDefault(require("./modules/Dimmer/DimmerDimmable")),_DimmerInner2=_interopRequireDefault(require("./modules/Dimmer/DimmerInner")),_Dropdown2=_interopRequireDefault(require("./modules/Dropdown")),_DropdownDivider2=_interopRequireDefault(require("./modules/Dropdown/DropdownDivider")),_DropdownHeader2=_interopRequireDefault(require("./modules/Dropdown/DropdownHeader")),_DropdownItem2=_interopRequireDefault(require("./modules/Dropdown/DropdownItem")),_DropdownMenu2=_interopRequireDefault(require("./modules/Dropdown/DropdownMenu")),_DropdownSearchInput2=_interopRequireDefault(require("./modules/Dropdown/DropdownSearchInput")),_Embed2=_interopRequireDefault(require("./modules/Embed")),_Modal2=_interopRequireDefault(require("./modules/Modal")),_ModalActions2=_interopRequireDefault(require("./modules/Modal/ModalActions")),_ModalContent2=_interopRequireDefault(require("./modules/Modal/ModalContent")),_ModalDescription2=_interopRequireDefault(require("./modules/Modal/ModalDescription")),_ModalHeader2=_interopRequireDefault(require("./modules/Modal/ModalHeader")),_Popup2=_interopRequireDefault(require("./modules/Popup")),_PopupContent2=_interopRequireDefault(require("./modules/Popup/PopupContent")),_PopupHeader2=_interopRequireDefault(require("./modules/Popup/PopupHeader")),_Progress2=_interopRequireDefault(require("./modules/Progress")),_Rating2=_interopRequireDefault(require("./modules/Rating")),_RatingIcon2=_interopRequireDefault(require("./modules/Rating/RatingIcon")),_Search2=_interopRequireDefault(require("./modules/Search")),_SearchCategory2=_interopRequireDefault(require("./modules/Search/SearchCategory")),_SearchResult2=_interopRequireDefault(require("./modules/Search/SearchResult")),_SearchResults2=_interopRequireDefault(require("./modules/Search/SearchResults")),_Sidebar2=_interopRequireDefault(require("./modules/Sidebar")),_SidebarPushable2=_interopRequireDefault(require("./modules/Sidebar/SidebarPushable")),_SidebarPusher2=_interopRequireDefault(require("./modules/Sidebar/SidebarPusher")),_Sticky2=_interopRequireDefault(require("./modules/Sticky")),_Tab2=_interopRequireDefault(require("./modules/Tab")),_TabPane2=_interopRequireDefault(require("./modules/Tab/TabPane")),_Transition2=_interopRequireDefault(require("./modules/Transition")),_TransitionGroup2=_interopRequireDefault(require("./modules/Transition/TransitionGroup")),_Advertisement2=_interopRequireDefault(require("./views/Advertisement")),_Card2=_interopRequireDefault(require("./views/Card/Card")),_CardContent2=_interopRequireDefault(require("./views/Card/CardContent")),_CardDescription2=_interopRequireDefault(require("./views/Card/CardDescription")),_CardGroup2=_interopRequireDefault(require("./views/Card/CardGroup")),_CardHeader2=_interopRequireDefault(require("./views/Card/CardHeader")),_CardMeta2=_interopRequireDefault(require("./views/Card/CardMeta")),_Comment2=_interopRequireDefault(require("./views/Comment")),_CommentAction2=_interopRequireDefault(require("./views/Comment/CommentAction")),_CommentActions2=_interopRequireDefault(require("./views/Comment/CommentActions")),_CommentAuthor2=_interopRequireDefault(require("./views/Comment/CommentAuthor")),_CommentAvatar2=_interopRequireDefault(require("./views/Comment/CommentAvatar")),_CommentContent2=_interopRequireDefault(require("./views/Comment/CommentContent")),_CommentGroup2=_interopRequireDefault(require("./views/Comment/CommentGroup")),_CommentMetadata2=_interopRequireDefault(require("./views/Comment/CommentMetadata")),_CommentText2=_interopRequireDefault(require("./views/Comment/CommentText")),_Feed2=_interopRequireDefault(require("./views/Feed")),_FeedContent2=_interopRequireDefault(require("./views/Feed/FeedContent")),_FeedDate2=_interopRequireDefault(require("./views/Feed/FeedDate")),_FeedEvent2=_interopRequireDefault(require("./views/Feed/FeedEvent")),_FeedExtra2=_interopRequireDefault(require("./views/Feed/FeedExtra")),_FeedLabel2=_interopRequireDefault(require("./views/Feed/FeedLabel")),_FeedLike2=_interopRequireDefault(require("./views/Feed/FeedLike")),_FeedMeta2=_interopRequireDefault(require("./views/Feed/FeedMeta")),_FeedSummary2=_interopRequireDefault(require("./views/Feed/FeedSummary")),_FeedUser2=_interopRequireDefault(require("./views/Feed/FeedUser")),_Item2=_interopRequireDefault(require("./views/Item")),_ItemContent2=_interopRequireDefault(require("./views/Item/ItemContent")),_ItemDescription2=_interopRequireDefault(require("./views/Item/ItemDescription")),_ItemExtra2=_interopRequireDefault(require("./views/Item/ItemExtra")),_ItemGroup2=_interopRequireDefault(require("./views/Item/ItemGroup")),_ItemHeader2=_interopRequireDefault(require("./views/Item/ItemHeader")),_ItemImage2=_interopRequireDefault(require("./views/Item/ItemImage")),_ItemMeta2=_interopRequireDefault(require("./views/Item/ItemMeta")),_Statistic2=_interopRequireDefault(require("./views/Statistic")),_StatisticGroup2=_interopRequireDefault(require("./views/Statistic/StatisticGroup")),_StatisticLabel2=_interopRequireDefault(require("./views/Statistic/StatisticLabel")),_StatisticValue2=_interopRequireDefault(require("./views/Statistic/StatisticValue"))},{"./addons/Confirm":1445,"./addons/MountNode":1447,"./addons/Pagination":1455,"./addons/Pagination/PaginationItem":1454,"./addons/Portal":1458,"./addons/Portal/PortalInner":1457,"./addons/Radio":1460,"./addons/Responsive":1462,"./addons/Select":1465,"./addons/TextArea":1467,"./addons/TransitionablePortal":1469,"./behaviors/Visibility":1471,"./collections/Breadcrumb":1475,"./collections/Breadcrumb/BreadcrumbDivider":1473,"./collections/Breadcrumb/BreadcrumbSection":1474,"./collections/Form":1486,"./collections/Form/FormButton":1477,"./collections/Form/FormCheckbox":1478,"./collections/Form/FormDropdown":1479,"./collections/Form/FormField":1480,"./collections/Form/FormGroup":1481,"./collections/Form/FormInput":1482,"./collections/Form/FormRadio":1483,"./collections/Form/FormSelect":1484,"./collections/Form/FormTextArea":1485,"./collections/Grid":1490,"./collections/Grid/GridColumn":1488,"./collections/Grid/GridRow":1489,"./collections/Menu":1495,"./collections/Menu/MenuHeader":1492,"./collections/Menu/MenuItem":1493,"./collections/Menu/MenuMenu":1494,"./collections/Message":1501,"./collections/Message/MessageContent":1497,"./collections/Message/MessageHeader":1498,"./collections/Message/MessageItem":1499,"./collections/Message/MessageList":1500,"./collections/Table":1509,"./collections/Table/TableBody":1503,"./collections/Table/TableCell":1504,"./collections/Table/TableFooter":1505,"./collections/Table/TableHeader":1506,"./collections/Table/TableHeaderCell":1507,"./collections/Table/TableRow":1508,"./elements/Button/Button":1510,"./elements/Button/ButtonContent":1511,"./elements/Button/ButtonGroup":1512,"./elements/Button/ButtonOr":1513,"./elements/Container":1516,"./elements/Divider":1518,"./elements/Flag":1520,"./elements/Header":1524,"./elements/Header/HeaderContent":1522,"./elements/Header/HeaderSubheader":1523,"./elements/Icon":1527,"./elements/Icon/IconGroup":1526,"./elements/Image":1530,"./elements/Image/ImageGroup":1529,"./elements/Input":1532,"./elements/Label":1536,"./elements/Label/LabelDetail":1534,"./elements/Label/LabelGroup":1535,"./elements/List":1544,"./elements/List/ListContent":1538,"./elements/List/ListDescription":1539,"./elements/List/ListHeader":1540,"./elements/List/ListIcon":1541,"./elements/List/ListItem":1542,"./elements/List/ListList":1543,"./elements/Loader":1546,"./elements/Placeholder":1552,"./elements/Placeholder/PlaceholderHeader":1548,"./elements/Placeholder/PlaceholderImage":1549,"./elements/Placeholder/PlaceholderLine":1550,"./elements/Placeholder/PlaceholderParagraph":1551,"./elements/Rail":1554,"./elements/Reveal":1557,"./elements/Reveal/RevealContent":1556,"./elements/Segment":1561,"./elements/Segment/SegmentGroup":1559,"./elements/Segment/SegmentInline":1560,"./elements/Step":1567,"./elements/Step/StepContent":1563,"./elements/Step/StepDescription":1564,"./elements/Step/StepGroup":1565,"./elements/Step/StepTitle":1566,"./modules/Accordion/Accordion":1595,"./modules/Accordion/AccordionAccordion":1596,"./modules/Accordion/AccordionContent":1597,"./modules/Accordion/AccordionPanel":1598,"./modules/Accordion/AccordionTitle":1599,"./modules/Checkbox":1601,"./modules/Dimmer":1605,"./modules/Dimmer/DimmerDimmable":1603,"./modules/Dimmer/DimmerInner":1604,"./modules/Dropdown":1612,"./modules/Dropdown/DropdownDivider":1607,"./modules/Dropdown/DropdownHeader":1608,"./modules/Dropdown/DropdownItem":1609,"./modules/Dropdown/DropdownMenu":1610,"./modules/Dropdown/DropdownSearchInput":1611,"./modules/Embed":1614,"./modules/Modal":1620,"./modules/Modal/ModalActions":1616,"./modules/Modal/ModalContent":1617,"./modules/Modal/ModalDescription":1618,"./modules/Modal/ModalHeader":1619,"./modules/Popup":1625,"./modules/Popup/PopupContent":1623,"./modules/Popup/PopupHeader":1624,"./modules/Progress":1629,"./modules/Rating":1632,"./modules/Rating/RatingIcon":1631,"./modules/Search":1638,"./modules/Search/SearchCategory":1634,"./modules/Search/SearchResult":1636,"./modules/Search/SearchResults":1637,"./modules/Sidebar":1642,"./modules/Sidebar/SidebarPushable":1640,"./modules/Sidebar/SidebarPusher":1641,"./modules/Sticky":1644,"./modules/Tab":1647,"./modules/Tab/TabPane":1646,"./modules/Transition":1650,"./modules/Transition/TransitionGroup":1649,"./views/Advertisement":1652,"./views/Card/Card":1653,"./views/Card/CardContent":1654,"./views/Card/CardDescription":1655,"./views/Card/CardGroup":1656,"./views/Card/CardHeader":1657,"./views/Card/CardMeta":1658,"./views/Comment":1668,"./views/Comment/CommentAction":1660,"./views/Comment/CommentActions":1661,"./views/Comment/CommentAuthor":1662,"./views/Comment/CommentAvatar":1663,"./views/Comment/CommentContent":1664,"./views/Comment/CommentGroup":1665,"./views/Comment/CommentMetadata":1666,"./views/Comment/CommentText":1667,"./views/Feed":1679,"./views/Feed/FeedContent":1670,"./views/Feed/FeedDate":1671,"./views/Feed/FeedEvent":1672,"./views/Feed/FeedExtra":1673,"./views/Feed/FeedLabel":1674,"./views/Feed/FeedLike":1675,"./views/Feed/FeedMeta":1676,"./views/Feed/FeedSummary":1677,"./views/Feed/FeedUser":1678,"./views/Item":1688,"./views/Item/ItemContent":1681,"./views/Item/ItemDescription":1682,"./views/Item/ItemExtra":1683,"./views/Item/ItemGroup":1684,"./views/Item/ItemHeader":1685,"./views/Item/ItemImage":1686,"./views/Item/ItemMeta":1687,"./views/Statistic":1693,"./views/Statistic/StatisticGroup":1690,"./views/Statistic/StatisticLabel":1691,"./views/Statistic/StatisticValue":1692,"@babel/runtime/helpers/interopRequireDefault":13,"@stardust-ui/react-component-ref":107}],1569:[function(require,module,exports){!function(process){!function(){"use strict";function getDefaultPropName(prop){return"default".concat(prop[0].toUpperCase()+prop.slice(1))}function getAutoControlledStateValue(propName,props,state){var propValue=props[propName];if(void 0!==propValue)return propValue;if(3<arguments.length&&void 0!==arguments[3]&&arguments[3]){propValue=props[getDefaultPropName(propName)];if(void 0!==propValue)return propValue;if(state){propValue=state[propName];if(void 0!==propValue)return propValue}}return"checked"!==propName&&("value"===propName?props.multiple?[]:"":void 0)}var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectSpread2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=exports.getAutoControlledStateValue=exports.getDefaultPropName=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectSpread"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_isUndefined2=_interopRequireDefault(require("lodash/isUndefined")),_startsWith2=_interopRequireDefault(require("lodash/startsWith")),_filter2=_interopRequireDefault(require("lodash/filter")),_isEmpty2=_interopRequireDefault(require("lodash/isEmpty")),_keys2=_interopRequireDefault(require("lodash/keys")),_intersection2=_interopRequireDefault(require("lodash/intersection")),_has2=_interopRequireDefault(require("lodash/has")),_each2=_interopRequireDefault(require("lodash/each")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_interopRequireDefault=require("react"),_interopRequireDefault=(exports.getDefaultPropName=getDefaultPropName,exports.getAutoControlledStateValue=getAutoControlledStateValue,function(_Component){function AutoControlledComponent(){var _this;(0,_classCallCheck2.default)(this,AutoControlledComponent);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];_this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(AutoControlledComponent)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"trySetState",function(state,callback){var newState=Object.keys(state).reduce(function(acc,prop){return void 0===_this.props[prop]&&(acc[prop]=state[prop]),acc},{});0<Object.keys(newState).length&&_this.setState(newState,callback)});var name,propTypes,defaultProps,_getPrototypeOf2=_this.constructor.autoControlledProps,_state=(0,_invoke2.default)((0,_assertThisInitialized2.default)(_this),"getInitialAutoControlledState",_this.props)||{},_this$constructor=("production"!==process.env.NODE_ENV&&(defaultProps=(_this$constructor=_this.constructor).defaultProps,name=_this$constructor.name,propTypes=_this$constructor.propTypes,_getPrototypeOf2||console.error("Auto controlled ".concat(name," must specify a static autoControlledProps array.")),(0,_each2.default)(_getPrototypeOf2,function(prop){var defaultProp=getDefaultPropName(prop);(0,_has2.default)(propTypes,defaultProp)||console.error("".concat(name,' is missing "').concat(defaultProp,'" propTypes validation for auto controlled prop "').concat(prop,'".')),(0,_has2.default)(propTypes,prop)||console.error("".concat(name,' is missing propTypes validation for auto controlled prop "').concat(prop,'".'))}),_this$constructor=(0,_intersection2.default)(_getPrototypeOf2,(0,_keys2.default)(defaultProps)),(0,_isEmpty2.default)(_this$constructor)||console.error(["Do not set defaultProps for autoControlledProps. You can set defaults by","setting state in the constructor or using an ES7 property initializer","(https://babeljs.io/blog/2015/06/07/react-on-es6-plus#property-initializers)","See ".concat(name,' props: "').concat(_this$constructor,'".')].join(" ")),defaultProps=(0,_filter2.default)(_getPrototypeOf2,function(prop){return(0,_startsWith2.default)(prop,"default")}),(0,_isEmpty2.default)(defaultProps)||console.error(["Do not add default props to autoControlledProps.","Default props are automatically handled.","See ".concat(name,' autoControlledProps: "').concat(defaultProps,'".')].join(" "))),_getPrototypeOf2.reduce(function(acc,prop){var defaultPropName,_name;return acc[prop]=getAutoControlledStateValue(prop,_this.props,_state,!0),"production"!==process.env.NODE_ENV&&(defaultPropName=getDefaultPropName(prop),_name=_this.constructor.name,(0,_isUndefined2.default)(_this.props[defaultPropName])||(0,_isUndefined2.default)(_this.props[prop])||console.error("".concat(_name,' prop "').concat(prop,'" is auto controlled. Specify either ').concat(defaultPropName," or ").concat(prop,", but not both."))),acc},{}));return _this.state=(0,_objectSpread2.default)({},_state,_this$constructor),_this}return(0,_inherits2.default)(AutoControlledComponent,_Component),(0,_createClass2.default)(AutoControlledComponent,[{key:"UNSAFE_componentWillReceiveProps",value:function(nextProps){var newState=this.constructor.autoControlledProps.reduce(function(acc,prop){return!(0,_isUndefined2.default)(nextProps[prop])&&(acc[prop]=nextProps[prop]),acc},{});0<Object.keys(newState).length&&this.setState(newState)}}]),AutoControlledComponent}(_interopRequireDefault.Component));exports.default=_interopRequireDefault}.call(this)}.call(this,require("_process"))},{"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/each":910,"lodash/filter":914,"lodash/has":951,"lodash/intersection":957,"lodash/invoke":959,"lodash/isEmpty":966,"lodash/isUndefined":982,"lodash/keys":986,"lodash/startsWith":1009,react:1427}],1570:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectSpread2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectSpread"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_isUndefined2=_interopRequireDefault(require("lodash/isUndefined")),_startsWith2=_interopRequireDefault(require("lodash/startsWith")),_filter2=_interopRequireDefault(require("lodash/filter")),_isEmpty2=_interopRequireDefault(require("lodash/isEmpty")),_keys2=_interopRequireDefault(require("lodash/keys")),_intersection2=_interopRequireDefault(require("lodash/intersection")),_has2=_interopRequireDefault(require("lodash/has")),_each2=_interopRequireDefault(require("lodash/each")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_interopRequireDefault=require("react"),_AutoControlledComponent=require("./AutoControlledComponent"),_interopRequireDefault=function(_Component){function ModernAutoControlledComponent(){(0,_classCallCheck2.default)(this,ModernAutoControlledComponent);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];var _this,name,propTypes,defaultProps,_getPrototypeOf2=(_this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(ModernAutoControlledComponent)).call.apply(_getPrototypeOf2,[this].concat(args)))).constructor,autoControlledProps=_getPrototypeOf2.autoControlledProps,_getPrototypeOf2=_getPrototypeOf2.getAutoControlledStateFromProps,state=(0,_invoke2.default)((0,_assertThisInitialized2.default)(_this),"getInitialAutoControlledState",_this.props)||{},_this$constructor2=("production"!==process.env.NODE_ENV&&(defaultProps=(_this$constructor2=_this.constructor).defaultProps,name=_this$constructor2.name,propTypes=_this$constructor2.propTypes,_this$constructor2.getDerivedStateFromProps!==ModernAutoControlledComponent.getDerivedStateFromProps&&console.error("Auto controlled ".concat(name," must specify a static getAutoControlledStateFromProps() instead of getDerivedStateFromProps().")),(0,_each2.default)(autoControlledProps,function(prop){var defaultProp=(0,_AutoControlledComponent.getDefaultPropName)(prop);(0,_has2.default)(propTypes,defaultProp)||console.error("".concat(name,' is missing "').concat(defaultProp,'" propTypes validation for auto controlled prop "').concat(prop,'".')),(0,_has2.default)(propTypes,prop)||console.error("".concat(name,' is missing propTypes validation for auto controlled prop "').concat(prop,'".'))}),_this$constructor2=(0,_intersection2.default)(autoControlledProps,(0,_keys2.default)(defaultProps)),(0,_isEmpty2.default)(_this$constructor2)||console.error(["Do not set defaultProps for autoControlledProps. You can set defaults by","setting state in the constructor or using an ES7 property initializer","(https://babeljs.io/blog/2015/06/07/react-on-es6-plus#property-initializers)","See ".concat(name,' props: "').concat(_this$constructor2,'".')].join(" ")),defaultProps=(0,_filter2.default)(autoControlledProps,function(prop){return(0,_startsWith2.default)(prop,"default")}),(0,_isEmpty2.default)(defaultProps)||console.error(["Do not add default props to autoControlledProps.","Default props are automatically handled.","See ".concat(name,' autoControlledProps: "').concat(defaultProps,'".')].join(" "))),autoControlledProps.reduce(function(acc,prop){var defaultPropName,_name;return acc[prop]=(0,_AutoControlledComponent.getAutoControlledStateValue)(prop,_this.props,state,!0),"production"!==process.env.NODE_ENV&&(defaultPropName=(0,_AutoControlledComponent.getDefaultPropName)(prop),_name=_this.constructor.name,(0,_isUndefined2.default)(_this.props[defaultPropName])||(0,_isUndefined2.default)(_this.props[prop])||console.error("".concat(_name,' prop "').concat(prop,'" is auto controlled. Specify either ').concat(defaultPropName," or ").concat(prop,", but not both."))),acc},{}));return _this.state=(0,_objectSpread2.default)({},state,_this$constructor2,{autoControlledProps:autoControlledProps,getAutoControlledStateFromProps:_getPrototypeOf2}),_this}return(0,_inherits2.default)(ModernAutoControlledComponent,_Component),(0,_createClass2.default)(ModernAutoControlledComponent,null,[{key:"getDerivedStateFromProps",value:function(props,state){var autoControlledProps=state.autoControlledProps,getAutoControlledStateFromProps=state.getAutoControlledStateFromProps,autoControlledProps=autoControlledProps.reduce(function(acc,prop){return!(0,_isUndefined2.default)(props[prop])&&(acc[prop]=props[prop]),acc},{});return getAutoControlledStateFromProps?(getAutoControlledStateFromProps=getAutoControlledStateFromProps(props,(0,_objectSpread2.default)({},state,autoControlledProps)),(0,_objectSpread2.default)({},autoControlledProps,getAutoControlledStateFromProps)):autoControlledProps}},{key:"getAutoControlledStateFromProps",value:function(){return null}}]),ModernAutoControlledComponent}(_interopRequireDefault.Component);exports.default=_interopRequireDefault}.call(this)}.call(this,require("_process"))},{"./AutoControlledComponent":1569,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/each":910,"lodash/filter":914,"lodash/has":951,"lodash/intersection":957,"lodash/invoke":959,"lodash/isEmpty":966,"lodash/isUndefined":982,"lodash/keys":986,"lodash/startsWith":1009,react:1427}],1571:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ALL_ICONS_IN_ALL_CONTEXTS=exports.COMPONENT_CONTEXT_SPECIFIC_ICONS=exports.ICONS_AND_ALIASES=exports.ICON_ALIASES=exports.ICONS=exports.BRANDS=exports.WRITING=exports.VEHICLES=exports.USERS_PEOPLE=exports.STATUS=exports.SPORTS=exports.SPINNERS=exports.SHAPES=exports.PAYMENTS_SHOPPING=exports.OBJECTS=exports.MEDICAL=exports.MAPS=exports.LOGISTICS=exports.INTERFACES=exports.IMAGES=exports.HEALTH=exports.HANDS_GESTURES=exports.GENDERS=exports.FILES=exports.EDITORS=exports.DESIGN=exports.DATE_TIME=exports.CURRENCY=exports.COMPUTERS=exports.COMMUNICATION=exports.CODE=exports.CHESS=exports.BUSINESS=exports.AUDIO_VIDEO=exports.ARROWS=exports.ACCESSIBILITY=exports.TRANSITIONS=exports.STATIC_TRANSITIONS=exports.DIRECTIONAL_TRANSITIONS=exports.WIDTHS=exports.VISIBILITY=exports.VERTICAL_ALIGNMENTS=exports.TEXT_ALIGNMENTS=exports.SIZES=exports.FLOATS=exports.COLORS=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_uniq2=_interopRequireDefault(require("lodash/uniq")),_values2=_interopRequireDefault(require("lodash/values")),_interopRequireDefault=_interopRequireDefault(require("lodash/keys")),require=require("./numberToWord"),_interopRequireDefault=(exports.COLORS=["red","orange","yellow","olive","green","teal","blue","violet","purple","pink","brown","grey","black"],exports.FLOATS=["left","right"],exports.SIZES=["mini","tiny","small","medium","large","big","huge","massive"],exports.TEXT_ALIGNMENTS=["left","center","right","justified"],exports.VERTICAL_ALIGNMENTS=["bottom","middle","top"],exports.VISIBILITY=["mobile","tablet","computer","large screen","widescreen"],[].concat((0,_toConsumableArray2.default)((0,_interopRequireDefault.default)(require.numberToWordMap)),(0,_toConsumableArray2.default)((0,_interopRequireDefault.default)(require.numberToWordMap).map(Number)),(0,_toConsumableArray2.default)((0,_values2.default)(require.numberToWordMap)))),_values2=(exports.WIDTHS=_interopRequireDefault,["browse","browse right","drop","fade","fade up","fade down","fade left","fade right","fly up","fly down","fly left","fly right","horizontal flip","vertical flip","scale","slide up","slide down","slide left","slide right","swing up","swing down","swing left","swing right","zoom"]),require=(exports.DIRECTIONAL_TRANSITIONS=_values2,["jiggle","flash","shake","pulse","tada","bounce","glow"]),_interopRequireDefault=(exports.STATIC_TRANSITIONS=require,[].concat(_values2,require)),_values2=(exports.TRANSITIONS=_interopRequireDefault,["american sign language interpreting","assistive listening systems","audio description","blind","braille","closed captioning","closed captioning outline","deaf","low vision","phone volume","question circle","question circle outline","sign language","tty","universal access","wheelchair"]),require=(exports.ACCESSIBILITY=_values2,["angle double down","angle double left","angle double right","angle double up","angle down","angle left","angle right","angle up","arrow alternate circle down","arrow alternate circle down outline","arrow alternate circle left","arrow alternate circle left outline","arrow alternate circle right","arrow alternate circle right outline","arrow alternate circle up","arrow alternate circle up outline","arrow circle down","arrow circle left","arrow circle right","arrow circle up","arrow down","arrow left","arrow right","arrow up","arrows alternate","arrows alternate horizontal","arrows alternate vertical","caret down","caret left","caret right","caret square down","caret square down outline","caret square left","caret square left outline","caret square right","caret square right outline","caret square up","caret square up outline","caret up","cart arrow down","chart line","chevron circle down","chevron circle left","chevron circle right","chevron circle up","chevron down","chevron left","chevron right","chevron up","cloud download","cloud upload","download","exchange","expand arrows alternate","external alternate","external square alternate","hand point down","hand point down outline","hand point left","hand point left outline","hand point right","hand point right outline","hand point up","hand point up outline","hand pointer","hand pointer outline","history","level down alternate","level up alternate","location arrow","long arrow alternate down","long arrow alternate left","long arrow alternate right","long arrow alternate up","mouse pointer","play","random","recycle","redo","redo alternate","reply","reply all","retweet","share","share square","share square outline","sign-in","sign-out","sign-in alternate","sign-out alternate","sort","sort alphabet down","sort alphabet up","sort amount down","sort amount up","sort down","sort numeric down","sort numeric up","sort up","sync","sync alternate","text height","text width","undo","undo alternate","upload","zoom-in","zoom-out"]),_interopRequireDefault=(exports.ARROWS=require,["audio description","backward","circle","circle outline","closed captioning","closed captioning outline","compress","eject","expand","expand arrows alternate","fast backward","fast forward","file audio","file audio outline","file video","file video outline","film","forward","headphones","microphone","microphone slash","music","pause","pause circle","pause circle outline","phone volume","play","play circle","play circle outline","podcast","random","redo","redo alternate","rss","rss square","step backward","step forward","stop","stop circle","stop circle outline","sync","sync alternate","undo","undo alternate","video","volume down","volume off","volume up"]),BUSINESS=(exports.AUDIO_VIDEO=_interopRequireDefault,["address book","address book outline","address card","address card outline","archive","balance scale","birthday cake","book","briefcase","building","building outline","bullhorn","bullseye","calculator","calendar","calendar outline","calendar alternate","calendar alternate outline","certificate","chart area","chart bar","chart bar outline","chart line","chart pie","clipboard","clipboard outline","coffee","columns","compass","compass outline","copy","copy outline","copyright","copyright outline","cut","edit","edit outline","envelope","envelope outline","envelope open","envelope open outline","envelope square","eraser","fax","file","file outline","file alternate","file alternate outline","folder","folder outline","folder open","folder open outline","globe","industry","paperclip","paste","pen square","pencil alternate","percent","phone","phone square","phone volume","registered","registered outline","save","save outline","sitemap","sticky note","sticky note outline","suitcase","table","tag","tags","tasks","thumbtack","trademark"]),CHESS=(exports.BUSINESS=BUSINESS,["chess","chess bishop","chess board","chess king","chess knight","chess pawn","chess queen","chess rook","square full"]),CODE=(exports.CHESS=CHESS,["archive","barcode","bath","bug","code","code branch","coffee","file","file outline","file alternate","file alternate outline","file code","file code outline","filter","fire extinguisher","folder","folder outline","folder open","folder open outline","keyboard","keyboard outline","microchip","qrcode","shield alternate","sitemap","terminal","user secret","window close","window close outline","window maximize","window maximize outline","window minimize","window minimize outline","window restore","window restore outline"]),COMMUNICATION=(exports.CODE=CODE,["address book","address book outline","address card","address card outline","american sign language interpreting","assistive listening systems","at","bell","bell outline","bell slash","bell slash outline","bullhorn","comment","comment outline","comment alternate","comment alternate outline","comments","comments outline","envelope","envelope outline","envelope open","envelope open outline","envelope square","fax","inbox","language","microphone","microphone slash","mobile","mobile alternate","paper plane","paper plane outline","phone","phone square","phone volume","rss","rss square","tty","wifi"]),COMPUTERS=(exports.COMMUNICATION=COMMUNICATION,["desktop","download","hdd","hdd outline","headphones","keyboard","keyboard outline","laptop","microchip","mobile","mobile alternate","plug","power off","print","save","save outline","server","tablet","tablet alternate","tv","upload"]),CURRENCY=(exports.COMPUTERS=COMPUTERS,["dollar sign","euro sign","lira sign","money bill alternate","money bill alternate outline","pound sign","ruble sign","rupee sign","shekel sign","won sign","yen sign"]),DATE_TIME=(exports.CURRENCY=CURRENCY,["bell","bell outline","bell slash","bell slash outline","calendar","calendar outline","calendar alternate","calendar alternate outline","calendar check","calendar check outline","calendar minus","calendar minus outline","calendar plus","calendar plus outline","calendar times","calendar times outline","clock","clock outline","hourglass","hourglass outline","hourglass end","hourglass half","hourglass start","stopwatch"]),DESIGN=(exports.DATE_TIME=DATE_TIME,["adjust","clone","clone outline","copy","copy outline","crop","crosshairs","cut","edit","edit outline","eraser","eye","eye dropper","eye slash","eye slash outline","object group","object group outline","object ungroup","object ungroup outline","paint brush","paste","pencil alternate","save","save outline","tint"]),EDITORS=(exports.DESIGN=DESIGN,["align center","align justify","align left","align right","bold","clipboard","clipboard outline","clone","clone outline","columns","copy","copy outline","cut","edit","edit outline","eraser","file","file outline","file alternate","file alternate outline","font","heading","i cursor","indent","italic","linkify","list","list alternate","list alternate outline","list ol","list ul","outdent","paper plane","paper plane outline","paperclip","paragraph","paste","pencil alternate","print","quote left","quote right","redo","redo alternate","reply","reply all","share","strikethrough","subscript","superscript","sync","sync alternate","table","tasks","text height","text width","th","th large","th list","trash","trash alternate","trash alternate outline","underline","undo","undo alternate","unlink"]),FILES=(exports.EDITORS=EDITORS,["archive","clone","clone outline","copy","copy outline","cut","file","file outline","file alternate","file alternate outline","file archive","file archive outline","file audio","file audio outline","file code","file code outline","file excel","file excel outline","file image","file image outline","file pdf","file pdf outline","file powerpoint","file powerpoint outline","file video","file video outline","file word","file word outline","folder","folder outline","folder open","folder open outline","paste","save","save outline","sticky note","sticky note outline"]),GENDERS=(exports.FILES=FILES,["genderless","mars","mars double","mars stroke","mars stroke horizontal","mars stroke vertical","mercury","neuter","transgender","transgender alternate","venus","venus double","venus mars"]),HANDS_GESTURES=(exports.GENDERS=GENDERS,["hand lizard","hand lizard outline","hand paper","hand paper outline","hand peace","hand peace outline","hand point down","hand point down outline","hand point left","hand point left outline","hand point right","hand point right outline","hand point up","hand point up outline","hand pointer","hand pointer outline","hand rock","hand rock outline","hand scissors","hand scissors outline","hand spock","hand spock outline","handshake","handshake outline","thumbs down","thumbs down outline","thumbs up","thumbs up outline"]),HEALTH=(exports.HANDS_GESTURES=HANDS_GESTURES,["ambulance","h square","heart","heart outline","heartbeat","hospital","hospital outline","medkit","plus square","plus square outline","stethoscope","user md","wheelchair"]),IMAGES=(exports.HEALTH=HEALTH,["adjust","bolt","camera","camera retro","clone","clone outline","compress","expand","eye","eye dropper","eye slash","eye slash outline","file image","file image outline","film","id badge","id badge outline","id card","id card outline","image","image outline","images","images outline","sliders horizontal","tint"]),INTERFACES=(exports.IMAGES=IMAGES,["ban","barcode","bars","beer","bell","bell outline","bell slash","bell slash outline","bug","bullhorn","bullseye","calculator","calendar","calendar outline","calendar alternate","calendar alternate outline","calendar check","calendar check outline","calendar minus","calendar minus outline","calendar plus","calendar plus outline","calendar times","calendar times outline","certificate","check","check circle","check circle outline","check square","check square outline","circle","circle outline","clipboard","clipboard outline","clone","clone outline","cloud","cloud download","cloud upload","coffee","cog","cogs","copy","copy outline","cut","database","dot circle","dot circle outline","download","edit","edit outline","ellipsis horizontal","ellipsis vertical","envelope","envelope outline","envelope open","envelope open outline","eraser","exclamation","exclamation circle","exclamation triangle","external alternate","external square alternate","eye","eye slash","eye slash outline","file","file outline","file alternate","file alternate outline","filter","flag","flag outline","flag checkered","folder","folder outline","folder open","folder open outline","frown","frown outline","hashtag","heart","heart outline","history","home","i cursor","info","info circle","language","magic","meh","meh outline","microphone","microphone slash","minus","minus circle","minus square","minus square outline","paste","pencil alternate","plus","plus circle","plus square","plus square outline","qrcode","question","question circle","question circle outline","quote left","quote right","redo","redo alternate","reply","reply all","rss","rss square","save","save outline","search","search minus","search plus","share","share alternate","share alternate square","share square","share square outline","shield alternate","sign-in","sign-out","signal","sitemap","sliders horizontal","smile","smile outline","sort","sort alphabet down","sort alphabet up","sort amount down","sort amount up","sort down","sort numeric down","sort numeric up","sort up","star","star outline","star half","star half outline","sync","sync alternate","thumbs down","thumbs down outline","thumbs up","thumbs up outline","times","times circle","times circle outline","toggle off","toggle on","trash","trash alternate","trash alternate outline","trophy","undo","undo alternate","upload","user","user outline","user circle","user circle outline","wifi"]),LOGISTICS=(exports.INTERFACES=INTERFACES,["box","boxes","clipboard check","clipboard list","dolly","dolly flatbed","pallet","shipping fast","truck","warehouse"]),MAPS=(exports.LOGISTICS=LOGISTICS,["ambulance","anchor","balance scale","bath","bed","beer","bell","bell outline","bell slash","bell slash outline","bicycle","binoculars","birthday cake","blind","bomb","book","bookmark","bookmark outline","briefcase","building","building outline","car","coffee","crosshairs","dollar sign","eye","eye slash","eye slash outline","fighter jet","fire","fire extinguisher","flag","flag outline","flag checkered","flask","gamepad","gavel","gift","glass martini","globe","graduation cap","h square","heart","heart outline","heartbeat","home","hospital","hospital outline","image","image outline","images","images outline","industry","info","info circle","key","leaf","lemon","lemon outline","life ring","life ring outline","lightbulb","lightbulb outline","location arrow","low vision","magnet","male","map","map outline","map marker","map marker alternate","map pin","map signs","medkit","money bill alternate","money bill alternate outline","motorcycle","music","newspaper","newspaper outline","paw","phone","phone square","phone volume","plane","plug","plus","plus square","plus square outline","print","recycle","road","rocket","search","search minus","search plus","ship","shopping bag","shopping basket","shopping cart","shower","street view","subway","suitcase","tag","tags","taxi","thumbtack","ticket alternate","tint","train","tree","trophy","truck","tty","umbrella","university","utensil spoon","utensils","wheelchair","wifi","wrench"]),MEDICAL=(exports.MAPS=MAPS,["ambulance","band aid","dna","first aid","heart","heart outline","heartbeat","hospital","hospital outline","hospital symbol","pills","plus","stethoscope","syringe","thermometer","user md","weight"]),OBJECTS=(exports.MEDICAL=MEDICAL,["ambulance","anchor","archive","balance scale","bath","bed","beer","bell","bell outline","bicycle","binoculars","birthday cake","bomb","book","bookmark","bookmark outline","briefcase","bug","building","building outline","bullhorn","bullseye","bus","calculator","calendar","calendar outline","calendar alternate","calendar alternate outline","camera","camera retro","car","clipboard","clipboard outline","cloud","coffee","cog","cogs","compass","compass outline","copy","copy outline","cube","cubes","cut","envelope","envelope outline","envelope open","envelope open outline","eraser","eye","eye dropper","fax","fighter jet","file","file outline","file alternate","file alternate outline","film","fire","fire extinguisher","flag","flag outline","flag checkered","flask","futbol","futbol outline","gamepad","gavel","gem","gem outline","gift","glass martini","globe","graduation cap","hdd","hdd outline","headphones","heart","heart outline","home","hospital","hospital outline","hourglass","hourglass outline","image","image outline","images","images outline","industry","key","keyboard","keyboard outline","laptop","leaf","lemon","lemon outline","life ring","life ring outline","lightbulb","lightbulb outline","lock","lock open","magic","magnet","map","map outline","map marker","map marker alternate","map pin","map signs","medkit","microchip","microphone","mobile","mobile alternate","money bill alternate","money bill alternate outline","moon","moon outline","motorcycle","newspaper","newspaper outline","paint brush","paper plane","paper plane outline","paperclip","paste","paw","pencil alternate","phone","plane","plug","print","puzzle piece","road","rocket","save","save outline","search","shield alternate","shopping bag","shopping basket","shopping cart","shower","snowflake","snowflake outline","space shuttle","star","star outline","sticky note","sticky note outline","stopwatch","subway","suitcase","sun","sun outline","tablet","tablet alternate","tachometer alternate","tag","tags","taxi","thumbtack","ticket alternate","train","trash","trash alternate","trash alternate outline","tree","trophy","truck","tv","umbrella","university","unlock","unlock alternate","utensil spoon","utensils","wheelchair","wrench"]),PAYMENTS_SHOPPING=(exports.OBJECTS=OBJECTS,["bell","bell outline","bookmark","bookmark outline","bullhorn","camera","camera retro","cart arrow down","cart plus","certificate","credit card","credit card outline","gem","gem outline","gift","handshake","handshake outline","heart","heart outline","key","shopping bag","shopping basket","shopping cart","star","star outline","tag","tags","thumbs down","thumbs down outline","thumbs up","thumbs up outline","trophy"]),SHAPES=(exports.PAYMENTS_SHOPPING=PAYMENTS_SHOPPING,["bookmark","bookmark outline","calendar","calendar outline","certificate","circle","circle outline","cloud","comment","comment outline","file","file outline","folder","folder outline","heart","heart outline","map marker","play","square","square outline","star","star outline"]),SPINNERS=(exports.SHAPES=SHAPES,["asterisk","certificate","circle notch","cog","compass","compass outline","crosshairs","life ring","life ring outline","snowflake","snowflake outline","spinner","sun","sun outline","sync"]),SPORTS=(exports.SPINNERS=SPINNERS,["baseball ball","basketball ball","bowling ball","football ball","futbol","futbol outline","golf ball","hockey puck","quidditch","table tennis","volleyball ball"]),STATUS=(exports.SPORTS=SPORTS,["ban","battery empty","battery full","battery half","battery quarter","battery three quarters","bell","bell outline","bell slash","bell slash outline","calendar","calendar outline","calendar alternate","calendar alternate outline","calendar check","calendar check outline","calendar minus","calendar minus outline","calendar plus","calendar plus outline","calendar times","calendar times outline","cart arrow down","cart plus","exclamation","exclamation circle","exclamation triangle","eye","eye slash","eye slash outline","file","file outline","file alternate","file alternate outline","folder","folder outline","folder open","folder open outline","info","info circle","lock","lock open","minus","minus circle","minus square","minus square outline","plus","plus circle","plus square","plus square outline","question","question circle","question circle outline","shield alternate","shopping cart","sign in alternate","sign out alternate","thermometer empty","thermometer full","thermometer half","thermometer quarter","thermometer three quarters","thumbs down","thumbs down outline","thumbs up","thumbs up outline","toggle off","toggle on","unlock","unlock alternate"]),USERS_PEOPLE=(exports.STATUS=STATUS,["address book","address book outline","address card","address card outline","bed","blind","child","female","frown","frown outline","id badge","id badge outline","id card","id card outline","male","meh","meh outline","power off","smile","smile outline","street view","user","user outline","user circle","user circle outline","user md","user plus","user secret","user times","users","wheelchair"]),VEHICLES=(exports.USERS_PEOPLE=USERS_PEOPLE,["ambulance","bicycle","bus","car","fighter jet","motorcycle","paper plane","paper plane outline","plane","rocket","ship","shopping cart","space shuttle","subway","taxi","train","truck","wheelchair"]),WRITING=(exports.VEHICLES=VEHICLES,["archive","book","bookmark","bookmark outline","edit","edit outline","envelope","envelope outline","envelope open","envelope open outline","eraser","file","file outline","file alternate","file alternate outline","folder","folder outline","folder open","folder open outline","keyboard","keyboard outline","newspaper","newspaper outline","paper plane","paper plane outline","paperclip","paragraph","pen square","pencil alternate","quote left","quote right","sticky note","sticky note outline","thumbtack"]),BRANDS=(exports.WRITING=WRITING,["500px","accessible","accusoft","adn","adversal","affiliatetheme","algolia","amazon","amazon pay","amilia","android","angellist","angrycreative","angular","app store","app store ios","apper","apple","apple pay","asymmetrik","audible","autoprefixer","avianex","aviato","aws","bandcamp","behance","behance square","bimobject","bitbucket","bitcoin","bity","black tie","blackberry","blogger","blogger b","bluetooth","bluetooth b","btc","buromobelexperte","buysellads","cc amazon pay","cc amex","cc apple pay","cc diners club","cc discover","cc jcb","cc mastercard","cc paypal","cc stripe","cc visa","centercode","chrome","cloudscale","cloudsmith","cloudversify","codepen","codiepie","connectdevelop","contao","cpanel","creative commons","css3","css3 alternate","cuttlefish","d and d","dashcube","delicious","deploydog","deskpro","deviantart","digg","digital ocean","discord","discourse","dochub","docker","draft2digital","dribbble","dribbble square","dropbox","drupal","dyalog","earlybirds","edge","elementor","ember","empire","envira","erlang","ethereum","etsy","expeditedssl","facebook","facebook f","facebook messenger","facebook square","firefox","first order","firstdraft","flickr","flipboard","fly","font awesome","font awesome alternate","font awesome flag","fonticons","fonticons fi","fort awesome","fort awesome alternate","forumbee","foursquare","free code camp","freebsd","get pocket","gg","gg circle","git","git square","github","github alternate","github square","gitkraken","gitlab","gitter","glide","glide g","gofore","goodreads","goodreads g","google","google drive","google play","google plus","google plus g","google plus square","google wallet","gratipay","grav","gripfire","grunt","gulp","hacker news","hacker news square","hips","hire a helper","hooli","hotjar","houzz","html5","hubspot","imdb","instagram","internet explorer","ioxhost","itunes","itunes note","jenkins","joget","joomla","js","js square","jsfiddle","keycdn","kickstarter","kickstarter k","korvue","laravel","lastfm","lastfm square","leanpub","less","linechat","linkedin","linkedin alternate","linode","linux","lyft","magento","maxcdn","medapps","medium","medium m","medrt","meetup","microsoft","mix","mixcloud","mizuni","modx","monero","napster","nintendo switch","node","node js","npm","ns8","nutritionix","odnoklassniki","odnoklassniki square","opencart","openid","opera","optin monster","osi","page4","pagelines","palfed","patreon","paypal","periscope","phabricator","phoenix framework","php","pied piper","pied piper alternate","pied piper pp","pinterest","pinterest p","pinterest square","playstation","product hunt","pushed","python","qq","quinscape","quora","ravelry","react","rebel","redriver","reddit","reddit alien","reddit square","rendact","renren","replyd","resolving","rocketchat","rockrms","safari","sass","schlix","scribd","searchengin","sellcast","sellsy","servicestack","shirtsinbulk","simplybuilt","sistrix","skyatlas","skype","slack","slack hash","slideshare","snapchat","snapchat ghost","snapchat square","soundcloud","speakap","spotify","stack exchange","stack overflow","staylinked","steam","steam square","steam symbol","sticker mule","strava","stripe","stripe s","studiovinari","stumbleupon","stumbleupon circle","superpowers","supple","telegram","telegram plane","tencent weibo","themeisle","trello","tripadvisor","tumblr","tumblr square","twitch","twitter","twitter square","typo3","uber","uikit","uniregistry","untappd","usb","ussunnah","vaadin","viacoin","viadeo","viadeo square","viber","vimeo","vimeo square","vimeo v","vine","vk","vnv","vuejs","wechat","weibo","weixin","whatsapp","whatsapp square","whmcs","wikipedia w","windows","wordpress","wordpress simple","wpbeginner","wpexplorer","wpforms","xbox","xing","xing square","y combinator","yahoo","yandex","yandex international","yelp","yoast","youtube","youtube square"]),_values2=(exports.BRANDS=BRANDS,(0,_uniq2.default)([].concat(_values2,require,_interopRequireDefault,BUSINESS,CHESS,CODE,COMMUNICATION,COMPUTERS,CURRENCY,DATE_TIME,DESIGN,EDITORS,FILES,GENDERS,HANDS_GESTURES,HEALTH,IMAGES,INTERFACES,LOGISTICS,MAPS,MEDICAL,OBJECTS,PAYMENTS_SHOPPING,SHAPES,SPINNERS,SPORTS,STATUS,USERS_PEOPLE,VEHICLES,WRITING,BRANDS))),require=(exports.ICONS=_values2,["chess rock","ordered list","unordered list","user doctor","shield","puzzle","add circle","add square","add to calendar","add to cart","add user","add","alarm mute","alarm","ald","als","announcement","area chart","area graph","arrow down cart","asexual","asl interpreting","asl","assistive listening devices","attach","attention","balance","bar","bathtub","battery four","battery high","battery low","battery one","battery three","battery two","battery zero","birthday","block layout","bluetooth alternative","broken chain","browser","call square","call","cancel","cart","cc","chain","chat","checked calendar","checkmark","circle notched","close","cny","cocktail","commenting","computer","configure","content","deafness","delete calendar","delete","detective","discussions","doctor","dollar","dont","drivers license","dropdown","emergency","envira gallery","erase","eur","euro","eyedropper","factory","favorite","feed","female homosexual","file text","file text outline","find","first aid","fork","game","gay","gbp","google plus circle","google plus official","grab","graduation","grid layout","group","h","hand victory","handicap","hard of hearing","header","help circle","help","heterosexual","hide","hotel","hourglass four","hourglass full","hourglass one","hourglass three","hourglass two","idea","ils","in cart","inr","intergender","intersex","jpy","krw","lab","law","legal","lesbian","lightning","like","line graph","linkedin square","linkify","lira","list layout","magnify","mail forward","mail outline","mail square","mail","male homosexual","man","marker","mars alternate","mars horizontal","mars vertical","microsoft edge","military","ms edge","mute","new pied piper","non binary transgender","numbered list","options","other gender horizontal","other gender vertical","other gender","payment","paypal card","pencil square","photo","picture","pie chart","pie graph","pied piper hat","pin","plus cart","point","pointing down","pointing left","pointing right","pointing up","pound","power cord","power","privacy","r circle","rain","record","refresh","remove circle","remove from calendar","remove user","remove","repeat","rmb","rouble","rub","ruble","rupee","s15","selected radio","send","setting","settings","shekel","sheqel","shipping","shop","shuffle","shutdown","sidebar","signing","signup","sliders","soccer","sort alphabet ascending","sort alphabet descending","sort ascending","sort content ascending","sort content descending","sort descending","sort numeric ascending","sort numeric descending","sound","spy","stripe card","student","talk","target","teletype","television","text cursor","text telephone","theme","thermometer","thumb tack","time","tm","toggle down","toggle left","toggle right","toggle up","translate","travel","treatment","triangle down","triangle left","triangle right","triangle up","try","unhide","unlinkify","unmute","usd","user cancel","user close","user delete","user x","vcard","video camera","video play","volume control phone","wait","warning circle","warning sign","warning","wi-fi","winner","wizard","woman","won","wordpress beginner","wordpress forms","world","write square","x","yen","zip","zoom in","zoom out","zoom","bitbucket square","checkmark box","circle thin","cloud download","cloud upload","compose","conversation","credit card alternative","currency","dashboard","diamond","disk","exchange","external share","external square","external","facebook official","food","hourglass zero","level down","level up","log out","meanpath","money","move","pencil","protect","radio","remove bookmark","resize horizontal","resize vertical","sign in","sign out","spoon","star half empty","star half full","ticket","times rectangle","write","youtube play"]),_interopRequireDefault=(exports.ICON_ALIASES=require,(0,_uniq2.default)([].concat((0,_toConsumableArray2.default)(_values2),require))),BUSINESS=(exports.ICONS_AND_ALIASES=_interopRequireDefault,["left dropdown"]),CHESS=(exports.COMPONENT_CONTEXT_SPECIFIC_ICONS=BUSINESS,(0,_uniq2.default)([].concat((0,_toConsumableArray2.default)(_interopRequireDefault),BUSINESS)));exports.ALL_ICONS_IN_ALL_CONTEXTS=CHESS},{"./numberToWord":1593,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/toConsumableArray":27,"lodash/keys":986,"lodash/uniq":1025,"lodash/values":1027}],1572:[function(require,module,exports){"use strict";function getValue(key,prev,next){return((0,_has2.default)(next,key)?next:prev)[key]}var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_slicedToArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.mergeChildMappings=exports.getChildMapping=void 0,_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"))),_has2=_interopRequireDefault(require("lodash/has")),_keys2=_interopRequireDefault(require("lodash/keys")),_forEach2=_interopRequireDefault(require("lodash/forEach")),_filter2=_interopRequireDefault(require("lodash/filter")),_keyBy2=_interopRequireDefault(require("lodash/keyBy")),_react=require("react");exports.getChildMapping=function(children){return(0,_keyBy2.default)((0,_filter2.default)(_react.Children.toArray(children),_react.isValidElement),"key")};exports.mergeChildMappings=function(){var prev=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},next=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},childMapping={},_getPendingKeys=function(prev,next){var nextKeysPending={},pendingKeys=[];return(0,_forEach2.default)((0,_keys2.default)(prev),function(prevKey){(0,_has2.default)(next,prevKey)?pendingKeys.length&&(nextKeysPending[prevKey]=pendingKeys,pendingKeys=[]):pendingKeys.push(prevKey)}),[nextKeysPending,pendingKeys]}(prev,next),_getPendingKeys=(0,_slicedToArray2.default)(_getPendingKeys,2),nextKeysPending=_getPendingKeys[0],_getPendingKeys=_getPendingKeys[1];return(0,_forEach2.default)((0,_keys2.default)(next),function(nextKey){(0,_has2.default)(nextKeysPending,nextKey)&&(0,_forEach2.default)(nextKeysPending[nextKey],function(pendingKey){childMapping[pendingKey]=getValue(pendingKey,prev,next)}),childMapping[nextKey]=getValue(nextKey,prev,next)}),(0,_forEach2.default)(_getPendingKeys,function(pendingKey){childMapping[pendingKey]=getValue(pendingKey,prev,next)}),childMapping}},{"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/slicedToArray":25,"lodash/filter":914,"lodash/forEach":921,"lodash/has":951,"lodash/keyBy":985,"lodash/keys":986,react:1427}],1573:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_find2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.isNil=exports.findByType=exports.someByType=void 0,_interopRequireDefault(require("lodash/find"))),_some2=_interopRequireDefault(require("lodash/some")),_react=require("react");exports.someByType=function(children,type){return(0,_some2.default)(_react.Children.toArray(children),{type:type})},exports.findByType=function(children,type){return(0,_find2.default)(_react.Children.toArray(children),{type:type})};exports.isNil=function(children){return null==children||Array.isArray(children)&&0===children.length}},{"@babel/runtime/helpers/interopRequireDefault":13,"lodash/find":915,"lodash/some":1005,react:1427}],1574:[function(require,module,exports){"use strict";function useValueAndKey(val,key){return val&&!0!==val&&"".concat(val," ").concat(key)}var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_typeof2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.useWidthProp=exports.useVerticalAlignProp=exports.useTextAlignProp=exports.useMultipleProp=exports.useKeyOrValueAndKey=exports.useValueAndKey=exports.useKeyOnly=void 0,_interopRequireDefault(require("@babel/runtime/helpers/typeof"))),_numberToWord=require("./numberToWord");exports.useKeyOnly=function(val,key){return val&&key},exports.useValueAndKey=useValueAndKey,exports.useKeyOrValueAndKey=function(val,key){return val&&(!0===val?key:"".concat(val," ").concat(key))},exports.useMultipleProp=function(val,key){return val&&!0!==val?val.replace("large screen","large-screen").replace(/ vertically/g,"-vertically").split(" ").map(function(prop){return"".concat(prop.replace("-"," ")," ").concat(key)}).join(" "):null},exports.useTextAlignProp=function(val){return"justified"===val?"justified":useValueAndKey(val,"aligned")},exports.useVerticalAlignProp=function(val){return useValueAndKey(val,"aligned")};exports.useWidthProp=function(val){var valType,widthClass=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"";return 2<arguments.length&&void 0!==arguments[2]&&arguments[2]&&"equal"===val?"equal width":"string"!==(valType=(0,_typeof2.default)(val))&&"number"!==valType||!widthClass?(0,_numberToWord.numberToWord)(val):"".concat((0,_numberToWord.numberToWord)(val)," ").concat(widthClass)}},{"./numberToWord":1593,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":30}],1575:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_itemFactories=require("./itemFactories"),_rangeFactories=require("./rangeFactories"),_paginationUtils=require("./paginationUtils");exports.default=function(rawOptions){var rawOptions=(0,_paginationUtils.typifyOptions)(rawOptions),activePage=rawOptions.activePage,totalPages=rawOptions.totalPages,pageFactory=(0,_itemFactories.createPageFactory)(activePage),rawOptions=(0,_paginationUtils.isSimplePagination)(rawOptions)?(0,_rangeFactories.createSimpleRange)(1,totalPages,pageFactory):(0,_rangeFactories.createComplexRange)(rawOptions,pageFactory);return[(0,_itemFactories.createFirstPage)(),(0,_itemFactories.createPrevItem)(activePage)].concat((0,_toConsumableArray2.default)(rawOptions),[(0,_itemFactories.createNextItem)(activePage,totalPages),(0,_itemFactories.createLastItem)(totalPages)])}},{"./itemFactories":1577,"./paginationUtils":1578,"./rangeFactories":1579,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/toConsumableArray":27}],1576:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_createPaginationItems=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _createPaginationItems.default}}),_interopRequireDefault(require("./createPaginationItems")))},{"./createPaginationItems":1575,"@babel/runtime/helpers/interopRequireDefault":13}],1577:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createLastItem=exports.createNextItem=exports.createPageFactory=exports.createPrevItem=exports.createFirstPage=exports.createEllipsisItem=void 0;exports.createEllipsisItem=function(pageNumber){return{active:!1,type:"ellipsisItem",value:pageNumber}},exports.createFirstPage=function(){return{active:!1,type:"firstItem",value:1}},exports.createPrevItem=function(activePage){return{active:!1,type:"prevItem",value:Math.max(1,activePage-1)}},exports.createPageFactory=function(activePage){return function(pageNumber){return{active:activePage===pageNumber,type:"pageItem",value:pageNumber}}},exports.createNextItem=function(activePage,totalPages){return{active:!1,type:"nextItem",value:Math.min(activePage+1,totalPages)}};exports.createLastItem=function(totalPages){return{active:!1,type:"lastItem",value:totalPages}}},{}],1578:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.typifyOptions=exports.isSimplePagination=void 0;exports.isSimplePagination=function(_ref){var boundaryRange=_ref.boundaryRange,hideEllipsis=_ref.hideEllipsis,siblingRange=_ref.siblingRange;return _ref.totalPages<=1+(hideEllipsis?0:2)+2*siblingRange+2*boundaryRange};exports.typifyOptions=function(_ref2){return{activePage:+_ref2.activePage,boundaryRange:+_ref2.boundaryRange,hideEllipsis:!!_ref2.hideEllipsis,siblingRange:+_ref2.siblingRange,totalPages:+_ref2.totalPages}}},{}],1579:[function(require,module,exports){"use strict";function createSimpleRange(start,end,pageFactory){return(0,_map2.default)((0,_range2.default)(start,end+1),pageFactory)}var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.createComplexRange=exports.createSimpleRange=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_range2=_interopRequireDefault(require("lodash/range")),_map2=_interopRequireDefault(require("lodash/map")),_suffixFactories=require("./suffixFactories");exports.createSimpleRange=createSimpleRange;exports.createComplexRange=function(options,pageFactory){var activePage=options.activePage,boundaryRange=options.boundaryRange,hideEllipsis=options.hideEllipsis,siblingRange=options.siblingRange,options=options.totalPages,ellipsisSize=hideEllipsis?0:1,firstGroupEnd=boundaryRange,firstGroup=createSimpleRange(1,firstGroupEnd,pageFactory),boundaryRange=options+1-boundaryRange,options=createSimpleRange(boundaryRange,options,pageFactory),activePage=Math.min(Math.max(activePage-siblingRange,firstGroupEnd+ellipsisSize+1),boundaryRange-ellipsisSize-2*siblingRange-1),ellipsisSize=activePage+2*siblingRange,siblingRange=createSimpleRange(activePage,ellipsisSize,pageFactory);return[].concat((0,_toConsumableArray2.default)(firstGroup),[!hideEllipsis&&(0,_suffixFactories.createInnerPrefix)(firstGroupEnd,activePage,pageFactory)],(0,_toConsumableArray2.default)(siblingRange),[!hideEllipsis&&(0,_suffixFactories.createInnerSuffix)(ellipsisSize,boundaryRange,pageFactory)],(0,_toConsumableArray2.default)(options)).filter(Boolean)}},{"./suffixFactories":1580,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/toConsumableArray":27,"lodash/map":989,"lodash/range":999}],1580:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createInnerSuffix=exports.createInnerPrefix=void 0;var _itemFactories=require("./itemFactories");exports.createInnerPrefix=function(firstGroupEnd,innerGroupStart,pageFactory){innerGroupStart-=1;return(innerGroupStart!==firstGroupEnd+1?_itemFactories.createEllipsisItem:pageFactory)(innerGroupStart)};exports.createInnerSuffix=function(innerGroupEnd,lastGroupStart,pageFactory){innerGroupEnd+=1;return(innerGroupEnd!==lastGroupStart-1?_itemFactories.createEllipsisItem:pageFactory)(innerGroupEnd)}},{"./itemFactories":1577}],1581:[function(require,module,exports){"use strict";function typeOf(){var _Object$prototype$toS;return(_Object$prototype$toS=Object.prototype.toString).call.apply(_Object$prototype$toS,arguments)}function disallow(disallowedProps){return function(props,propName,componentName){var disallowed;if(Array.isArray(disallowedProps))return!(0,_isNil2.default)(props[propName])&&!1!==props[propName]&&0<(disallowed=disallowedProps.reduce(function(acc,disallowedProp){return(0,_isNil2.default)(props[disallowedProp])||!1===props[disallowedProp]?acc:[].concat((0,_toConsumableArray2.default)(acc),[disallowedProp])},[])).length?new Error(["Prop `".concat(propName,"` in `").concat(componentName,"` conflicts with props: `").concat(disallowed.join("`, `"),"`."),"They cannot be defined together, choose one or the other."].join(" ")):void 0;throw new Error(["Invalid argument supplied to disallow, expected an instance of array."," See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(""))}}function every(validators){return function(props,propName,componentName){for(var _len=arguments.length,rest=new Array(3<_len?_len-3:0),_key=3;_key<_len;_key++)rest[_key-3]=arguments[_key];if(Array.isArray(validators))return(0,_flow2.default)((0,_map2.default)(function(validator){if("function"!=typeof validator)throw new Error('every() argument "validators" should contain functions, found: '.concat(typeOf(validator),"."));return validator.apply(void 0,[props,propName,componentName].concat(rest))}),_compact2.default)(validators)[0];throw new Error(["Invalid argument supplied to every, expected an instance of array.","See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(" "))}}function itemShorthand(){return every([disallow(["children"]),_propTypes.default.oneOfType([_propTypes.default.func,_propTypes.default.node,_propTypes.default.object,_propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.node,_propTypes.default.object]))])]).apply(void 0,arguments)}var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_toConsumableArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ref=exports.refObject=exports.deprecate=exports.collectionShorthand=exports.itemShorthand=exports.contentShorthand=exports.multipleProp=exports.demand=exports.givenProps=exports.some=exports.every=exports.disallow=exports.suggest=exports.domNode=void 0,_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"))),_difference2=_interopRequireDefault(require("lodash/fp/difference")),_trim2=_interopRequireDefault(require("lodash/fp/trim")),_isObject2=_interopRequireDefault(require("lodash/fp/isObject")),_pick2=_interopRequireDefault(require("lodash/fp/pick")),_keys2=_interopRequireDefault(require("lodash/fp/keys")),_isPlainObject2=_interopRequireDefault(require("lodash/fp/isPlainObject")),_isFunction2=_interopRequireDefault(require("lodash/fp/isFunction")),_compact2=_interopRequireDefault(require("lodash/fp/compact")),_isNil2=_interopRequireDefault(require("lodash/fp/isNil")),_take2=_interopRequireDefault(require("lodash/fp/take")),_sortBy2=_interopRequireDefault(require("lodash/fp/sortBy")),_sum2=_interopRequireDefault(require("lodash/fp/sum")),_min2=_interopRequireDefault(require("lodash/fp/min")),_map2=_interopRequireDefault(require("lodash/fp/map")),_flow2=_interopRequireDefault(require("lodash/fp/flow")),_memoize2=_interopRequireDefault(require("lodash/fp/memoize")),_propTypes=_interopRequireDefault(require("prop-types")),_leven=_interopRequireDefault(require("./leven")),_interopRequireDefault=(exports.domNode=function(props,propName){if(void 0!==props[propName]&&!(props[propName]instanceof Element))return new Error('Invalid prop "'.concat(propName,'" supplied, expected a DOM node.'))},exports.suggest=function(suggestions){var findBestSuggestions,suggestionsLookup;if(Array.isArray(suggestions))return findBestSuggestions=(0,_memoize2.default)(function(str){var propValueWords=str.split(" ");return(0,_flow2.default)((0,_map2.default)(function(suggestion){var suggestionWords=suggestion.split(" ");return{suggestion:suggestion,score:(0,_flow2.default)((0,_map2.default)(function(x){return(0,_map2.default)(function(y){return(0,_leven.default)(x,y)},suggestionWords)}),(0,_map2.default)(_min2.default),_sum2.default)(propValueWords)+(0,_flow2.default)((0,_map2.default)(function(x){return(0,_map2.default)(function(y){return(0,_leven.default)(x,y)},propValueWords)}),(0,_map2.default)(_min2.default),_sum2.default)(suggestionWords)}}),(0,_sortBy2.default)(["score","suggestion"]),(0,_take2.default)(3))(suggestions)}),suggestionsLookup=suggestions.reduce(function(acc,key){return acc[key.split(" ").sort().join(" ")]=!0,acc},{}),function(props,propName,componentName){props=props[propName];if(props&&!suggestionsLookup[props]){var propValueSorted=props.split(" ").sort().join(" ");if(!suggestionsLookup[propValueSorted]){propValueSorted=findBestSuggestions(props);if(!propValueSorted.some(function(x){return 0===x.score}))return new Error(["Invalid prop `".concat(propName,"` of value `").concat(props,"` supplied to `").concat(componentName,"`."),"\n\nInstead of `".concat(props,"`, did you mean:"),propValueSorted.map(function(x){return"\n  - ".concat(x.suggestion)}).join(""),"\n"].join(""))}}};throw new Error("Invalid argument supplied to suggest, expected an instance of array.")},exports.disallow=disallow,exports.every=every,exports.some=function(validators){return function(props,propName,componentName){for(var _len2=arguments.length,rest=new Array(3<_len2?_len2-3:0),_key2=3;_key2<_len2;_key2++)rest[_key2-3]=arguments[_key2];if(!Array.isArray(validators))throw new Error(["Invalid argument supplied to some, expected an instance of array.","See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(" "));var error,errors=(0,_compact2.default)((0,_map2.default)(validators,function(validator){if((0,_isFunction2.default)(validator))return validator.apply(void 0,[props,propName,componentName].concat(rest));throw new Error('some() argument "validators" should contain functions, found: '.concat(typeOf(validator),"."))}));if(errors.length===validators.length)return(error=new Error("One of these validators must pass:")).message+="\n".concat((0,_map2.default)(errors,function(err,i){return"[".concat(i+1,"]: ").concat(err.message)}).join("\n")),error}},exports.givenProps=function(propsShape,validator){return function(props,propName,componentName){for(var error,prettyProps,_len3=arguments.length,rest=new Array(3<_len3?_len3-3:0),_key3=3;_key3<_len3;_key3++)rest[_key3-3]=arguments[_key3];if(!(0,_isPlainObject2.default)(propsShape))throw new Error(["Invalid argument supplied to givenProps, expected an object.","See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(" "));if("function"!=typeof validator)throw new Error(["Invalid argument supplied to givenProps, expected a function.","See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(" "));return(0,_keys2.default)(propsShape).every(function(key){var val=propsShape[key];return"function"==typeof val?!val.apply(void 0,[props,key,componentName].concat(rest)):val===props[propName]})&&(error=validator.apply(void 0,[props,propName,componentName].concat(rest)))?(prettyProps="{ ".concat((0,_keys2.default)((0,_pick2.default)((0,_keys2.default)(propsShape),props)).map(function(key){var val=props[key],renderedValue=val;return"string"==typeof val?renderedValue='"'.concat(val,'"'):Array.isArray(val)?renderedValue="[".concat(val.join(", "),"]"):(0,_isObject2.default)(val)&&(renderedValue="{...}"),"".concat(key,": ").concat(renderedValue)}).join(", ")," }"),error.message="Given props ".concat(prettyProps,": ").concat(error.message),error):void 0}},exports.demand=function(requiredProps){return function(props,propName,componentName){var missingRequired;if(Array.isArray(requiredProps))return void 0!==props[propName]&&0<(missingRequired=requiredProps.filter(function(requiredProp){return void 0===props[requiredProp]})).length?new Error("`".concat(propName,"` prop in `").concat(componentName,"` requires props: `").concat(missingRequired.join("`, `"),"`.")):void 0;throw new Error(["Invalid `requiredProps` argument supplied to require, expected an instance of array."," See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(""))}},exports.multipleProp=function(possible){return function(props,propName,componentName){if(!Array.isArray(possible))throw new Error(["Invalid argument supplied to some, expected an instance of array.","See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(" "));var props=props[propName];if(!(0,_isNil2.default)(props)&&!1!==props)return props=props.replace("large screen","large-screen").replace(/ vertically/g,"-vertically").split(" ").map(function(val){return(0,_trim2.default)(val).replace("-"," ")}),0<(props=(0,_difference2.default)(props,possible)).length?new Error("`".concat(propName,"` prop in `").concat(componentName,"` has invalid values: `").concat(props.join("`, `"),"`.")):void 0}},exports.contentShorthand=function(){return every([disallow(["children"]),_propTypes.default.node]).apply(void 0,arguments)},exports.itemShorthand=itemShorthand,exports.collectionShorthand=function(){return every([disallow(["children"]),_propTypes.default.arrayOf(itemShorthand)]).apply(void 0,arguments)},exports.deprecate=function(help,validator){return function(props,propName,componentName){if("string"!=typeof help)throw new Error(["Invalid `help` argument supplied to deprecate, expected a string.","See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(" "));if(void 0!==props[propName]){var error=new Error("The `".concat(propName,"` prop in `").concat(componentName,"` is deprecated."));if(help&&(error.message+=" ".concat(help)),validator){if("function"!=typeof validator)throw new Error(["Invalid argument supplied to deprecate, expected a function.","See `".concat(propName,"` prop in `").concat(componentName,"`.")].join(" "));for(var _len4=arguments.length,args=new Array(3<_len4?_len4-3:0),_key4=3;_key4<_len4;_key4++)args[_key4-3]=arguments[_key4];props=validator.apply(void 0,[props,propName,componentName].concat(args));props&&(error.message="".concat(error.message," ").concat(props.message))}return error}}},_propTypes.default.shape({current:_propTypes.default.object})),require=(exports.refObject=_interopRequireDefault,_propTypes.default.oneOfType([_propTypes.default.func,_interopRequireDefault]));exports.ref=require},{"./leven":1590,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/toConsumableArray":27,"lodash/fp/compact":926,"lodash/fp/difference":928,"lodash/fp/flow":931,"lodash/fp/isFunction":933,"lodash/fp/isNil":934,"lodash/fp/isObject":935,"lodash/fp/isPlainObject":936,"lodash/fp/keys":937,"lodash/fp/map":938,"lodash/fp/memoize":939,"lodash/fp/min":940,"lodash/fp/pick":941,"lodash/fp/sortBy":943,"lodash/fp/sum":945,"lodash/fp/take":946,"lodash/fp/trim":948,"prop-types":1046}],1582:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_inRange2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("lodash/inRange"))),_first3=_interopRequireDefault(require("lodash/first")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_some2=_interopRequireDefault(require("lodash/some"));exports.default=function(node,e){var clientX,clientRects,bottom,left;return!(0,_some2.default)([e,node],_isNil2.default)&&(e.target&&((0,_invoke2.default)(e.target,"setAttribute","data-suir-click-target",!0),document.querySelector("[data-suir-click-target=true]"))?((0,_invoke2.default)(e.target,"removeAttribute","data-suir-click-target"),node.contains(e.target)):(clientX=e.clientX,e=e.clientY,!(0,_some2.default)([clientX,e],_isNil2.default)&&(clientRects=node.getClientRects(),!!(node.offsetWidth&&node.offsetHeight&&clientRects&&clientRects.length))&&(clientRects=(node=(0,_first3.default)(clientRects)).top,bottom=node.bottom,left=node.left,node=node.right,!(0,_some2.default)([clientRects,bottom,left,node],_isNil2.default))&&(0,_inRange2.default)(e,clientRects,bottom+.001)&&(0,_inRange2.default)(clientX,left,node+.001)))}},{"@babel/runtime/helpers/interopRequireDefault":13,"lodash/first":917,"lodash/inRange":955,"lodash/invoke":959,"lodash/isNil":972,"lodash/some":1005}],1583:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;require=require("@semantic-ui-react/event-stack").instance;exports.default=require},{"@semantic-ui-react/event-stack":36}],1584:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectSpread2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.createShorthand=createShorthand,exports.createShorthandFactory=createShorthandFactory,exports.createHTMLParagraph=exports.createHTMLLabel=exports.createHTMLInput=exports.createHTMLImage=exports.createHTMLIframe=exports.createHTMLDivision=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectSpread"))),_typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof")),_uniq2=_interopRequireDefault(require("lodash/uniq")),_isArray2=_interopRequireDefault(require("lodash/isArray")),_isPlainObject2=_interopRequireDefault(require("lodash/isPlainObject")),_isFunction2=_interopRequireDefault(require("lodash/isFunction")),_isNumber2=_interopRequireDefault(require("lodash/isNumber")),_isString2=_interopRequireDefault(require("lodash/isString")),_isBoolean2=_interopRequireDefault(require("lodash/isBoolean")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_classnames=_interopRequireDefault(require("classnames")),_react=_interopRequireWildcard(require("react"));function createShorthand(Component,mapValueToProps,val){var valIsString,valIsNumber,valIsFunction,valIsReactElement,valIsPropsObject,valIsPrimitiveValue,_options$overrideProp,props,mergedClassesNames,_options$defaultProps,options=3<arguments.length&&void 0!==arguments[3]?arguments[3]:{};if("function"!=typeof Component&&"string"!=typeof Component)throw new Error("createShorthand() Component must be a string or function.");return(0,_isNil2.default)(val)||(0,_isBoolean2.default)(val)?null:(valIsString=(0,_isString2.default)(val),valIsNumber=(0,_isNumber2.default)(val),valIsFunction=(0,_isFunction2.default)(val),valIsReactElement=(0,_react.isValidElement)(val),valIsPropsObject=(0,_isPlainObject2.default)(val),valIsPrimitiveValue=valIsString||valIsNumber||(0,_isArray2.default)(val),valIsFunction||valIsReactElement||valIsPropsObject||valIsPrimitiveValue?(_options$defaultProps=void 0===(_options$defaultProps=options.defaultProps)?{}:_options$defaultProps,mapValueToProps=valIsReactElement&&val.props||valIsPropsObject&&val||valIsPrimitiveValue&&mapValueToProps(val),_options$overrideProp=options.overrideProps,_options$overrideProp=(0,_isFunction2.default)(_options$overrideProp=void 0===_options$overrideProp?{}:_options$overrideProp)?_options$overrideProp((0,_objectSpread2.default)({},_options$defaultProps,mapValueToProps)):_options$overrideProp,props=(0,_objectSpread2.default)({},_options$defaultProps,mapValueToProps,_options$overrideProp),(_options$defaultProps.className||_options$overrideProp.className||mapValueToProps.className)&&(mergedClassesNames=(0,_classnames.default)(_options$defaultProps.className,_options$overrideProp.className,mapValueToProps.className),props.className=(0,_uniq2.default)(mergedClassesNames.split(" ")).join(" ")),(_options$defaultProps.style||_options$overrideProp.style||mapValueToProps.style)&&(props.style=(0,_objectSpread2.default)({},_options$defaultProps.style,mapValueToProps.style,_options$overrideProp.style)),(0,_isNil2.default)(props.key)&&(mergedClassesNames=props.childKey,mapValueToProps=void 0===(_options$defaultProps=options.autoGenerateKey)||_options$defaultProps,(0,_isNil2.default)(mergedClassesNames)?mapValueToProps&&(valIsString||valIsNumber)&&(props.key=val):(props.key="function"==typeof mergedClassesNames?mergedClassesNames(props):mergedClassesNames,delete props.childKey)),valIsReactElement?(0,_react.cloneElement)(val,props):valIsPrimitiveValue||valIsPropsObject?_react.default.createElement(Component,props):valIsFunction?val(Component,props,props.children):void 0):("production"!==process.env.NODE_ENV&&console.error(["Shorthand value must be a string|number|array|object|ReactElement|function."," Use null|undefined|boolean for none"," Received ".concat((0,_typeof2.default)(val),".")].join("")),null))}function createShorthandFactory(Component,mapValueToProps){if("function"!=typeof Component&&"string"!=typeof Component)throw new Error("createShorthandFactory() Component must be a string or function.");return function(val,options){return createShorthand(Component,mapValueToProps,val,options)}}createShorthand.handledProps=[];_interopRequireDefault=createShorthandFactory("div",function(val){return{children:val}}),exports.createHTMLDivision=_interopRequireDefault,_interopRequireWildcard=createShorthandFactory("iframe",function(src){return{src:src}}),exports.createHTMLIframe=_interopRequireWildcard,_interopRequireDefault=createShorthandFactory("img",function(val){return{src:val}}),exports.createHTMLImage=_interopRequireDefault,_interopRequireWildcard=createShorthandFactory("input",function(val){return{type:val}}),exports.createHTMLInput=_interopRequireWildcard,_interopRequireDefault=createShorthandFactory("label",function(val){return{children:val}}),exports.createHTMLLabel=_interopRequireDefault,_interopRequireWildcard=createShorthandFactory("p",function(val){return{children:val}});exports.createHTMLParagraph=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/typeof":30,_process:1042,classnames:116,"lodash/isArray":961,"lodash/isBoolean":964,"lodash/isFunction":969,"lodash/isNil":972,"lodash/isNumber":973,"lodash/isPlainObject":976,"lodash/isString":979,"lodash/uniq":1025,react:1427}],1585:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,exports.default=function(Component,props,getDefault){if(Component=void 0===(Component=Component.defaultProps)?{}:Component,props.as&&props.as!==Component.as)return props.as;if(getDefault){getDefault=getDefault();if(getDefault)return getDefault}return props.href?"a":Component.as||"div"}},{}],1586:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(Component,props){var Component=Component.handledProps,handledProps=void 0===Component?[]:Component;return Object.keys(props).reduce(function(acc,prop){return"childKey"!==prop&&-1===handledProps.indexOf(prop)&&(acc[prop]=props[prop]),acc},{})}},{}],1587:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_includes2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.partitionHTMLProps=exports.htmlImageProps=exports.htmlInputProps=exports.htmlInputEvents=exports.htmlInputAttrs=void 0,_interopRequireDefault(require("lodash/includes"))),_forEach2=_interopRequireDefault(require("lodash/forEach")),_interopRequireDefault=["selected","defaultValue","defaultChecked","accept","autoCapitalize","autoComplete","autoCorrect","autoFocus","checked","disabled","form","id","lang","list","max","maxLength","min","minLength","multiple","name","pattern","placeholder","readOnly","required","step","title","type","value"],require=(exports.htmlInputAttrs=_interopRequireDefault,["onKeyDown","onKeyPress","onKeyUp","onFocus","onBlur","onChange","onInput","onClick","onContextMenu","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp","onSelect","onTouchCancel","onTouchEnd","onTouchMove","onTouchStart"]),htmlInputProps=(exports.htmlInputEvents=require,[].concat(_interopRequireDefault,require));exports.htmlInputProps=htmlInputProps,exports.htmlImageProps=["alt","height","src","srcSet","width"];exports.partitionHTMLProps=function(props){var options=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},_options$htmlProps=options.htmlProps,htmlProps=void 0===_options$htmlProps?htmlInputProps:_options$htmlProps,_options$htmlProps=options.includeAria,includeAria=void 0===_options$htmlProps||_options$htmlProps,inputProps={},rest={};return(0,_forEach2.default)(props,function(val,prop){var possibleAria=includeAria&&(/^aria-.*$/.test(prop)||"role"===prop);((0,_includes2.default)(htmlProps,prop)||possibleAria?inputProps:rest)[prop]=val}),[inputProps,rest]}},{"@babel/runtime/helpers/interopRequireDefault":13,"lodash/forEach":921,"lodash/includes":956}],1588:[function(require,module,exports){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_exportNames=(Object.defineProperty(exports,"__esModule",{value:!0}),{AutoControlledComponent:!0,ModernAutoControlledComponent:!0,getChildMapping:!0,mergeChildMappings:!0,childrenUtils:!0,useKeyOnly:!0,useKeyOrValueAndKey:!0,useValueAndKey:!0,useMultipleProp:!0,useTextAlignProp:!0,useVerticalAlignProp:!0,useWidthProp:!0,customPropTypes:!0,eventStack:!0,getUnhandledProps:!0,getElementType:!0,htmlInputAttrs:!0,htmlInputEvents:!0,htmlInputProps:!0,htmlImageProps:!0,partitionHTMLProps:!0,isBrowser:!0,doesNodeContainClick:!0,leven:!0,createPaginationItems:!0,SUI:!0,numberToWordMap:!0,numberToWord:!0,normalizeOffset:!0,normalizeTransitionDuration:!0,objectDiff:!0}),_AutoControlledComponent2=(Object.defineProperty(exports,"AutoControlledComponent",{enumerable:!0,get:function(){return _AutoControlledComponent2.default}}),Object.defineProperty(exports,"ModernAutoControlledComponent",{enumerable:!0,get:function(){return _ModernAutoControlledComponent2.default}}),Object.defineProperty(exports,"getChildMapping",{enumerable:!0,get:function(){return _childMapping.getChildMapping}}),Object.defineProperty(exports,"mergeChildMappings",{enumerable:!0,get:function(){return _childMapping.mergeChildMappings}}),Object.defineProperty(exports,"useKeyOnly",{enumerable:!0,get:function(){return _classNameBuilders.useKeyOnly}}),Object.defineProperty(exports,"useKeyOrValueAndKey",{enumerable:!0,get:function(){return _classNameBuilders.useKeyOrValueAndKey}}),Object.defineProperty(exports,"useValueAndKey",{enumerable:!0,get:function(){return _classNameBuilders.useValueAndKey}}),Object.defineProperty(exports,"useMultipleProp",{enumerable:!0,get:function(){return _classNameBuilders.useMultipleProp}}),Object.defineProperty(exports,"useTextAlignProp",{enumerable:!0,get:function(){return _classNameBuilders.useTextAlignProp}}),Object.defineProperty(exports,"useVerticalAlignProp",{enumerable:!0,get:function(){return _classNameBuilders.useVerticalAlignProp}}),Object.defineProperty(exports,"useWidthProp",{enumerable:!0,get:function(){return _classNameBuilders.useWidthProp}}),Object.defineProperty(exports,"eventStack",{enumerable:!0,get:function(){return _eventStack2.default}}),Object.defineProperty(exports,"getUnhandledProps",{enumerable:!0,get:function(){return _getUnhandledProps2.default}}),Object.defineProperty(exports,"getElementType",{enumerable:!0,get:function(){return _getElementType2.default}}),Object.defineProperty(exports,"htmlInputAttrs",{enumerable:!0,get:function(){return _htmlPropsUtils.htmlInputAttrs}}),Object.defineProperty(exports,"htmlInputEvents",{enumerable:!0,get:function(){return _htmlPropsUtils.htmlInputEvents}}),Object.defineProperty(exports,"htmlInputProps",{enumerable:!0,get:function(){return _htmlPropsUtils.htmlInputProps}}),Object.defineProperty(exports,"htmlImageProps",{enumerable:!0,get:function(){return _htmlPropsUtils.htmlImageProps}}),Object.defineProperty(exports,"partitionHTMLProps",{enumerable:!0,get:function(){return _htmlPropsUtils.partitionHTMLProps}}),Object.defineProperty(exports,"isBrowser",{enumerable:!0,get:function(){return _isBrowser2.default}}),Object.defineProperty(exports,"doesNodeContainClick",{enumerable:!0,get:function(){return _doesNodeContainClick2.default}}),Object.defineProperty(exports,"leven",{enumerable:!0,get:function(){return _leven2.default}}),Object.defineProperty(exports,"createPaginationItems",{enumerable:!0,get:function(){return _createPaginationItems2.default}}),Object.defineProperty(exports,"numberToWordMap",{enumerable:!0,get:function(){return _numberToWord.numberToWordMap}}),Object.defineProperty(exports,"numberToWord",{enumerable:!0,get:function(){return _numberToWord.numberToWord}}),Object.defineProperty(exports,"normalizeOffset",{enumerable:!0,get:function(){return _normalizeOffset2.default}}),Object.defineProperty(exports,"normalizeTransitionDuration",{enumerable:!0,get:function(){return _normalizeTransitionDuration2.default}}),Object.defineProperty(exports,"objectDiff",{enumerable:!0,get:function(){return _objectDiff2.default}}),exports.SUI=exports.customPropTypes=exports.childrenUtils=void 0,_interopRequireDefault(require("./AutoControlledComponent"))),_ModernAutoControlledComponent2=_interopRequireDefault(require("./ModernAutoControlledComponent")),_childMapping=require("./childMapping"),_childrenUtils=_interopRequireWildcard(require("./childrenUtils")),_classNameBuilders=(exports.childrenUtils=_childrenUtils,require("./classNameBuilders")),_childrenUtils=_interopRequireWildcard(require("./customPropTypes")),_eventStack2=(exports.customPropTypes=_childrenUtils,_interopRequireDefault(require("./eventStack"))),_factories=require("./factories"),_getUnhandledProps2=(Object.keys(_factories).forEach(function(key){"default"===key||"__esModule"===key||Object.prototype.hasOwnProperty.call(_exportNames,key)||Object.defineProperty(exports,key,{enumerable:!0,get:function(){return _factories[key]}})}),_interopRequireDefault(require("./getUnhandledProps"))),_getElementType2=_interopRequireDefault(require("./getElementType")),_htmlPropsUtils=require("./htmlPropsUtils"),_isBrowser2=_interopRequireDefault(require("./isBrowser")),_doesNodeContainClick2=_interopRequireDefault(require("./doesNodeContainClick")),_leven2=_interopRequireDefault(require("./leven")),_createPaginationItems2=_interopRequireDefault(require("./createPaginationItems")),_childrenUtils=_interopRequireWildcard(require("./SUI")),_numberToWord=(exports.SUI=_childrenUtils,require("./numberToWord")),_normalizeOffset2=_interopRequireDefault(require("./normalizeOffset")),_normalizeTransitionDuration2=_interopRequireDefault(require("./normalizeTransitionDuration")),_objectDiff2=_interopRequireDefault(require("./objectDiff"))},{"./AutoControlledComponent":1569,"./ModernAutoControlledComponent":1570,"./SUI":1571,"./childMapping":1572,"./childrenUtils":1573,"./classNameBuilders":1574,"./createPaginationItems":1576,"./customPropTypes":1581,"./doesNodeContainClick":1582,"./eventStack":1583,"./factories":1584,"./getElementType":1585,"./getUnhandledProps":1586,"./htmlPropsUtils":1587,"./isBrowser":1589,"./leven":1590,"./normalizeOffset":1591,"./normalizeTransitionDuration":1592,"./numberToWord":1593,"./objectDiff":1594,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14}],1589:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_typeof2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/typeof"))),_isNil2=_interopRequireDefault(require("lodash/isNil")),hasDocument="object"===("undefined"==typeof document?"undefined":(0,_typeof2.default)(document))&&null!==document,hasWindow="object"===("undefined"==typeof window?"undefined":(0,_typeof2.default)(window))&&null!==window&&window.self===window;exports.default=function isBrowser(){return(0,_isNil2.default)(isBrowser.override)?hasDocument&&hasWindow:isBrowser.override}},{"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":30,"lodash/isNil":972}],1590:[function(require,module,exports){!function(process){!function(){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var arr,charCodeCache,leven=function(){return 0};"production"!==process.env.NODE_ENV&&(arr=[],charCodeCache=[],leven=function(a,b){if(a===b)return 0;var bCharCode,ret,tmp,tmp2,aLen=a.length,bLen=b.length;if(0===aLen)return bLen;if(0===bLen)return aLen;for(var i=0,j=0;i<aLen;)charCodeCache[i]=a.charCodeAt(i),arr[i]=++i;for(;j<bLen;)for(bCharCode=b.charCodeAt(j),tmp=j++,ret=j,i=0;i<aLen;i++)tmp2=bCharCode===charCodeCache[i]?tmp:tmp+1,ret=arr[i]=ret<(tmp=arr[i])?ret<tmp2?ret+1:tmp2:tmp<tmp2?tmp+1:tmp2;return ret});exports.default=leven}.call(this)}.call(this,require("_process"))},{_process:1042}],1591:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(value){return"number"==typeof value||"string"==typeof value?[value,value]:value}},{}],1592:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(duration,type){return"number"==typeof duration||"string"==typeof duration?duration:duration[type]}},{}],1593:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_typeof2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.numberToWord=function(value){var type=(0,_typeof2.default)(value);return"string"!==type&&"number"!==type?"":numberToWordMap[value]||value},exports.numberToWordMap=void 0,_interopRequireDefault(require("@babel/runtime/helpers/typeof"))),numberToWordMap={1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",10:"ten",11:"eleven",12:"twelve",13:"thirteen",14:"fourteen",15:"fifteen",16:"sixteen"};exports.numberToWordMap=numberToWordMap},{"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/typeof":30}],1594:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_isEqual2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("lodash/isEqual"))),_has2=_interopRequireDefault(require("lodash/has")),_transform2=_interopRequireDefault(require("lodash/transform"));exports.default=function(source,target){return(0,_transform2.default)(source,function(res,val,key){(0,_has2.default)(target,key)?(0,_isEqual2.default)(val,target[key])||(res[key]=target[key]):res[key]="[DELETED]"},{})}},{"@babel/runtime/helpers/interopRequireDefault":13,"lodash/has":951,"lodash/isEqual":967,"lodash/transform":1022}],1595:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_AccordionAccordion=_interopRequireDefault(require("./AccordionAccordion")),_AccordionContent=_interopRequireDefault(require("./AccordionContent")),_AccordionPanel=_interopRequireDefault(require("./AccordionPanel")),_interopRequireDefault=_interopRequireDefault(require("./AccordionTitle"));function Accordion(props){var className=props.className,fluid=props.fluid,inverted=props.inverted,styled=props.styled,fluid=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(styled,"styled"),className),inverted=(0,_lib.getUnhandledProps)(Accordion,props);return _react.default.createElement(_AccordionAccordion.default,(0,_extends2.default)({},inverted,{className:fluid}))}Accordion.handledProps=["className","fluid","inverted","styled"],Accordion.propTypes="production"!==process.env.NODE_ENV?{className:_propTypes.default.string,fluid:_propTypes.default.bool,inverted:_propTypes.default.bool,styled:_propTypes.default.bool}:{},Accordion.Accordion=_AccordionAccordion.default,Accordion.Content=_AccordionContent.default,Accordion.Panel=_AccordionPanel.default,Accordion.Title=_interopRequireDefault.default,exports.default=Accordion}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./AccordionAccordion":1596,"./AccordionContent":1597,"./AccordionPanel":1598,"./AccordionTitle":1599,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1596:[function(require,module,exports){!function(process){!function(){"use strict";function warnIfPropsAreInvalid(props,state){props=props.exclusive,state=state.activeIndex,props&&"number"!=typeof state?console.error("`activeIndex` must be a number if `exclusive` is true"):props||(0,_isArray2.default)(state)||console.error("`activeIndex` must be an array if `exclusive` is false")}var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_map2=_interopRequireDefault(require("lodash/map")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_without2=_interopRequireDefault(require("lodash/without")),_includes2=_interopRequireDefault(require("lodash/includes")),_isArray2=_interopRequireDefault(require("lodash/isArray")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_AccordionPanel=_interopRequireDefault(require("./AccordionPanel")),_interopRequireDefault=function(_Component){function AccordionAccordion(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,AccordionAccordion);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(AccordionAccordion)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeNewIndex",function(index){var exclusive=_this.props.exclusive,activeIndex=_this.state.activeIndex;return exclusive?index===activeIndex?-1:index:(0,_includes2.default)(activeIndex,index)?(0,_without2.default)(activeIndex,index):[].concat((0,_toConsumableArray2.default)(activeIndex),[index])}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTitleClick",function(e,titleProps){var index=titleProps.index;_this.trySetState({activeIndex:_this.computeNewIndex(index)}),(0,_invoke2.default)(_this.props,"onTitleClick",e,titleProps)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"isIndexActive",function(index){var exclusive=_this.props.exclusive,activeIndex=_this.state.activeIndex;return exclusive?activeIndex===index:(0,_includes2.default)(activeIndex,index)}),_this}return(0,_inherits2.default)(AccordionAccordion,_Component),(0,_createClass2.default)(AccordionAccordion,[{key:"getInitialAutoControlledState",value:function(_ref){return{activeIndex:_ref.exclusive?-1:[]}}},{key:"componentDidMount",value:function(){"production"!==process.env.NODE_ENV&&warnIfPropsAreInvalid(this.props,this.state)}},{key:"componentDidUpdate",value:function(){"production"!==process.env.NODE_ENV&&warnIfPropsAreInvalid(this.props,this.state)}},{key:"render",value:function(){var _this2=this,_this$props=this.props,className=_this$props.className,children=_this$props.children,_this$props=_this$props.panels,className=(0,_classnames.default)("accordion",className),rest=(0,_lib.getUnhandledProps)(AccordionAccordion,this.props),ElementType=(0,_lib.getElementType)(AccordionAccordion,this.props);return _react.default.createElement(ElementType,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?(0,_map2.default)(_this$props,function(panel,index){return _AccordionPanel.default.create(panel,{defaultProps:{active:_this2.isIndexActive(index),index:index,onTitleClick:_this2.handleTitleClick}})}):children)}}]),AccordionAccordion}(_lib.AutoControlledComponent);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"defaultProps",{exclusive:!0}),(0,_defineProperty2.default)(_interopRequireDefault,"autoControlledProps",["activeIndex"]),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["activeIndex","as","children","className","defaultActiveIndex","exclusive","onTitleClick","panels"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,activeIndex:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.number),_propTypes.default.number])]),children:_propTypes.default.node,className:_propTypes.default.string,defaultActiveIndex:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.number),_propTypes.default.number])]),exclusive:_propTypes.default.bool,onTitleClick:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_propTypes.default.func]),panels:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_propTypes.default.arrayOf(_propTypes.default.shape({content:_lib.customPropTypes.itemShorthand,title:_lib.customPropTypes.itemShorthand}))])}:{},_interopRequireDefault.create=(0,_lib.createShorthandFactory)(_interopRequireDefault,function(content){return{content:content}})}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./AccordionPanel":1598,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/possibleConstructorReturn":23,"@babel/runtime/helpers/toConsumableArray":27,_process:1042,classnames:116,"lodash/includes":956,"lodash/invoke":959,"lodash/isArray":961,"lodash/map":989,"lodash/without":1028,"prop-types":1046,react:1427}],1597:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function AccordionContent(props){var active=props.active,children=props.children,className=props.className,content=props.content,active=(0,_classnames.default)("content",(0,_lib.useKeyOnly)(active,"active"),className),className=(0,_lib.getUnhandledProps)(AccordionContent,props),props=(0,_lib.getElementType)(AccordionContent,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:active}),_lib.childrenUtils.isNil(children)?content:children)}AccordionContent.handledProps=["active","as","children","className","content"],AccordionContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},AccordionContent.create=(0,_lib.createShorthandFactory)(AccordionContent,function(content){return{content:content}}),exports.default=AccordionContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1598:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_classCallCheck2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"))),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_interopRequireWildcard=require("../../lib"),_AccordionTitle=_interopRequireDefault(require("./AccordionTitle")),_AccordionContent=_interopRequireDefault(require("./AccordionContent")),_interopRequireDefault=function(_Component){function AccordionPanel(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,AccordionPanel);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(AccordionPanel)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleTitleOverrides",function(predefinedProps){return{onClick:function(e,titleProps){(0,_invoke2.default)(predefinedProps,"onClick",e,titleProps),(0,_invoke2.default)(_this.props,"onTitleClick",e,titleProps)}}}),_this}return(0,_inherits2.default)(AccordionPanel,_Component),(0,_createClass2.default)(AccordionPanel,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,content=_this$props.content,index=_this$props.index,_this$props=_this$props.title;return _react.default.createElement(_react.Fragment,null,_AccordionTitle.default.create(_this$props,{autoGenerateKey:!1,defaultProps:{active:active,index:index},overrideProps:this.handleTitleOverrides}),_AccordionContent.default.create(content,{autoGenerateKey:!1,defaultProps:{active:active}}))}}]),AccordionPanel}(_react.Component);(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["active","content","index","onTitleClick","title"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{active:_propTypes.default.bool,content:_interopRequireWildcard.customPropTypes.itemShorthand,index:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),onTitleClick:_propTypes.default.func,title:_interopRequireWildcard.customPropTypes.itemShorthand}:{},_interopRequireDefault.create=(0,_interopRequireWildcard.createShorthandFactory)(_interopRequireDefault,null),exports.default=_interopRequireDefault}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./AccordionContent":1597,"./AccordionTitle":1599,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/invoke":959,"prop-types":1046,react:1427}],1599:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon")),_interopRequireWildcard=function(_Component){function AccordionTitle(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,AccordionTitle);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(AccordionTitle)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){return(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),_this}return(0,_inherits2.default)(AccordionTitle,_Component),(0,_createClass2.default)(AccordionTitle,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,children=_this$props.children,className=_this$props.className,content=_this$props.content,_this$props=_this$props.icon,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),"title",className),className=(0,_lib.getUnhandledProps)(AccordionTitle,this.props),ElementType=(0,_lib.getElementType)(AccordionTitle,this.props),_this$props=(0,_isNil2.default)(_this$props)?"dropdown":_this$props;return _lib.childrenUtils.isNil(children)?_react.default.createElement(ElementType,(0,_extends2.default)({},className,{className:active,onClick:this.handleClick}),_Icon.default.create(_this$props,{autoGenerateKey:!1}),content):_react.default.createElement(ElementType,(0,_extends2.default)({},className,{className:active,onClick:this.handleClick}),children)}}]),AccordionTitle}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","children","className","content","icon","index","onClick"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,icon:_lib.customPropTypes.itemShorthand,index:_propTypes.default.oneOfType([_propTypes.default.string,_propTypes.default.number]),onClick:_propTypes.default.func}:{},_interopRequireWildcard.create=(0,_lib.createShorthandFactory)(_interopRequireWildcard,function(content){return{content:content}})}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/isNil":972,"prop-types":1046,react:1427}],1600:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_set2=_interopRequireDefault(require("lodash/set")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_isNil2=(_interopRequireDefault(require("lodash/get")),_interopRequireDefault(require("lodash/isNil"))),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function Checkbox(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Checkbox);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Checkbox)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"inputRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"labelRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"canToggle",function(){var _this$props=_this.props,disabled=_this$props.disabled,radio=_this$props.radio,_this$props=_this$props.readOnly,checked=_this.state.checked;return!(disabled||_this$props||radio&&checked)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeTabIndex",function(){var _this$props2=_this.props,disabled=_this$props2.disabled,_this$props2=_this$props2.tabIndex;return(0,_isNil2.default)(_this$props2)?disabled?-1:0:_this$props2}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){var id=_this.props.id,_this$state=_this.state,checked=_this$state.checked,_this$state=_this$state.indeterminate,isInputClick=(0,_invoke2.default)(_this.inputRef.current,"contains",e.target),isLabelClick=(0,_invoke2.default)(_this.labelRef.current,"contains",e.target),isInputClick=!isLabelClick&&!isInputClick,id=!(0,_isNil2.default)(id);isLabelClick&&id||(0,_invoke2.default)(_this.props,"onClick",e,(0,_objectSpread2.default)({},_this.props,{checked:!checked,indeterminate:!!_this$state})),_this.isClickFromMouse&&(_this.isClickFromMouse=!1,isLabelClick&&!id&&_this.handleChange(e),isInputClick&&_this.handleChange(e),isLabelClick)&&id&&e.stopPropagation()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleChange",function(e){var checked=_this.state.checked;_this.canToggle()&&((0,_invoke2.default)(_this.props,"onChange",e,(0,_objectSpread2.default)({},_this.props,{checked:!checked,indeterminate:!1})),_this.trySetState({checked:!checked,indeterminate:!1}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleMouseDown",function(e){var _this$state2=_this.state,checked=_this$state2.checked,_this$state2=_this$state2.indeterminate;(0,_invoke2.default)(_this.props,"onMouseDown",e,(0,_objectSpread2.default)({},_this.props,{checked:!!checked,indeterminate:!!_this$state2})),e.defaultPrevented||(0,_invoke2.default)(_this.inputRef.current,"focus"),e.preventDefault()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleMouseUp",function(e){var _this$state3=_this.state,checked=_this$state3.checked,_this$state3=_this$state3.indeterminate;_this.isClickFromMouse=!0,(0,_invoke2.default)(_this.props,"onMouseUp",e,(0,_objectSpread2.default)({},_this.props,{checked:!!checked,indeterminate:!!_this$state3}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"setIndeterminate",function(){var indeterminate=_this.state.indeterminate;(0,_set2.default)(_this.inputRef,"current.indeterminate",!!indeterminate)}),_this}return(0,_inherits2.default)(Checkbox,_Component),(0,_createClass2.default)(Checkbox,[{key:"componentDidMount",value:function(){this.setIndeterminate()}},{key:"componentDidUpdate",value:function(){this.setIndeterminate()}},{key:"render",value:function(){var _this$props3=this.props,className=_this$props3.className,disabled=_this$props3.disabled,label=_this$props3.label,id=_this$props3.id,name=_this$props3.name,radio=_this$props3.radio,readOnly=_this$props3.readOnly,slider=_this$props3.slider,toggle=_this$props3.toggle,type=_this$props3.type,_this$props3=_this$props3.value,_this$state4=this.state,checked=_this$state4.checked,_this$state4=_this$state4.indeterminate,_this$state4=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(checked,"checked"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(_this$state4,"indeterminate"),(0,_lib.useKeyOnly)((0,_isNil2.default)(label),"fitted"),(0,_lib.useKeyOnly)(radio,"radio"),(0,_lib.useKeyOnly)(readOnly,"read-only"),(0,_lib.useKeyOnly)(slider,"slider"),(0,_lib.useKeyOnly)(toggle,"toggle"),"checkbox",className),radio=(0,_lib.getUnhandledProps)(Checkbox,this.props),readOnly=(0,_lib.getElementType)(Checkbox,this.props),slider=(0,_lib.partitionHTMLProps)(radio,{htmlProps:_lib.htmlInputAttrs}),toggle=(0,_slicedToArray2.default)(slider,2),className=toggle[0],radio=toggle[1],slider=(0,_lib.createHTMLLabel)(label,{defaultProps:{htmlFor:id},autoGenerateKey:!1})||_react.default.createElement("label",{htmlFor:id});return _react.default.createElement(readOnly,(0,_extends2.default)({},radio,{className:_this$state4,onClick:this.handleClick,onChange:this.handleChange,onMouseDown:this.handleMouseDown,onMouseUp:this.handleMouseUp}),_react.default.createElement(_reactComponentRef.Ref,{innerRef:this.inputRef},_react.default.createElement("input",(0,_extends2.default)({},className,{checked:checked,className:"hidden",disabled:disabled,id:id,name:name,readOnly:!0,tabIndex:this.computeTabIndex(),type:type,value:_this$props3}))),_react.default.createElement(_reactComponentRef.Ref,{innerRef:this.labelRef},slider))}}]),Checkbox}(_lib.AutoControlledComponent);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{type:"checkbox"}),(0,_defineProperty2.default)(_interopRequireWildcard,"autoControlledProps",["checked","indeterminate"]),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["as","checked","className","defaultChecked","defaultIndeterminate","disabled","fitted","id","indeterminate","label","name","onChange","onClick","onMouseDown","onMouseUp","radio","readOnly","slider","tabIndex","toggle","type","value"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,checked:_interopRequireDefault.default.bool,className:_interopRequireDefault.default.string,defaultChecked:_interopRequireDefault.default.bool,defaultIndeterminate:_interopRequireDefault.default.bool,disabled:_interopRequireDefault.default.bool,fitted:_interopRequireDefault.default.bool,id:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string]),indeterminate:_interopRequireDefault.default.bool,label:_lib.customPropTypes.itemShorthand,name:_interopRequireDefault.default.string,onChange:_interopRequireDefault.default.func,onClick:_interopRequireDefault.default.func,onMouseDown:_interopRequireDefault.default.func,onMouseUp:_interopRequireDefault.default.func,radio:_lib.customPropTypes.every([_interopRequireDefault.default.bool,_lib.customPropTypes.disallow(["slider","toggle"])]),readOnly:_interopRequireDefault.default.bool,slider:_lib.customPropTypes.every([_interopRequireDefault.default.bool,_lib.customPropTypes.disallow(["radio","toggle"])]),tabIndex:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string]),toggle:_lib.customPropTypes.every([_interopRequireDefault.default.bool,_lib.customPropTypes.disallow(["radio","slider"])]),type:_interopRequireDefault.default.oneOf(["checkbox","radio"]),value:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.string,_interopRequireDefault.default.number])}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@babel/runtime/helpers/slicedToArray":25,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"lodash/get":950,"lodash/invoke":959,"lodash/isNil":972,"lodash/set":1003,"prop-types":1046,react:1427}],1601:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Checkbox=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Checkbox.default}}),_interopRequireDefault(require("./Checkbox")))},{"./Checkbox":1600,"@babel/runtime/helpers/interopRequireDefault":13}],1602:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Portal=_interopRequireDefault(require("../../addons/Portal")),_interopRequireWildcard=_interopRequireDefault(require("./DimmerDimmable")),_DimmerInner=_interopRequireDefault(require("./DimmerInner")),_interopRequireDefault=function(_Component){function Dimmer(){var _getPrototypeOf2;(0,_classCallCheck2.default)(this,Dimmer);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _getPrototypeOf2=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Dimmer)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_getPrototypeOf2),"handlePortalMount",function(){(0,_lib.isBrowser)()&&(document.body.classList.add("dimmed"),document.body.classList.add("dimmable"))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_getPrototypeOf2),"handlePortalUnmount",function(){(0,_lib.isBrowser)()&&(document.body.classList.remove("dimmed"),document.body.classList.remove("dimmable"))}),_getPrototypeOf2}return(0,_inherits2.default)(Dimmer,_Component),(0,_createClass2.default)(Dimmer,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,_this$props=_this$props.page,rest=(0,_lib.getUnhandledProps)(Dimmer,this.props);return _this$props?_react.default.createElement(_Portal.default,{closeOnEscape:!1,closeOnDocumentClick:!1,onMount:this.handlePortalMount,onUnmount:this.handlePortalUnmount,open:active,openOnTriggerClick:!1},_react.default.createElement(_DimmerInner.default,(0,_extends2.default)({},rest,{active:active,page:_this$props}))):_react.default.createElement(_DimmerInner.default,(0,_extends2.default)({},rest,{active:active,page:_this$props}))}}]),Dimmer}(_react.Component);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"Dimmable",_interopRequireWildcard.default),(0,_defineProperty2.default)(_interopRequireDefault,"Inner",_DimmerInner.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["active","page"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{active:_propTypes.default.bool,page:_propTypes.default.bool}:{},_interopRequireDefault.create=(0,_lib.createShorthandFactory)(_interopRequireDefault,function(value){return{content:value}})}.call(this)}.call(this,require("_process"))},{"../../addons/Portal":1458,"../../lib":1588,"./DimmerDimmable":1603,"./DimmerInner":1604,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"prop-types":1046,react:1427}],1603:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function DimmerDimmable(props){var blurring=props.blurring,className=props.className,children=props.children,content=props.content,dimmed=props.dimmed,blurring=(0,_classnames.default)((0,_lib.useKeyOnly)(blurring,"blurring"),(0,_lib.useKeyOnly)(dimmed,"dimmed"),"dimmable",className),dimmed=(0,_lib.getUnhandledProps)(DimmerDimmable,props),className=(0,_lib.getElementType)(DimmerDimmable,props);return _react.default.createElement(className,(0,_extends2.default)({},dimmed,{className:blurring}),_lib.childrenUtils.isNil(children)?content:children)}DimmerDimmable.handledProps=["as","blurring","children","className","content","dimmed"],DimmerDimmable.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,blurring:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,dimmed:_propTypes.default.bool}:{},exports.default=DimmerDimmable}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1604:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function DimmerInner(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,DimmerInner);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(DimmerInner)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"containerRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"contentRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){var contentRef=_this.contentRef.current;(0,_invoke2.default)(_this.props,"onClick",e,_this.props),contentRef&&contentRef!==e.target&&(0,_lib.doesNodeContainClick)(contentRef,e)||(0,_invoke2.default)(_this.props,"onClickOutside",e,_this.props)}),_this}return(0,_inherits2.default)(DimmerInner,_Component),(0,_createClass2.default)(DimmerInner,[{key:"componentDidMount",value:function(){var active=this.props.active;this.toggleStyles(active)}},{key:"componentDidUpdate",value:function(prevProps){var currentActive=this.props.active;prevProps.active!==currentActive&&this.toggleStyles(currentActive)}},{key:"toggleStyles",value:function(active){var containerRef=this.containerRef.current;containerRef&&containerRef.style&&(active?containerRef.style.setProperty("display","flex","important"):containerRef.style.removeProperty("display"))}},{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,children=_this$props.children,className=_this$props.className,content=_this$props.content,disabled=_this$props.disabled,inverted=_this$props.inverted,page=_this$props.page,simple=_this$props.simple,_this$props=_this$props.verticalAlign,active=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(active,"active transition visible"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(page,"page"),(0,_lib.useKeyOnly)(simple,"simple"),(0,_lib.useVerticalAlignProp)(_this$props),"dimmer",className),disabled=(0,_lib.getUnhandledProps)(DimmerInner,this.props),inverted=(0,_lib.getElementType)(DimmerInner,this.props),page=_lib.childrenUtils.isNil(children)?content:children;return _react.default.createElement(_reactComponentRef.Ref,{innerRef:this.containerRef},_react.default.createElement(inverted,(0,_extends2.default)({},disabled,{className:active,onClick:this.handleClick}),page&&_react.default.createElement("div",{className:"content",ref:this.contentRef},page)))}}]),DimmerInner}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","children","className","content","disabled","inverted","onClick","onClickOutside","page","simple","verticalAlign"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,active:_interopRequireDefault.default.bool,children:_interopRequireDefault.default.node,className:_interopRequireDefault.default.string,content:_lib.customPropTypes.contentShorthand,disabled:_interopRequireDefault.default.bool,onClick:_interopRequireDefault.default.func,onClickOutside:_interopRequireDefault.default.func,inverted:_interopRequireDefault.default.bool,page:_interopRequireDefault.default.bool,simple:_interopRequireDefault.default.bool,verticalAlign:_interopRequireDefault.default.oneOf(["bottom","top"])}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"lodash/invoke":959,"prop-types":1046,react:1427}],1605:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Dimmer=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Dimmer.default}}),_interopRequireDefault(require("./Dimmer")))},{"./Dimmer":1602,"@babel/runtime/helpers/interopRequireDefault":13}],1606:[function(require,module,exports){!function(process){!function(){"use strict";function getKeyOrValue(key,value){return(0,_isNil2.default)(key)?value:key}var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_get3=_interopRequireDefault(require("@babel/runtime/helpers/get")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_compact2=_interopRequireDefault(require("lodash/compact")),_map2=_interopRequireDefault(require("lodash/map")),_every2=_interopRequireDefault(require("lodash/every")),_without2=_interopRequireDefault(require("lodash/without")),_findIndex2=_interopRequireDefault(require("lodash/findIndex")),_find2=_interopRequireDefault(require("lodash/find")),_reduce2=_interopRequireDefault(require("lodash/reduce")),_some2=_interopRequireDefault(require("lodash/some")),_escapeRegExp2=_interopRequireDefault(require("lodash/escapeRegExp")),_deburr2=_interopRequireDefault(require("lodash/deburr")),_isFunction2=_interopRequireDefault(require("lodash/isFunction")),_filter2=_interopRequireDefault(require("lodash/filter")),_pick2=_interopRequireDefault(require("lodash/pick")),_dropRight2=_interopRequireDefault(require("lodash/dropRight")),_isEmpty2=_interopRequireDefault(require("lodash/isEmpty")),_size2=_interopRequireDefault(require("lodash/size")),_difference2=_interopRequireDefault(require("lodash/difference")),_union2=_interopRequireDefault(require("lodash/union")),_get4=_interopRequireDefault(require("lodash/get")),_includes2=_interopRequireDefault(require("lodash/includes")),_noop2=_interopRequireDefault(require("lodash/noop")),_isUndefined2=_interopRequireDefault(require("lodash/isUndefined")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_isEqual2=_interopRequireDefault(require("lodash/isEqual")),_has2=_interopRequireDefault(require("lodash/has")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_eventStack=_interopRequireDefault(require("@semantic-ui-react/event-stack")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_keyboardKey=_interopRequireDefault(require("keyboard-key")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_shallowequal=_interopRequireDefault(require("shallowequal")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon")),_Label=_interopRequireDefault(require("../../elements/Label")),_interopRequireWildcard=_interopRequireDefault(require("./DropdownDivider")),_DropdownItem=_interopRequireDefault(require("./DropdownItem")),_DropdownHeader=_interopRequireDefault(require("./DropdownHeader")),_DropdownMenu=_interopRequireDefault(require("./DropdownMenu")),_DropdownSearchInput=_interopRequireDefault(require("./DropdownSearchInput")),_interopRequireDefault=function(_Component){function Dropdown(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Dropdown);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Dropdown)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"searchRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"sizerRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"ref",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleChange",function(e,value){(0,_invoke2.default)(_this.props,"onChange",e,(0,_objectSpread2.default)({},_this.props,{value:value}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"closeOnChange",function(e){var _this$props=_this.props,closeOnChange=_this$props.closeOnChange,_this$props=_this$props.multiple;((0,_isUndefined2.default)(closeOnChange)?!_this$props:closeOnChange)&&_this.close(e,_noop2.default)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"closeOnEscape",function(e){_this.props.closeOnEscape&&_keyboardKey.default.getCode(e)===_keyboardKey.default.Escape&&(e.preventDefault(),_this.close(e))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"moveSelectionOnKeyDown",function(e){var _this$props2=_this.props,multiple=_this$props2.multiple,_this$props2=_this$props2.selectOnNavigation;(0,_defineProperty2.default)(_moves={},_keyboardKey.default.ArrowDown,1),(0,_defineProperty2.default)(_moves,_keyboardKey.default.ArrowUp,-1);var _moves=_moves[_keyboardKey.default.getCode(e)];void 0!==_moves&&(e.preventDefault(),_this.moveSelectionBy(_moves),!multiple)&&_this$props2&&_this.makeSelectedItemActive(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"openOnSpace",function(e){_keyboardKey.default.getCode(e)===_keyboardKey.default.Spacebar&&(e.preventDefault(),_this.open(e))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"openOnArrow",function(e){var code=_keyboardKey.default.getCode(e);(0,_includes2.default)([_keyboardKey.default.ArrowDown,_keyboardKey.default.ArrowUp],code)&&!_this.state.open&&(e.preventDefault(),_this.open(e))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"makeSelectedItemActive",function(e){var _this$state=_this.state,open=_this$state.open,_this$state=_this$state.value,multiple=_this.props.multiple,item=_this.getSelectedItem(),selectedValue=(0,_get4.default)(item,"value");!(0,_isNil2.default)(selectedValue)&&open&&(open=multiple?(0,_union2.default)(_this.state.value,[selectedValue]):selectedValue,multiple?!!(0,_difference2.default)(open,_this$state).length:open!==_this$state)&&(_this.setValue(open),_this.setSelectedIndex(open),_this.handleChange(e,open),item["data-additional"])&&(0,_invoke2.default)(_this.props,"onAddItem",e,(0,_objectSpread2.default)({},_this.props,{value:selectedValue}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"selectItemOnEnter",function(e){var optionSize,search=_this.props.search;_keyboardKey.default.getCode(e)!==_keyboardKey.default.Enter&&(search||_keyboardKey.default.getCode(e)!==_keyboardKey.default.Spacebar)||(e.preventDefault(),optionSize=(0,_size2.default)(_this.getMenuOptions()),search&&0===optionSize)||(_this.makeSelectedItemActive(e),_this.closeOnChange(e),_this.clearSearchQuery(),search&&(0,_invoke2.default)(_this.searchRef.current,"focus"))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"removeItemOnBackspace",function(e){var _this$props3=_this.props,multiple=_this$props3.multiple,_this$props3=_this$props3.search,_this$state2=_this.state,searchQuery=_this$state2.searchQuery,_this$state2=_this$state2.value;_keyboardKey.default.getCode(e)===_keyboardKey.default.Backspace&&!searchQuery&&_this$props3&&multiple&&!(0,_isEmpty2.default)(_this$state2)&&(e.preventDefault(),searchQuery=(0,_dropRight2.default)(_this$state2),_this.setValue(searchQuery),_this.setSelectedIndex(searchQuery),_this.handleChange(e,searchQuery))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"closeOnDocumentClick",function(e){!_this.props.closeOnBlur||_this.ref.current&&(0,_lib.doesNodeContainClick)(_this.ref.current,e)||_this.close()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleMouseDown",function(e){_this.isMouseDown=!0,(0,_invoke2.default)(_this.props,"onMouseDown",e,_this.props),document.addEventListener("mouseup",_this.handleDocumentMouseUp)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleDocumentMouseUp",function(){_this.isMouseDown=!1,document.removeEventListener("mouseup",_this.handleDocumentMouseUp)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){var _this$props4=_this.props,minCharacters=_this$props4.minCharacters,_this$props4=_this$props4.search,_this$state3=_this.state,open=_this$state3.open,_this$state3=_this$state3.searchQuery;if((0,_invoke2.default)(_this.props,"onClick",e,_this.props),e.stopPropagation(),!_this$props4)return _this.toggle(e);!open&&(_this$state3.length>=minCharacters||1===minCharacters)?_this.open(e):(0,_invoke2.default)(_this.searchRef.current,"focus")}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleIconClick",function(e){var clearable=_this.props.clearable,hasValue=_this.hasValue();(0,_invoke2.default)(_this.props,"onClick",e,_this.props),e.stopPropagation(),clearable&&hasValue?_this.clearValue(e):_this.toggle(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleItemClick",function(e,item){var newValue,_this$props5=_this.props,multiple=_this$props5.multiple,_this$props5=_this$props5.search,currentValue=_this.state.value,value=item.value;e.stopPropagation(),(multiple||item.disabled)&&e.nativeEvent.stopImmediatePropagation(),item.disabled||(item=item["data-additional"],newValue=multiple?(0,_union2.default)(_this.state.value,[value]):value,(multiple?(0,_difference2.default)(newValue,currentValue).length:newValue!==currentValue)&&(_this.setValue(newValue),_this.setSelectedIndex(value),_this.handleChange(e,newValue)),_this.clearSearchQuery(value),_this$props5?(0,_invoke2.default)(_this.searchRef.current,"focus"):(0,_invoke2.default)(_this.ref.current,"focus"),_this.closeOnChange(e),item&&(0,_invoke2.default)(_this.props,"onAddItem",e,(0,_objectSpread2.default)({},_this.props,{value:value})))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleFocus",function(e){_this.state.focus||((0,_invoke2.default)(_this.props,"onFocus",e,_this.props),_this.setState({focus:!0}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleBlur",function(e){var closeOnBlur,multiple,currentTarget=(0,_get4.default)(e,"currentTarget");currentTarget&&currentTarget.contains(document.activeElement)||(closeOnBlur=(currentTarget=_this.props).closeOnBlur,multiple=currentTarget.multiple,currentTarget=currentTarget.selectOnBlur,_this.isMouseDown)||((0,_invoke2.default)(_this.props,"onBlur",e,_this.props),currentTarget&&!multiple&&(_this.makeSelectedItemActive(e),closeOnBlur)&&_this.close(),_this.setState({focus:!1}),_this.clearSearchQuery())}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleSearchChange",function(e,_ref){var _ref=_ref.value,minCharacters=(e.stopPropagation(),_this.props.minCharacters),open=_this.state.open;(0,_invoke2.default)(_this.props,"onSearchChange",e,(0,_objectSpread2.default)({},_this.props,{searchQuery:_ref})),_this.trySetState({searchQuery:_ref,selectedIndex:0}),!open&&_ref.length>=minCharacters?_this.open():open&&1!==minCharacters&&_ref.length<minCharacters&&_this.close()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getKeyAndValues",function(options){return options&&options.map(function(option){return(0,_pick2.default)(option,["key","value"])})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getMenuOptions",function(){var re,value=0<arguments.length&&void 0!==arguments[0]?arguments[0]:_this.state.value,options=1<arguments.length&&void 0!==arguments[1]?arguments[1]:_this.props.options,searchQuery=2<arguments.length&&void 0!==arguments[2]?arguments[2]:_this.state.searchQuery,_this$props7=_this.props,additionLabel=_this$props7.additionLabel,additionPosition=_this$props7.additionPosition,allowAdditions=_this$props7.allowAdditions,deburr=_this$props7.deburr,multiple=_this$props7.multiple,_this$props7=_this$props7.search;return multiple&&(options=(0,_filter2.default)(options,function(opt){return!(0,_includes2.default)(value,opt.value)})),_this$props7&&searchQuery&&(options=(0,_isFunction2.default)(_this$props7)?_this$props7(options,searchQuery):(multiple=deburr?(0,_deburr2.default)(searchQuery):searchQuery,re=new RegExp((0,_escapeRegExp2.default)(multiple),"i"),(0,_filter2.default)(options,function(opt){return re.test(deburr?(0,_deburr2.default)(opt.text):opt.text)}))),allowAdditions&&_this$props7&&searchQuery&&!(0,_some2.default)(options,{text:searchQuery})&&(multiple={key:"addition",text:[_react.default.isValidElement(additionLabel)?_react.default.cloneElement(additionLabel,{key:"addition-label"}):additionLabel||"",_react.default.createElement("b",{key:"addition-query"},searchQuery)],value:searchQuery,className:"addition","data-additional":!0},"top"===additionPosition?options.unshift(multiple):options.push(multiple)),options}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getSelectedItem",function(){var selectedIndex=_this.state.selectedIndex,options=_this.getMenuOptions();return(0,_get4.default)(options,"[".concat(selectedIndex,"]"))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getEnabledIndices",function(givenOptions){givenOptions=givenOptions||_this.getMenuOptions();return(0,_reduce2.default)(givenOptions,function(memo,item,index){return item.disabled||memo.push(index),memo},[])}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getItemByValue",function(value){var options=_this.props.options;return(0,_find2.default)(options,{value:value})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getMenuItemIndexByValue",function(value,givenOptions){givenOptions=givenOptions||_this.getMenuOptions();return(0,_findIndex2.default)(givenOptions,["value",value])}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getDropdownAriaOptions",function(){var _this$props8=_this.props,loading=_this$props8.loading,disabled=_this$props8.disabled,search=_this$props8.search,_this$props8=_this$props8.multiple,search={role:search?"combobox":"listbox","aria-busy":loading,"aria-disabled":disabled,"aria-expanded":!!_this.state.open};return"listbox"===search.role&&(search["aria-multiselectable"]=_this$props8),search}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"clearSearchQuery",function(value){var searchQuery=_this.state.searchQuery;void 0!==searchQuery&&""!==searchQuery&&(_this.trySetState({searchQuery:""}),_this.setSelectedIndex(value,void 0,""))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"setValue",function(value){_this.trySetState({value:value})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"setSelectedIndex",function(){var firstIndex,value=0<arguments.length&&void 0!==arguments[0]?arguments[0]:_this.state.value,optionsProps=1<arguments.length&&void 0!==arguments[1]?arguments[1]:_this.props.options,searchQuery=2<arguments.length&&void 0!==arguments[2]?arguments[2]:_this.state.searchQuery,multiple=_this.props.multiple,selectedIndex=_this.state.selectedIndex,optionsProps=_this.getMenuOptions(value,optionsProps,searchQuery),searchQuery=_this.getEnabledIndices(optionsProps);!selectedIndex||selectedIndex<0?(firstIndex=searchQuery[0],firstIndex=multiple?firstIndex:_this.getMenuItemIndexByValue(value,optionsProps)||searchQuery[0]):multiple?selectedIndex>=optionsProps.length-1&&(firstIndex=searchQuery[searchQuery.length-1]):(multiple=_this.getMenuItemIndexByValue(value,optionsProps),firstIndex=(0,_includes2.default)(searchQuery,multiple)?multiple:void 0),(!firstIndex||firstIndex<0)&&(firstIndex=searchQuery[0]),_this.setState({selectedIndex:firstIndex})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleLabelClick",function(e,labelProps){e.stopPropagation(),_this.setState({selectedLabel:labelProps.value}),(0,_invoke2.default)(_this.props,"onLabelClick",e,labelProps)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleLabelRemove",function(e,labelProps){e.stopPropagation();var value=_this.state.value,value=(0,_without2.default)(value,labelProps.value);_this.setValue(value),_this.setSelectedIndex(value),_this.handleChange(e,value)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"moveSelectionBy",function(offset){var lastIndex,nextIndex,startIndex=1<arguments.length&&void 0!==arguments[1]?arguments[1]:_this.state.selectedIndex,options=_this.getMenuOptions();void 0===options||(0,_every2.default)(options,"disabled")||(lastIndex=options.length-1,nextIndex=startIndex+offset,!_this.props.wrapSelection&&(lastIndex<nextIndex||nextIndex<0)?nextIndex=startIndex:lastIndex<nextIndex?nextIndex=0:nextIndex<0&&(nextIndex=lastIndex),options[nextIndex].disabled?_this.moveSelectionBy(offset,nextIndex):(_this.setState({selectedIndex:nextIndex}),_this.scrollSelectedItemIntoView()))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleIconOverrides",function(predefinedProps){var clearable=_this.props.clearable;return{className:(0,_classnames.default)(clearable&&_this.hasValue()&&"clear",predefinedProps.className),onClick:function(e){(0,_invoke2.default)(predefinedProps,"onClick",e,predefinedProps),_this.handleIconClick(e)}}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"clearValue",function(e){var newValue=_this.props.multiple?[]:"";_this.setValue(newValue),_this.setSelectedIndex(newValue),_this.handleChange(e,newValue)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeSearchInputTabIndex",function(){var _this$props9=_this.props,disabled=_this$props9.disabled,_this$props9=_this$props9.tabIndex;return(0,_isNil2.default)(_this$props9)?disabled?-1:0:_this$props9}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeSearchInputWidth",function(){var searchQuery=_this.state.searchQuery;if(_this.sizerRef.current&&searchQuery)return _this.sizerRef.current.style.display="inline",_this.sizerRef.current.textContent=searchQuery,searchQuery=Math.ceil(_this.sizerRef.current.getBoundingClientRect().width),_this.sizerRef.current.style.removeProperty("display"),searchQuery}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeTabIndex",function(){var _this$props10=_this.props,disabled=_this$props10.disabled,search=_this$props10.search,_this$props10=_this$props10.tabIndex;if(!search)return disabled?-1:(0,_isNil2.default)(_this$props10)?0:_this$props10}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleSearchInputOverrides",function(predefinedProps){return{onChange:function(e,inputProps){(0,_invoke2.default)(predefinedProps,"onChange",e,inputProps),_this.handleSearchChange(e,inputProps)}}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"hasValue",function(){var multiple=_this.props.multiple,value=_this.state.value;return multiple?!(0,_isEmpty2.default)(value):!(0,_isNil2.default)(value)&&""!==value}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"scrollSelectedItemIntoView",function(){var menu,item,isOutOfUpperView,isOutOfLowerView;_this.ref.current&&(menu=_this.ref.current.querySelector(".menu.visible"))&&(item=menu.querySelector(".item.selected"))&&(isOutOfUpperView=item.offsetTop<menu.scrollTop,isOutOfLowerView=item.offsetTop+item.clientHeight>menu.scrollTop+menu.clientHeight,isOutOfUpperView?menu.scrollTop=item.offsetTop:isOutOfLowerView&&(menu.scrollTop=item.offsetTop+item.clientHeight-menu.clientHeight))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"setOpenDirection",function(){var spaceAtTheBottom,dropdownRect,menu;_this.ref.current&&(menu=_this.ref.current.querySelector(".menu.visible"))&&(dropdownRect=_this.ref.current.getBoundingClientRect(),menu=menu.clientHeight,spaceAtTheBottom=document.documentElement.clientHeight-dropdownRect.top-dropdownRect.height-menu,dropdownRect=dropdownRect.top-menu,!(menu=spaceAtTheBottom<0&&spaceAtTheBottom<dropdownRect)!=!_this.state.upward)&&_this.trySetState({upward:menu})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"open",function(e){var _this$props11=_this.props,disabled=_this$props11.disabled,_this$props11=(_this$props11.open,_this$props11.search);disabled||(_this$props11&&(0,_invoke2.default)(_this.searchRef.current,"focus"),(0,_invoke2.default)(_this.props,"onOpen",e,_this.props),_this.trySetState({open:!0}),_this.scrollSelectedItemIntoView())}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"close",function(e){var callback=1<arguments.length&&void 0!==arguments[1]?arguments[1]:_this.handleClose;_this.state.open&&((0,_invoke2.default)(_this.props,"onClose",e,_this.props),_this.trySetState({open:!1},callback))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClose",function(){var hasSearchFocus=document.activeElement===_this.searchRef.current,hasDropdownFocus=(!hasSearchFocus&&_this.ref.current&&_this.ref.current.blur(),document.activeElement===_this.ref.current);_this.setState({focus:hasSearchFocus||hasDropdownFocus})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"toggle",function(e){return _this.state.open?_this.close(e):_this.open(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderText",function(){var _this$props12=_this.props,multiple=_this$props12.multiple,placeholder=_this$props12.placeholder,search=_this$props12.search,_this$props12=_this$props12.text,_this$state4=_this.state,searchQuery=_this$state4.searchQuery,value=_this$state4.value,_this$state4=_this$state4.open,hasValue=_this.hasValue(),search=(0,_classnames.default)(placeholder&&!hasValue&&"default","text",search&&searchQuery&&"filtered"),searchQuery=placeholder;return _this$props12?searchQuery=_this$props12:_this$state4&&!multiple?searchQuery=(0,_get4.default)(_this.getSelectedItem(),"text"):hasValue&&(searchQuery=(0,_get4.default)(_this.getItemByValue(value),"text")),_react.default.createElement("div",{className:search,role:"alert","aria-live":"polite","aria-atomic":!0},searchQuery)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderSearchInput",function(){var _this$props13=_this.props,search=_this$props13.search,_this$props13=_this$props13.searchInput,searchQuery=_this.state.searchQuery;return search&&_react.default.createElement(_reactComponentRef.Ref,{innerRef:_this.searchRef},_DropdownSearchInput.default.create(_this$props13,{defaultProps:{style:{width:_this.computeSearchInputWidth()},tabIndex:_this.computeSearchInputTabIndex(),value:searchQuery},overrideProps:_this.handleSearchInputOverrides}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderSearchSizer",function(){var _this$props14=_this.props,search=_this$props14.search,_this$props14=_this$props14.multiple;return search&&_this$props14&&_react.default.createElement("span",{className:"sizer",ref:_this.sizerRef})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderLabels",function(){var _this$props15=_this.props,multiple=_this$props15.multiple,renderLabel=_this$props15.renderLabel,_this$props15=_this.state,selectedLabel=_this$props15.selectedLabel,_this$props15=_this$props15.value;if(multiple&&!(0,_isEmpty2.default)(_this$props15))return multiple=(0,_map2.default)(_this$props15,_this.getItemByValue),(0,_map2.default)((0,_compact2.default)(multiple),function(item,index){var defaultProps={active:item.value===selectedLabel,as:"a",key:getKeyOrValue(item.key,item.value),onClick:_this.handleLabelClick,onRemove:_this.handleLabelRemove,value:item.value};return _Label.default.create(renderLabel(item,index,defaultProps),{defaultProps:defaultProps})})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderOptions",function(){var isActive,_this$props16=_this.props,lazyLoad=_this$props16.lazyLoad,multiple=_this$props16.multiple,search=_this$props16.search,_this$props16=_this$props16.noResultsMessage,_this$state6=_this.state,open=_this$state6.open,selectedIndex=_this$state6.selectedIndex,value=_this$state6.value;return lazyLoad&&!open?null:(_this$state6=_this.getMenuOptions(),null!==_this$props16&&search&&(0,_isEmpty2.default)(_this$state6)?_react.default.createElement("div",{className:"message"},_this$props16):(isActive=multiple?function(optValue){return(0,_includes2.default)(value,optValue)}:function(optValue){return optValue===value},(0,_map2.default)(_this$state6,function(opt,i){return _DropdownItem.default.create((0,_objectSpread2.default)({active:isActive(opt.value),onClick:_this.handleItemClick,selected:selectedIndex===i},opt,{key:getKeyOrValue(opt.key,opt.value),style:(0,_objectSpread2.default)({},opt.style,{pointerEvents:"all"})}))})))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderMenu",function(){var _this$props17=_this.props,children=_this$props17.children,direction=_this$props17.direction,_this$props17=_this$props17.header,open=_this.state.open,ariaOptions=_this.getDropdownMenuAriaOptions();return _lib.childrenUtils.isNil(children)?_react.default.createElement(_DropdownMenu.default,(0,_extends2.default)({},ariaOptions,{direction:direction,open:open}),_DropdownHeader.default.create(_this$props17,{autoGenerateKey:!1}),_this.renderOptions()):(_this$props17=_react.Children.only(children),children=(0,_classnames.default)(direction,(0,_lib.useKeyOnly)(open,"visible"),_this$props17.props.className),(0,_react.cloneElement)(_this$props17,(0,_objectSpread2.default)({className:children},ariaOptions)))}),_this}return(0,_inherits2.default)(Dropdown,_Component),(0,_createClass2.default)(Dropdown,[{key:"getInitialAutoControlledState",value:function(){return{focus:!1,searchQuery:""}}},{key:"UNSAFE_componentWillMount",value:function(){var _this$state7=this.state,open=_this$state7.open,_this$state7=_this$state7.value;this.setValue(_this$state7),this.setSelectedIndex(_this$state7),open&&this.open()}},{key:"UNSAFE_componentWillReceiveProps",value:function(nextProps){var isNextValueArray,hasValue;(0,_get3.default)((0,_getPrototypeOf3.default)(Dropdown.prototype),"UNSAFE_componentWillReceiveProps",this).call(this,nextProps),"production"!==process.env.NODE_ENV&&(isNextValueArray=Array.isArray(nextProps.value),(hasValue=(0,_has2.default)(nextProps,"value"))&&nextProps.multiple&&!isNextValueArray?console.error("Dropdown `value` must be an array when `multiple` is set."+" Received type: `".concat(Object.prototype.toString.call(nextProps.value),"`.")):hasValue&&!nextProps.multiple&&isNextValueArray&&console.error("Dropdown `value` must not be an array when `multiple` is not set. Either set `multiple={true}` or use a string or number value.")),(0,_shallowequal.default)(nextProps.value,this.props.value)||(this.setValue(nextProps.value),this.setSelectedIndex(nextProps.value)),(0,_isEqual2.default)(this.getKeyAndValues(nextProps.options),this.getKeyAndValues(this.props.options))||this.setSelectedIndex(void 0,nextProps.options)}},{key:"shouldComponentUpdate",value:function(nextProps,nextState){return!(0,_shallowequal.default)(nextProps,this.props)||!(0,_shallowequal.default)(nextState,this.state)}},{key:"componentDidUpdate",value:function(prevProps,prevState){var _this$props18=this.props,closeOnBlur=_this$props18.closeOnBlur,minCharacters=_this$props18.minCharacters,openOnFocus=_this$props18.openOnFocus,_this$props18=_this$props18.search;!prevState.focus&&this.state.focus?this.isMouseDown||(_this$props18=!_this$props18||1===minCharacters&&!this.state.open,openOnFocus&&_this$props18&&this.open()):prevState.focus&&!this.state.focus&&!this.isMouseDown&&closeOnBlur&&this.close(),!prevState.open&&this.state.open?(this.setOpenDirection(),this.scrollSelectedItemIntoView()):prevState.open&&this.state.open}},{key:"getDropdownMenuAriaOptions",value:function(){var _this$props19=this.props,search=_this$props19.search,_this$props19=_this$props19.multiple,ariaOptions={};return search&&(ariaOptions["aria-multiselectable"]=_this$props19,ariaOptions.role="listbox"),ariaOptions}},{key:"render",value:function(){var _this$props20=this.props,basic=_this$props20.basic,button=_this$props20.button,className=_this$props20.className,compact=_this$props20.compact,disabled=_this$props20.disabled,error=_this$props20.error,fluid=_this$props20.fluid,floating=_this$props20.floating,icon=_this$props20.icon,inline=_this$props20.inline,item=_this$props20.item,labeled=_this$props20.labeled,loading=_this$props20.loading,multiple=_this$props20.multiple,pointing=_this$props20.pointing,search=_this$props20.search,selection=_this$props20.selection,scrolling=_this$props20.scrolling,simple=_this$props20.simple,_this$props20=_this$props20.trigger,_this$state8=this.state,focus=_this$state8.focus,open=_this$state8.open,_this$state8=_this$state8.upward,disabled=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(open,"active visible"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(error,"error"),(0,_lib.useKeyOnly)(loading,"loading"),(0,_lib.useKeyOnly)(basic,"basic"),(0,_lib.useKeyOnly)(button,"button"),(0,_lib.useKeyOnly)(compact,"compact"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(floating,"floating"),(0,_lib.useKeyOnly)(inline,"inline"),(0,_lib.useKeyOnly)(labeled,"labeled"),(0,_lib.useKeyOnly)(item,"item"),(0,_lib.useKeyOnly)(multiple,"multiple"),(0,_lib.useKeyOnly)(search,"search"),(0,_lib.useKeyOnly)(selection,"selection"),(0,_lib.useKeyOnly)(simple,"simple"),(0,_lib.useKeyOnly)(scrolling,"scrolling"),(0,_lib.useKeyOnly)(_this$state8,"upward"),(0,_lib.useKeyOrValueAndKey)(pointing,"pointing"),"dropdown",className),error=(0,_lib.getUnhandledProps)(Dropdown,this.props),loading=(0,_lib.getElementType)(Dropdown,this.props),basic=this.getDropdownAriaOptions(loading,this.props);return _react.default.createElement(_reactComponentRef.Ref,{innerRef:this.ref},_react.default.createElement(loading,(0,_extends2.default)({},error,basic,{className:disabled,onBlur:this.handleBlur,onClick:this.handleClick,onMouseDown:this.handleMouseDown,onFocus:this.handleFocus,onChange:this.handleChange,tabIndex:this.computeTabIndex()}),this.renderLabels(),this.renderSearchInput(),this.renderSearchSizer(),_this$props20||this.renderText(),_Icon.default.create(icon,{overrideProps:this.handleIconOverrides,autoGenerateKey:!1}),this.renderMenu(),open&&_react.default.createElement(_eventStack.default,{name:"keydown",on:this.closeOnEscape}),open&&_react.default.createElement(_eventStack.default,{name:"keydown",on:this.moveSelectionOnKeyDown}),open&&_react.default.createElement(_eventStack.default,{name:"click",on:this.closeOnDocumentClick}),open&&_react.default.createElement(_eventStack.default,{name:"keydown",on:this.selectItemOnEnter}),focus&&_react.default.createElement(_eventStack.default,{name:"keydown",on:this.removeItemOnBackspace}),focus&&!open&&_react.default.createElement(_eventStack.default,{name:"keydown",on:this.openOnArrow}),focus&&!open&&_react.default.createElement(_eventStack.default,{name:"keydown",on:this.openOnSpace})))}}]),Dropdown}(_lib.AutoControlledComponent);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"defaultProps",{additionLabel:"Add ",additionPosition:"top",closeOnBlur:!0,closeOnEscape:!0,deburr:!1,icon:"dropdown",minCharacters:1,noResultsMessage:"No results found.",openOnFocus:!0,renderLabel:function(_ref2){return _ref2.text},searchInput:"text",selectOnBlur:!0,selectOnNavigation:!0,wrapSelection:!0}),(0,_defineProperty2.default)(_interopRequireDefault,"autoControlledProps",["open","searchQuery","selectedLabel","value","upward"]),(0,_defineProperty2.default)(_interopRequireDefault,"Divider",_interopRequireWildcard.default),(0,_defineProperty2.default)(_interopRequireDefault,"Header",_DropdownHeader.default),(0,_defineProperty2.default)(_interopRequireDefault,"Item",_DropdownItem.default),(0,_defineProperty2.default)(_interopRequireDefault,"Menu",_DropdownMenu.default),(0,_defineProperty2.default)(_interopRequireDefault,"SearchInput",_DropdownSearchInput.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["additionLabel","additionPosition","allowAdditions","as","basic","button","children","className","clearable","closeOnBlur","closeOnChange","closeOnEscape","compact","deburr","defaultOpen","defaultSearchQuery","defaultSelectedLabel","defaultUpward","defaultValue","direction","disabled","error","floating","fluid","header","icon","inline","item","labeled","lazyLoad","loading","minCharacters","multiple","noResultsMessage","onAddItem","onBlur","onChange","onClick","onClose","onFocus","onLabelClick","onMouseDown","onOpen","onSearchChange","open","openOnFocus","options","placeholder","pointing","renderLabel","scrolling","search","searchInput","searchQuery","selectOnBlur","selectOnNavigation","selectedLabel","selection","simple","tabIndex","text","trigger","upward","value","wrapSelection"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,additionLabel:_propTypes.default.oneOfType([_propTypes.default.element,_propTypes.default.string]),additionPosition:_propTypes.default.oneOf(["top","bottom"]),allowAdditions:_lib.customPropTypes.every([_lib.customPropTypes.demand(["options","selection","search"]),_propTypes.default.bool]),basic:_propTypes.default.bool,button:_propTypes.default.bool,children:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["options","selection"]),_lib.customPropTypes.givenProps({children:_propTypes.default.any.isRequired},_propTypes.default.element.isRequired)]),className:_propTypes.default.string,clearable:_propTypes.default.bool,closeOnBlur:_propTypes.default.bool,closeOnEscape:_propTypes.default.bool,closeOnChange:_propTypes.default.bool,compact:_propTypes.default.bool,deburr:_propTypes.default.bool,defaultOpen:_propTypes.default.bool,defaultSearchQuery:_propTypes.default.string,defaultSelectedLabel:_lib.customPropTypes.every([_lib.customPropTypes.demand(["multiple"]),_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string])]),defaultUpward:_propTypes.default.bool,defaultValue:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string,_propTypes.default.bool,_propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.string,_propTypes.default.number,_propTypes.default.bool]))]),direction:_propTypes.default.oneOf(["left","right"]),disabled:_propTypes.default.bool,error:_propTypes.default.bool,floating:_propTypes.default.bool,fluid:_propTypes.default.bool,header:_propTypes.default.node,icon:_propTypes.default.oneOfType([_propTypes.default.node,_propTypes.default.object]),inline:_propTypes.default.bool,item:_propTypes.default.bool,labeled:_propTypes.default.bool,lazyLoad:_propTypes.default.bool,loading:_propTypes.default.bool,minCharacters:_propTypes.default.number,multiple:_propTypes.default.bool,noResultsMessage:_propTypes.default.node,onAddItem:_propTypes.default.func,onBlur:_propTypes.default.func,onChange:_propTypes.default.func,onClick:_propTypes.default.func,onClose:_propTypes.default.func,onFocus:_propTypes.default.func,onLabelClick:_propTypes.default.func,onMouseDown:_propTypes.default.func,onOpen:_propTypes.default.func,onSearchChange:_propTypes.default.func,open:_propTypes.default.bool,openOnFocus:_propTypes.default.bool,options:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_propTypes.default.arrayOf(_propTypes.default.shape(_DropdownItem.default.propTypes))]),placeholder:_propTypes.default.string,pointing:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["left","right","top","top left","top right","bottom","bottom left","bottom right"])]),renderLabel:_propTypes.default.func,scrolling:_propTypes.default.bool,search:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.func]),searchInput:_propTypes.default.oneOfType([_propTypes.default.array,_propTypes.default.node,_propTypes.default.object]),searchQuery:_propTypes.default.string,selectOnBlur:_propTypes.default.bool,selectOnNavigation:_propTypes.default.bool,selectedLabel:_lib.customPropTypes.every([_lib.customPropTypes.demand(["multiple"]),_propTypes.default.oneOfType([_propTypes.default.string,_propTypes.default.number])]),selection:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_lib.customPropTypes.demand(["options"]),_propTypes.default.bool]),simple:_propTypes.default.bool,tabIndex:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),text:_propTypes.default.string,trigger:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["selection","text"]),_propTypes.default.node]),value:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.string,_propTypes.default.number,_propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.string,_propTypes.default.number]))]),upward:_propTypes.default.bool,wrapSelection:_propTypes.default.bool}:{}}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../elements/Label":1536,"../../lib":1588,"./DropdownDivider":1607,"./DropdownHeader":1608,"./DropdownItem":1609,"./DropdownMenu":1610,"./DropdownSearchInput":1611,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/get":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@semantic-ui-react/event-stack":36,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"keyboard-key":662,"lodash/compact":904,"lodash/deburr":907,"lodash/difference":908,"lodash/dropRight":909,"lodash/escapeRegExp":912,"lodash/every":913,"lodash/filter":914,"lodash/find":915,"lodash/findIndex":916,"lodash/get":950,"lodash/has":951,"lodash/includes":956,"lodash/invoke":959,"lodash/isEmpty":966,"lodash/isEqual":967,"lodash/isFunction":969,"lodash/isNil":972,"lodash/isUndefined":982,"lodash/map":989,"lodash/noop":994,"lodash/pick":996,"lodash/reduce":1001,"lodash/size":1004,"lodash/some":1005,"lodash/union":1024,"lodash/without":1028,"prop-types":1046,react:1427,shallowequal:1694}],1607:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function DropdownDivider(props){var className=props.className,className=(0,_classnames.default)("divider",className),rest=(0,_lib.getUnhandledProps)(DropdownDivider,props),props=(0,_lib.getElementType)(DropdownDivider,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}))}DropdownDivider.handledProps=["as","className"],DropdownDivider.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,className:_propTypes.default.string}:{},exports.default=DropdownDivider}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1608:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon"));function DropdownHeader(props){var children=props.children,className=props.className,content=props.content,icon=props.icon,className=(0,_classnames.default)("header",className),rest=(0,_lib.getUnhandledProps)(DropdownHeader,props),props=(0,_lib.getElementType)(DropdownHeader,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_Icon.default.create(icon,{autoGenerateKey:!1}),content):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}DropdownHeader.handledProps=["as","children","className","content","icon"],DropdownHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,icon:_lib.customPropTypes.itemShorthand}:{},DropdownHeader.create=(0,_lib.createShorthandFactory)(DropdownHeader,function(content){return{content:content}}),exports.default=DropdownHeader}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1609:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Flag=_interopRequireDefault(require("../../elements/Flag")),_Icon=_interopRequireDefault(require("../../elements/Icon")),_Image=_interopRequireDefault(require("../../elements/Image")),_Label=_interopRequireDefault(require("../../elements/Label")),_interopRequireWildcard=function(_Component){function DropdownItem(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,DropdownItem);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(DropdownItem)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),_this}return(0,_inherits2.default)(DropdownItem,_Component),(0,_createClass2.default)(DropdownItem,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,children=_this$props.children,className=_this$props.className,content=_this$props.content,disabled=_this$props.disabled,description=_this$props.description,flag=_this$props.flag,icon=_this$props.icon,image=_this$props.image,label=_this$props.label,selected=_this$props.selected,_this$props=_this$props.text,className=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(selected,"selected"),"item",className),icon=(0,_isNil2.default)(icon)?_lib.childrenUtils.someByType(children,"DropdownMenu")&&"dropdown":icon,rest=(0,_lib.getUnhandledProps)(DropdownItem,this.props),ElementType=(0,_lib.getElementType)(DropdownItem,this.props),disabled={role:"option","aria-disabled":disabled,"aria-checked":active,"aria-selected":selected};return _lib.childrenUtils.isNil(children)?(active=_Flag.default.create(flag,{autoGenerateKey:!1}),selected=_Icon.default.create(icon,{autoGenerateKey:!1}),flag=_Image.default.create(image,{autoGenerateKey:!1}),icon=_Label.default.create(label,{autoGenerateKey:!1}),image=(0,_lib.createShorthand)("span",function(val){return{children:val}},description,{defaultProps:{className:"description"},autoGenerateKey:!1}),label=(0,_lib.createShorthand)("span",function(val){return{children:val}},_lib.childrenUtils.isNil(content)?_this$props:content,{defaultProps:{className:"text"},autoGenerateKey:!1}),_react.default.createElement(ElementType,(0,_extends2.default)({},rest,disabled,{className:className,onClick:this.handleClick}),flag,selected,active,icon,image,label)):_react.default.createElement(ElementType,(0,_extends2.default)({},rest,disabled,{className:className,onClick:this.handleClick}),children)}}]),DropdownItem}(_react.Component);(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","children","className","content","description","disabled","flag","icon","image","label","onClick","selected","text","value"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,description:_lib.customPropTypes.itemShorthand,disabled:_propTypes.default.bool,flag:_lib.customPropTypes.itemShorthand,icon:_lib.customPropTypes.itemShorthand,image:_lib.customPropTypes.itemShorthand,label:_lib.customPropTypes.itemShorthand,onClick:_propTypes.default.func,selected:_propTypes.default.bool,text:_lib.customPropTypes.contentShorthand,value:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.number,_propTypes.default.string])}:{},_interopRequireWildcard.create=(0,_lib.createShorthandFactory)(_interopRequireWildcard,function(opts){return opts}),exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../elements/Flag":1520,"../../elements/Icon":1527,"../../elements/Image":1530,"../../elements/Label":1536,"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/isNil":972,"prop-types":1046,react:1427}],1610:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function DropdownMenu(props){var children=props.children,className=props.className,content=props.content,direction=props.direction,open=props.open,scrolling=props.scrolling,direction=(0,_classnames.default)(direction,(0,_lib.useKeyOnly)(open,"visible"),(0,_lib.useKeyOnly)(scrolling,"scrolling"),"menu transition",className),open=(0,_lib.getUnhandledProps)(DropdownMenu,props),scrolling=(0,_lib.getElementType)(DropdownMenu,props);return _react.default.createElement(scrolling,(0,_extends2.default)({},open,{className:direction}),_lib.childrenUtils.isNil(children)?content:children)}DropdownMenu.handledProps=["as","children","className","content","direction","open","scrolling"],DropdownMenu.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,direction:_propTypes.default.oneOf(["left","right"]),open:_propTypes.default.bool,scrolling:_propTypes.default.bool}:{},exports.default=DropdownMenu}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1611:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_get2=_interopRequireDefault(require("lodash/get")),_classnames=_interopRequireDefault(require("classnames")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function DropdownSearchInput(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,DropdownSearchInput);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(DropdownSearchInput)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleChange",function(e){var value=(0,_get2.default)(e,"target.value");(0,_invoke2.default)(_this.props,"onChange",e,(0,_objectSpread2.default)({},_this.props,{value:value}))}),_this}return(0,_inherits2.default)(DropdownSearchInput,_Component),(0,_createClass2.default)(DropdownSearchInput,[{key:"render",value:function(){var _this$props=this.props,autoComplete=_this$props.autoComplete,className=_this$props.className,tabIndex=_this$props.tabIndex,type=_this$props.type,_this$props=_this$props.value,className=(0,_classnames.default)("search",className),rest=(0,_lib.getUnhandledProps)(DropdownSearchInput,this.props);return _react.default.createElement("input",(0,_extends2.default)({},rest,{"aria-autocomplete":"list",autoComplete:autoComplete,className:className,onChange:this.handleChange,tabIndex:tabIndex,type:type,value:_this$props}))}}]),DropdownSearchInput}(_react.Component);(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{autoComplete:"off",type:"text"}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["as","autoComplete","className","tabIndex","type","value"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,autoComplete:_interopRequireDefault.default.string,className:_interopRequireDefault.default.string,tabIndex:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string]),type:_interopRequireDefault.default.string,value:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string])}:{},_interopRequireWildcard.create=(0,_lib.createShorthandFactory)(_interopRequireWildcard,function(type){return{type:type}}),exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/get":950,"lodash/invoke":959,"prop-types":1046,react:1427}],1612:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Dropdown=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Dropdown.default}}),_interopRequireDefault(require("./Dropdown")))},{"./Dropdown":1606,"@babel/runtime/helpers/interopRequireDefault":13}],1613:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon")),_interopRequireDefault=function(_Component){function Embed(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Embed);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Embed)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){var onClick=_this.props.onClick,active=_this.state.active;onClick&&onClick(e,(0,_objectSpread2.default)({},_this.props,{active:!0})),active||_this.trySetState({active:!0})}),_this}return(0,_inherits2.default)(Embed,_Component),(0,_createClass2.default)(Embed,[{key:"getSrc",value:function(){var _this$props=this.props,_this$props$autoplay=_this$props.autoplay,_this$props$autoplay=void 0===_this$props$autoplay||_this$props$autoplay,_this$props$brandedUI=_this$props.brandedUI,_this$props$brandedUI=void 0!==_this$props$brandedUI&&_this$props$brandedUI,_this$props$color=_this$props.color,_this$props$color=void 0===_this$props$color?"#444444":_this$props$color,_this$props$hd=_this$props.hd,_this$props$hd=void 0===_this$props$hd||_this$props$hd,id=_this$props.id,source=_this$props.source,_this$props=_this$props.url;return"youtube"===source?["//www.youtube.com/embed/".concat(id),"?autohide=true","&amp;autoplay=".concat(_this$props$autoplay),"&amp;color=".concat(encodeURIComponent(_this$props$color)),"&amp;hq=".concat(_this$props$hd),"&amp;jsapi=false","&amp;modestbranding=".concat(_this$props$brandedUI),"&amp;rel=".concat(_this$props$brandedUI?0:1)].join(""):"vimeo"===source?["//player.vimeo.com/video/".concat(id),"?api=false","&amp;autoplay=".concat(_this$props$autoplay),"&amp;byline=false","&amp;color=".concat(encodeURIComponent(_this$props$color)),"&amp;portrait=false","&amp;title=false"].join(""):_this$props}},{key:"render",value:function(){var _this$props2=this.props,aspectRatio=_this$props2.aspectRatio,className=_this$props2.className,icon=_this$props2.icon,_this$props2=_this$props2.placeholder,active=this.state.active,aspectRatio=(0,_classnames.default)("ui",aspectRatio,(0,_lib.useKeyOnly)(active,"active"),"embed",className),active=(0,_lib.getUnhandledProps)(Embed,this.props),className=(0,_lib.getElementType)(Embed,this.props),icon=void 0!==icon?icon:"video play";return _react.default.createElement(className,(0,_extends2.default)({},active,{className:aspectRatio,onClick:this.handleClick}),_Icon.default.create(icon,{autoGenerateKey:!1}),_this$props2&&_react.default.createElement("img",{className:"placeholder",src:_this$props2}),this.renderEmbed())}},{key:"renderEmbed",value:function(){var _this$props3=this.props,children=_this$props3.children,content=_this$props3.content,iframe=_this$props3.iframe,_this$props3=_this$props3.source;return this.state.active?_lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement("div",{className:"embed"},(0,_lib.createHTMLIframe)(_lib.childrenUtils.isNil(iframe)?this.getSrc():iframe,{defaultProps:{allowFullScreen:!1,frameBorder:0,height:"100%",scrolling:"no",src:this.getSrc(),title:"Embedded content from ".concat(_this$props3,"."),width:"100%"},autoGenerateKey:!1})):_react.default.createElement("div",{className:"embed"},content):_react.default.createElement("div",{className:"embed"},children):null}}]),Embed}(_lib.AutoControlledComponent);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"autoControlledProps",["active"]),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["active","as","aspectRatio","autoplay","brandedUI","children","className","color","content","defaultActive","hd","icon","id","iframe","onClick","placeholder","source","url"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,aspectRatio:_propTypes.default.oneOf(["4:3","16:9","21:9"]),autoplay:_lib.customPropTypes.every([_lib.customPropTypes.demand(["source"]),_propTypes.default.bool]),brandedUI:_lib.customPropTypes.every([_lib.customPropTypes.demand(["source"]),_propTypes.default.bool]),children:_propTypes.default.node,className:_propTypes.default.string,color:_lib.customPropTypes.every([_lib.customPropTypes.demand(["source"]),_propTypes.default.string]),content:_lib.customPropTypes.contentShorthand,defaultActive:_propTypes.default.bool,hd:_lib.customPropTypes.every([_lib.customPropTypes.demand(["source"]),_propTypes.default.bool]),icon:_lib.customPropTypes.itemShorthand,id:_lib.customPropTypes.every([_lib.customPropTypes.demand(["source"]),_propTypes.default.string]),iframe:_lib.customPropTypes.every([_lib.customPropTypes.demand(["source"]),_lib.customPropTypes.itemShorthand]),onClick:_propTypes.default.func,placeholder:_propTypes.default.string,source:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["sourceUrl"]),_propTypes.default.oneOf(["youtube","vimeo"])]),url:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["source"]),_propTypes.default.string])}:{}}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"prop-types":1046,react:1427}],1614:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Embed=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Embed.default}}),_interopRequireDefault(require("./Embed")))},{"./Embed":1613,"@babel/runtime/helpers/interopRequireDefault":13}],1615:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_pick2=_interopRequireDefault(require("lodash/pick")),_includes2=_interopRequireDefault(require("lodash/includes")),_reduce2=_interopRequireDefault(require("lodash/reduce")),_isEmpty2=_interopRequireDefault(require("lodash/isEmpty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_shallowequal=_interopRequireDefault(require("shallowequal")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon")),_MountNode=_interopRequireDefault(require("../../addons/MountNode")),_Portal=_interopRequireDefault(require("../../addons/Portal")),_ModalHeader=_interopRequireDefault(require("./ModalHeader")),_ModalContent=_interopRequireDefault(require("./ModalContent")),_ModalActions=_interopRequireDefault(require("./ModalActions")),_interopRequireWildcard=_interopRequireDefault(require("./ModalDescription")),_utils=require("./utils"),_interopRequireDefault=function(_Component){function Modal(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Modal);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Modal)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"legacy",(0,_lib.isBrowser)()&&(0,_utils.isLegacy)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"ref",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"dimmerRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"latestDocumentMouseDownEvent",null),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getMountNode",function(){return(0,_lib.isBrowser)()?_this.props.mountNode||document.body:null}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleActionsOverrides",function(predefinedProps){return{onActionClick:function(e,actionProps){(0,_invoke2.default)(predefinedProps,"onActionClick",e,actionProps),(0,_invoke2.default)(_this.props,"onActionClick",e,_this.props),_this.handleClose(e)}}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClose",function(e){(0,_invoke2.default)(_this.props,"onClose",e,_this.props),_this.trySetState({open:!1})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleDocumentMouseDown",function(e){_this.latestDocumentMouseDownEvent=e}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleDocumentClick",function(e){var closeOnDimmerClick=_this.props.closeOnDimmerClick,currentDocumentMouseDownEvent=_this.latestDocumentMouseDownEvent;_this.latestDocumentMouseDownEvent=null,!closeOnDimmerClick||(0,_lib.doesNodeContainClick)(_this.ref.current,currentDocumentMouseDownEvent)||(0,_lib.doesNodeContainClick)(_this.ref.current,e)||((0,_invoke2.default)(_this.props,"onClose",e,_this.props),_this.trySetState({open:!1}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleIconOverrides",function(predefinedProps){return{onClick:function(e){(0,_invoke2.default)(predefinedProps,"onClick",e),_this.handleClose(e)}}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleOpen",function(e){(0,_invoke2.default)(_this.props,"onOpen",e,_this.props),_this.trySetState({open:!0})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handlePortalMount",function(e){var eventPool=_this.props.eventPool;_this.setState({scrolling:!1}),_this.setPositionAndClassNames(),_lib.eventStack.sub("mousedown",_this.handleDocumentMouseDown,{pool:eventPool,target:_this.dimmerRef.current}),_lib.eventStack.sub("click",_this.handleDocumentClick,{pool:eventPool,target:_this.dimmerRef.current}),(0,_invoke2.default)(_this.props,"onMount",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handlePortalUnmount",function(e){var eventPool=_this.props.eventPool;cancelAnimationFrame(_this.animationRequestId),_lib.eventStack.unsub("mousedown",_this.handleDocumentMouseDown,{pool:eventPool,target:_this.dimmerRef.current}),_lib.eventStack.unsub("click",_this.handleDocumentClick,{pool:eventPool,target:_this.dimmerRef.current}),(0,_invoke2.default)(_this.props,"onUnmount",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"setDimmerNodeStyle",function(){var current=_this.dimmerRef.current;current&&current.style&&"flex"!==current.style.display&&current.style.setProperty("display","flex","important")}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"setPositionAndClassNames",function(){var rect,scrolling,isFitted,_this$props=_this.props,centered=_this$props.centered,_this$props=_this$props.dimmer,newState={},centered=(_this.ref.current&&(rect=_this.ref.current.getBoundingClientRect(),scrolling=!(isFitted=(0,_utils.canFit)(rect)),isFitted=_this.legacy?(0,_utils.getLegacyStyles)(isFitted,centered,rect):{},(0,_shallowequal.default)(_this.state.legacyStyles,isFitted)||(newState.legacyStyles=isFitted),_this.state.scrolling!==scrolling)&&(newState.scrolling=scrolling),(0,_classnames.default)((0,_lib.useKeyOnly)(_this$props,"dimmable dimmed"),(0,_lib.useKeyOnly)("blurring"===_this$props," blurring"),(0,_lib.useKeyOnly)(scrolling," scrolling")));_this.state.mountClasses!==centered&&(newState.mountClasses=centered),(0,_isEmpty2.default)(newState)||_this.setState(newState),_this.animationRequestId=requestAnimationFrame(_this.setPositionAndClassNames),_this.setDimmerNodeStyle()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderContent",function(rest){var _this$props2=_this.props,actions=_this$props2.actions,basic=_this$props2.basic,children=_this$props2.children,className=_this$props2.className,closeIcon=_this$props2.closeIcon,content=_this$props2.content,header=_this$props2.header,mountNode=_this$props2.mountNode,size=_this$props2.size,_this$props2=_this$props2.style,_this$state=_this.state,legacyStyles=_this$state.legacyStyles,mountClasses=_this$state.mountClasses,_this$state=_this$state.scrolling,size=(0,_classnames.default)("ui",size,(0,_lib.useKeyOnly)(basic,"basic"),(0,_lib.useKeyOnly)(_this.legacy,"legacy"),(0,_lib.useKeyOnly)(_this$state,"scrolling"),"modal transition visible active",className),basic=(0,_lib.getElementType)(Modal,_this.props),_this$state=_Icon.default.create(!0===closeIcon?"close":closeIcon,{overrideProps:_this.handleIconOverrides});return _react.default.createElement(_reactComponentRef.Ref,{innerRef:_this.ref},_react.default.createElement(basic,(0,_extends2.default)({},rest,{className:size,style:(0,_objectSpread2.default)({},legacyStyles,_this$props2)}),_react.default.createElement(_MountNode.default,{className:mountClasses,node:mountNode}),_this$state,_lib.childrenUtils.isNil(children)?_react.default.createElement(_react.Fragment,null,_ModalHeader.default.create(header,{autoGenerateKey:!1}),_ModalContent.default.create(content,{autoGenerateKey:!1}),_ModalActions.default.create(actions,{overrideProps:_this.handleActionsOverrides})):children))}),_this}return(0,_inherits2.default)(Modal,_Component),(0,_createClass2.default)(Modal,[{key:"componentWillUnmount",value:function(){this.handlePortalUnmount()}},{key:"render",value:function(){var portalPropNames,rest,unhandled,open=this.state.open,_this$props3=this.props,centered=_this$props3.centered,closeOnDocumentClick=_this$props3.closeOnDocumentClick,dimmer=_this$props3.dimmer,eventPool=_this$props3.eventPool,_this$props3=_this$props3.trigger,mountNode=this.getMountNode();return(0,_lib.isBrowser)()?(unhandled=(0,_lib.getUnhandledProps)(Modal,this.props),portalPropNames=_Portal.default.handledProps,rest=(0,_reduce2.default)(unhandled,function(acc,val,key){return(0,_includes2.default)(portalPropNames,key)||(acc[key]=val),acc},{}),unhandled=(0,_pick2.default)(unhandled,portalPropNames),dimmer=(0,_classnames.default)("ui","inverted"===dimmer&&"inverted",!centered&&"top aligned","page modals dimmer transition visible active"),_react.default.createElement(_Portal.default,(0,_extends2.default)({closeOnDocumentClick:closeOnDocumentClick},unhandled,{trigger:_this$props3,eventPool:eventPool,mountNode:mountNode,open:open,onClose:this.handleClose,onMount:this.handlePortalMount,onOpen:this.handleOpen,onUnmount:this.handlePortalUnmount}),_react.default.createElement("div",{className:dimmer,ref:this.dimmerRef},this.renderContent(rest)))):(0,_react.isValidElement)(_this$props3)?_this$props3:null}}]),Modal}(_lib.AutoControlledComponent);(0,_defineProperty2.default)(_interopRequireDefault,"defaultProps",{centered:!0,dimmer:!0,closeOnDimmerClick:!0,closeOnDocumentClick:!1,eventPool:"Modal"}),(0,_defineProperty2.default)(_interopRequireDefault,"autoControlledProps",["open"]),(0,_defineProperty2.default)(_interopRequireDefault,"Header",_ModalHeader.default),(0,_defineProperty2.default)(_interopRequireDefault,"Content",_ModalContent.default),(0,_defineProperty2.default)(_interopRequireDefault,"Description",_interopRequireWildcard.default),(0,_defineProperty2.default)(_interopRequireDefault,"Actions",_ModalActions.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["actions","as","basic","centered","children","className","closeIcon","closeOnDimmerClick","closeOnDocumentClick","content","defaultOpen","dimmer","eventPool","header","mountNode","onActionClick","onClose","onMount","onOpen","onUnmount","open","size","style","trigger"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,actions:_lib.customPropTypes.itemShorthand,basic:_propTypes.default.bool,centered:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,closeIcon:_propTypes.default.oneOfType([_propTypes.default.node,_propTypes.default.object,_propTypes.default.bool]),closeOnDimmerClick:_propTypes.default.bool,closeOnDocumentClick:_propTypes.default.bool,content:_lib.customPropTypes.itemShorthand,defaultOpen:_propTypes.default.bool,dimmer:_propTypes.default.oneOf([!0,"inverted","blurring"]),eventPool:_propTypes.default.string,header:_lib.customPropTypes.itemShorthand,mountNode:_propTypes.default.any,onActionClick:_propTypes.default.func,onClose:_propTypes.default.func,onMount:_propTypes.default.func,onOpen:_propTypes.default.func,onUnmount:_propTypes.default.func,open:_propTypes.default.bool,size:_propTypes.default.oneOf(["mini","tiny","small","large","fullscreen"]),style:_propTypes.default.object,trigger:_propTypes.default.node}:{},exports.default=_interopRequireDefault}.call(this)}.call(this,require("_process"))},{"../../addons/MountNode":1447,"../../addons/Portal":1458,"../../elements/Icon":1527,"../../lib":1588,"./ModalActions":1616,"./ModalContent":1617,"./ModalDescription":1618,"./ModalHeader":1619,"./utils":1621,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"lodash/includes":956,"lodash/invoke":959,"lodash/isEmpty":966,"lodash/pick":996,"lodash/reduce":1001,"prop-types":1046,react:1427,shallowequal:1694}],1616:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_map2=_interopRequireDefault(require("lodash/map")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Button=_interopRequireDefault(require("../../elements/Button")),_interopRequireWildcard=function(_Component){function ModalActions(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,ModalActions);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(ModalActions)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleButtonOverrides",function(predefinedProps){return{onClick:function(e,buttonProps){(0,_invoke2.default)(predefinedProps,"onClick",e,buttonProps),(0,_invoke2.default)(_this.props,"onActionClick",e,buttonProps)}}}),_this}return(0,_inherits2.default)(ModalActions,_Component),(0,_createClass2.default)(ModalActions,[{key:"render",value:function(){var _this2=this,_this$props=this.props,actions=_this$props.actions,children=_this$props.children,className=_this$props.className,_this$props=_this$props.content,className=(0,_classnames.default)("actions",className),rest=(0,_lib.getUnhandledProps)(ModalActions,this.props),ElementType=(0,_lib.getElementType)(ModalActions,this.props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(_this$props)?_react.default.createElement(ElementType,(0,_extends2.default)({},rest,{className:className}),(0,_map2.default)(actions,function(action){return _Button.default.create(action,{overrideProps:_this2.handleButtonOverrides})})):_react.default.createElement(ElementType,(0,_extends2.default)({},rest,{className:className}),_this$props):_react.default.createElement(ElementType,(0,_extends2.default)({},rest,{className:className}),children)}}]),ModalActions}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["actions","as","children","className","content","onActionClick"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,actions:_lib.customPropTypes.collectionShorthand,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,onActionClick:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["children"]),_propTypes.default.func])}:{},_interopRequireWildcard.create=(0,_lib.createShorthandFactory)(_interopRequireWildcard,function(actions){return{actions:actions}})}.call(this)}.call(this,require("_process"))},{"../../elements/Button":1514,"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/map":989,"prop-types":1046,react:1427}],1617:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ModalContent(props){var children=props.children,className=props.className,content=props.content,image=props.image,scrolling=props.scrolling,className=(0,_classnames.default)(className,(0,_lib.useKeyOnly)(image,"image"),(0,_lib.useKeyOnly)(scrolling,"scrolling"),"content"),image=(0,_lib.getUnhandledProps)(ModalContent,props),scrolling=(0,_lib.getElementType)(ModalContent,props);return _react.default.createElement(scrolling,(0,_extends2.default)({},image,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ModalContent.handledProps=["as","children","className","content","image","scrolling"],ModalContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,image:_propTypes.default.bool,scrolling:_propTypes.default.bool}:{},ModalContent.create=(0,_lib.createShorthandFactory)(ModalContent,function(content){return{content:content}}),exports.default=ModalContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1618:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ModalDescription(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("description",className),rest=(0,_lib.getUnhandledProps)(ModalDescription,props),props=(0,_lib.getElementType)(ModalDescription,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ModalDescription.handledProps=["as","children","className","content"],ModalDescription.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=ModalDescription}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1619:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ModalHeader(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)(className,"header"),rest=(0,_lib.getUnhandledProps)(ModalHeader,props),props=(0,_lib.getElementType)(ModalHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ModalHeader.handledProps=["as","children","className","content"],ModalHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},ModalHeader.create=(0,_lib.createShorthandFactory)(ModalHeader,function(content){return{content:content}}),exports.default=ModalHeader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1620:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Modal=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Modal.default}}),_interopRequireDefault(require("./Modal")))},{"./Modal":1615,"@babel/runtime/helpers/interopRequireDefault":13}],1621:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isLegacy=exports.getLegacyStyles=exports.canFit=void 0;exports.canFit=function(modalRect){var scrollHeight=modalRect.height+0,modalRect=modalRect.height+0,contextHeight=window.innerHeight;return contextHeight/2+-modalRect/2+scrollHeight+50<contextHeight},exports.getLegacyStyles=function(isFitted,centered,modalRect){centered=centered&&isFitted?-modalRect.height/2:0;return{marginLeft:-modalRect.width/2,marginTop:centered}};exports.isLegacy=function(){return!window.ActiveXObject&&"ActiveXObject"in window}},{}],1622:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_merge2=_interopRequireDefault(require("lodash/merge")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_isArray2=_interopRequireDefault(require("lodash/isArray")),_pick2=_interopRequireDefault(require("lodash/pick")),_includes2=_interopRequireDefault(require("lodash/includes")),_reduce2=_interopRequireDefault(require("lodash/reduce")),_without2=_interopRequireDefault(require("lodash/without")),_eventStack=_interopRequireDefault(require("@semantic-ui-react/event-stack")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_reactPopper=require("react-popper"),_shallowequal=_interopRequireDefault(require("shallowequal")),_lib=require("../../lib"),_Portal=_interopRequireDefault(require("../../addons/Portal")),_positions=require("./lib/positions"),_createReferenceProxy=_interopRequireDefault(require("./lib/createReferenceProxy")),_PopupContent=_interopRequireDefault(require("./PopupContent")),_PopupHeader=_interopRequireDefault(require("./PopupHeader")),_interopRequireWildcard=function(_Component){function Popup(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Popup);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Popup)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"state",{}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"open",!1),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"triggerRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getPortalProps",function(){var portalProps={},_this$props=_this.props,on=_this$props.on,_this$props=_this$props.hoverable,on=(0,_isArray2.default)(on)?on:[on];return _this$props&&(portalProps.closeOnPortalMouseLeave=!0,portalProps.mouseLeaveDelay=300),(0,_includes2.default)(on,"hover")&&(portalProps.openOnTriggerClick=!1,portalProps.closeOnTriggerClick=!1,portalProps.openOnTriggerMouseEnter=!0,portalProps.closeOnTriggerMouseLeave=!0,portalProps.mouseLeaveDelay=70,portalProps.mouseEnterDelay=50),(0,_includes2.default)(on,"click")&&(portalProps.openOnTriggerClick=!0,portalProps.closeOnTriggerClick=!0,portalProps.closeOnDocumentClick=!0),(0,_includes2.default)(on,"focus")&&(portalProps.openOnTriggerFocus=!0,portalProps.closeOnTriggerBlur=!0),portalProps}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"hideOnScroll",function(e){_this.setState({closed:!0}),_lib.eventStack.unsub("scroll",_this.hideOnScroll,{target:window}),_this.timeoutId=setTimeout(function(){_this.setState({closed:!1})},50),_this.handleClose(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClose",function(e){(0,_invoke2.default)(_this.props,"onClose",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleOpen",function(e){(0,_invoke2.default)(_this.props,"onOpen",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handlePortalMount",function(e){(0,_invoke2.default)(_this.props,"onMount",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handlePortalUnmount",function(e){(_this.positionUpdate=null,_invoke2.default)(_this.props,"onUnmount",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderContent",function(_ref){var popperPlacement=_ref.placement,popperRef=_ref.ref,scheduleUpdate=_ref.scheduleUpdate,_ref=_ref.style,_this$props2=_this.props,basic=_this$props2.basic,children=_this$props2.children,className=_this$props2.className,content=_this$props2.content,hideOnScroll=_this$props2.hideOnScroll,flowing=_this$props2.flowing,header=_this$props2.header,inverted=_this$props2.inverted,size=_this$props2.size,style=_this$props2.style,_this$props2=_this$props2.wide,contentRestProps=_this.state.contentRestProps,scheduleUpdate=(_this.positionUpdate=scheduleUpdate,(0,_classnames.default)("ui",_positions.placementMapping[popperPlacement],size,(0,_lib.useKeyOrValueAndKey)(_this$props2,"wide"),(0,_lib.useKeyOnly)(basic,"basic"),(0,_lib.useKeyOnly)(flowing,"flowing"),(0,_lib.useKeyOnly)(inverted,"inverted"),"popup transition visible",className)),popperPlacement=(0,_lib.getElementType)(Popup,_this.props),size=(0,_objectSpread2.default)({left:"auto",right:"auto"},_ref,style);return _react.default.createElement(_reactComponentRef.Ref,{innerRef:popperRef},_react.default.createElement(popperPlacement,(0,_extends2.default)({},contentRestProps,{className:scheduleUpdate,style:size}),_lib.childrenUtils.isNil(children)?_react.default.createElement(_react.default.Fragment,null,_PopupHeader.default.create(header,{autoGenerateKey:!1}),_PopupContent.default.create(content,{autoGenerateKey:!1})):children,hideOnScroll&&_react.default.createElement(_eventStack.default,{on:_this.hideOnScroll,name:"scroll",target:"window"})))}),_this}return(0,_inherits2.default)(Popup,_Component),(0,_createClass2.default)(Popup,[{key:"componentDidUpdate",value:function(prevProps){(0,_shallowequal.default)(this.props.popperDependencies,prevProps.popperDependencies)||this.handleUpdate()}},{key:"componentWillUnmount",value:function(){clearTimeout(this.timeoutId)}},{key:"handleUpdate",value:function(){this.positionUpdate&&this.positionUpdate()}},{key:"render",value:function(){var _this$props3=this.props,context=_this$props3.context,disabled=_this$props3.disabled,eventsEnabled=_this$props3.eventsEnabled,offset=_this$props3.offset,pinned=_this$props3.pinned,popperModifiers=_this$props3.popperModifiers,position=_this$props3.position,positionFixed=_this$props3.positionFixed,_this$props3=_this$props3.trigger,_this$state=this.state,closed=_this$state.closed,_this$state=_this$state.portalRestProps;return closed||disabled?_this$props3:(closed=(0,_merge2.default)({arrow:{enabled:!1},flip:{enabled:!pinned},keepTogether:{enabled:!!offset},offset:{offset:offset}},popperModifiers),disabled=(0,_createReferenceProxy.default)((0,_isNil2.default)(context)?this.triggerRef:context),pinned=(0,_objectSpread2.default)({},this.getPortalProps(),_this$state),_react.default.createElement(_Portal.default,(0,_extends2.default)({},pinned,{onClose:this.handleClose,onMount:this.handlePortalMount,onOpen:this.handleOpen,onUnmount:this.handlePortalUnmount,trigger:_this$props3,triggerRef:this.triggerRef}),_react.default.createElement(_reactPopper.Popper,{eventsEnabled:eventsEnabled,modifiers:closed,placement:_positions.positionsMapping[position],positionFixed:positionFixed,referenceElement:disabled},this.renderContent)))}}],[{key:"getDerivedStateFromProps",value:function(props,state){return state.closed||state.disabled?{}:(state=(0,_lib.getUnhandledProps)(Popup,props),{contentRestProps:(0,_reduce2.default)(state,function(acc,val,key){return(0,_includes2.default)(_Portal.default.handledProps,key)||(acc[key]=val),acc},{}),portalRestProps:(0,_pick2.default)(state,_Portal.default.handledProps)})}}]),Popup}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{disabled:!1,eventsEnabled:!0,offset:0,on:["click","hover"],pinned:!1,position:"top left"}),(0,_defineProperty2.default)(_interopRequireWildcard,"Content",_PopupContent.default),(0,_defineProperty2.default)(_interopRequireWildcard,"Header",_PopupHeader.default),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["as","basic","children","className","content","context","disabled","eventsEnabled","flowing","header","hideOnScroll","hoverable","inverted","offset","on","onClose","onMount","onOpen","onUnmount","pinned","popperDependencies","popperModifiers","position","positionFixed","size","style","trigger","wide"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,basic:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.itemShorthand,context:_propTypes.default.oneOfType([_propTypes.default.object,_lib.customPropTypes.refObject]),disabled:_propTypes.default.bool,eventsEnabled:_propTypes.default.bool,flowing:_propTypes.default.bool,header:_lib.customPropTypes.itemShorthand,hideOnScroll:_propTypes.default.bool,hoverable:_propTypes.default.bool,inverted:_propTypes.default.bool,offset:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),on:_propTypes.default.oneOfType([_propTypes.default.oneOf(["hover","click","focus"]),_propTypes.default.arrayOf(_propTypes.default.oneOf(["hover","click","focus"]))]),onClose:_propTypes.default.func,onMount:_propTypes.default.func,onOpen:_propTypes.default.func,onUnmount:_propTypes.default.func,pinned:_propTypes.default.bool,position:_propTypes.default.oneOf(_positions.positions),positionFixed:_propTypes.default.bool,popperModifiers:_propTypes.default.object,popperDependencies:_propTypes.default.array,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium","big","massive")),style:_propTypes.default.object,trigger:_propTypes.default.node,wide:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["very"])])}:{}}.call(this)}.call(this,require("_process"))},{"../../addons/Portal":1458,"../../lib":1588,"./PopupContent":1623,"./PopupHeader":1624,"./lib/createReferenceProxy":1626,"./lib/positions":1627,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@semantic-ui-react/event-stack":36,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"lodash/includes":956,"lodash/invoke":959,"lodash/isArray":961,"lodash/isNil":972,"lodash/merge":992,"lodash/pick":996,"lodash/reduce":1001,"lodash/without":1028,"prop-types":1046,react:1427,"react-popper":1389,shallowequal:1694}],1623:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=PopupContent,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function PopupContent(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("content",className),rest=(0,_lib.getUnhandledProps)(PopupContent,props),props=(0,_lib.getElementType)(PopupContent,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}PopupContent.handledProps=["as","children","className","content"],PopupContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},PopupContent.create=(0,_lib.createShorthandFactory)(PopupContent,function(children){return{children:children}})}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1624:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=PopupHeader,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function PopupHeader(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("header",className),rest=(0,_lib.getUnhandledProps)(PopupHeader,props),props=(0,_lib.getElementType)(PopupHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}PopupHeader.handledProps=["as","children","className","content"],PopupHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},PopupHeader.create=(0,_lib.createShorthandFactory)(PopupHeader,function(children){return{children:children}})}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1625:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Popup=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Popup.default}}),_interopRequireDefault(require("./Popup")))},{"./Popup":1622,"@babel/runtime/helpers/interopRequireDefault":13}],1626:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_classCallCheck2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"))),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_memoize2=_interopRequireDefault(require("lodash/memoize")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_reactComponentRef=require("@stardust-ui/react-component-ref"),ReferenceProxy=function(){function ReferenceProxy(refObject){(0,_classCallCheck2.default)(this,ReferenceProxy),this.ref=refObject}return(0,_createClass2.default)(ReferenceProxy,[{key:"getBoundingClientRect",value:function(){return(0,_invoke2.default)(this.ref.current,"getBoundingClientRect",{})}},{key:"clientWidth",get:function(){return this.getBoundingClientRect().width}},{key:"clientHeight",get:function(){return this.getBoundingClientRect().height}},{key:"parentNode",get:function(){return this.ref.current?this.ref.current.parentNode:void 0}}]),ReferenceProxy}(),_interopRequireDefault=(0,_memoize2.default)(function(reference){return new ReferenceProxy((0,_reactComponentRef.isRefObject)(reference)?reference:(0,_reactComponentRef.toRefObject)(reference))});exports.default=_interopRequireDefault},{"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/interopRequireDefault":13,"@stardust-ui/react-component-ref":107,"lodash/invoke":959,"lodash/memoize":991}],1627:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_invert2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.placementMapping=exports.positions=exports.positionsMapping=void 0,_interopRequireDefault(require("lodash/invert"))),_interopRequireDefault=_interopRequireDefault(require("lodash/keys")),require={"top center":"top","top left":"top-start","top right":"top-end","bottom center":"bottom","bottom left":"bottom-start","bottom right":"bottom-end","right center":"right","left center":"left"},_interopRequireDefault=(exports.positionsMapping=require,(0,_interopRequireDefault.default)(require)),_interopRequireDefault=(exports.positions=_interopRequireDefault,(0,_invert2.default)(require));exports.placementMapping=_interopRequireDefault},{"@babel/runtime/helpers/interopRequireDefault":13,"lodash/invert":958,"lodash/keys":986}],1628:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_round2=_interopRequireDefault(require("lodash/round")),_clamp2=_interopRequireDefault(require("lodash/clamp")),_isUndefined2=_interopRequireDefault(require("lodash/isUndefined")),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function Progress(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Progress);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Progress)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"calculatePercent",function(){var _this$props=_this.props,percent=_this$props.percent,total=_this$props.total,_this$props=_this$props.value;return(0,_isUndefined2.default)(percent)?(0,_isUndefined2.default)(total)||(0,_isUndefined2.default)(_this$props)?void 0:_this$props/total*100:percent}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeValueText",function(percent){var _this$props2=_this.props,progress=_this$props2.progress,total=_this$props2.total,_this$props2=_this$props2.value;return"value"===progress?_this$props2:"ratio"===progress?"".concat(_this$props2,"/").concat(total):"".concat(percent,"%")}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getPercent",function(){var _this$props3=_this.props,precision=_this$props3.precision,progress=_this$props3.progress,total=_this$props3.total,_this$props3=_this$props3.value,percent=(0,_clamp2.default)(_this.calculatePercent(),0,100);return(0,_isUndefined2.default)(total)||(0,_isUndefined2.default)(_this$props3)||"value"!==progress?"value"===progress?_this$props3:(0,_isUndefined2.default)(precision)?percent:(0,_round2.default)(percent,precision):_this$props3/total*100}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"isAutoSuccess",function(){var _this$props4=_this.props,autoSuccess=_this$props4.autoSuccess,percent=_this$props4.percent,total=_this$props4.total,_this$props4=_this$props4.value;return autoSuccess&&(100<=percent||total<=_this$props4)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderLabel",function(){var _this$props5=_this.props,children=_this$props5.children,content=_this$props5.content,_this$props5=_this$props5.label;return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?(0,_lib.createHTMLDivision)(_this$props5,{autoGenerateKey:!1,defaultProps:{className:"label"}}):_react.default.createElement("div",{className:"label"},content):_react.default.createElement("div",{className:"label"},children)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderProgress",function(percent){var _this$props6=_this.props,precision=_this$props6.precision,_this$props6=_this$props6.progress;if(_this$props6||!(0,_isUndefined2.default)(precision))return _react.default.createElement("div",{className:"progress"},_this.computeValueText(percent))}),_this}return(0,_inherits2.default)(Progress,_Component),(0,_createClass2.default)(Progress,[{key:"render",value:function(){var _this$props7=this.props,active=_this$props7.active,attached=_this$props7.attached,className=_this$props7.className,color=_this$props7.color,disabled=_this$props7.disabled,error=_this$props7.error,indicating=_this$props7.indicating,inverted=_this$props7.inverted,size=_this$props7.size,success=_this$props7.success,_this$props7=_this$props7.warning,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(active||indicating,"active"),(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(error,"error"),(0,_lib.useKeyOnly)(indicating,"indicating"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useKeyOnly)(success||this.isAutoSuccess(),"success"),(0,_lib.useKeyOnly)(_this$props7,"warning"),(0,_lib.useValueAndKey)(attached,"attached"),"progress",className),size=(0,_lib.getUnhandledProps)(Progress,this.props),active=(0,_lib.getElementType)(Progress,this.props),disabled=this.getPercent()||0;return _react.default.createElement(active,(0,_extends2.default)({},size,{className:color,"data-percent":Math.floor(disabled)}),_react.default.createElement("div",{className:"bar",style:{width:"".concat(disabled,"%")}},this.renderProgress(disabled)),this.renderLabel())}}]),Progress}(_react.Component);(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","attached","autoSuccess","children","className","color","content","disabled","error","indicating","inverted","label","percent","precision","progress","size","success","total","value","warning"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,active:_interopRequireDefault.default.bool,attached:_interopRequireDefault.default.oneOf(["top","bottom"]),autoSuccess:_interopRequireDefault.default.bool,children:_interopRequireDefault.default.node,className:_interopRequireDefault.default.string,color:_interopRequireDefault.default.oneOf(_lib.SUI.COLORS),content:_lib.customPropTypes.contentShorthand,disabled:_interopRequireDefault.default.bool,error:_interopRequireDefault.default.bool,indicating:_interopRequireDefault.default.bool,inverted:_interopRequireDefault.default.bool,label:_lib.customPropTypes.itemShorthand,percent:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["total","value"]),_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string])]),precision:_interopRequireDefault.default.number,progress:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.bool,_interopRequireDefault.default.oneOf(["percent","ratio","value"])]),size:_interopRequireDefault.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"mini","huge","massive")),success:_interopRequireDefault.default.bool,total:_lib.customPropTypes.every([_lib.customPropTypes.demand(["value"]),_lib.customPropTypes.disallow(["percent"]),_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string])]),value:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["percent"]),_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string])]),warning:_interopRequireDefault.default.bool}:{},exports.default=_interopRequireWildcard}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/clamp":902,"lodash/isUndefined":982,"lodash/round":1002,"lodash/without":1028,"prop-types":1046,react:1427}],1629:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Progress=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Progress.default}}),_interopRequireDefault(require("./Progress")))},{"./Progress":1628,"@babel/runtime/helpers/interopRequireDefault":13}],1630:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_times2=_interopRequireDefault(require("lodash/times")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_RatingIcon=_interopRequireDefault(require("./RatingIcon")),_interopRequireDefault=function(_Component){function Rating(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Rating);for(var _len=arguments.length,_args=new Array(_len),_key=0;_key<_len;_key++)_args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Rating)).call.apply(_getPrototypeOf2,[this].concat(_args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleIconClick",function(e,_ref){var _ref=_ref.index,_this$props=_this.props,clearable=_this$props.clearable,disabled=_this$props.disabled,maxRating=_this$props.maxRating,_this$props=_this$props.onRate,rating=_this.state.rating;disabled||(disabled=_ref+1,"auto"===clearable&&1===maxRating?disabled=+!rating:!0===clearable&&disabled===rating&&(disabled=0),_this.trySetState({rating:disabled,isSelecting:!1}),_this$props&&_this$props(e,(0,_objectSpread2.default)({},_this.props,{rating:disabled})))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleIconMouseEnter",function(e,_ref2){_ref2=_ref2.index;_this.props.disabled||_this.setState({selectedIndex:_ref2,isSelecting:!0})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleMouseLeave",function(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];_invoke2.default.apply(void 0,[_this.props,"onMouseLeave"].concat(args)),_this.props.disabled||_this.setState({selectedIndex:-1,isSelecting:!1})}),_this}return(0,_inherits2.default)(Rating,_Component),(0,_createClass2.default)(Rating,[{key:"render",value:function(){var _this2=this,_this$props2=this.props,className=_this$props2.className,disabled=_this$props2.disabled,icon=_this$props2.icon,maxRating=_this$props2.maxRating,_this$props2=_this$props2.size,_this$state=this.state,rating=_this$state.rating,selectedIndex=_this$state.selectedIndex,isSelecting=_this$state.isSelecting,_this$state=(0,_classnames.default)("ui",icon,_this$props2,(0,_lib.useKeyOnly)(disabled,"disabled"),(0,_lib.useKeyOnly)(isSelecting&&!disabled&&0<=selectedIndex,"selected"),"rating",className),icon=(0,_lib.getUnhandledProps)(Rating,this.props),_this$props2=(0,_lib.getElementType)(Rating,this.props);return _react.default.createElement(_this$props2,(0,_extends2.default)({},icon,{className:_this$state,role:"radiogroup",onMouseLeave:this.handleMouseLeave,tabIndex:disabled?0:-1}),(0,_times2.default)(maxRating,function(i){return _react.default.createElement(_RatingIcon.default,{tabIndex:disabled?-1:0,active:i+1<=rating,"aria-checked":rating===i+1,"aria-posinset":i+1,"aria-setsize":maxRating,index:i,key:i,onClick:_this2.handleIconClick,onMouseEnter:_this2.handleIconMouseEnter,selected:i<=selectedIndex&&isSelecting})}))}}]),Rating}(_lib.AutoControlledComponent);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"autoControlledProps",["rating"]),(0,_defineProperty2.default)(_interopRequireDefault,"defaultProps",{clearable:"auto",maxRating:1}),(0,_defineProperty2.default)(_interopRequireDefault,"Icon",_RatingIcon.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["as","className","clearable","defaultRating","disabled","icon","maxRating","onRate","rating","size"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,className:_propTypes.default.string,clearable:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["auto"])]),defaultRating:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),disabled:_propTypes.default.bool,icon:_propTypes.default.oneOf(["star","heart"]),maxRating:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),onRate:_propTypes.default.func,rating:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium","big"))}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./RatingIcon":1631,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/invoke":959,"lodash/times":1014,"lodash/without":1028,"prop-types":1046,react:1427}],1631:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_keyboardKey=_interopRequireDefault(require("keyboard-key")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function RatingIcon(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,RatingIcon);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(RatingIcon)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleKeyUp",function(e){switch((0,_invoke2.default)(_this.props,"onKeyUp",e,_this.props),_keyboardKey.default.getCode(e)){case _keyboardKey.default.Enter:case _keyboardKey.default.Spacebar:e.preventDefault(),(0,_invoke2.default)(_this.props,"onClick",e,_this.props)}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleMouseEnter",function(e){(0,_invoke2.default)(_this.props,"onMouseEnter",e,_this.props)}),_this}return(0,_inherits2.default)(RatingIcon,_Component),(0,_createClass2.default)(RatingIcon,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,className=_this$props.className,_this$props=_this$props.selected,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(_this$props,"selected"),"icon",className),_this$props=(0,_lib.getUnhandledProps)(RatingIcon,this.props),className=(0,_lib.getElementType)(RatingIcon,this.props);return _react.default.createElement(className,(0,_extends2.default)({},_this$props,{className:active,onClick:this.handleClick,onKeyUp:this.handleKeyUp,onMouseEnter:this.handleMouseEnter,role:"radio"}))}}]),RatingIcon}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{as:"i"}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","className","index","onClick","onKeyUp","onMouseEnter","selected"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,active:_interopRequireDefault.default.bool,className:_interopRequireDefault.default.string,index:_interopRequireDefault.default.number,onClick:_interopRequireDefault.default.func,onKeyUp:_interopRequireDefault.default.func,onMouseEnter:_interopRequireDefault.default.func,selected:_interopRequireDefault.default.bool}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"keyboard-key":662,"lodash/invoke":959,"prop-types":1046,react:1427}],1632:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Rating=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Rating.default}}),_interopRequireDefault(require("./Rating")))},{"./Rating":1630,"@babel/runtime/helpers/interopRequireDefault":13}],1633:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_slicedToArray2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_objectWithoutProperties2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_get3=_interopRequireDefault(require("@babel/runtime/helpers/get")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_isEmpty2=_interopRequireDefault(require("lodash/isEmpty")),_partialRight2=_interopRequireDefault(require("lodash/partialRight")),_inRange2=_interopRequireDefault(require("lodash/inRange")),_map2=_interopRequireDefault(require("lodash/map")),_get4=_interopRequireDefault(require("lodash/get")),_reduce2=_interopRequireDefault(require("lodash/reduce")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_keyboardKey=_interopRequireDefault(require("keyboard-key")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_shallowequal=_interopRequireDefault(require("shallowequal")),_lib=require("../../lib"),_Input=_interopRequireDefault(require("../../elements/Input")),_SearchCategory=_interopRequireDefault(require("./SearchCategory")),_SearchResult=_interopRequireDefault(require("./SearchResult")),_SearchResults=_interopRequireDefault(require("./SearchResults")),_interopRequireDefault=function(_Component){function Search(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Search);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Search)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleResultSelect",function(e,result){(0,_invoke2.default)(_this.props,"onResultSelect",e,(0,_objectSpread2.default)({},_this.props,{result:result}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleSelectionChange",function(e){var result=_this.getSelectedResult();(0,_invoke2.default)(_this.props,"onSelectionChange",e,(0,_objectSpread2.default)({},_this.props,{result:result}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"closeOnEscape",function(e){_keyboardKey.default.getCode(e)===_keyboardKey.default.Escape&&(e.preventDefault(),_this.close())}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"moveSelectionOnKeyDown",function(e){switch(_keyboardKey.default.getCode(e)){case _keyboardKey.default.ArrowDown:e.preventDefault(),_this.moveSelectionBy(e,1);break;case _keyboardKey.default.ArrowUp:e.preventDefault(),_this.moveSelectionBy(e,-1)}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"selectItemOnEnter",function(e){var result;_keyboardKey.default.getCode(e)===_keyboardKey.default.Enter&&(result=_this.getSelectedResult())&&(e.preventDefault(),_this.setValue(result.title),_this.handleResultSelect(e,result),_this.close())}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"closeOnDocumentClick",function(e){_this.close()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleMouseDown",function(e){_this.isMouseDown=!0,(0,_invoke2.default)(_this.props,"onMouseDown",e,_this.props),_lib.eventStack.sub("mouseup",_this.handleDocumentMouseUp)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleDocumentMouseUp",function(){_this.isMouseDown=!1,_lib.eventStack.unsub("mouseup",_this.handleDocumentMouseUp)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleInputClick",function(e){e.nativeEvent.stopImmediatePropagation(),_this.tryOpen()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleItemClick",function(e,_ref){_ref=_ref.id,_ref=_this.getSelectedResult(_ref);e.nativeEvent.stopImmediatePropagation(),_this.setValue(_ref.title),_this.handleResultSelect(e,_ref),_this.close()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleItemMouseDown",function(e){e.preventDefault()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleFocus",function(e){(0,_invoke2.default)(_this.props,"onFocus",e,_this.props),_this.setState({focus:!0})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleBlur",function(e){(0,_invoke2.default)(_this.props,"onBlur",e,_this.props),_this.setState({focus:!1})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleSearchChange",function(e){e.stopPropagation();var minCharacters=_this.props.minCharacters,open=_this.state.open,newQuery=e.target.value;(0,_invoke2.default)(_this.props,"onSearchChange",e,(0,_objectSpread2.default)({},_this.props,{value:newQuery})),newQuery.length<minCharacters?_this.close():open||_this.tryOpen(newQuery),_this.setValue(newQuery)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getFlattenedResults",function(){var _this$props=_this.props,category=_this$props.category,_this$props=_this$props.results;return category?(0,_reduce2.default)(_this$props,function(memo,categoryData){return memo.concat(categoryData.results)},[]):_this$props}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"getSelectedResult",function(){var index=0<arguments.length&&void 0!==arguments[0]?arguments[0]:_this.state.selectedIndex,results=_this.getFlattenedResults();return(0,_get4.default)(results,index)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"setValue",function(value){var selectFirstResult=_this.props.selectFirstResult;_this.trySetState({value:value,selectedIndex:selectFirstResult?0:-1})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"moveSelectionBy",function(e,offset){var selectedIndex=_this.state.selectedIndex,lastIndex=_this.getFlattenedResults().length-1,selectedIndex=selectedIndex+offset;lastIndex<selectedIndex?selectedIndex=0:selectedIndex<0&&(selectedIndex=lastIndex),_this.setState({selectedIndex:selectedIndex}),_this.scrollSelectedItemIntoView(),_this.handleSelectionChange(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"scrollSelectedItemIntoView",function(){var menu,item,isOutOfUpperView,isOutOfLowerView;(0,_lib.isBrowser)()&&(item=(menu=document.querySelector(".ui.search.active.visible .results.visible")).querySelector(".result.active"))&&(isOutOfUpperView=item.offsetTop<menu.scrollTop,isOutOfLowerView=item.offsetTop+item.clientHeight>menu.scrollTop+menu.clientHeight,isOutOfUpperView?menu.scrollTop=item.offsetTop:isOutOfLowerView&&(menu.scrollTop=item.offsetTop+item.clientHeight-menu.clientHeight))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"tryOpen",function(){var currentValue=0<arguments.length&&void 0!==arguments[0]?arguments[0]:_this.state.value,minCharacters=_this.props.minCharacters;currentValue.length<minCharacters||_this.open()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"open",function(){_this.trySetState({open:!0})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"close",function(){_this.trySetState({open:!1})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderSearchInput",function(rest){var _this$props2=_this.props,icon=_this$props2.icon,_this$props2=_this$props2.input,value=_this.state.value;return _Input.default.create(_this$props2,{autoGenerateKey:!1,defaultProps:(0,_objectSpread2.default)({},rest,{icon:icon,input:{className:"prompt",tabIndex:"0",autoComplete:"off"},onChange:_this.handleSearchChange,onClick:_this.handleInputClick,value:value})})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderNoResults",function(){var _this$props3=_this.props,noResultsDescription=_this$props3.noResultsDescription,_this$props3=_this$props3.noResultsMessage;return _react.default.createElement("div",{className:"message empty"},_react.default.createElement("div",{className:"header"},_this$props3),noResultsDescription&&_react.default.createElement("div",{className:"description"},noResultsDescription))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderResult",function(_ref2,index,_array){var childKey=_ref2.childKey,_ref2=(0,_objectWithoutProperties2.default)(_ref2,["childKey"]),resultRenderer=_this.props.resultRenderer,selectedIndex=_this.state.selectedIndex,index=index+(3<arguments.length&&void 0!==arguments[3]?arguments[3]:0);return _react.default.createElement(_SearchResult.default,(0,_extends2.default)({key:childKey||_ref2.id||_ref2.title,active:selectedIndex===index,onClick:_this.handleItemClick,onMouseDown:_this.handleItemMouseDown,renderer:resultRenderer},_ref2,{id:index}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderResults",function(){var results=_this.props.results;return(0,_map2.default)(results,_this.renderResult)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderCategories",function(){var _this$props4=_this.props,categoryLayoutRenderer=_this$props4.categoryLayoutRenderer,categoryRenderer=_this$props4.categoryRenderer,_this$props4=_this$props4.results,selectedIndex=_this.state.selectedIndex,count=0;return(0,_map2.default)(_this$props4,function(_ref3){var childKey=_ref3.childKey,_ref3=(0,_objectWithoutProperties2.default)(_ref3,["childKey"]),childKey=(0,_objectSpread2.default)({key:childKey||_ref3.name,active:(0,_inRange2.default)(selectedIndex,count,count+_ref3.results.length),layoutRenderer:categoryLayoutRenderer,renderer:categoryRenderer},_ref3),renderFn=(0,_partialRight2.default)(_this.renderResult,count);return count+=_ref3.results.length,_react.default.createElement(_SearchCategory.default,childKey,_ref3.results.map(renderFn))})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderMenuContent",function(){var _this$props5=_this.props,category=_this$props5.category,showNoResults=_this$props5.showNoResults,_this$props5=_this$props5.results;return(0,_isEmpty2.default)(_this$props5)?showNoResults?_this.renderNoResults():null:category?_this.renderCategories():_this.renderResults()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"renderResultsMenu",function(){var resultsClasses=_this.state.open?"visible":"",menuContent=_this.renderMenuContent();if(menuContent)return _react.default.createElement(_SearchResults.default,{className:resultsClasses},menuContent)}),_this}return(0,_inherits2.default)(Search,_Component),(0,_createClass2.default)(Search,[{key:"UNSAFE_componentWillMount",value:function(){var _this$state=this.state,open=_this$state.open,_this$state=_this$state.value;this.setValue(_this$state),open&&this.open()}},{key:"UNSAFE_componentWillReceiveProps",value:function(nextProps){(0,_get3.default)((0,_getPrototypeOf3.default)(Search.prototype),"UNSAFE_componentWillReceiveProps",this).call(this,nextProps),(0,_shallowequal.default)(nextProps.value,this.props.value)||this.setValue(nextProps.value)}},{key:"shouldComponentUpdate",value:function(nextProps,nextState){return!(0,_shallowequal.default)(nextProps,this.props)||!(0,_shallowequal.default)(nextState,this.state)}},{key:"componentDidUpdate",value:function(prevProps,prevState){!prevState.focus&&this.state.focus?(this.isMouseDown||this.tryOpen(),this.state.open&&_lib.eventStack.sub("keydown",[this.moveSelectionOnKeyDown,this.selectItemOnEnter])):prevState.focus&&!this.state.focus&&(this.isMouseDown||this.close(),_lib.eventStack.unsub("keydown",[this.moveSelectionOnKeyDown,this.selectItemOnEnter])),!prevState.open&&this.state.open?(this.open(),_lib.eventStack.sub("click",this.closeOnDocumentClick),_lib.eventStack.sub("keydown",[this.closeOnEscape,this.moveSelectionOnKeyDown,this.selectItemOnEnter])):prevState.open&&!this.state.open&&(this.close(),_lib.eventStack.unsub("click",this.closeOnDocumentClick),_lib.eventStack.unsub("keydown",[this.closeOnEscape,this.moveSelectionOnKeyDown,this.selectItemOnEnter]))}},{key:"componentWillUnmount",value:function(){_lib.eventStack.unsub("click",this.closeOnDocumentClick),_lib.eventStack.unsub("keydown",[this.closeOnEscape,this.moveSelectionOnKeyDown,this.selectItemOnEnter])}},{key:"render",value:function(){var _this$state2=this.state,searchClasses=_this$state2.searchClasses,focus=_this$state2.focus,_this$state2=_this$state2.open,_this$props6=this.props,aligned=_this$props6.aligned,category=_this$props6.category,className=_this$props6.className,fluid=_this$props6.fluid,loading=_this$props6.loading,_this$props6=_this$props6.size,_this$state2=(0,_classnames.default)("ui",_this$state2&&"active visible",_this$props6,searchClasses,(0,_lib.useKeyOnly)(category,"category"),(0,_lib.useKeyOnly)(focus,"focus"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(loading,"loading"),(0,_lib.useValueAndKey)(aligned,"aligned"),"search",className),_this$props6=(0,_lib.getUnhandledProps)(Search,this.props),searchClasses=(0,_lib.getElementType)(Search,this.props),category=(0,_lib.partitionHTMLProps)(_this$props6,{htmlProps:_lib.htmlInputAttrs}),focus=(0,_slicedToArray2.default)(category,2),fluid=focus[0],loading=focus[1];return _react.default.createElement(searchClasses,(0,_extends2.default)({},loading,{className:_this$state2,onBlur:this.handleBlur,onFocus:this.handleFocus,onMouseDown:this.handleMouseDown}),this.renderSearchInput(fluid),this.renderResultsMenu())}}]),Search}(_lib.AutoControlledComponent);exports.default=_interopRequireDefault,(0,_defineProperty2.default)(_interopRequireDefault,"defaultProps",{icon:"search",input:"text",minCharacters:1,noResultsMessage:"No results found.",showNoResults:!0}),(0,_defineProperty2.default)(_interopRequireDefault,"autoControlledProps",["open","value"]),(0,_defineProperty2.default)(_interopRequireDefault,"Category",_SearchCategory.default),(0,_defineProperty2.default)(_interopRequireDefault,"Result",_SearchResult.default),(0,_defineProperty2.default)(_interopRequireDefault,"Results",_SearchResults.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["aligned","as","category","categoryLayoutRenderer","categoryRenderer","className","defaultOpen","defaultValue","fluid","icon","input","loading","minCharacters","noResultsDescription","noResultsMessage","onBlur","onFocus","onMouseDown","onResultSelect","onSearchChange","onSelectionChange","open","resultRenderer","results","selectFirstResult","showNoResults","size","value"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,defaultOpen:_propTypes.default.bool,defaultValue:_propTypes.default.string,icon:_propTypes.default.oneOfType([_propTypes.default.node,_propTypes.default.object]),minCharacters:_propTypes.default.number,noResultsDescription:_propTypes.default.node,noResultsMessage:_propTypes.default.node,open:_propTypes.default.bool,results:_propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.shape(_SearchResult.default.propTypes)),_propTypes.default.shape(_SearchCategory.default.propTypes)]),selectFirstResult:_propTypes.default.bool,showNoResults:_propTypes.default.bool,value:_propTypes.default.string,categoryLayoutRenderer:_propTypes.default.func,categoryRenderer:_propTypes.default.func,resultRenderer:_propTypes.default.func,onBlur:_propTypes.default.func,onFocus:_propTypes.default.func,onMouseDown:_propTypes.default.func,onResultSelect:_propTypes.default.func,onSearchChange:_propTypes.default.func,onSelectionChange:_propTypes.default.func,aligned:_propTypes.default.string,category:_propTypes.default.bool,className:_propTypes.default.string,fluid:_propTypes.default.bool,input:_lib.customPropTypes.itemShorthand,loading:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium"))}:{}}.call(this)}.call(this,require("_process"))},{"../../elements/Input":1532,"../../lib":1588,"./SearchCategory":1634,"./SearchResult":1636,"./SearchResults":1637,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/get":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/objectWithoutProperties":21,"@babel/runtime/helpers/possibleConstructorReturn":23,"@babel/runtime/helpers/slicedToArray":25,_process:1042,classnames:116,"keyboard-key":662,"lodash/get":950,"lodash/inRange":955,"lodash/invoke":959,"lodash/isEmpty":966,"lodash/map":989,"lodash/partialRight":995,"lodash/reduce":1001,"lodash/without":1028,"prop-types":1046,react:1427,shallowequal:1694}],1634:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_interopRequireDefault=_interopRequireDefault(require("./SearchCategoryLayout"));function SearchCategory(props){var active=props.active,children=props.children,className=props.className,content=props.content,layoutRenderer=props.layoutRenderer,renderer=props.renderer,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),"category",className),className=(0,_lib.getUnhandledProps)(SearchCategory,props),ElementType=(0,_lib.getElementType)(SearchCategory,props),renderer=renderer(props),props=_lib.childrenUtils.isNil(children)?content:children;return _react.default.createElement(ElementType,(0,_extends2.default)({},className,{className:active}),layoutRenderer({categoryContent:renderer,resultsContent:props}))}SearchCategory.handledProps=["active","as","children","className","content","layoutRenderer","name","renderer","results"],SearchCategory.defaultProps={layoutRenderer:_interopRequireDefault.default,renderer:function(_ref){return _ref.name}},SearchCategory.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,name:_propTypes.default.string,layoutRenderer:_propTypes.default.func,renderer:_propTypes.default.func,results:_propTypes.default.array}:{},exports.default=SearchCategory}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./SearchCategoryLayout":1635,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1635:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_propTypes=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("prop-types"))),_react=_interopRequireDefault(require("react"));function SearchCategoryLayout(props){var categoryContent=props.categoryContent,props=props.resultsContent;return _react.default.createElement(_react.default.Fragment,null,_react.default.createElement("div",{className:"name"},categoryContent),_react.default.createElement("div",{className:"results"},props))}SearchCategoryLayout.handledProps=["categoryContent","resultsContent"],SearchCategoryLayout.propTypes="production"!==process.env.NODE_ENV?{categoryContent:_propTypes.default.element.isRequired,resultsContent:_propTypes.default.element.isRequired}:{},exports.default=SearchCategoryLayout}.call(this)}.call(this,require("_process"))},{"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,"prop-types":1046,react:1427}],1636:[function(require,module,exports){!function(process){!function(){"use strict";function defaultRenderer(_ref){var image=_ref.image,price=_ref.price,title=_ref.title,_ref=_ref.description;return[image&&_react.default.createElement("div",{key:"image",className:"image"},(0,_lib.createHTMLImage)(image,{autoGenerateKey:!1})),_react.default.createElement("div",{key:"content",className:"content"},price&&_react.default.createElement("div",{className:"price"},price),title&&_react.default.createElement("div",{className:"title"},title),_ref&&_react.default.createElement("div",{className:"description"},_ref))]}var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_classnames=_interopRequireDefault(require("classnames")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=(defaultRenderer.handledProps=[],function(_Component){function SearchResult(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,SearchResult);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(SearchResult)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){var onClick=_this.props.onClick;onClick&&onClick(e,_this.props)}),_this}return(0,_inherits2.default)(SearchResult,_Component),(0,_createClass2.default)(SearchResult,[{key:"render",value:function(){var _this$props=this.props,active=_this$props.active,className=_this$props.className,_this$props=_this$props.renderer,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),"result",className),className=(0,_lib.getUnhandledProps)(SearchResult,this.props),ElementType=(0,_lib.getElementType)(SearchResult,this.props);return _react.default.createElement(ElementType,(0,_extends2.default)({},className,{className:active,onClick:this.handleClick}),_this$props(this.props))}}]),SearchResult}(_react.Component));exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{renderer:defaultRenderer}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","className","content","description","id","image","onClick","price","renderer","title"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,active:_interopRequireDefault.default.bool,className:_interopRequireDefault.default.string,content:_lib.customPropTypes.contentShorthand,description:_interopRequireDefault.default.string,id:_interopRequireDefault.default.oneOfType([_interopRequireDefault.default.number,_interopRequireDefault.default.string]),image:_interopRequireDefault.default.string,onClick:_interopRequireDefault.default.func,price:_interopRequireDefault.default.string,renderer:_interopRequireDefault.default.func,title:_interopRequireDefault.default.string.isRequired}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"prop-types":1046,react:1427}],1637:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function SearchResults(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("results transition",className),rest=(0,_lib.getUnhandledProps)(SearchResults,props),props=(0,_lib.getElementType)(SearchResults,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}SearchResults.handledProps=["as","children","className","content"],SearchResults.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=SearchResults}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1638:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Search=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Search.default}}),_interopRequireDefault(require("./Search")))},{"./Search":1633,"@babel/runtime/helpers/interopRequireDefault":13}],1639:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_reactComponentEventListener=require("@stardust-ui/react-component-event-listener"),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=_interopRequireDefault(require("./SidebarPushable")),_interopRequireDefault=_interopRequireDefault(require("./SidebarPusher")),Sidebar=function(_Component){function Sidebar(props){var _this;return(0,_classCallCheck2.default)(this,Sidebar),_this=(0,_possibleConstructorReturn2.default)(this,(0,_getPrototypeOf2.default)(Sidebar).call(this,props)),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"ref",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleAnimationStart",function(){var callback=_this.props.visible?"onVisible":"onHide";clearTimeout(_this.animationTimer),_this.animationTimer=setTimeout(_this.handleAnimationEnd,Sidebar.animationDuration),_this.skipNextCallback?_this.skipNextCallback=!1:(0,_invoke2.default)(_this.props,callback,null,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleAnimationEnd",function(){var callback=_this.props.visible?"onShow":"onHidden";_this.setState({animationTick:0}),(0,_invoke2.default)(_this.props,callback,null,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleDocumentClick",function(e){(0,_lib.doesNodeContainClick)(_this.ref.current,e)||(_this.skipNextCallback=!0,(0,_invoke2.default)(_this.props,"onHide",e,(0,_objectSpread2.default)({},_this.props,{visible:!1})))}),_this.state={animationTick:0,visible:props.visible},_this}return(0,_inherits2.default)(Sidebar,_Component),(0,_createClass2.default)(Sidebar,[{key:"componentDidUpdate",value:function(prevProps,prevState){this.state.animationTick>prevState.animationTick&&this.handleAnimationStart()}},{key:"componentWillUnmount",value:function(){clearTimeout(this.animationTimer)}},{key:"render",value:function(){var _this$props=this.props,animation=_this$props.animation,className=_this$props.className,children=_this$props.children,content=_this$props.content,direction=_this$props.direction,target=_this$props.target,visible=_this$props.visible,_this$props=_this$props.width,animationTick=this.state.animationTick,animation=(0,_classnames.default)("ui",animation,direction,_this$props,(0,_lib.useKeyOnly)(0<animationTick,"animating"),(0,_lib.useKeyOnly)(visible,"visible"),"sidebar",className),direction=(0,_lib.getUnhandledProps)(Sidebar,this.props),_this$props=(0,_lib.getElementType)(Sidebar,this.props),animationTick=(0,_reactComponentRef.isRefObject)(target)?target:(0,_reactComponentRef.toRefObject)(target);return _react.default.createElement(_reactComponentRef.Ref,{innerRef:this.ref},_react.default.createElement(_this$props,(0,_extends2.default)({},direction,{className:animation}),_lib.childrenUtils.isNil(children)?content:children,visible&&_react.default.createElement(_reactComponentEventListener.EventListener,{listener:this.handleDocumentClick,targetRef:animationTick,type:"click"})))}}],[{key:"getDerivedStateFromProps",value:function(props,state){var tickIncrement=!!props.visible==!!state.visible?0:1;return{animationTick:state.animationTick+tickIncrement,visible:props.visible}}}]),Sidebar}(_react.Component);(0,_defineProperty2.default)(Sidebar,"defaultProps",{direction:"left",target:_reactComponentEventListener.documentRef,visible:!1}),(0,_defineProperty2.default)(Sidebar,"animationDuration",500),(0,_defineProperty2.default)(Sidebar,"autoControlledProps",["visible"]),(0,_defineProperty2.default)(Sidebar,"Pushable",_interopRequireWildcard.default),(0,_defineProperty2.default)(Sidebar,"Pusher",_interopRequireDefault.default),(0,_defineProperty2.default)(Sidebar,"handledProps",["animation","as","children","className","content","direction","onHidden","onHide","onShow","onVisible","target","visible","width"]),Sidebar.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,animation:_propTypes.default.oneOf(["overlay","push","scale down","uncover","slide out","slide along"]),children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,direction:_propTypes.default.oneOf(["top","right","bottom","left"]),onHide:_propTypes.default.func,onHidden:_propTypes.default.func,onShow:_propTypes.default.func,onVisible:_propTypes.default.func,target:_propTypes.default.oneOfType([_lib.customPropTypes.domNode,_lib.customPropTypes.refObject]),visible:_propTypes.default.bool,width:_propTypes.default.oneOf(["very thin","thin","wide","very wide"])}:{},exports.default=Sidebar}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./SidebarPushable":1640,"./SidebarPusher":1641,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@stardust-ui/react-component-event-listener":100,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"lodash/invoke":959,"prop-types":1046,react:1427}],1640:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function SidebarPushable(props){var className=props.className,children=props.children,content=props.content,className=(0,_classnames.default)("pushable",className),rest=(0,_lib.getUnhandledProps)(SidebarPushable,props),props=(0,_lib.getElementType)(SidebarPushable,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}SidebarPushable.handledProps=["as","children","className","content"],SidebarPushable.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=SidebarPushable}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1641:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function SidebarPusher(props){var className=props.className,dimmed=props.dimmed,children=props.children,content=props.content,dimmed=(0,_classnames.default)("pusher",(0,_lib.useKeyOnly)(dimmed,"dimmed"),className),className=(0,_lib.getUnhandledProps)(SidebarPusher,props),props=(0,_lib.getElementType)(SidebarPusher,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:dimmed}),_lib.childrenUtils.isNil(children)?content:children)}SidebarPusher.handledProps=["as","children","className","content","dimmed"],SidebarPusher.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,dimmed:_propTypes.default.bool}:{},exports.default=SidebarPusher}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1642:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Sidebar=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Sidebar.default}}),_interopRequireDefault(require("./Sidebar")))},{"./Sidebar":1639,"@babel/runtime/helpers/interopRequireDefault":13}],1643:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_reactComponentRef=require("@stardust-ui/react-component-ref"),_classnames=_interopRequireDefault(require("classnames")),_interopRequireDefault=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_interopRequireWildcard=function(_Component){function Sticky(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Sticky);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Sticky)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"state",{sticky:!1}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"stickyRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"triggerRef",(0,_react.createRef)()),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"addListeners",function(props){props=props.scrollContext,props=(0,_reactComponentRef.isRefObject)(props)?props.current:props;props&&(_lib.eventStack.sub("resize",_this.handleUpdate,{target:props}),_lib.eventStack.sub("scroll",_this.handleUpdate,{target:props}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"removeListeners",function(){var scrollContext=_this.props.scrollContext,scrollContext=(0,_reactComponentRef.isRefObject)(scrollContext)?scrollContext.current:scrollContext;scrollContext&&(_lib.eventStack.unsub("resize",_this.handleUpdate,{target:scrollContext}),_lib.eventStack.unsub("scroll",_this.handleUpdate,{target:scrollContext}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"update",function(e){var pushing=_this.state.pushing;if(_this.ticking=!1,_this.assignRects(),pushing)return _this.didReachStartingPoint()?_this.stickToContextTop(e):_this.didTouchScreenBottom()?_this.stickToScreenBottom(e):_this.stickToContextBottom(e);if(_this.isOversized()){if(0<_this.contextRect.top)return _this.stickToContextTop(e);if(_this.contextRect.bottom<window.innerHeight)return _this.stickToContextBottom(e)}return _this.didTouchScreenTop()?_this.didReachContextBottom()?_this.stickToContextBottom(e):_this.stickToScreenTop(e):_this.stickToContextTop(e)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleUpdate",function(e){_this.ticking||(_this.ticking=!0,_this.frameId=requestAnimationFrame(function(){return _this.update(e)}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"assignRects",function(){var context=_this.props.context,context=(0,_reactComponentRef.isRefObject)(context)?context.current:context||document.body;_this.triggerRect=_this.triggerRef.current.getBoundingClientRect(),_this.contextRect=context.getBoundingClientRect(),_this.stickyRect=_this.stickyRef.current.getBoundingClientRect()}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"didReachContextBottom",function(){var offset=_this.props.offset;return _this.stickyRect.height+offset>=_this.contextRect.bottom}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"didReachStartingPoint",function(){return _this.stickyRect.top<=_this.triggerRect.top}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"didTouchScreenTop",function(){return _this.triggerRect.top<_this.props.offset}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"didTouchScreenBottom",function(){var bottomOffset=_this.props.bottomOffset;return _this.contextRect.bottom+bottomOffset>window.innerHeight}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"isOversized",function(){return _this.stickyRect.height>window.innerHeight}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"pushing",function(pushing){_this.props.pushing&&_this.setState({pushing:pushing})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"stick",function(e,bound){_this.setState({bound:bound,sticky:!0}),(0,_invoke2.default)(_this.props,"onStick",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"unstick",function(e,bound){_this.setState({bound:bound,sticky:!1}),(0,_invoke2.default)(_this.props,"onUnstick",e,_this.props)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"stickToContextBottom",function(e){(0,_invoke2.default)(_this.props,"onBottom",e,_this.props),_this.stick(e,!0),_this.pushing(!0)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"stickToContextTop",function(e){(0,_invoke2.default)(_this.props,"onTop",e,_this.props),_this.unstick(e,!1),_this.pushing(!1)}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"stickToScreenBottom",function(e){var bottom=_this.props.bottomOffset;_this.stick(e,!1),_this.setState({bottom:bottom,top:null})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"stickToScreenTop",function(e){var top=_this.props.offset;_this.stick(e,!1),_this.setState({top:top,bottom:null})}),_this}return(0,_inherits2.default)(Sticky,_Component),(0,_createClass2.default)(Sticky,[{key:"componentDidMount",value:function(){(0,_lib.isBrowser)()&&this.props.active&&(this.handleUpdate(),this.addListeners(this.props))}},{key:"UNSAFE_componentWillReceiveProps",value:function(nextProps){var _this$props=this.props,current=_this$props.active,_this$props=_this$props.scrollContext,next=nextProps.active,nextScrollContext=nextProps.scrollContext;current===next?_this$props!==nextScrollContext&&(this.removeListeners(),this.addListeners(nextProps)):next?(this.handleUpdate(),this.addListeners(nextProps)):(this.removeListeners(),this.setState({sticky:!1}))}},{key:"componentWillUnmount",value:function(){(0,_lib.isBrowser)()&&this.props.active&&(this.removeListeners(),cancelAnimationFrame(this.frameId))}},{key:"computeStyle",value:function(){var styleElement=this.props.styleElement,_this$state=this.state,bottom=_this$state.bottom,bound=_this$state.bound,sticky=_this$state.sticky,_this$state=_this$state.top;return sticky?(0,_objectSpread2.default)({bottom:bound?0:bottom,top:bound?void 0:_this$state,width:this.triggerRect.width},styleElement):styleElement}},{key:"render",value:function(){var _this$props2=this.props,children=_this$props2.children,_this$props2=_this$props2.className,_this$state2=this.state,bottom=_this$state2.bottom,bound=_this$state2.bound,_this$state2=_this$state2.sticky,rest=(0,_lib.getUnhandledProps)(Sticky,this.props),ElementType=(0,_lib.getElementType)(Sticky,this.props),_this$props2=(0,_classnames.default)(_this$state2&&"ui",_this$state2&&"stuck-container",_this$state2&&(bound?"bound-container":"fixed-container"),_this$props2),bound=(0,_classnames.default)("ui",_this$state2&&(bound?"bound bottom":"fixed"),_this$state2&&!bound&&(null===bottom?"top":"bottom"),"sticky"),bottom=_this$state2&&this.stickyRect?{height:this.stickyRect.height}:{};return _react.default.createElement(ElementType,(0,_extends2.default)({},rest,{className:_this$props2}),_react.default.createElement("div",{ref:this.triggerRef,style:bottom}),_react.default.createElement("div",{className:bound,ref:this.stickyRef,style:this.computeStyle()},children))}}]),Sticky}(_react.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{active:!0,bottomOffset:0,offset:0,scrollContext:(0,_lib.isBrowser)()?window:null}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["active","as","bottomOffset","children","className","context","offset","onBottom","onStick","onTop","onUnstick","pushing","scrollContext","styleElement"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_interopRequireDefault.default.elementType,active:_interopRequireDefault.default.bool,bottomOffset:_interopRequireDefault.default.number,children:_interopRequireDefault.default.node,className:_interopRequireDefault.default.string,context:_interopRequireDefault.default.oneOfType([_lib.customPropTypes.domNode,_lib.customPropTypes.refObject]),offset:_interopRequireDefault.default.number,onBottom:_interopRequireDefault.default.func,onStick:_interopRequireDefault.default.func,onTop:_interopRequireDefault.default.func,onUnstick:_interopRequireDefault.default.func,pushing:_interopRequireDefault.default.bool,scrollContext:_interopRequireDefault.default.oneOfType([_lib.customPropTypes.domNode,_lib.customPropTypes.refObject]),styleElement:_interopRequireDefault.default.object}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,"@stardust-ui/react-component-ref":107,_process:1042,classnames:116,"lodash/invoke":959,"prop-types":1046,react:1427}],1644:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Sticky=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Sticky.default}}),_interopRequireDefault(require("./Sticky")))},{"./Sticky":1643,"@babel/runtime/helpers/interopRequireDefault":13}],1645:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectWithoutProperties2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"))),_objectSpread2=_interopRequireDefault(require("@babel/runtime/helpers/objectSpread")),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_map2=_interopRequireDefault(require("lodash/map")),_get2=_interopRequireDefault(require("lodash/get")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Grid=_interopRequireDefault(require("../../collections/Grid/Grid")),_GridColumn=_interopRequireDefault(require("../../collections/Grid/GridColumn")),_Menu=_interopRequireDefault(require("../../collections/Menu/Menu")),_TabPane=_interopRequireDefault(require("./TabPane")),_interopRequireDefault=function(_Component){function Tab(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Tab);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Tab)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleItemClick",function(e,_ref){_ref=_ref.index;(0,_invoke2.default)(_this.props,"onTabChange",e,(0,_objectSpread2.default)({},_this.props,{activeIndex:_ref})),_this.trySetState({activeIndex:_ref})}),_this}return(0,_inherits2.default)(Tab,_Component),(0,_createClass2.default)(Tab,[{key:"getInitialAutoControlledState",value:function(){return{activeIndex:0}}},{key:"renderItems",value:function(){var _this$props=this.props,panes=_this$props.panes,_this$props=_this$props.renderActiveOnly,activeIndex=this.state.activeIndex;return _this$props?(0,_invoke2.default)((0,_get2.default)(panes,"[".concat(activeIndex,"]")),"render",this.props):(0,_map2.default)(panes,function(_ref2,index){_ref2=_ref2.pane;return _TabPane.default.create(_ref2,{overrideProps:{active:index===activeIndex}})})}},{key:"renderMenu",value:function(){var _this$props2=this.props,menu=_this$props2.menu,panes=_this$props2.panes,_this$props2=_this$props2.menuPosition,activeIndex=this.state.activeIndex;return!0===menu.tabular&&"right"===_this$props2&&(menu.tabular="right"),_Menu.default.create(menu,{autoGenerateKey:!1,overrideProps:{items:(0,_map2.default)(panes,"menuItem"),onItemClick:this.handleItemClick,activeIndex:activeIndex}})}},{key:"renderVertical",value:function(menu){var _this$props3=this.props,grid=_this$props3.grid,_this$props3=_this$props3.menuPosition,paneWidth=grid.paneWidth,tabWidth=grid.tabWidth,grid=(0,_objectWithoutProperties2.default)(grid,["paneWidth","tabWidth"]),_this$props3=_this$props3||("right"===menu.props.tabular?"right":"left");return _react.default.createElement(_Grid.default,grid,"left"===_this$props3&&_GridColumn.default.create({width:tabWidth,children:menu},{autoGenerateKey:!1}),_GridColumn.default.create({width:paneWidth,children:this.renderItems(),stretched:!0},{autoGenerateKey:!1}),"right"===_this$props3&&_GridColumn.default.create({width:tabWidth,children:menu},{autoGenerateKey:!1}))}},{key:"render",value:function(){var menu=this.renderMenu(),rest=(0,_lib.getUnhandledProps)(Tab,this.props),ElementType=(0,_lib.getElementType)(Tab,this.props);return menu.props.vertical?_react.default.createElement(ElementType,rest,this.renderVertical(menu)):_react.default.createElement(ElementType,rest,"bottom"!==menu.props.attached&&menu,this.renderItems(),"bottom"===menu.props.attached&&menu)}}]),Tab}(_lib.AutoControlledComponent);(0,_defineProperty2.default)(_interopRequireDefault,"autoControlledProps",["activeIndex"]),(0,_defineProperty2.default)(_interopRequireDefault,"defaultProps",{grid:{paneWidth:12,tabWidth:4},menu:{attached:!0,tabular:!0},renderActiveOnly:!0}),(0,_defineProperty2.default)(_interopRequireDefault,"Pane",_TabPane.default),(0,_defineProperty2.default)(_interopRequireDefault,"handledProps",["activeIndex","as","defaultActiveIndex","grid","menu","menuPosition","onTabChange","panes","renderActiveOnly"]),_interopRequireDefault.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,defaultActiveIndex:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),activeIndex:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),menu:_propTypes.default.object,menuPosition:_propTypes.default.oneOf(["left","right"]),grid:_propTypes.default.object,onTabChange:_propTypes.default.func,panes:_propTypes.default.arrayOf(_propTypes.default.shape({menuItem:_lib.customPropTypes.itemShorthand,pane:_lib.customPropTypes.itemShorthand,render:_propTypes.default.func})),renderActiveOnly:_propTypes.default.bool}:{},exports.default=_interopRequireDefault}.call(this)}.call(this,require("_process"))},{"../../collections/Grid/Grid":1487,"../../collections/Grid/GridColumn":1488,"../../collections/Menu/Menu":1491,"../../lib":1588,"./TabPane":1646,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/objectWithoutProperties":21,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/get":950,"lodash/invoke":959,"lodash/map":989,"prop-types":1046,react:1427}],1646:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Segment=_interopRequireDefault(require("../../elements/Segment/Segment"));function TabPane(props){var active=props.active,children=props.children,className=props.className,content=props.content,loading=props.loading,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),(0,_lib.useKeyOnly)(loading,"loading"),"tab",className),loading=(0,_lib.getUnhandledProps)(TabPane,props),className=(0,_lib.getElementType)(TabPane,props),props={};return className===_Segment.default&&(props.attached="bottom"),_react.default.createElement(className,(0,_extends2.default)({},props,loading,{className:active}),_lib.childrenUtils.isNil(children)?content:children)}TabPane.handledProps=["active","as","children","className","content","loading"],TabPane.defaultProps={as:_Segment.default,active:!0},TabPane.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,loading:_propTypes.default.bool}:{},TabPane.create=(0,_lib.createShorthandFactory)(TabPane,function(content){return{content:content}}),exports.default=TabPane}.call(this)}.call(this,require("_process"))},{"../../elements/Segment/Segment":1558,"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1647:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Tab=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Tab.default}}),_interopRequireDefault(require("./Tab")))},{"./Tab":1645,"@babel/runtime/helpers/interopRequireDefault":13}],1648:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectSpread2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectSpread"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_includes2=_interopRequireDefault(require("lodash/includes")),_isNil2=_interopRequireDefault(require("lodash/isNil")),_get2=_interopRequireDefault(require("lodash/get")),_invoke2=_interopRequireDefault(require("lodash/invoke")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=require("react"),_lib=require("../../lib"),_interopRequireDefault=_interopRequireDefault(require("./TransitionGroup")),TRANSITION_TYPE={ENTERING:"show",EXITING:"hide"},Transition=function(_Component){function Transition(){var _this;(0,_classCallCheck2.default)(this,Transition);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];_this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Transition)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleStart",function(){var duration=_this.props.duration,status=_this.nextStatus;_this.nextStatus=null,_this.setState({status:status,animating:!0},function(){var durationValue=(0,_lib.normalizeTransitionDuration)(duration,TRANSITION_TYPE[status]);(0,_invoke2.default)(_this.props,"onStart",null,(0,_objectSpread2.default)({},_this.props,{status:status})),_this.timeoutId=setTimeout(_this.handleComplete,durationValue)})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleComplete",function(){var status,callback,current=_this.state.status;(0,_invoke2.default)(_this.props,"onComplete",null,(0,_objectSpread2.default)({},_this.props,{status:current})),_this.nextStatus?_this.handleStart():(status=_this.computeCompletedStatus(),callback=current===Transition.ENTERING?"onShow":"onHide",_this.setState({status:status,animating:!1},function(){(0,_invoke2.default)(_this.props,callback,null,(0,_objectSpread2.default)({},_this.props,{status:status}))}))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"updateStatus",function(){var animating=_this.state.animating;_this.nextStatus&&(_this.nextStatus=_this.computeNextStatus(),animating||_this.handleStart())}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeClasses",function(){var _this$props=_this.props,animation=_this$props.animation,directional=_this$props.directional,_this$props=_this$props.children,_this$state=_this.state,animating=_this$state.animating,_this$state=_this$state.status,_this$props=(0,_get2.default)(_this$props,"props.className");return((0,_isNil2.default)(directional)?(0,_includes2.default)(_lib.SUI.DIRECTIONAL_TRANSITIONS,animation):directional)?(0,_classnames.default)(animation,_this$props,(0,_lib.useKeyOnly)(animating,"animating"),(0,_lib.useKeyOnly)(_this$state===Transition.ENTERING,"in"),(0,_lib.useKeyOnly)(_this$state===Transition.EXITING,"out"),(0,_lib.useKeyOnly)(_this$state===Transition.EXITED,"hidden"),(0,_lib.useKeyOnly)(_this$state!==Transition.EXITED,"visible"),"transition"):(0,_classnames.default)(animation,_this$props,(0,_lib.useKeyOnly)(animating,"animating transition"))}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeCompletedStatus",function(){var unmountOnHide=_this.props.unmountOnHide;return _this.state.status===Transition.ENTERING?Transition.ENTERED:unmountOnHide?Transition.UNMOUNTED:Transition.EXITED}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeInitialStatuses",function(){var _this$props2=_this.props,visible=_this$props2.visible,mountOnShow=_this$props2.mountOnShow,transitionOnMount=_this$props2.transitionOnMount,_this$props2=_this$props2.unmountOnHide;return visible?transitionOnMount?{initial:Transition.EXITED,next:Transition.ENTERING}:{initial:Transition.ENTERED}:mountOnShow||_this$props2?{initial:Transition.UNMOUNTED}:{initial:Transition.EXITED}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeNextStatus",function(){var _this$state2=_this.state,animating=_this$state2.animating,_this$state2=_this$state2.status;return animating?_this$state2===Transition.ENTERING?Transition.EXITING:Transition.ENTERING:_this$state2===Transition.ENTERED?Transition.EXITING:Transition.ENTERING}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeStatuses",function(props){var status=_this.state.status;return props.visible?{current:status===Transition.UNMOUNTED&&Transition.EXITED,next:status!==Transition.ENTERING&&status!==Transition.ENTERED&&Transition.ENTERING}:{next:(status===Transition.ENTERING||status===Transition.ENTERED)&&Transition.EXITING}}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"computeStyle",function(){var _this$props3=_this.props,children=_this$props3.children,_this$props3=_this$props3.duration,status=_this.state.status,children=(0,_get2.default)(children,"props.style"),status=TRANSITION_TYPE[status],_this$props3=status&&"".concat((0,_lib.normalizeTransitionDuration)(_this$props3,status),"ms");return(0,_objectSpread2.default)({},children,{animationDuration:_this$props3})});var _getPrototypeOf2=_this.computeInitialStatuses(),_status=_getPrototypeOf2.initial,_getPrototypeOf2=_getPrototypeOf2.next;return _this.nextStatus=_getPrototypeOf2,_this.state={status:_status},_this}return(0,_inherits2.default)(Transition,_Component),(0,_createClass2.default)(Transition,[{key:"componentDidMount",value:function(){this.updateStatus()}},{key:"UNSAFE_componentWillReceiveProps",value:function(nextProps){var nextProps=this.computeStatuses(nextProps),status=nextProps.current,nextProps=nextProps.next;this.nextStatus=nextProps,status&&this.setState({status:status})}},{key:"componentDidUpdate",value:function(){this.updateStatus()}},{key:"componentWillUnmount",value:function(){clearTimeout(this.timeoutId)}},{key:"render",value:function(){var children=this.props.children;return this.state.status===Transition.UNMOUNTED?null:(0,_react.cloneElement)(children,{className:this.computeClasses(),style:this.computeStyle()})}}]),Transition}(_react.Component);exports.default=Transition,(0,_defineProperty2.default)(Transition,"defaultProps",{animation:"fade",duration:500,visible:!0,mountOnShow:!0,transitionOnMount:!1,unmountOnHide:!1}),(0,_defineProperty2.default)(Transition,"ENTERED","ENTERED"),(0,_defineProperty2.default)(Transition,"ENTERING","ENTERING"),(0,_defineProperty2.default)(Transition,"EXITED","EXITED"),(0,_defineProperty2.default)(Transition,"EXITING","EXITING"),(0,_defineProperty2.default)(Transition,"UNMOUNTED","UNMOUNTED"),(0,_defineProperty2.default)(Transition,"Group",_interopRequireDefault.default),(0,_defineProperty2.default)(Transition,"handledProps",["animation","children","directional","duration","mountOnShow","onComplete","onHide","onShow","onStart","reactKey","transitionOnMount","unmountOnHide","visible"]),Transition.propTypes="production"!==process.env.NODE_ENV?{animation:_propTypes.default.oneOfType([_propTypes.default.oneOf(_lib.SUI.TRANSITIONS),_propTypes.default.string]),children:_propTypes.default.element.isRequired,directional:_propTypes.default.bool,duration:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.shape({hide:_propTypes.default.number,show:_propTypes.default.number}),_propTypes.default.string]),visible:_propTypes.default.bool,mountOnShow:_propTypes.default.bool,onComplete:_propTypes.default.func,onHide:_propTypes.default.func,onShow:_propTypes.default.func,onStart:_propTypes.default.func,reactKey:_propTypes.default.string,transitionOnMount:_propTypes.default.bool,unmountOnHide:_propTypes.default.bool}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./TransitionGroup":1649,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"lodash/get":950,"lodash/includes":956,"lodash/invoke":959,"lodash/isNil":972,"prop-types":1046,react:1427}],1649:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectSpread2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectSpread"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_values2=_interopRequireDefault(require("lodash/values")),_get2=_interopRequireDefault(require("lodash/get")),_has2=_interopRequireDefault(require("lodash/has")),_forEach2=_interopRequireDefault(require("lodash/forEach")),_mapValues2=_interopRequireDefault(require("lodash/mapValues")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Transition=_interopRequireDefault(require("./Transition")),_interopRequireWildcard=function(_React$Component){function TransitionGroup(){var _this;(0,_classCallCheck2.default)(this,TransitionGroup);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];_this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(TransitionGroup)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleOnHide",function(nothing,childProps){var reactKey=childProps.reactKey;_this.setState(function(state){state=(0,_objectSpread2.default)({},state.children);return delete state[reactKey],{children:state}})}),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"wrapChild",function(child){var options=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},_this$props=_this.props,animation=_this$props.animation,directional=_this$props.directional,_this$props=_this$props.duration,key=child.key,_options$visible=options.visible,options=options.transitionOnMount;return _react.default.createElement(_Transition.default,{animation:animation,directional:directional,duration:_this$props,key:key,onHide:_this.handleOnHide,reactKey:key,transitionOnMount:void 0!==options&&options,visible:void 0===_options$visible||_options$visible},child)});var _getPrototypeOf2=_this.props.children;return _this.state={children:(0,_mapValues2.default)((0,_lib.getChildMapping)(_getPrototypeOf2),function(child){return _this.wrapChild(child)})},_this}return(0,_inherits2.default)(TransitionGroup,_React$Component),(0,_createClass2.default)(TransitionGroup,[{key:"UNSAFE_componentWillReceiveProps",value:function(nextProps){var _this2=this,prevMapping=this.state.children,nextMapping=(0,_lib.getChildMapping)(nextProps.children),children=(0,_lib.mergeChildMappings)(prevMapping,nextMapping);(0,_forEach2.default)(children,function(child,key){var hasPrev=(0,_has2.default)(prevMapping,key),hasNext=(0,_has2.default)(nextMapping,key),prevChild=prevMapping[key],isLeaving=!(0,_get2.default)(prevChild,"props.visible");!hasNext||hasPrev&&!isLeaving?hasNext||!hasPrev||isLeaving?(hasPrev=(hasNext=prevChild.props).visible,isLeaving=hasNext.transitionOnMount,children[key]=_this2.wrapChild(child,{transitionOnMount:isLeaving,visible:hasPrev})):children[key]=(0,_react.cloneElement)(prevChild,{visible:!1}):children[key]=_this2.wrapChild(child,{transitionOnMount:!0})}),this.setState({children:children})}},{key:"render",value:function(){var children=this.state.children,ElementType=(0,_lib.getElementType)(TransitionGroup,this.props),rest=(0,_lib.getUnhandledProps)(TransitionGroup,this.props);return _react.default.createElement(ElementType,rest,(0,_values2.default)(children))}}]),TransitionGroup}(_react.default.Component);exports.default=_interopRequireWildcard,(0,_defineProperty2.default)(_interopRequireWildcard,"defaultProps",{as:_react.Fragment,animation:"fade",duration:500}),(0,_defineProperty2.default)(_interopRequireWildcard,"handledProps",["animation","as","children","directional","duration"]),_interopRequireWildcard.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,animation:_propTypes.default.oneOfType([_propTypes.default.oneOf(_lib.SUI.TRANSITIONS),_propTypes.default.string]),children:_propTypes.default.node,directional:_propTypes.default.bool,duration:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.shape({hide:_propTypes.default.number.isRequired,show:_propTypes.default.number.isRequired}),_propTypes.default.string])}:{}}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./Transition":1648,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/objectSpread":19,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,"lodash/forEach":921,"lodash/get":950,"lodash/has":951,"lodash/mapValues":990,"lodash/values":1027,"prop-types":1046,react:1427}],1650:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Transition=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Transition.default}}),_interopRequireDefault(require("./Transition")))},{"./Transition":1648,"@babel/runtime/helpers/interopRequireDefault":13}],1651:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function Advertisement(props){var centered=props.centered,children=props.children,className=props.className,content=props.content,test=props.test,unit=props.unit,unit=(0,_classnames.default)("ui",unit,(0,_lib.useKeyOnly)(centered,"centered"),(0,_lib.useKeyOnly)(test,"test"),"ad",className),centered=(0,_lib.getUnhandledProps)(Advertisement,props),className=(0,_lib.getElementType)(Advertisement,props);return _react.default.createElement(className,(0,_extends2.default)({},centered,{className:unit,"data-text":test}),_lib.childrenUtils.isNil(children)?content:children)}Advertisement.handledProps=["as","centered","children","className","content","test","unit"],Advertisement.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,centered:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,test:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.number,_propTypes.default.string]),unit:_propTypes.default.oneOf(["medium rectangle","large rectangle","vertical rectangle","small rectangle","mobile banner","banner","vertical banner","top banner","half banner","button","square button","small button","skyscraper","wide skyscraper","leaderboard","large leaderboard","mobile leaderboard","billboard","panorama","netboard","half page","square","small square"]).isRequired}:{},exports.default=Advertisement}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1652:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Advertisement=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Advertisement.default}}),_interopRequireDefault(require("./Advertisement")))},{"./Advertisement":1651,"@babel/runtime/helpers/interopRequireDefault":13}],1653:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")),_createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass")),_possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")),_getPrototypeOf3=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")),_assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")),_inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits")),_defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireWildcard(require("react")),_lib=require("../../lib"),_Image=_interopRequireDefault(require("../../elements/Image")),_CardContent=_interopRequireDefault(require("./CardContent")),_interopRequireWildcard=_interopRequireDefault(require("./CardDescription")),_CardGroup=_interopRequireDefault(require("./CardGroup")),_CardHeader=_interopRequireDefault(require("./CardHeader")),_interopRequireDefault=_interopRequireDefault(require("./CardMeta")),Card=function(_Component){function Card(){var _getPrototypeOf2,_this;(0,_classCallCheck2.default)(this,Card);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return _this=(0,_possibleConstructorReturn2.default)(this,(_getPrototypeOf2=(0,_getPrototypeOf3.default)(Card)).call.apply(_getPrototypeOf2,[this].concat(args))),(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"handleClick",function(e){var onClick=_this.props.onClick;onClick&&onClick(e,_this.props)}),_this}return(0,_inherits2.default)(Card,_Component),(0,_createClass2.default)(Card,[{key:"render",value:function(){var _this$props=this.props,centered=_this$props.centered,children=_this$props.children,className=_this$props.className,color=_this$props.color,content=_this$props.content,description=_this$props.description,extra=_this$props.extra,fluid=_this$props.fluid,header=_this$props.header,href=_this$props.href,image=_this$props.image,link=_this$props.link,meta=_this$props.meta,onClick=_this$props.onClick,_this$props=_this$props.raised,color=(0,_classnames.default)("ui",color,(0,_lib.useKeyOnly)(centered,"centered"),(0,_lib.useKeyOnly)(fluid,"fluid"),(0,_lib.useKeyOnly)(link,"link"),(0,_lib.useKeyOnly)(_this$props,"raised"),"card",className),centered=(0,_lib.getUnhandledProps)(Card,this.props),fluid=(0,_lib.getElementType)(Card,this.props,function(){if(onClick)return"a"});return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement(fluid,(0,_extends2.default)({},centered,{className:color,href:href,onClick:this.handleClick}),_Image.default.create(image,{autoGenerateKey:!1,defaultProps:{ui:!1,wrapped:!0}}),(description||header||meta)&&_react.default.createElement(_CardContent.default,{description:description,header:header,meta:meta}),extra&&_react.default.createElement(_CardContent.default,{extra:!0},extra)):_react.default.createElement(fluid,(0,_extends2.default)({},centered,{className:color,href:href,onClick:this.handleClick}),content):_react.default.createElement(fluid,(0,_extends2.default)({},centered,{className:color,href:href,onClick:this.handleClick}),children)}}]),Card}(_react.Component);exports.default=Card,(0,_defineProperty2.default)(Card,"Content",_CardContent.default),(0,_defineProperty2.default)(Card,"Description",_interopRequireWildcard.default),(0,_defineProperty2.default)(Card,"Group",_CardGroup.default),(0,_defineProperty2.default)(Card,"Header",_CardHeader.default),(0,_defineProperty2.default)(Card,"Meta",_interopRequireDefault.default),(0,_defineProperty2.default)(Card,"handledProps",["as","centered","children","className","color","content","description","extra","fluid","header","href","image","link","meta","onClick","raised"]),Card.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,centered:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),content:_lib.customPropTypes.contentShorthand,description:_lib.customPropTypes.itemShorthand,extra:_lib.customPropTypes.contentShorthand,fluid:_propTypes.default.bool,header:_lib.customPropTypes.itemShorthand,href:_propTypes.default.string,image:_lib.customPropTypes.itemShorthand,link:_propTypes.default.bool,meta:_lib.customPropTypes.itemShorthand,onClick:_propTypes.default.func,raised:_propTypes.default.bool}:{}}.call(this)}.call(this,require("_process"))},{"../../elements/Image":1530,"../../lib":1588,"./CardContent":1654,"./CardDescription":1655,"./CardGroup":1656,"./CardHeader":1657,"./CardMeta":1658,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/interopRequireWildcard":14,"@babel/runtime/helpers/possibleConstructorReturn":23,_process:1042,classnames:116,"prop-types":1046,react:1427}],1654:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_CardDescription=_interopRequireDefault(require("./CardDescription")),_CardHeader=_interopRequireDefault(require("./CardHeader")),_CardMeta=_interopRequireDefault(require("./CardMeta"));function CardContent(props){var children=props.children,className=props.className,content=props.content,description=props.description,extra=props.extra,header=props.header,meta=props.meta,textAlign=props.textAlign,extra=(0,_classnames.default)((0,_lib.useKeyOnly)(extra,"extra"),(0,_lib.useTextAlignProp)(textAlign),"content",className),textAlign=(0,_lib.getUnhandledProps)(CardContent,props),className=(0,_lib.getElementType)(CardContent,props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement(className,(0,_extends2.default)({},textAlign,{className:extra}),(0,_lib.createShorthand)(_CardHeader.default,function(val){return{content:val}},header,{autoGenerateKey:!1}),(0,_lib.createShorthand)(_CardMeta.default,function(val){return{content:val}},meta,{autoGenerateKey:!1}),(0,_lib.createShorthand)(_CardDescription.default,function(val){return{content:val}},description,{autoGenerateKey:!1})):_react.default.createElement(className,(0,_extends2.default)({},textAlign,{className:extra}),content):_react.default.createElement(className,(0,_extends2.default)({},textAlign,{className:extra}),children)}CardContent.handledProps=["as","children","className","content","description","extra","header","meta","textAlign"],CardContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,description:_lib.customPropTypes.itemShorthand,extra:_propTypes.default.bool,header:_lib.customPropTypes.itemShorthand,meta:_lib.customPropTypes.itemShorthand,textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified"))}:{},exports.default=CardContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./CardDescription":1655,"./CardHeader":1657,"./CardMeta":1658,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1655:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CardDescription(props){var children=props.children,className=props.className,content=props.content,textAlign=props.textAlign,textAlign=(0,_classnames.default)((0,_lib.useTextAlignProp)(textAlign),"description",className),className=(0,_lib.getUnhandledProps)(CardDescription,props),props=(0,_lib.getElementType)(CardDescription,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:textAlign}),_lib.childrenUtils.isNil(children)?content:children)}CardDescription.handledProps=["as","children","className","content","textAlign"],CardDescription.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified"))}:{},exports.default=CardDescription}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1656:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_map2=_interopRequireDefault(require("lodash/map")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Card=_interopRequireDefault(require("./Card"));function CardGroup(props){var centered=props.centered,children=props.children,className=props.className,content=props.content,doubling=props.doubling,items=props.items,itemsPerRow=props.itemsPerRow,stackable=props.stackable,textAlign=props.textAlign,centered=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(centered,"centered"),(0,_lib.useKeyOnly)(doubling,"doubling"),(0,_lib.useKeyOnly)(stackable,"stackable"),(0,_lib.useTextAlignProp)(textAlign),(0,_lib.useWidthProp)(itemsPerRow),"cards",className),doubling=(0,_lib.getUnhandledProps)(CardGroup,props),stackable=(0,_lib.getElementType)(CardGroup,props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?(textAlign=(0,_map2.default)(items,function(item){var key=item.key||[item.header,item.description].join("-");return _react.default.createElement(_Card.default,(0,_extends2.default)({key:key},item))}),_react.default.createElement(stackable,(0,_extends2.default)({},doubling,{className:centered}),textAlign)):_react.default.createElement(stackable,(0,_extends2.default)({},doubling,{className:centered}),content):_react.default.createElement(stackable,(0,_extends2.default)({},doubling,{className:centered}),children)}CardGroup.handledProps=["as","centered","children","className","content","doubling","items","itemsPerRow","stackable","textAlign"],CardGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,centered:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,doubling:_propTypes.default.bool,items:_lib.customPropTypes.collectionShorthand,itemsPerRow:_propTypes.default.oneOf(_lib.SUI.WIDTHS),stackable:_propTypes.default.bool,textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified"))}:{},exports.default=CardGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./Card":1653,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/map":989,"lodash/without":1028,"prop-types":1046,react:1427}],1657:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CardHeader(props){var children=props.children,className=props.className,content=props.content,textAlign=props.textAlign,textAlign=(0,_classnames.default)((0,_lib.useTextAlignProp)(textAlign),"header",className),className=(0,_lib.getUnhandledProps)(CardHeader,props),props=(0,_lib.getElementType)(CardHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:textAlign}),_lib.childrenUtils.isNil(children)?content:children)}CardHeader.handledProps=["as","children","className","content","textAlign"],CardHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified"))}:{},exports.default=CardHeader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1658:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CardMeta(props){var children=props.children,className=props.className,content=props.content,textAlign=props.textAlign,textAlign=(0,_classnames.default)((0,_lib.useTextAlignProp)(textAlign),"meta",className),className=(0,_lib.getUnhandledProps)(CardMeta,props),props=(0,_lib.getElementType)(CardMeta,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:textAlign}),_lib.childrenUtils.isNil(children)?content:children)}CardMeta.handledProps=["as","children","className","content","textAlign"],CardMeta.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,textAlign:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.TEXT_ALIGNMENTS,"justified"))}:{},exports.default=CardMeta}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1659:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_CommentAction=_interopRequireDefault(require("./CommentAction")),_CommentActions=_interopRequireDefault(require("./CommentActions")),_CommentAuthor=_interopRequireDefault(require("./CommentAuthor")),_CommentAvatar=_interopRequireDefault(require("./CommentAvatar")),_CommentContent=_interopRequireDefault(require("./CommentContent")),_CommentGroup=_interopRequireDefault(require("./CommentGroup")),_CommentMetadata=_interopRequireDefault(require("./CommentMetadata")),_interopRequireDefault=_interopRequireDefault(require("./CommentText"));function Comment(props){var className=props.className,children=props.children,collapsed=props.collapsed,content=props.content,collapsed=(0,_classnames.default)((0,_lib.useKeyOnly)(collapsed,"collapsed"),"comment",className),className=(0,_lib.getUnhandledProps)(Comment,props),props=(0,_lib.getElementType)(Comment,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:collapsed}),_lib.childrenUtils.isNil(children)?content:children)}Comment.handledProps=["as","children","className","collapsed","content"],Comment.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,collapsed:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand}:{},Comment.Author=_CommentAuthor.default,Comment.Action=_CommentAction.default,Comment.Actions=_CommentActions.default,Comment.Avatar=_CommentAvatar.default,Comment.Content=_CommentContent.default,Comment.Group=_CommentGroup.default,Comment.Metadata=_CommentMetadata.default,Comment.Text=_interopRequireDefault.default,exports.default=Comment}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./CommentAction":1660,"./CommentActions":1661,"./CommentAuthor":1662,"./CommentAvatar":1663,"./CommentContent":1664,"./CommentGroup":1665,"./CommentMetadata":1666,"./CommentText":1667,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1660:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CommentAction(props){var active=props.active,className=props.className,children=props.children,content=props.content,active=(0,_classnames.default)((0,_lib.useKeyOnly)(active,"active"),className),className=(0,_lib.getUnhandledProps)(CommentAction,props),props=(0,_lib.getElementType)(CommentAction,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:active}),_lib.childrenUtils.isNil(children)?content:children)}CommentAction.handledProps=["active","as","children","className","content"],CommentAction.defaultProps={as:"a"},CommentAction.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,active:_propTypes.default.bool,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=CommentAction}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1661:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CommentActions(props){var className=props.className,children=props.children,content=props.content,className=(0,_classnames.default)("actions",className),rest=(0,_lib.getUnhandledProps)(CommentActions,props),props=(0,_lib.getElementType)(CommentActions,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}CommentActions.handledProps=["as","children","className","content"],CommentActions.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=CommentActions}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1662:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CommentAuthor(props){var className=props.className,children=props.children,content=props.content,className=(0,_classnames.default)("author",className),rest=(0,_lib.getUnhandledProps)(CommentAuthor,props),props=(0,_lib.getElementType)(CommentAuthor,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}CommentAuthor.handledProps=["as","children","className","content"],CommentAuthor.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=CommentAuthor}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1663:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CommentAvatar(props){var className=props.className,src=props.src,className=(0,_classnames.default)("avatar",className),rest=(0,_lib.getUnhandledProps)(CommentAvatar,props),rest=(0,_lib.partitionHTMLProps)(rest,{htmlProps:_lib.htmlImageProps}),rest=(0,_slicedToArray2.default)(rest,2),imageProps=rest[0],rest=rest[1],props=(0,_lib.getElementType)(CommentAvatar,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),(0,_lib.createHTMLImage)(src,{autoGenerateKey:!1,defaultProps:imageProps}))}CommentAvatar.handledProps=["as","className","src"],CommentAvatar.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,className:_propTypes.default.string,src:_propTypes.default.string}:{},exports.default=CommentAvatar}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/slicedToArray":25,_process:1042,classnames:116,"prop-types":1046,react:1427}],1664:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CommentContent(props){var className=props.className,children=props.children,content=props.content,className=(0,_classnames.default)(className,"content"),rest=(0,_lib.getUnhandledProps)(CommentContent,props),props=(0,_lib.getElementType)(CommentContent,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}CommentContent.handledProps=["as","children","className","content"],CommentContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=CommentContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1665:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CommentGroup(props){var className=props.className,children=props.children,collapsed=props.collapsed,content=props.content,minimal=props.minimal,size=props.size,threaded=props.threaded,size=(0,_classnames.default)("ui",size,(0,_lib.useKeyOnly)(collapsed,"collapsed"),(0,_lib.useKeyOnly)(minimal,"minimal"),(0,_lib.useKeyOnly)(threaded,"threaded"),"comments",className),collapsed=(0,_lib.getUnhandledProps)(CommentGroup,props),minimal=(0,_lib.getElementType)(CommentGroup,props);return _react.default.createElement(minimal,(0,_extends2.default)({},collapsed,{className:size}),_lib.childrenUtils.isNil(children)?content:children)}CommentGroup.handledProps=["as","children","className","collapsed","content","minimal","size","threaded"],CommentGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,collapsed:_propTypes.default.bool,content:_lib.customPropTypes.contentShorthand,minimal:_propTypes.default.bool,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"medium")),threaded:_propTypes.default.bool}:{},exports.default=CommentGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1666:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CommentMetadata(props){var className=props.className,children=props.children,content=props.content,className=(0,_classnames.default)("metadata",className),rest=(0,_lib.getUnhandledProps)(CommentMetadata,props),props=(0,_lib.getElementType)(CommentMetadata,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}CommentMetadata.handledProps=["as","children","className","content"],CommentMetadata.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=CommentMetadata}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1667:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function CommentText(props){var className=props.className,children=props.children,content=props.content,className=(0,_classnames.default)(className,"text"),rest=(0,_lib.getUnhandledProps)(CommentText,props),props=(0,_lib.getElementType)(CommentText,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}CommentText.handledProps=["as","children","className","content"],CommentText.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=CommentText}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1668:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Comment=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Comment.default}}),_interopRequireDefault(require("./Comment")))},{"./Comment":1659,"@babel/runtime/helpers/interopRequireDefault":13}],1669:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectWithoutProperties2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_without2=_interopRequireDefault(require("lodash/without")),_map2=_interopRequireDefault(require("lodash/map")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_FeedContent=_interopRequireDefault(require("./FeedContent")),_FeedDate=_interopRequireDefault(require("./FeedDate")),_FeedEvent=_interopRequireDefault(require("./FeedEvent")),_FeedExtra=_interopRequireDefault(require("./FeedExtra")),_FeedLabel=_interopRequireDefault(require("./FeedLabel")),_FeedLike=_interopRequireDefault(require("./FeedLike")),_FeedMeta=_interopRequireDefault(require("./FeedMeta")),_FeedSummary=_interopRequireDefault(require("./FeedSummary")),_interopRequireDefault=_interopRequireDefault(require("./FeedUser"));function Feed(props){var children=props.children,className=props.className,events=props.events,size=props.size,size=(0,_classnames.default)("ui",size,"feed",className),className=(0,_lib.getUnhandledProps)(Feed,props),props=(0,_lib.getElementType)(Feed,props);return _lib.childrenUtils.isNil(children)?(events=(0,_map2.default)(events,function(eventProps){var childKey=eventProps.childKey,date=eventProps.date,meta=eventProps.meta,summary=eventProps.summary,eventProps=(0,_objectWithoutProperties2.default)(eventProps,["childKey","date","meta","summary"]),childKey=childKey||[date,meta,summary].join("-");return _react.default.createElement(_FeedEvent.default,(0,_extends2.default)({date:date,key:childKey,meta:meta,summary:summary},eventProps))}),_react.default.createElement(props,(0,_extends2.default)({},className,{className:size}),events)):_react.default.createElement(props,(0,_extends2.default)({},className,{className:size}),children)}Feed.handledProps=["as","children","className","events","size"],Feed.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,events:_lib.customPropTypes.collectionShorthand,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"mini","tiny","medium","big","huge","massive"))}:{},Feed.Content=_FeedContent.default,Feed.Date=_FeedDate.default,Feed.Event=_FeedEvent.default,Feed.Extra=_FeedExtra.default,Feed.Label=_FeedLabel.default,Feed.Like=_FeedLike.default,Feed.Meta=_FeedMeta.default,Feed.Summary=_FeedSummary.default,Feed.User=_interopRequireDefault.default,exports.default=Feed}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./FeedContent":1670,"./FeedDate":1671,"./FeedEvent":1672,"./FeedExtra":1673,"./FeedLabel":1674,"./FeedLike":1675,"./FeedMeta":1676,"./FeedSummary":1677,"./FeedUser":1678,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectWithoutProperties":21,_process:1042,classnames:116,"lodash/map":989,"lodash/without":1028,"prop-types":1046,react:1427}],1670:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_FeedDate=_interopRequireDefault(require("./FeedDate")),_FeedExtra=_interopRequireDefault(require("./FeedExtra")),_FeedMeta=_interopRequireDefault(require("./FeedMeta")),_FeedSummary=_interopRequireDefault(require("./FeedSummary"));function FeedContent(props){var children=props.children,className=props.className,content=props.content,extraImages=props.extraImages,extraText=props.extraText,date=props.date,meta=props.meta,summary=props.summary,className=(0,_classnames.default)("content",className),rest=(0,_lib.getUnhandledProps)(FeedContent,props),props=(0,_lib.getElementType)(FeedContent,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),(0,_lib.createShorthand)(_FeedDate.default,function(val){return{content:val}},date,{autoGenerateKey:!1}),(0,_lib.createShorthand)(_FeedSummary.default,function(val){return{content:val}},summary,{autoGenerateKey:!1}),content,(0,_lib.createShorthand)(_FeedExtra.default,function(val){return{text:!0,content:val}},extraText,{autoGenerateKey:!1}),(0,_lib.createShorthand)(_FeedExtra.default,function(val){return{images:val}},extraImages,{autoGenerateKey:!1}),(0,_lib.createShorthand)(_FeedMeta.default,function(val){return{content:val}},meta,{autoGenerateKey:!1})):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}FeedContent.handledProps=["as","children","className","content","date","extraImages","extraText","meta","summary"],FeedContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,date:_lib.customPropTypes.itemShorthand,extraImages:_FeedExtra.default.propTypes.images,extraText:_lib.customPropTypes.itemShorthand,meta:_lib.customPropTypes.itemShorthand,summary:_lib.customPropTypes.itemShorthand}:{},exports.default=FeedContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./FeedDate":1671,"./FeedExtra":1673,"./FeedMeta":1676,"./FeedSummary":1677,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1671:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function FeedDate(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("date",className),rest=(0,_lib.getUnhandledProps)(FeedDate,props),props=(0,_lib.getElementType)(FeedDate,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}FeedDate.handledProps=["as","children","className","content"],FeedDate.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},exports.default=FeedDate}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1672:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_FeedContent=_interopRequireDefault(require("./FeedContent")),_FeedLabel=_interopRequireDefault(require("./FeedLabel"));function FeedEvent(props){var content=props.content,children=props.children,className=props.className,date=props.date,extraImages=props.extraImages,extraText=props.extraText,image=props.image,icon=props.icon,meta=props.meta,summary=props.summary,className=(0,_classnames.default)("event",className),rest=(0,_lib.getUnhandledProps)(FeedEvent,props),props=(0,_lib.getElementType)(FeedEvent,props),hasContentProp=content||date||extraImages||extraText||meta||summary,content={content:content,date:date,extraImages:extraImages,extraText:extraText,meta:meta,summary:summary};return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),(0,_lib.createShorthand)(_FeedLabel.default,function(val){return{icon:val}},icon,{autoGenerateKey:!1}),(0,_lib.createShorthand)(_FeedLabel.default,function(val){return{image:val}},image,{autoGenerateKey:!1}),hasContentProp&&_react.default.createElement(_FeedContent.default,content),children)}FeedEvent.handledProps=["as","children","className","content","date","extraImages","extraText","icon","image","meta","summary"],FeedEvent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.itemShorthand,date:_lib.customPropTypes.itemShorthand,extraImages:_lib.customPropTypes.itemShorthand,extraText:_lib.customPropTypes.itemShorthand,icon:_lib.customPropTypes.itemShorthand,image:_lib.customPropTypes.itemShorthand,meta:_lib.customPropTypes.itemShorthand,summary:_lib.customPropTypes.itemShorthand}:{},exports.default=FeedEvent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./FeedContent":1670,"./FeedLabel":1674,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1673:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_map2=_interopRequireDefault(require("lodash/map")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function FeedExtra(props){var children=props.children,className=props.className,content=props.content,images=props.images,text=props.text,text=(0,_classnames.default)((0,_lib.useKeyOnly)(images,"images"),(0,_lib.useKeyOnly)(content||text,"text"),"extra",className),className=(0,_lib.getUnhandledProps)(FeedExtra,props),props=(0,_lib.getElementType)(FeedExtra,props);return _lib.childrenUtils.isNil(children)?(images=(0,_map2.default)(images,function(image,index){index=[index,image].join("-");return(0,_lib.createHTMLImage)(image,{key:index})}),_react.default.createElement(props,(0,_extends2.default)({},className,{className:text}),content,images)):_react.default.createElement(props,(0,_extends2.default)({},className,{className:text}),children)}FeedExtra.handledProps=["as","children","className","content","images","text"],FeedExtra.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,images:_lib.customPropTypes.every([_lib.customPropTypes.disallow(["text"]),_propTypes.default.oneOfType([_propTypes.default.bool,_lib.customPropTypes.collectionShorthand])]),text:_propTypes.default.bool}:{},exports.default=FeedExtra}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/map":989,"prop-types":1046,react:1427}],1674:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon"));function FeedLabel(props){var children=props.children,className=props.className,content=props.content,icon=props.icon,image=props.image,className=(0,_classnames.default)("label",className),rest=(0,_lib.getUnhandledProps)(FeedLabel,props),props=(0,_lib.getElementType)(FeedLabel,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),content,_Icon.default.create(icon,{autoGenerateKey:!1}),(0,_lib.createHTMLImage)(image)):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}FeedLabel.handledProps=["as","children","className","content","icon","image"],FeedLabel.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,icon:_lib.customPropTypes.itemShorthand,image:_lib.customPropTypes.itemShorthand}:{},exports.default=FeedLabel}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1675:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Icon=_interopRequireDefault(require("../../elements/Icon"));function FeedLike(props){var children=props.children,className=props.className,content=props.content,icon=props.icon,className=(0,_classnames.default)("like",className),rest=(0,_lib.getUnhandledProps)(FeedLike,props),props=(0,_lib.getElementType)(FeedLike,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_Icon.default.create(icon,{autoGenerateKey:!1}),content):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}FeedLike.handledProps=["as","children","className","content","icon"],FeedLike.defaultProps={as:"a"},FeedLike.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,icon:_lib.customPropTypes.itemShorthand}:{},exports.default=FeedLike}.call(this)}.call(this,require("_process"))},{"../../elements/Icon":1527,"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1676:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_FeedLike=_interopRequireDefault(require("./FeedLike"));function FeedMeta(props){var children=props.children,className=props.className,content=props.content,like=props.like,className=(0,_classnames.default)("meta",className),rest=(0,_lib.getUnhandledProps)(FeedMeta,props),props=(0,_lib.getElementType)(FeedMeta,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),(0,_lib.createShorthand)(_FeedLike.default,function(val){return{content:val}},like,{autoGenerateKey:!1}),content):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}FeedMeta.handledProps=["as","children","className","content","like"],FeedMeta.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,like:_lib.customPropTypes.itemShorthand}:{},exports.default=FeedMeta}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./FeedLike":1675,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1677:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_FeedDate=_interopRequireDefault(require("./FeedDate")),_FeedUser=_interopRequireDefault(require("./FeedUser"));function FeedSummary(props){var children=props.children,className=props.className,content=props.content,date=props.date,user=props.user,className=(0,_classnames.default)("summary",className),rest=(0,_lib.getUnhandledProps)(FeedSummary,props),props=(0,_lib.getElementType)(FeedSummary,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),(0,_lib.createShorthand)(_FeedUser.default,function(val){return{content:val}},user,{autoGenerateKey:!1}),content&&" ",content,content&&" ",(0,_lib.createShorthand)(_FeedDate.default,function(val){return{content:val}},date,{autoGenerateKey:!1})):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}FeedSummary.handledProps=["as","children","className","content","date","user"],FeedSummary.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,date:_lib.customPropTypes.itemShorthand,user:_lib.customPropTypes.itemShorthand}:{},exports.default=FeedSummary}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./FeedDate":1671,"./FeedUser":1678,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1678:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function FeedUser(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("user",className),rest=(0,_lib.getUnhandledProps)(FeedUser,props),props=(0,_lib.getElementType)(FeedUser,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}FeedUser.handledProps=["as","children","className","content"],FeedUser.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},FeedUser.defaultProps={as:"a"},exports.default=FeedUser}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1679:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Feed=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Feed.default}}),_interopRequireDefault(require("./Feed")))},{"./Feed":1669,"@babel/runtime/helpers/interopRequireDefault":13}],1680:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_ItemContent=_interopRequireDefault(require("./ItemContent")),_ItemDescription=_interopRequireDefault(require("./ItemDescription")),_ItemExtra=_interopRequireDefault(require("./ItemExtra")),_ItemGroup=_interopRequireDefault(require("./ItemGroup")),_ItemHeader=_interopRequireDefault(require("./ItemHeader")),_ItemImage=_interopRequireDefault(require("./ItemImage")),_interopRequireDefault=_interopRequireDefault(require("./ItemMeta"));function Item(props){var children=props.children,className=props.className,content=props.content,description=props.description,extra=props.extra,header=props.header,image=props.image,meta=props.meta,className=(0,_classnames.default)("item",className),rest=(0,_lib.getUnhandledProps)(Item,props),props=(0,_lib.getElementType)(Item,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_ItemImage.default.create(image,{autoGenerateKey:!1}),_react.default.createElement(_ItemContent.default,{content:content,description:description,extra:extra,header:header,meta:meta})):_react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),children)}Item.handledProps=["as","children","className","content","description","extra","header","image","meta"],Item.Content=_ItemContent.default,Item.Description=_ItemDescription.default,Item.Extra=_ItemExtra.default,Item.Group=_ItemGroup.default,Item.Header=_ItemHeader.default,Item.Image=_ItemImage.default,Item.Meta=_interopRequireDefault.default,Item.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,description:_lib.customPropTypes.itemShorthand,extra:_lib.customPropTypes.itemShorthand,header:_lib.customPropTypes.itemShorthand,image:_lib.customPropTypes.itemShorthand,meta:_lib.customPropTypes.itemShorthand}:{},exports.default=Item}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./ItemContent":1681,"./ItemDescription":1682,"./ItemExtra":1683,"./ItemGroup":1684,"./ItemHeader":1685,"./ItemImage":1686,"./ItemMeta":1687,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1681:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_ItemHeader=_interopRequireDefault(require("./ItemHeader")),_ItemDescription=_interopRequireDefault(require("./ItemDescription")),_ItemExtra=_interopRequireDefault(require("./ItemExtra")),_ItemMeta=_interopRequireDefault(require("./ItemMeta"));function ItemContent(props){var children=props.children,className=props.className,content=props.content,description=props.description,extra=props.extra,header=props.header,meta=props.meta,verticalAlign=props.verticalAlign,verticalAlign=(0,_classnames.default)((0,_lib.useVerticalAlignProp)(verticalAlign),"content",className),className=(0,_lib.getUnhandledProps)(ItemContent,props),props=(0,_lib.getElementType)(ItemContent,props);return _lib.childrenUtils.isNil(children)?_react.default.createElement(props,(0,_extends2.default)({},className,{className:verticalAlign}),_ItemHeader.default.create(header,{autoGenerateKey:!1}),_ItemMeta.default.create(meta,{autoGenerateKey:!1}),_ItemDescription.default.create(description,{autoGenerateKey:!1}),_ItemExtra.default.create(extra,{autoGenerateKey:!1}),content):_react.default.createElement(props,(0,_extends2.default)({},className,{className:verticalAlign}),children)}ItemContent.handledProps=["as","children","className","content","description","extra","header","meta","verticalAlign"],ItemContent.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,description:_lib.customPropTypes.itemShorthand,extra:_lib.customPropTypes.itemShorthand,header:_lib.customPropTypes.itemShorthand,meta:_lib.customPropTypes.itemShorthand,verticalAlign:_propTypes.default.oneOf(_lib.SUI.VERTICAL_ALIGNMENTS)}:{},exports.default=ItemContent}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./ItemDescription":1682,"./ItemExtra":1683,"./ItemHeader":1685,"./ItemMeta":1687,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1682:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ItemDescription(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("description",className),rest=(0,_lib.getUnhandledProps)(ItemDescription,props),props=(0,_lib.getElementType)(ItemDescription,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ItemDescription.handledProps=["as","children","className","content"],ItemDescription.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},ItemDescription.create=(0,_lib.createShorthandFactory)(ItemDescription,function(content){return{content:content}}),exports.default=ItemDescription}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1683:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ItemExtra(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("extra",className),rest=(0,_lib.getUnhandledProps)(ItemExtra,props),props=(0,_lib.getElementType)(ItemExtra,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ItemExtra.handledProps=["as","children","className","content"],ItemExtra.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},ItemExtra.create=(0,_lib.createShorthandFactory)(ItemExtra,function(content){return{content:content}}),exports.default=ItemExtra}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1684:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_objectWithoutProperties2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"))),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_map2=_interopRequireDefault(require("lodash/map")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Item=_interopRequireDefault(require("./Item"));function ItemGroup(props){var children=props.children,className=props.className,content=props.content,divided=props.divided,items=props.items,link=props.link,relaxed=props.relaxed,unstackable=props.unstackable,divided=(0,_classnames.default)("ui",(0,_lib.useKeyOnly)(divided,"divided"),(0,_lib.useKeyOnly)(link,"link"),(0,_lib.useKeyOnly)(unstackable,"unstackable"),(0,_lib.useKeyOrValueAndKey)(relaxed,"relaxed"),"items",className),link=(0,_lib.getUnhandledProps)(ItemGroup,props),unstackable=(0,_lib.getElementType)(ItemGroup,props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?(relaxed=(0,_map2.default)(items,function(item){var childKey=item.childKey,item=(0,_objectWithoutProperties2.default)(item,["childKey"]),childKey=childKey||[item.content,item.description,item.header,item.meta].join("-");return _react.default.createElement(_Item.default,(0,_extends2.default)({},item,{key:childKey}))}),_react.default.createElement(unstackable,(0,_extends2.default)({},link,{className:divided}),relaxed)):_react.default.createElement(unstackable,(0,_extends2.default)({},link,{className:divided}),content):_react.default.createElement(unstackable,(0,_extends2.default)({},link,{className:divided}),children)}ItemGroup.handledProps=["as","children","className","content","divided","items","link","relaxed","unstackable"],ItemGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,divided:_propTypes.default.bool,items:_lib.customPropTypes.collectionShorthand,link:_propTypes.default.bool,relaxed:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.oneOf(["very"])]),unstackable:_propTypes.default.bool}:{},exports.default=ItemGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./Item":1680,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,"@babel/runtime/helpers/objectWithoutProperties":21,_process:1042,classnames:116,"lodash/map":989,"prop-types":1046,react:1427}],1685:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ItemHeader(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("header",className),rest=(0,_lib.getUnhandledProps)(ItemHeader,props),props=(0,_lib.getElementType)(ItemHeader,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ItemHeader.handledProps=["as","children","className","content"],ItemHeader.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},ItemHeader.create=(0,_lib.createShorthandFactory)(ItemHeader,function(content){return{content:content}}),exports.default=ItemHeader}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1686:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Image=_interopRequireDefault(require("../../elements/Image"));function ItemImage(props){var size=props.size,props=(0,_lib.getUnhandledProps)(ItemImage,props);return _react.default.createElement(_Image.default,(0,_extends2.default)({},props,{size:size,ui:!!size,wrapped:!0}))}ItemImage.handledProps=["size"],ItemImage.propTypes="production"!==process.env.NODE_ENV?{size:_Image.default.propTypes.size}:{},ItemImage.create=(0,_lib.createShorthandFactory)(ItemImage,function(src){return{src:src}}),exports.default=ItemImage}.call(this)}.call(this,require("_process"))},{"../../elements/Image":1530,"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,react:1427}],1687:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function ItemMeta(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("meta",className),rest=(0,_lib.getUnhandledProps)(ItemMeta,props),props=(0,_lib.getElementType)(ItemMeta,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}ItemMeta.handledProps=["as","children","className","content"],ItemMeta.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},ItemMeta.create=(0,_lib.createShorthandFactory)(ItemMeta,function(content){return{content:content}}),exports.default=ItemMeta}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1688:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Item=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Item.default}}),_interopRequireDefault(require("./Item")))},{"./Item":1680,"@babel/runtime/helpers/interopRequireDefault":13}],1689:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_StatisticGroup=_interopRequireDefault(require("./StatisticGroup")),_StatisticLabel=_interopRequireDefault(require("./StatisticLabel")),_StatisticValue=_interopRequireDefault(require("./StatisticValue"));function Statistic(props){var children=props.children,className=props.className,color=props.color,content=props.content,floated=props.floated,horizontal=props.horizontal,inverted=props.inverted,label=props.label,size=props.size,text=props.text,value=props.value,color=(0,_classnames.default)("ui",color,size,(0,_lib.useValueAndKey)(floated,"floated"),(0,_lib.useKeyOnly)(horizontal,"horizontal"),(0,_lib.useKeyOnly)(inverted,"inverted"),"statistic",className),size=(0,_lib.getUnhandledProps)(Statistic,props),floated=(0,_lib.getElementType)(Statistic,props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement(floated,(0,_extends2.default)({},size,{className:color}),_StatisticValue.default.create(value,{defaultProps:{text:text},autoGenerateKey:!1}),_StatisticLabel.default.create(label,{autoGenerateKey:!1})):_react.default.createElement(floated,(0,_extends2.default)({},size,{className:color}),content):_react.default.createElement(floated,(0,_extends2.default)({},size,{className:color}),children)}Statistic.handledProps=["as","children","className","color","content","floated","horizontal","inverted","label","size","text","value"],Statistic.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),content:_lib.customPropTypes.contentShorthand,floated:_propTypes.default.oneOf(_lib.SUI.FLOATS),horizontal:_propTypes.default.bool,inverted:_propTypes.default.bool,label:_lib.customPropTypes.contentShorthand,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"big","massive","medium")),text:_propTypes.default.bool,value:_lib.customPropTypes.contentShorthand}:{},Statistic.Group=_StatisticGroup.default,Statistic.Label=_StatisticLabel.default,Statistic.Value=_StatisticValue.default,Statistic.create=(0,_lib.createShorthandFactory)(Statistic,function(content){return{content:content}}),exports.default=Statistic}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./StatisticGroup":1690,"./StatisticLabel":1691,"./StatisticValue":1692,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/without":1028,"prop-types":1046,react:1427}],1690:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_without2=_interopRequireDefault(require("lodash/without")),_map2=_interopRequireDefault(require("lodash/map")),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib"),_Statistic=_interopRequireDefault(require("./Statistic"));function StatisticGroup(props){var children=props.children,className=props.className,color=props.color,content=props.content,horizontal=props.horizontal,inverted=props.inverted,items=props.items,size=props.size,widths=props.widths,color=(0,_classnames.default)("ui",color,size,(0,_lib.useKeyOnly)(horizontal,"horizontal"),(0,_lib.useKeyOnly)(inverted,"inverted"),(0,_lib.useWidthProp)(widths),"statistics",className),size=(0,_lib.getUnhandledProps)(StatisticGroup,props),horizontal=(0,_lib.getElementType)(StatisticGroup,props);return _lib.childrenUtils.isNil(children)?_lib.childrenUtils.isNil(content)?_react.default.createElement(horizontal,(0,_extends2.default)({},size,{className:color}),(0,_map2.default)(items,function(item){return _Statistic.default.create(item)})):_react.default.createElement(horizontal,(0,_extends2.default)({},size,{className:color}),content):_react.default.createElement(horizontal,(0,_extends2.default)({},size,{className:color}),children)}StatisticGroup.handledProps=["as","children","className","color","content","horizontal","inverted","items","size","widths"],StatisticGroup.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,color:_propTypes.default.oneOf(_lib.SUI.COLORS),content:_lib.customPropTypes.contentShorthand,horizontal:_propTypes.default.bool,inverted:_propTypes.default.bool,items:_lib.customPropTypes.collectionShorthand,size:_propTypes.default.oneOf((0,_without2.default)(_lib.SUI.SIZES,"big","massive","medium")),widths:_propTypes.default.oneOf(_lib.SUI.WIDTHS)}:{},exports.default=StatisticGroup}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"./Statistic":1689,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"lodash/map":989,"lodash/without":1028,"prop-types":1046,react:1427}],1691:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function StatisticLabel(props){var children=props.children,className=props.className,content=props.content,className=(0,_classnames.default)("label",className),rest=(0,_lib.getUnhandledProps)(StatisticLabel,props),props=(0,_lib.getElementType)(StatisticLabel,props);return _react.default.createElement(props,(0,_extends2.default)({},rest,{className:className}),_lib.childrenUtils.isNil(children)?content:children)}StatisticLabel.handledProps=["as","children","className","content"],StatisticLabel.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand}:{},StatisticLabel.create=(0,_lib.createShorthandFactory)(StatisticLabel,function(content){return{content:content}}),exports.default=StatisticLabel}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1692:[function(require,module,exports){!function(process){!function(){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_extends2=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,_interopRequireDefault(require("@babel/runtime/helpers/extends"))),_classnames=_interopRequireDefault(require("classnames")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_lib=require("../../lib");function StatisticValue(props){var children=props.children,className=props.className,content=props.content,text=props.text,text=(0,_classnames.default)((0,_lib.useKeyOnly)(text,"text"),"value",className),className=(0,_lib.getUnhandledProps)(StatisticValue,props),props=(0,_lib.getElementType)(StatisticValue,props);return _react.default.createElement(props,(0,_extends2.default)({},className,{className:text}),_lib.childrenUtils.isNil(children)?content:children)}StatisticValue.handledProps=["as","children","className","content","text"],StatisticValue.propTypes="production"!==process.env.NODE_ENV?{as:_propTypes.default.elementType,children:_propTypes.default.node,className:_propTypes.default.string,content:_lib.customPropTypes.contentShorthand,text:_propTypes.default.bool}:{},StatisticValue.create=(0,_lib.createShorthandFactory)(StatisticValue,function(content){return{content:content}}),exports.default=StatisticValue}.call(this)}.call(this,require("_process"))},{"../../lib":1588,"@babel/runtime/helpers/extends":8,"@babel/runtime/helpers/interopRequireDefault":13,_process:1042,classnames:116,"prop-types":1046,react:1427}],1693:[function(require,module,exports){"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_Statistic=(Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Statistic.default}}),_interopRequireDefault(require("./Statistic")))},{"./Statistic":1689,"@babel/runtime/helpers/interopRequireDefault":13}],1694:[function(require,module,exports){module.exports=function(objA,objB,compare,compareContext){if(void 0!==(ret=compare?compare.call(compareContext,objA,objB):void 0))return!!ret;if(objA!==objB){if("object"!=typeof objA||!objA||"object"!=typeof objB||!objB)return!1;var keysA=Object.keys(objA),keysB=Object.keys(objB);if(keysA.length!==keysB.length)return!1;for(var bHasOwnProperty=Object.prototype.hasOwnProperty.bind(objB),idx=0;idx<keysA.length;idx++){var key=keysA[idx];if(!bHasOwnProperty(key))return!1;var ret,valueA=objA[key],valueB=objB[key];if(!1===(ret=compare?compare.call(compareContext,valueA,valueB,key):void 0)||void 0===ret&&valueA!==valueB)return!1}}return!0}},{}],1695:[function(require,module,exports){!function(setImmediate,clearImmediate){!function(){var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;0<=msecs&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}.call(this)}.call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":1042,timers:1695}],1696:[function(require,module,exports){!function(process){!function(){"use strict";var isProduction="production"===process.env.NODE_ENV,prefix="Invariant failed";module.exports=function(condition,message){if(!condition){if(isProduction)throw new Error(prefix);condition="function"==typeof message?message():message,message=condition?"".concat(prefix,": ").concat(condition):prefix;throw new Error(message)}}}.call(this)}.call(this,require("_process"))},{_process:1042}],1697:[function(require,module,exports){!function(process){!function(){"use strict";var isProduction="production"===process.env.NODE_ENV;module.exports=function(condition,message){if(!isProduction&&!condition){condition="Warning: "+message;"undefined"!=typeof console&&console.warn(condition);try{throw Error(condition)}catch(x){}}}}.call(this)}.call(this,require("_process"))},{_process:1042}],1698:[function(require,module,exports){!function(global){!function(){var __extends,__assign,__rest,__decorate,__param,__metadata,__awaiter,__generator,__exportStar,__values,__read,__spread,__spreadArrays,__await,__asyncGenerator,__asyncDelegator,__asyncValues,__makeTemplateObject,__importStar,__importDefault,__classPrivateFieldGet,__classPrivateFieldSet,__createBinding;!function(factory){var root="object"==typeof global?global:"object"==typeof self?self:"object"==typeof this?this:{};function createExporter(exports,previous){return exports!==root&&("function"==typeof Object.create?Object.defineProperty(exports,"__esModule",{value:!0}):exports.__esModule=!0),function(id,v){return exports[id]=previous?previous(id,v):v}}"function"==typeof define&&define.amd?define("tslib",["exports"],function(exports){factory(createExporter(root,createExporter(exports)))}):"object"==typeof module&&"object"==typeof module.exports?factory(createExporter(root,createExporter(module.exports))):factory(createExporter(root))}(function(exporter){var extendStatics=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(d,b){d.__proto__=b}:function(d,b){for(var p in b)b.hasOwnProperty(p)&&(d[p]=b[p])});__extends=function(d,b){function __(){this.constructor=d}extendStatics(d,b),d.prototype=null===b?Object.create(b):(__.prototype=b.prototype,new __)},__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t},__rest=function(s,e){var t={};for(p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(null!=s&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])&&(t[p[i]]=s[p[i]]);return t},__decorate=function(decorators,target,key,desc){var d,c=arguments.length,r=c<3?target:null===desc?desc=Object.getOwnPropertyDescriptor(target,key):desc;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;0<=i;i--)(d=decorators[i])&&(r=(c<3?d(r):3<c?d(target,key,r):d(target,key))||r);return 3<c&&r&&Object.defineProperty(target,key,r),r},__param=function(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}},__metadata=function(metadataKey,metadataValue){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(metadataKey,metadataValue)},__awaiter=function(thisArg,_arguments,P,generator){return new(P=P||Promise)(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):((value=result.value)instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=function(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){var op=[n,v];if(f)throw new TypeError("Generator is already executing.");for(;_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,(op=t?[2&op[0],t.value]:op)[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=0<(t=_.trys).length&&t[t.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3]))_.label=op[1];else if(6===op[0]&&_.label<t[1])_.label=t[1],t=op;else{if(!(t&&_.label<t[2])){t[2]&&_.ops.pop(),_.trys.pop();continue}_.label=t[2],_.ops.push(op)}}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}}},__createBinding=function(o,m,k,k2){o[k2=void 0===k2?k:k2]=m[k]},__exportStar=function(m,exports){for(var p in m)"default"===p||exports.hasOwnProperty(p)||(exports[p]=m[p])},__values=function(o){var s="function"==typeof Symbol&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&"number"==typeof o.length)return{next:function(){return{value:(o=o&&i>=o.length?void 0:o)&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=function(o,n){var m="function"==typeof Symbol&&o[Symbol.iterator];if(!m)return o;var r,e,i=m.call(o),ar=[];try{for(;(void 0===n||0<n--)&&!(r=i.next()).done;)ar.push(r.value)}catch(error){e={error:error}}finally{try{r&&!r.done&&(m=i.return)&&m.call(i)}finally{if(e)throw e.error}}return ar},__spread=function(){for(var ar=[],i=0;i<arguments.length;i++)ar=ar.concat(__read(arguments[i]));return ar},__spreadArrays=function(){for(var s=0,i=0,il=arguments.length;i<il;i++)s+=arguments[i].length;for(var r=Array(s),k=0,i=0;i<il;i++)for(var a=arguments[i],j=0,jl=a.length;j<jl;j++,k++)r[k]=a[j];return r},__await=function(v){return this instanceof __await?(this.v=v,this):new __await(v)},__asyncGenerator=function(thisArg,_arguments,generator){var g,q,i;if(Symbol.asyncIterator)return g=generator.apply(thisArg,_arguments||[]),q=[],i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i;throw new TypeError("Symbol.asyncIterator is not defined.");function verb(n){g[n]&&(i[n]=function(v){return new Promise(function(a,b){1<q.push([n,v,a,b])||resume(n,v)})})}function resume(n,v){try{(r=g[n](v)).value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}catch(e){settle(q[0][3],e)}var r}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){f(v),q.shift(),q.length&&resume(q[0][0],q[0][1])}},__asyncDelegator=function(o){var p,i={};return verb("next"),verb("throw",function(e){throw e}),verb("return"),i[Symbol.iterator]=function(){return this},i;function verb(n,f){i[n]=o[n]?function(v){return(p=!p)?{value:__await(o[n](v)),done:"return"===n}:f?f(v):v}:f}},__asyncValues=function(o){var m,i;if(Symbol.asyncIterator)return(m=o[Symbol.asyncIterator])?m.call(o):(o=__values(o),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);throw new TypeError("Symbol.asyncIterator is not defined.");function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){(function(resolve,reject,d,v){Promise.resolve(v).then(function(v){resolve({value:v,done:d})},reject)})(resolve,reject,(v=o[n](v)).done,v.value)})}}},__makeTemplateObject=function(cooked,raw){return Object.defineProperty?Object.defineProperty(cooked,"raw",{value:raw}):cooked.raw=raw,cooked},__importStar=function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k in mod)Object.hasOwnProperty.call(mod,k)&&(result[k]=mod[k]);return result.default=mod,result},__importDefault=function(mod){return mod&&mod.__esModule?mod:{default:mod}},__classPrivateFieldGet=function(receiver,privateMap){if(privateMap.has(receiver))return privateMap.get(receiver);throw new TypeError("attempted to get private field on non-instance")},__classPrivateFieldSet=function(receiver,privateMap,value){if(privateMap.has(receiver))return privateMap.set(receiver,value),value;throw new TypeError("attempted to set private field on non-instance")},exporter("__extends",__extends),exporter("__assign",__assign),exporter("__rest",__rest),exporter("__decorate",__decorate),exporter("__param",__param),exporter("__metadata",__metadata),exporter("__awaiter",__awaiter),exporter("__generator",__generator),exporter("__exportStar",__exportStar),exporter("__createBinding",__createBinding),exporter("__values",__values),exporter("__read",__read),exporter("__spread",__spread),exporter("__spreadArrays",__spreadArrays),exporter("__await",__await),exporter("__asyncGenerator",__asyncGenerator),exporter("__asyncDelegator",__asyncDelegator),exporter("__asyncValues",__asyncValues),exporter("__makeTemplateObject",__makeTemplateObject),exporter("__importStar",__importStar),exporter("__importDefault",__importDefault),exporter("__classPrivateFieldGet",__classPrivateFieldGet),exporter("__classPrivateFieldSet",__classPrivateFieldSet)})}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],1699:[function(require,module,exports){"use strict";function valueOf(obj){return obj.valueOf?obj.valueOf():Object.prototype.valueOf.call(obj)}module.exports=function valueEqual(a,b){var aValue,bValue;return a===b||null!=a&&null!=b&&(Array.isArray(a)?Array.isArray(b)&&a.length===b.length&&a.every(function(item,index){return valueEqual(item,b[index])}):("object"==typeof a||"object"==typeof b)&&(aValue=valueOf(a),bValue=valueOf(b),aValue!==a||bValue!==b?valueEqual(aValue,bValue):Object.keys(Object.assign({},a,b)).every(function(key){return valueEqual(a[key],b[key])})))}},{}],1700:[function(require,module,exports){"use strict";function valueOf(e){return e.valueOf?e.valueOf():Object.prototype.valueOf.call(e)}module.exports=function valueEqual(u,r){var e,t;return u===r||null!=u&&null!=r&&(Array.isArray(u)?Array.isArray(r)&&u.length===r.length&&u.every(function(e,u){return valueEqual(e,r[u])}):("object"==typeof u||"object"==typeof r)&&(e=valueOf(u),t=valueOf(r),e!==u||t!==r?valueEqual(e,t):Object.keys(Object.assign({},u,r)).every(function(e){return valueEqual(u[e],r[e])})))}},{}],1701:[function(require,module,exports){!function(process){!function(){"use strict";"production"===process.env.NODE_ENV?module.exports=require("./cjs/value-equal.min.js"):module.exports=require("./cjs/value-equal.js")}.call(this)}.call(this,require("_process"))},{"./cjs/value-equal.js":1699,"./cjs/value-equal.min.js":1700,_process:1042}],1702:[function(require,module,exports){"use strict";var warning=function(){};module.exports=warning},{}],1703:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,require("core-js/stable"),require("regenerator-runtime/runtime");var _router=_interopRequireDefault(require("./schedules/router")),_reactRouterDom=require("react-router-dom"),_react=_interopRequireDefault(require("react")),_reactDom=_interopRequireDefault(require("react-dom")),_app=require("./schedules/app"),_sentryLogger=_interopRequireDefault(require("./schedules/common/sentryLogger")),_history=require("history"),_jspdfBrowserify=_interopRequireDefault(require("jspdf-browserify"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _getScheduleApp=function(appConfig){return(0,_app.ScheduleApp)((0,_history.createHashHistory)(),appConfig)};exports.default=function(el,appConfig){_reactDom.default.render(function(appConfig){return _react.default.createElement(_reactRouterDom.HashRouter,null,_react.default.createElement(_router.default,{scheduleApp:_getScheduleApp(appConfig),jsPDF:_jspdfBrowserify.default,sentry:(0,_sentryLogger.default)(appConfig)}))}(appConfig),function(el){return document.getElementById(el)}(el))}},{"./schedules/app":1704,"./schedules/common/sentryLogger":1715,"./schedules/router":1833,"core-js/stable":637,history:653,"jspdf-browserify":661,react:1427,"react-dom":1382,"react-router-dom":1421,"regenerator-runtime/runtime":1430}],1704:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ScheduleApp=exports.PropTypesScheduleApp=exports.PropTypesAppConfig=void 0;var _history=require("./history"),_store=require("./containers/store"),_googleAnalytics=_interopRequireDefault(require("./common/googleAnalytics")),_logoutMiddleware=_interopRequireDefault(require("./containers/logoutMiddleware")),_paramsMiddleware=_interopRequireDefault(require("./containers/paramsMiddleware")),_propTypes=_interopRequireDefault(require("prop-types")),_windowUtils=_interopRequireDefault(require("./common/windowUtils"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.ScheduleApp=function(browserHistory,appConfig){var windowUtils=(0,_windowUtils.default)(window),history=(0,_history.SchedulesHistory)(browserHistory),browserHistory=(0,_paramsMiddleware.default)(browserHistory,_googleAnalytics.default).middleware,windowUtils=(0,_logoutMiddleware.default)(windowUtils).middleware,browserHistory=(0,_store.StoreCreator)({paramsMiddleware:browserHistory,appConfig:appConfig,urlParams:history.params(),logoutMiddleware:windowUtils}).init();return{history:history,store:browserHistory,appConfig:appConfig}};require=_propTypes.default.shape({service_center_id:_propTypes.default.number,asset_id:_propTypes.default.number,tz_correction_offset:_propTypes.default.number,refresh_period:_propTypes.default.number}),exports.PropTypesAppConfig=require,_propTypes=_propTypes.default.shape({history:_history.PropTypesScheduleHistory.isRequired,store:_store.PropTypesStore.isRequired,appConfig:require.isRequired});exports.PropTypesScheduleApp=_propTypes},{"./common/googleAnalytics":1709,"./common/windowUtils":1733,"./containers/logoutMiddleware":1735,"./containers/paramsMiddleware":1736,"./containers/store":1830,"./history":1831,"prop-types":1046}],1705:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};exports.default=function(method){var memo=void 0,slice=Array.prototype.slice;return function(){var args=slice.call(arguments);if(!_ramda.default.equals(memo,args))return memo=args,method.apply(this,args)}}},{ramda:1137}],1706:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function AlertMessageComponent(props){function _isLevel(expected){return props.level==expected}return _react.default.createElement(_semanticUiReact.Message,{onDismiss:props.onConfirm,info:_isLevel("info"),error:_isLevel("error"),positive:_isLevel("positive"),negative:_isLevel("negative"),warning:_isLevel("warning"),hidden:!props.show,className:"no_auto_init"},_react.default.createElement(_semanticUiReact.Message.Header,null,props.header),_react.default.createElement(_semanticUiReact.Message.Content,null,props.content))}AlertMessageComponent.propTypes={show:_propTypes.default.bool,level:_propTypes.default.oneOf(["info","error","positive","warning"]),header:_propTypes.default.string,content:_propTypes.default.string,onConfirm:_propTypes.default.func},exports.default=AlertMessageComponent},{"prop-types":1046,react:1427,"semantic-ui-react":1568}],1707:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){function _toMoment(dateTime){return(0,_moment.default)(dateTime)}function _applyFormat(format){return _ramda.default.compose(function(format){return function(moment){return moment.format(format)}}(format),_toMoment)}_ref=_ref.calendar_display_24h;return{formatTime:_applyFormat(_ref?"HH:mm":"hh:mm A"),formatDate:_applyFormat("dddd, MMMM D")}}},{moment:1031,ramda:1137}],1708:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda")),_userInfo=_interopRequireDefault(require("./userInfo"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){var user=_ref.user,equipment_asset=_ref.equipment_asset,service_center=_ref.service_center,_usersCanViewOwnersInfo=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("users_can_view_reservation_owners")),_isEmployee=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("employee")),_isCollaborator=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("collaborator")),_ownerId=_ramda.default.compose(_ramda.default.defaultTo(null),_ramda.default.view(_ramda.default.lensPath(["owner","id"]))),_ownerName=_ramda.default.compose(_ramda.default.defaultTo(null),_ramda.default.view(_ramda.default.lensPath(["owner","name"]))),_ownerEmail=_ramda.default.compose(_ramda.default.defaultTo(null),_ramda.default.view(_ramda.default.lensPath(["owner","email"]))),_ownerPhone=_ramda.default.compose(_ramda.default.defaultTo(null),_ramda.default.view(_ramda.default.lensPath(["owner","phone"]))),_groupProfileName=_ramda.default.view(_ramda.default.lensPath(["group_profile","name"])),_piName=_ramda.default.view(_ramda.default.lensPath(["group_profile","pi","name"])),_availabilityInfo=_ramda.default.compose(_ramda.default.uniqBy(_ramda.default.prop("name")),_ramda.default.defaultTo([]),_ramda.default.prop("availability_info")),_collaboratorsInfo=_ramda.default.compose(_ramda.default.defaultTo(null),_ramda.default.prop("collaborators_info"));return function(event){var isServiceReservation="ServiceReservation"===event.type,isMaintenanceEvent="ServiceEvent"===event.type,_isEventOwner=function(){return(0,_userInfo.default)(user).loggedIn&&_ownerId(event)===user.id},_isEventAssignee=function(){return _isEventOwner()||_isCollaborator(event)},_showOwnerInfo=function(){return!!(0,_userInfo.default)(user).loggedIn&&(_isEventAssignee()||_usersCanViewOwnersInfo(equipment_asset)||_isEmployee(service_center))},needsApproval=isServiceReservation&&event.needs_approval,isConfirmed=isServiceReservation&&event.confirmed,isSameDay=(0,_moment.default)(event.start_date).isSame(event.end_date,"day"),minutes=(0,_moment.default)(event.end_date).diff(event.start_date,"minutes");return{isServiceReservation:isServiceReservation,isMaintenanceEvent:isMaintenanceEvent,ownerName:_ownerName(event),ownerEmail:_ownerEmail(event),ownerPhone:_ownerPhone(event),isEventOwner:_isEventOwner(event),showOwnerInfo:_showOwnerInfo(),isConfirmed:isConfirmed,pendingApproval:"pending"===event.status,isCancelled:"cancelled"===event.status,isTemporary:"temporary"===event.status,noShow:event.no_show,poorMatch:event.poor_match,needsApproval:needsApproval,showOwnerName:!(!_ownerName(event)||!user)&&(!((0,_userInfo.default)(user).loggedIn||!equipment_asset.public_can_view_reservation_owners)||_showOwnerInfo()),groupProfileName:_groupProfileName(event),piName:_piName(event),availabilityInfo:_availabilityInfo(event),isSameDay:isSameDay,minutes:minutes,cappingCausedApproval:isServiceReservation&&event.capping_caused_approval,hasEquipment:!!_ramda.default.prop("equipment_name",event),hasLinkedEvent:event.has_linked_reservations,hasNotes:!_ramda.default.compose(_ramda.default.isEmpty,_ramda.default.defaultTo(""),_ramda.default.prop("notes"))(event),hasUrgentComments:event.urgent_comments,isEventAssignee:_isEventAssignee(),collaboratorsInfo:_collaboratorsInfo(event),showPrice:(0,_userInfo.default)(user).loggedIn&&(_isEventAssignee()||_isEmployee(service_center))}}}},{"./userInfo":1732,moment:1031,ramda:1137}],1709:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,exports.default={sendPageView:function(pageUrl,fragment){window.ga&&(window.ga("set","page",pageUrl),window.ga("send","pageview","".concat(pageUrl,"#").concat(fragment)))}}},{}],1710:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=_interopRequireDefault(require("ramda")),_html2canvas=_interopRequireDefault(require("html2canvas"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(){function _getElement(cls){return $j(cls)}function _getHeight(element){return element.height()}var _calData=$j(".dhx_cal_data"),_calContainer=$j(".dhx_cal_container"),_gap=14,_getHeaderHeight=function(){return _ramda.default.compose(_ramda.default.sum,_ramda.default.map(_getHeight),_ramda.default.map(_getElement))([".dhx_cal_navline",".dhx_cal_header",".dhx_multi_day"])},_config={dpi:300,scale:1};return{elementImageData:function(element,format){return element=function(element,format){return function(){return(0,_html2canvas.default)(element,_config).then(function(canvas){return{height:canvas.height,width:canvas.width,data:canvas.toDataURL(format)}})}}(element,format),dataHeigth=_calData.height(),containerHeight=_calContainer.height(),format=_calData[0].scrollHeight,window.scroll({top:0}),_calContainer.height(format+_getHeaderHeight()+_gap),_calData.height(format),element().then(function(data){return _calData.height(dataHeigth),_calContainer.height(containerHeight),data});var dataHeigth,containerHeight}}}},{html2canvas:655,ramda:1137}],1711:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var jQuery={height:function(element,_height){return $j(element).height(_height)},getHeight:function(element){return $j(element).height()},getOuterHeight:function(element){return $j(element).outerHeight()},hide:function(element){return $j(element).hide()},show:function(element){return $j(element).show()},contains:function(parent,element){return!(!$j(parent).is(element)&&0===$j(parent).has(element).length)},trigger:function(event,data){return $j.event.trigger(event,data)},on:function(element,event,callback){return $j(element).on(event,callback)},off:function(element,event,callback){return $j(element).off(event,callback)},ajax:$j.ajax};exports.default=jQuery},{}],1712:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(jsPDF){return function(_ref){function pagePosition(_ref2){var width=_ref2.width,_ref2=_ref2.height;return{x:Math.abs(width-_pdfWidth)/2,y:Math.abs(_ref2-_pdfHeight)/2,width:width,height:_ref2}}function _ratio(imgWidth,imgHeight){return imgWidth/imgHeight}var orientation=_ref.orientation,unit=_ref.unit,_ref=_ref.format,pdf=new jsPDF(orientation,unit,_ref),_pdfWidth=pdf.internal.pageSize.width,_pdfHeight=pdf.internal.pageSize.height,_adjustPdfWidth=function(imgWidth,imgHeight){return pagePosition({width:_pdfWidth,height:_pdfWidth/_ratio(imgWidth,imgHeight)})},_adjustPdfHeight=function(imgWidth,imgHeight){return pagePosition({width:_pdfHeight*_ratio(imgWidth,imgHeight),height:_pdfHeight})},pageDimensions=function(imgWidth,imgHeight){if(imgHeight<imgWidth){var dimensions=_adjustPdfWidth(imgWidth,imgHeight);if(dimensions.height<_pdfHeight)return dimensions}return _adjustPdfHeight(imgWidth,imgHeight)};return{addImageToFit:function(_ref3,format){var width=_ref3.width,height=_ref3.height,_ref3=_ref3.data,width=pageDimensions(width,height);pdf.addImage(_ref3,format,width.x,width.y,width.width,width.height)},pageDimensions:pageDimensions,pagePosition:pagePosition,save:function(filename){return pdf.save(filename)}}}}},{}],1713:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;require=(require=require("ramda"))&&require.__esModule?require:{default:require};var _setShowProp=require.default.set(require.default.lensProp("show"));exports.default=function(modalType,initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState,action=1<arguments.length?arguments[1]:void 0;return modalType===action.modalType&&(action=function(action){return{showModal:_setShowProp(!0),closeModal:_setShowProp(!1)}[action.type]}(action))?action(state):state}}},{ramda:1137}],1714:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServiceCenterReducer=exports.ServiceCenterPropTypes=exports.EquipmentByCategoryListPropType=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _initialState={id:0,name:"",all_users_label:"",default_person_select_scope:"",manager:!1,employee:!1,calendar_display_24h:!1,current_user_can_confirm_usage:!1,enable_multi_day_events:!1,show_equipment_by_category:!1,equipment_by_category:[],equipment_text_filter:""},_seviceCenterDataFromAction=_ramda.default.view(_ramda.default.lensPath(["data","service_center"])),_setEquipmentTextFilter=_ramda.default.set(_ramda.default.lensProp("equipment_text_filter")),require=(exports.ServiceCenterReducer=function(){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:_initialState,fn=function(action){return{schedulesShow:_ramda.default.flip(_ramda.default.merge)(_seviceCenterDataFromAction(action)),serviceCentersEquipmentTextFilter:_setEquipmentTextFilter(action.value)}[action.type]}(1<arguments.length?arguments[1]:void 0);return fn?fn(state):state}},_propTypes.default.shape({id:_propTypes.default.number,name:_propTypes.default.string})),require=_propTypes.default.shape({cat_id:_propTypes.default.number,cat_name:_propTypes.default.string,equipment:_propTypes.default.arrayOf(require)}),require=_propTypes.default.arrayOf(require),_propTypes=(exports.EquipmentByCategoryListPropType=require,_propTypes.default.shape({id:_propTypes.default.number,name:_propTypes.default.string,all_users_label:_propTypes.default.string,default_person_select_scope:_propTypes.default.string,manager:_propTypes.default.bool,employee:_propTypes.default.bool,calendar_display_24h:_propTypes.default.bool,current_user_can_confirm_usage:_propTypes.default.bool,enable_multi_day_events:_propTypes.default.bool,show_equipment_by_category:_propTypes.default.bool,equipment_by_category:require}));exports.ServiceCenterPropTypes=_propTypes},{"prop-types":1046,ramda:1137}],1715:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var Sentry=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("@sentry/browser")),_ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}exports.default=function(_ref){var sentryDsn=_ref.sentryDsn,_ref=_ref.environment,tags={namespace:"frontend",application:"schedules"},_getTags=(!function(environment){return _ramda.default.equals(environment,"development")}(_ref)&&(Sentry.init({dsn:sentryDsn,environment:_ref}),Sentry.configureScope(function(scope){scope.setTags(tags)})),_ramda.default.compose(_ramda.default.merge(tags),_ramda.default.defaultTo({}),_ramda.default.prop("tags"))),_getExtras=_ramda.default.compose(_ramda.default.defaultTo({}),_ramda.default.prop("extras")),_setScopeTags=function(context){return function(scope){return scope.setTags(_getTags(context))}},_setScopeExtras=function(context){return function(scope){return scope.setExtras(_getExtras(context))}},_captureMessage=function(message){return function(){return Sentry.captureMessage(message)}},_captureException=function(error){return function(){return Sentry.captureException(error)}};return{message:function(_message){return Sentry.withScope(function(message,context){return _ramda.default.compose(_captureMessage(message),_setScopeExtras(context),_setScopeTags(context))}(_message,1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))},exception:function(error){return Sentry.withScope(function(error,context){return _ramda.default.compose(_captureException(error),_setScopeExtras(context),_setScopeTags(context))}(error,1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}))}}}},{"@sentry/browser":42,ramda:1137}],1716:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _calendarBackgrounds=require("./services/calendarBackgrounds"),_calendarEvents=require("./services/calendarEvents"),_equipments=require("./services/equipments"),_groups=require("./services/groups"),_requestHandler=_interopRequireDefault(require("./services/requestHandler")),_schedules=require("./services/schedules"),_service_centers=require("./services/service_centers"),_jQuery=_interopRequireDefault(require("./jQuery"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){_ref=_ref.sentry,_ref=(0,_requestHandler.default)({sentry:_ref,jQuery:_jQuery.default});return{schedules:(0,_schedules.ServicesSchedules)(_ref),calendarEvents:(0,_calendarEvents.ServicesCalendarEvents)(_ref),equipments:(0,_equipments.ServicesEquipments)(_ref),calendarBackgrounds:(0,_calendarBackgrounds.ServicesCalendarBackgrounds)(_ref),groups:(0,_groups.ServicesGroups)(_ref),service_centers:(0,_service_centers.ServicesServiceCenters)(_ref)}}},{"./jQuery":1711,"./services/calendarBackgrounds":1717,"./services/calendarEvents":1718,"./services/equipments":1719,"./services/groups":1720,"./services/requestHandler":1722,"./services/schedules":1723,"./services/service_centers":1727}],1717:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesCalendarBackgrounds=exports.PropTypesCalendarBackgroundModel=void 0;require=(require=require("prop-types"))&&require.__esModule?require:{default:require};exports.ServicesCalendarBackgrounds=function(_ref){var request=_ref.request;return{index:function(assetId,dates){return request("/calendar_backgrounds.json","GET",{asset_id:assetId,date:dates.moment.format("YYYY-MM-DD")})}}};require=require.default.shape({days:require.default.arrayOf(require.default.number),zones:require.default.arrayOf(require.default.number),css:require.default.string,html:require.default.string});exports.PropTypesCalendarBackgroundModel=require},{"prop-types":1046}],1718:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesCalendarEvents=void 0;exports.ServicesCalendarEvents=function(_ref){var request=_ref.request;return{show:function(eventId){return request("/calendar_events/".concat(eventId,".json"),"GET")}}}},{}],1719:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesEquipments=void 0;exports.ServicesEquipments=function(_ref){var request=_ref.request;return{toggleBookmark:function(asset_id){return request("/equipment/toggle_bookmark/".concat(asset_id,".json"),"POST")},toggleCancellationSubscription:function(asset_id){return request("/equipment/toggle_cancellation_subscription/".concat(asset_id,".json"),"POST")}}}},{}],1720:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesGroups=void 0;exports.ServicesGroups=function(_ref){var request=_ref.request;return{for_user:function(_ref2){var event_type=_ref2.event_type,owner_id=_ref2.owner_id,group_profile_id=_ref2.group_profile_id,service_center_id=_ref2.service_center_id,asset_id=_ref2.asset_id,_ref2=_ref2.usage_capping_enabled;return request("/groups/for_user.json","GET",{event_type:event_type,owner_id:owner_id,group_profile_id:group_profile_id,service_center_id:service_center_id,asset_id:asset_id,usage_capping_enabled:_ref2})}}}},{}],1721:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=(require=require("moment"))&&require.__esModule?require:{default:require};exports.default=function(){return{doRefreshBackgrounds:function(oldProps,nextProps){return oldAsset=oldProps.assetId,nextAsset=nextProps.assetId,oldAsset!==nextAsset||(oldAsset=oldProps.dates.moment,nextAsset=nextProps.dates.moment,!(0,_moment.default)(oldAsset).isSame(nextAsset,"week"))||(oldAsset=oldProps.dates.timeframe,nextAsset=nextProps.dates.timeframe,"month"===oldAsset&&"month"!==nextAsset||"month"!==oldAsset&&"month"===nextAsset);var oldAsset,nextAsset},doRefreshReservations:function(oldProps,nextProps){return!(oldProps.assetId===nextProps.assetId&&(0,_moment.default)(oldProps.dates.first).isSame(nextProps.dates.first,"day")&&(0,_moment.default)(oldProps.dates.last).isSame(nextProps.dates.last,"day"))}}}},{moment:1031}],1722:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _bluebird=_interopRequireDefault(require("bluebird")),_ramda=_interopRequireDefault(require("ramda")),_windowUtils=_interopRequireDefault(require("../windowUtils"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){function _reportToSentry(jqXHR,textStatus,errorThrown){var error;!function(jqXHR){return 0!==parseInt(jqXHR.status,10)}(jqXHR)||(error=new Error(function(jqXHR,textStatus){return"parsererror"===textStatus?"Parsing JSON Request failed.":"timeout"===textStatus?"Request Time out.":"abort"===textStatus?"Request was aborted by the server":_ramda.default.compose(_ramda.default.defaultTo("Unknown Error"),_ramda.default.prop(jqXHR.status))({400:"Server understood the request, but request content was invalid.",401:"Unauthorized access.",403:"Forbidden resource can't be accessed.",500:"Internal server error.",503:"Service unavailable."})}(jqXHR,textStatus)),sentry.exception(error,function(jqXHR,textStatus,errorThrown){return{extras:{XHRreadyState:jqXHR.readyState,XHRstatus:jqXHR.status,XHRresponseText:jqXHR.responseText,XHRstatusText:jqXHR.statusText,textStatus:textStatus,errorThrown:errorThrown}}}(jqXHR,textStatus,errorThrown)))}function _request(url,type,dataType){var data=3<arguments.length&&void 0!==arguments[3]?arguments[3]:{},ifModified=4<arguments.length?arguments[4]:void 0;return new _bluebird.default(function(response,reject){jQuery.ajax({url:url,type:type,dataType:dataType,data:data,ifModified:ifModified,success:function(data){return response(data||null)},error:_errorResponse(reject)})})}var sentry=_ref.sentry,jQuery=_ref.jQuery,_redirectUrl=(0,_windowUtils.default)(window).gotoLocation,_errorResponse=function(reject){return function(jqXHR,textStatus,errorThrown){if(302===jqXHR.status)return _redirectUrl(jqXHR.getResponseHeader("X_ajax_redirect_url"));_reportToSentry(jqXHR,textStatus,errorThrown),reject(new Error(errorThrown))}};return{request:function(url){return _request(url,1<arguments.length&&void 0!==arguments[1]?arguments[1]:"GET","json",2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},!1)},requestCached:function(url){return _request(url,1<arguments.length&&void 0!==arguments[1]?arguments[1]:"GET","json",2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},!0)},htmlRequest:function(url){return _request(url,1<arguments.length&&void 0!==arguments[1]?arguments[1]:"GET","html",2<arguments.length&&void 0!==arguments[2]?arguments[2]:{})}}}},{"../windowUtils":1733,bluebird:112,ramda:1137}],1723:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesSchedules=exports.PropTypesServiceReservationModel=exports.PropTypesServiceEventModel=exports.PropTypesEventModel=void 0;var obj=(obj=require("prop-types"))&&obj.__esModule?obj:{default:obj},_orderableItems=require("./schedules/orderableItems"),_serviceReservations=require("./schedules/serviceReservations"),_usageCappings=require("./schedules/usageCappings");exports.ServicesSchedules=function(_ref){var htmlRequest=_ref.htmlRequest,request=_ref.request,_ref=_ref.requestCached;return{show:function(asset_id){return request("/schedules/".concat(asset_id,".json"),"GET")},serviceReservations:(0,_serviceReservations.ServicesSchedulesServiceReservations)({htmlRequest:htmlRequest,request:request,requestCached:_ref}),orderableItems:(0,_orderableItems.ServicesSchedulesOrderableItem)({request:request}),usageCappings:(0,_usageCappings.ServicesSchedulesUsageCappings)({request:request})}};var require=obj.default.oneOfType([obj.default.instanceOf(Date),obj.default.string]),OwnerPropType=obj.default.shape({id:obj.default.number.isRequired,name:obj.default.string.isRequired,email:obj.default.string.isRequired}),PIPropType=obj.default.shape({name:obj.default.string.isRequired,phone:obj.default.string}),PIPropType=obj.default.shape({id:obj.default.number.isRequired,name:obj.default.string.isRequired,pi:PIPropType}),AvailabilityInfoPropType=obj.default.shape({name:obj.default.string,permission_names:obj.default.string,price:obj.default.string}),PropTypesServiceEventModel=obj.default.shape({id:obj.default.number.isRequired,equipment_id:obj.default.number.isRequired,start_date:require.isRequired,end_date:require.isRequired,type:obj.default.string.isRequired,status:obj.default.string.isRequired,readonly:obj.default.bool.isRequired,css_class:obj.default.string.isRequired,owner:OwnerPropType,equipment_name:obj.default.string,notes:obj.default.string,urgent_comments:obj.default.bool.isRequired,availability_info:obj.default.arrayOf(AvailabilityInfoPropType).isRequired}),require=(exports.PropTypesServiceEventModel=PropTypesServiceEventModel,obj.default.shape({id:obj.default.number.isRequired,equipment_id:obj.default.number.isRequired,start_date:require.isRequired,end_date:require.isRequired,actual_start_date:require.isRequired,actual_end_date:require.isRequired,billing_start_date:require.isRequired,billing_end_date:require.isRequired,type:obj.default.string.isRequired,status:obj.default.string.isRequired,readonly:obj.default.bool.isRequired,css_class:obj.default.string.isRequired,owner:OwnerPropType,group_profile:PIPropType.isRequired,equipment_name:obj.default.string,no_show:obj.default.bool.isRequired,has_linked_reservations:obj.default.bool.isRequired,parent_event_id:obj.default.number,overridable:obj.default.bool.isRequired,poor_match:obj.default.bool.isRequired,notes:obj.default.string,urgent_comments:obj.default.bool.isRequired,capping_caused_approval:obj.default.bool.isRequired,availability_info:obj.default.arrayOf(AvailabilityInfoPropType).isRequired,needs_approval:obj.default.bool.isRequired,approved:obj.default.bool.isRequired,confirmed:obj.default.bool.isRequired,service_project_id:obj.default.number})),OwnerPropType=(exports.PropTypesServiceReservationModel=require,obj.default.oneOfType([PropTypesServiceEventModel,require]));exports.PropTypesEventModel=OwnerPropType},{"./schedules/orderableItems":1724,"./schedules/serviceReservations":1725,"./schedules/usageCappings":1726,"prop-types":1046}],1724:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesSchedulesOrderableItem=exports.PropTypesOrderableItems=void 0;require=(require=require("prop-types"))&&require.__esModule?require:{default:require};exports.ServicesSchedulesOrderableItem=function(_ref){var request=_ref.request;return{index:function(assetId){return request("/schedules/".concat(assetId,"/orderable_items.json"),"GET")}}};var PropTypesAccessabilityEvent=require.default.shape({id:require.default.number.isRequired,readable_day_range:require.default.string.isRequired,readable_time_range:require.default.string.isRequired,prices:require.default.arrayOf(require.default.string).isRequired}),PropTypesAccessabilityEvent=require.default.shape({id:require.default.number.isRequired,supplier_catalog_number:require.default.string.isRequired,color:require.default.string.isRequired,accessability_events:require.default.arrayOf(PropTypesAccessabilityEvent).isRequired}),require=require.default.arrayOf(PropTypesAccessabilityEvent);exports.PropTypesOrderableItems=require},{"prop-types":1046}],1725:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesSchedulesServiceReservations=void 0;exports.ServicesSchedulesServiceReservations=function(_ref){var htmlRequest=_ref.htmlRequest,request=_ref.request,requestCached=_ref.requestCached;return{create:function(assetId,data){return request("/schedules/".concat(assetId,"/service_reservations.json"),"POST",data)},index:function(_ref2){var assetId=_ref2.assetId,dates=_ref2.dates,timeshift=_ref2.timeshift,additionalAssets=_ref2.additionalAssets;return(_ref2.cached?requestCached:request)("/schedules/".concat(assetId,"/service_reservations.json"),"GET",{from:dates.first.format("YYYY-MM-DD"),to:dates.last.format("YYYY-MM-DD"),timeshift:timeshift,additional_assets:additionalAssets,pp:"skip"})},update:function(assetId,reservationId,data){return request("/schedules/".concat(assetId,"/service_reservations/").concat(reservationId,".json"),"PUT",data)},editHtml:function(assetId,eventId,end_date_adjusted){return htmlRequest("/schedules/".concat(assetId,"/service_reservations/").concat(eventId,"/edit.html"),"GET",{end_date_adjusted:end_date_adjusted})}}}},{}],1726:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesSchedulesUsageCappings=void 0;exports.ServicesSchedulesUsageCappings=function(_ref){var request=_ref.request;return{index:function(assetId,owner_id){return request("/schedules/".concat(assetId,"/usage_cappings.json"),"GET",{owner_id:owner_id})}}}},{}],1727:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesServiceCenters=void 0;var _equipment=require("./service_centers/equipment");exports.ServicesServiceCenters=function(_ref){var htmlRequest=_ref.htmlRequest,request=_ref.request,_ref=_ref.requestCached;return{equipment:(0,_equipment.ServicesServiceCentersEquipment)({htmlRequest:htmlRequest,request:request,requestCached:_ref})}}},{"./service_centers/equipment":1728}],1728:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ServicesServiceCentersEquipment=void 0;exports.ServicesServiceCentersEquipment=function(_ref){var request=_ref.request;return{index:function(serviceCenterId){return request("/service_centers/".concat(serviceCenterId,"/equipment.json"),"GET")}}}},{}],1729:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.toLowerCase=void 0;exports.toLowerCase=function(str){return str.toLowerCase()}},{}],1730:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TimerObjectPropTypes=exports.TimerObject=void 0;require=(require=require("prop-types"))&&require.__esModule?require:{default:require};exports.TimerObject={startInterval:function(callback,period){return setInterval(callback,period)},stopInterval:function(intervalId){return clearInterval(intervalId)},startTimeout:function(callback,period){return setTimeout(callback,period)},stopTimeout:function(timeoutId){return clearTimeout(timeoutId)}};require=require.default.shape({startInterval:require.default.func,stopInterval:require.default.func,startTimeout:require.default.func,stopTimeout:require.default.func});exports.TimerObjectPropTypes=require},{"prop-types":1046}],1731:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={assetSettingsUrl:function(service_center_id,asset_id){return"/service_centers/".concat(service_center_id,"/equipment_settings/").concat(asset_id,"/edit")},confirmUsageUnconfirmedUrl:function(service_center_id,asset_id){service_center_id="/service_centers/".concat(service_center_id,"/confirm_usage/search/unconfirmed?filters[sort_by]=start_date&filters[asset_id][]=").concat(asset_id);return encodeURI(service_center_id)},serviceCenterUrl:function(service_center_id){return"/service_center/".concat(service_center_id,"/?tab=equipment")},serviceCenterExternalUrl:function(service_center_id){return"/service_center/show_external/".concat(service_center_id)},scheduleUrl:function(asset_id){var timeframe=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null,date=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,asset_id="/schedules/".concat(asset_id);return timeframe?(timeframe=["/schedule",timeframe],date&&timeframe.push(date),_ramda.default.join("#",[asset_id,_ramda.default.join("/",timeframe)])):asset_id},newReservationUrl:function(asset_id,timeframe,date,start_time,end_time){return"/schedules/".concat(asset_id,"#/schedule/").concat(timeframe,"/").concat(date,"/reservations/new/").concat(start_time,"/").concat(end_time)},editReservationUrl:function(asset_id,reservation_id,moment){return"/equipment/show/".concat(asset_id,"?event_id=").concat(reservation_id,"&date=").concat(moment)},poorMatchChangeUrl:function(asset_id,start_date){var prevDay=(0,_moment.default)(start_date).subtract(1,"days").format("YYYY-MM-DD"),start_date=(0,_moment.default)(start_date).add(1,"days").format("YYYY-MM-DD");return"/equipment/confirm_usage?asset_id=".concat(asset_id,"&end_date=").concat(start_date,"&start_date=").concat(prevDay)}}},{moment:1031,ramda:1137}],1732:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};exports.default=function(user){var _userId=_ramda.default.prop("id");return{loggedIn:_ramda.default.compose(_ramda.default.not,_ramda.default.isNil,_userId)(user)}}},{ramda:1137}],1733:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _urls=(require=require("./urls"))&&require.__esModule?require:{default:require};exports.default=function(windowObj){return{gotoAssetSettings:function(service_center_id,asset_id){windowObj.open(_urls.default.assetSettingsUrl(service_center_id,asset_id),"_blank")},gotoNewConfirmUsage:function(service_center_id,asset_id){windowObj.open(_urls.default.confirmUsageUnconfirmedUrl(service_center_id,asset_id),"_blank")},gotoServiceCenter:function(service_center_id){windowObj.location=_urls.default.serviceCenterUrl(service_center_id)},gotoServiceCenterExternal:function(service_center_id){windowObj.location=_urls.default.serviceCenterExternalUrl(service_center_id)},gotoSchedule:function(asset_id,timeframe,date){windowObj.location=_urls.default.scheduleUrl(asset_id,timeframe,date)},gotoNewReservation:function(asset_id,timeframe,date,start_time,end_time){windowObj.location=_urls.default.newReservationUrl(asset_id,timeframe,date,start_time,end_time)},gotoLocation:function(location){return windowObj.location=location},reload:function(){windowObj.location.reload()}}}},{"./urls":1731}],1734:[function(require,module,exports){!function(global){!function(){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _react=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("react")),_actions=require("./reducers/actions"),_equipmentAssetReducer=require("./reducers/equipmentAssetReducer"),_pdf=_interopRequireDefault(require("../common/pdf")),_propTypes=_interopRequireDefault(require("prop-types")),_app=require("../app"),_ramda=_interopRequireDefault(require("ramda")),_schedule=require("./schedule/schedule"),_mainLoader=_interopRequireDefault(require("./schedule/components/mainLoader")),_schedulerHack=_interopRequireDefault(require("./schedule/components/calendar/schedulerHack")),_selectLab=_interopRequireDefault(require("./selectLab/selectLab")),_selectUser=_interopRequireDefault(require("./selectUser/selectUser")),_services=_interopRequireDefault(require("../common/services")),_windowUtils=_interopRequireDefault(require("../common/windowUtils")),_reactRedux=require("react-redux"),_imageTools=_interopRequireDefault(require("../common/imageTools"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}function mapStateToProps(state){return{state:state}}function ScheduleApp(props){var loading=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.view(_ramda.default.lensPath(["schedules","show"])))(props.state.request);return(0,_react.useEffect)(function(){return props.actions.schedulesShow(props.state.appConfig.asset_id)},[]),_react.default.createElement("div",{id:"schedules_app"},props.state.equipment_asset.id?_react.default.createElement(_schedule.ScheduleLayout,props):_react.default.createElement(_mainLoader.default,{loading:loading}),_react.default.createElement(_selectUser.default,props),_react.default.createElement(_selectLab.default,props))}function _default(_ref){var jsPDF=_ref.jsPDF,_ref=_ref.sentry;return(0,_reactRedux.connect)(mapStateToProps,(0,_actions.ActionCreator)({services:(0,_services.default)({sentry:_ref}),windowUtils:(0,_windowUtils.default)(global.window),schedulerHack:_schedulerHack.default,pdfCreator:(0,_pdf.default)(jsPDF),imageTools:_imageTools.default}).mapDispatchToProps)(App)}var App;ScheduleApp.propTypes={state:_propTypes.default.shape({appConfig:_app.PropTypesAppConfig,request:_propTypes.default.shape({loading:_propTypes.default.bool,calendar_backgrounds:_propTypes.default.shape({index:_propTypes.default.bool}),equipments:_propTypes.default.shape({toogleBookmark:_propTypes.default.bool}),subscriptions:_propTypes.default.shape({toggleCancellationSubscrioption:_propTypes.default.bool}),schedules:_propTypes.default.shape({show:_propTypes.default.bool})}).isRequired,equipment_asset:_equipmentAssetReducer.EquipmentAssetPropTypes}).isRequired,actions:_actions.ActionsProptypes},App=ScheduleApp;exports.default=_default}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../app":1704,"../common/imageTools":1710,"../common/pdf":1712,"../common/services":1716,"../common/windowUtils":1733,"./reducers/actions":1738,"./reducers/equipmentAssetReducer":1754,"./schedule/components/calendar/schedulerHack":1777,"./schedule/components/mainLoader":1805,"./schedule/schedule":1815,"./selectLab/selectLab":1818,"./selectUser/selectUser":1829,"prop-types":1046,ramda:1137,react:1427,"react-redux":1406}],1735:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=_interopRequireDefault(require("ramda")),_userInfo=_interopRequireDefault(require("../common/userInfo"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(windowUtil){var _getUser=_ramda.default.prop("user"),_isLoggedIn=_ramda.default.compose(function(user){return(0,_userInfo.default)(user).loggedIn},_getUser);return{middleware:function(store){return function(next){return function(action){var oldParams=store.getState(),action=next(action);return function(oldParams,newParams){_isLoggedIn(oldParams)&&!_isLoggedIn(newParams)&&windowUtil.reload()}(oldParams,store.getState()),action}}}}}},{"../common/userInfo":1732,ramda:1137}],1736:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(history,googleAnalytics){function _newPathname(state){var start_time,end_time,path="/schedule/".concat(state.dates.timeframe,"/").concat(state.dates.date);return _showUserModal(state)||_showLabModal(state)?(start_time=_ramda.default.compose(_formatTime,_reservationStartTime)(state),end_time=_ramda.default.compose(_formatTime,_reservationEndTime)(state),_ramda.default.concat(path,"/events/new/".concat(start_time,"/").concat(end_time))):_showEventModal(state)?_ramda.default.concat(path,"/events/".concat(_eventModalEventId(state))):path}var _datesDate=_ramda.default.view(_ramda.default.lensPath(["dates","date"])),_datesTimeframe=_ramda.default.view(_ramda.default.lensPath(["dates","timeframe"])),_eventModalEventId=_ramda.default.view(_ramda.default.lensPath(["eventModal","eventId"])),_showEventModal=_ramda.default.view(_ramda.default.lensPath(["eventModal","show"])),_showUserModal=_ramda.default.view(_ramda.default.lensPath(["formSelectUser","showModal"])),_showLabModal=_ramda.default.view(_ramda.default.lensPath(["formSelectLab","showModal"])),_formatTime=function(date){return(0,_moment.default)(date).format("YYYY-MM-DD HH:mm")},_reservationStartTime=function(state){return _ramda.default.view(_ramda.default.lensPath(["formSelectUser","reservation_start_time"]),state)||_ramda.default.view(_ramda.default.lensPath(["formSelectLab","reservation_start_time"]),state)},_reservationEndTime=function(state){return _ramda.default.view(_ramda.default.lensPath(["formSelectUser","reservation_end_time"]),state)||_ramda.default.view(_ramda.default.lensPath(["formSelectLab","reservation_end_time"]),state)},_identicalDates=function(prevState,nextState){return _datesDate(prevState)===_datesDate(nextState)&&_datesTimeframe(prevState)===_datesTimeframe(nextState)},_identicalShowModal=function(prevState,nextState){return _ramda.default.equals(_showUserModal(prevState),_showUserModal(nextState))&&_ramda.default.equals(_showLabModal(prevState),_showLabModal(nextState))&&_ramda.default.equals(_showEventModal(prevState),_showEventModal(nextState))},_indenticalHistoryLocation=function(nextState){return history.location.pathname===_newPathname(nextState)},_pushHistory=function(state){!function(state){history&&history.push&&history.push(_newPathname(state))}(state),function(state){googleAnalytics&&googleAnalytics.sendPageView&&googleAnalytics.sendPageView(function(state){return"/schedules/".concat(state.equipment_asset.id)}(state),_newPathname(state))}(state)};return{middleware:function(store){return function(next){return function(action){var oldParams=store.getState(),action=next(action),newParams=store.getState();return _identicalDates(oldParams=oldParams,newParams=newParams)&&_identicalShowModal(oldParams,newParams)&&_indenticalHistoryLocation(newParams)||_pushHistory(newParams),action}}}}}},{moment:1031,ramda:1137}],1737:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _react=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("react")),_propTypes=_interopRequireDefault(require("prop-types")),_reactRedux=require("react-redux"),_app=_interopRequireDefault(require("./app"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}function ScheduleProvider(props){return _react.default.createElement(_reactRedux.Provider,{store:props.store},(0,_react.createElement)((0,_app.default)({jsPDF:props.jsPDF,sentry:props.sentry})))}ScheduleProvider.propTypes={store:_propTypes.default.object.isRequired,jsPDF:_propTypes.default.func.isRequired,sentry:_propTypes.default.object.isRequired},exports.default=ScheduleProvider},{"./app":1734,"prop-types":1046,react:1427,"react-redux":1406}],1738:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ActionsProptypes=exports.ActionCreator=void 0;var _downloadPdf=_interopRequireDefault(require("./actions/downloadPdf")),_loadEventModal=_interopRequireDefault(require("./actions/loadEventModal")),_propTypes=_interopRequireDefault(require("prop-types")),_serviceAction=_interopRequireDefault(require("./serviceAction")),_serviceCalendarBackgroundIndex=_interopRequireDefault(require("./actions/serviceCalendarBackgroundIndex")),_serviceReservationCreate=_interopRequireDefault(require("./actions/serviceReservationCreate")),_serviceReservationIndex=_interopRequireDefault(require("./actions/serviceReservationIndex")),_serviceReservationSave=_interopRequireDefault(require("./actions/serviceReservationSave")),_serviceReservationUpdate=_interopRequireDefault(require("./actions/serviceReservationUpdate")),_setUserSelect=_interopRequireDefault(require("./actions/setUserSelect")),_toggleAdditionalAsset=_interopRequireDefault(require("./actions/toggleAdditionalAsset"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.ActionCreator=function(_ref){var services=_ref.services,schedulerHack=_ref.schedulerHack,windowUtils=_ref.windowUtils,pdfCreator=_ref.pdfCreator,imageTools=_ref.imageTools;return{mapDispatchToProps:function(dispatch){return{actions:{increase:function(){dispatch({type:"increase"})},decrease:function(){dispatch({type:"decrease"})},toggleFavorite:function(services,dispatch){return function(assetId){return(0,_serviceAction.default)({dispatch:dispatch,promise:services.equipments.toggleBookmark(assetId),loadingLense:["equipments","toogleBookmark"],completeAction:"toggleFavorite"})}}(services,dispatch),toggleCancellationSubscription:function(services,dispatch){return function(assetId){return(0,_serviceAction.default)({dispatch:dispatch,promise:services.equipments.toggleCancellationSubscription(assetId),loadingLense:["equipments","toggleCancellationSubscription"],completeAction:"toggleCancellationSubscription"})}}(services,dispatch),serviceReservationCreate:(0,_serviceReservationCreate.default)({dispatch:dispatch,serviceReservationSave:(0,_serviceReservationSave.default)({services:services,dispatch:dispatch,windowUtils:windowUtils})}),serviceReservationIndex:(0,_serviceReservationIndex.default)(services,dispatch),serviceReservationUpdate:(0,_serviceReservationUpdate.default)(services,dispatch),serviceReservationSave:(0,_serviceReservationSave.default)({services:services,dispatch:dispatch,windowUtils:windowUtils}),calendarBackgroundIndex:(0,_serviceCalendarBackgroundIndex.default)(services,dispatch),orderableItemsIndex:function(services,dispatch){return function(assetId){return(0,_serviceAction.default)({dispatch:dispatch,promise:services.schedules.orderableItems.index(assetId),loadingLense:["orderable_items","index"],completeAction:"orderableItemsIndex"})}}(services,dispatch),schedulesShow:function(services,dispatch){return function(assetId){return(0,_serviceAction.default)({dispatch:dispatch,promise:services.schedules.show(assetId),loadingLense:["schedules","show"],completeAction:"schedulesShow"})}}(services,dispatch),scheduleLink:function(asset_id){windowUtils.gotoSchedule(asset_id)},clickAssetSettingsLink:function(service_center_id,asset_id){windowUtils.gotoAssetSettings(service_center_id,asset_id)},clickNewConfirmUsageLink:function(service_center_id,asset_id){windowUtils.gotoNewConfirmUsage(service_center_id,asset_id)},clickServiceCenterLink:function(service_center_id,loggedIn){(loggedIn?windowUtils.gotoServiceCenter:windowUtils.gotoServiceCenterExternal)(service_center_id)},showAlertBox:function(modal,level,header,content){dispatch({type:"showAlertBox",modal:modal,level:level,header:header,content:content})},closeAlertBox:function(){dispatch({type:"closeAlertBox"})},resetTimeoutAlertBox:function(){dispatch({type:"resetTimeoutAlertBox"})},setAlertBoxTimeoutId:function(timeoutId){dispatch({type:"setAlertBoxTimeoutId",timeoutId:timeoutId})},showDescriptionModal:function(){dispatch({type:"showModal",modalType:"description"})},closeDescriptionModal:function(){dispatch({type:"closeModal",modalType:"description"})},showCalendarDetailsModal:function(){dispatch({type:"showModal",modalType:"calendarDetails"})},closeCalendarDetailsModal:function(){dispatch({type:"closeModal",modalType:"calendarDetails"})},showEventModal:function(eventId,isNewEvent){dispatch({type:"showEventModal",eventId:eventId,isNewEvent:isNewEvent})},loadEventModal:(0,_loadEventModal.default)({services:services,dispatch:dispatch,schedulerHack:schedulerHack}),closeEventModal:function(){dispatch({type:"closeEventModal"})},timeframeSelect:function(timeframe){dispatch({type:"timeframeSelect",timeframe:timeframe})},dateSelect:function(date){dispatch({type:"dateSelect",date:date})},timeframeDateSelect:function(timeframe,date){dispatch({type:"timeframeDateSelect",timeframe:timeframe,date:date})},prevDate:function(){dispatch({type:"prevDate"})},nextDate:function(){dispatch({type:"nextDate"})},onStartDragReservation:function(reservation){dispatch({type:"onStartDragReservation",reservation:reservation})},onEndDragReservation:function(){dispatch({type:"onEndDragReservation"})},showReservationUpdateModal:function(header,content,reservation){dispatch({type:"showReservationUpdateModal",data:{header:header,content:content,reservation:reservation}})},resetReservationUpdateModal:function(){dispatch({type:"resetReservationUpdateModal"})},updateReservation:function(reservation){dispatch({type:"updateReservation",reservation:reservation})},setSelectUserTimes:function(start_time,end_time){dispatch({type:"setSelectUserTimes",start_time:start_time,end_time:end_time})},selectReservationType:function(reservationType){dispatch({type:"selectReservationType",reservationType:reservationType})},selectUserSearchScope:function(userSearchScope){dispatch({type:"selectUserSearchScope",userSearchScope:userSearchScope})},openModalUserSelect:function(equipmentId,start_time,end_time){dispatch({type:"closeAlertBox"}),dispatch({type:"openModalUserSelect",equipmentId:equipmentId,start_time:start_time,end_time:end_time})},closeModalUserSelect:function(){dispatch({type:"closeAlertBox"}),dispatch({type:"closeModalUserSelect"})},setUserDropdownText:function(text){dispatch({type:"setUserDropdownText",text:text})},setUserSelect:(0,_setUserSelect.default)(services,dispatch),setUserGroups:function(data){dispatch({type:"setUserGroups",data:data})},setGroupSelect:function(group_id){dispatch({type:"setGroupSelect",group_id:group_id})},openModalLabSelect:function(equipmentId,start_time,end_time){dispatch({type:"closeAlertBox"}),dispatch({type:"openModalLabSelect",equipmentId:equipmentId,start_time:start_time,end_time:end_time})},closeModalLabSelect:function(){dispatch({type:"closeAlertBox"}),dispatch({type:"closeModalLabSelect"})},showBackgroundMessage:function(message){dispatch({type:"showBackgroundMessage",message:message})},closeBackgroundMessage:function(){dispatch({type:"closeBackgroundMessage"})},showLinkedReservationModal:function(eventId,parentEventId){dispatch({type:"showLinkedReservationModal",eventId:eventId,parentEventId:parentEventId})},closeLinkedReservationModal:function(){dispatch({type:"closeLinkedReservationModal"})},toggleAdditionalAssets:(0,_toggleAdditionalAsset.default)(services,dispatch),downloadPdf:(0,_downloadPdf.default)({dispatch:dispatch,pdfCreator:pdfCreator,imageTools:imageTools}),serviceCentersEquipmentTextFilter:function(value){dispatch({type:"serviceCentersEquipmentTextFilter",value:value})}}}}}};require=_propTypes.default.shape({schedulesShow:_propTypes.default.func,clickScheduleLink:_propTypes.default.func,increase:_propTypes.default.func,decrease:_propTypes.default.func,toggleFavorite:_propTypes.default.func,toggleCancellatiionSubscription:_propTypes.default.func,clickAssetSettingsLink:_propTypes.default.func,clickNewConfirmUsageLink:_propTypes.default.func,clickServiceCenterLink:_propTypes.default.func,showDescriptionModal:_propTypes.default.func,closeDescriptionModal:_propTypes.default.func,showCalendarDetailsModal:_propTypes.default.func,closeCalendarDetailsModal:_propTypes.default.func,timeframeSelect:_propTypes.default.func,timeframeDateSelect:_propTypes.default.func,dateSelect:_propTypes.default.func,prevDate:_propTypes.default.func,nextDate:_propTypes.default.func,serviceReservationCreate:_propTypes.default.func,serviceReservationIndex:_propTypes.default.func,serviceReservationUpdate:_propTypes.default.func,showAlertBox:_propTypes.default.func,closeAlertBox:_propTypes.default.func,resetTimeoutAlertBox:_propTypes.default.func,setAlertBoxTimeoutId:_propTypes.default.func,onStartDragReservation:_propTypes.default.func,onEndDragReservation:_propTypes.default.func,resetReservationUpdateModal:_propTypes.default.func,updateReservation:_propTypes.default.func,openModalUserSelect:_propTypes.default.func,closeModalUserSelect:_propTypes.default.func,serviceReservationSave:_propTypes.default.func,selectReservationType:_propTypes.default.func,selectUserSearchScope:_propTypes.default.func,setUserDropdownText:_propTypes.default.func,setUserSelect:_propTypes.default.func,setUserGroups:_propTypes.default.func,setGroupSelect:_propTypes.default.func,openModalLabSelect:_propTypes.default.func,closeModalLabSelect:_propTypes.default.func,showEventModal:_propTypes.default.func,loadEventModal:_propTypes.default.shape({load:_propTypes.default.func,cancelChanges:_propTypes.default.func}),showBackgroundMessage:_propTypes.default.func,closeBackgroundMessage:_propTypes.default.func,showLinkedReservationModal:_propTypes.default.func,closeLinkedReservationModal:_propTypes.default.func,toggleAdditionalAssets:_propTypes.default.func,downloadPdf:_propTypes.default.func,cerviceCentersEquipmentTextFilter:_propTypes.default.func}).isRequired;exports.ActionsProptypes=require},{"./actions/downloadPdf":1739,"./actions/loadEventModal":1740,"./actions/serviceCalendarBackgroundIndex":1742,"./actions/serviceReservationCreate":1743,"./actions/serviceReservationIndex":1744,"./actions/serviceReservationSave":1745,"./actions/serviceReservationUpdate":1746,"./actions/setUserSelect":1747,"./actions/toggleAdditionalAsset":1748,"./serviceAction":1763,"prop-types":1046}],1739:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _bluebird=_interopRequireDefault(require("bluebird")),_serviceAction=_interopRequireDefault(require("../serviceAction"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){var dispatch=_ref.dispatch,pdfCreator=_ref.pdfCreator,imageTools=_ref.imageTools;return function(element,filename){var promise=new _bluebird.default(function(resolve){imageTools().elementImageData(element,"image/png").then(function(data){var objectPdf=pdfCreator({orientation:"l",unit:"mm",format:"a4"});objectPdf.addImageToFit(data,"PNG"),objectPdf.save(filename),resolve()})});return(0,_serviceAction.default)({dispatch:dispatch,promise:promise,loadingLense:["download","pdf"],completeAction:"downloadedPdf"})}}},{"../serviceAction":1763,bluebird:112}],1740:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _serviceAction2=(require=require("../serviceAction"))&&require.__esModule?require:{default:require};exports.default=function(_ref){function cancelChanges(isNewEvent,refreshReservations){isNewEvent?schedulerHack.removeServiceEvent():_closeReservationModal(refreshReservations)}var services=_ref.services,dispatch=_ref.dispatch,schedulerHack=_ref.schedulerHack,_closeReservationModal=function(refreshReservations){return schedulerHack.destroy(),dispatch({type:"closeEventModal"}),refreshReservations(),!0};return{load:function(_ref2){function _closeEventModal(){return _closeReservationModal(refreshReservations)}function _cancelChanges(){return cancelChanges(isNewEvent,refreshReservations)}function _refreshEventModal(){return dispatch({type:"clearHtmlForm"}),schedulerHack.destroy(),_serviceAction()}function _showBackgroundMessage(message){dispatch({type:"showBackgroundMessage",message:message})}function _closeBackgroundMessage(){dispatch({type:"closeBackgroundMessage"}),refreshReservations()}function _setHtmlForm(htmlForm){return dispatch({type:"setHtmlForm",htmlForm:htmlForm}),htmlForm}function _catchError(error){return dispatch({type:"closeEventModal"}),error}function _serviceAction(){return(0,_serviceAction2.default)({dispatch:dispatch,promise:services.calendarEvents.show(eventId).then(function(_ref6){var data=_ref6.data,_ref6=_ref6.meta;return data.has_linked_event?(dispatch({type:"closeEventModal"}),dispatch({type:"showLinkedReservationModal",eventId:data.id,parentEventId:data.parent_event_id}),data):(_setGlobalSchedulerEvent({data:data,meta:_ref6}),_promiseLoadEditHtml({event:data,meta:_ref6}))}).catch(_catchError),loadingLense:["calendar_events","show"],completeAction:"loadEventModalFinished"})}var eventId=_ref2.eventId,isNewEvent=_ref2.isNewEvent,refreshReservations=_ref2.refreshReservations,end_date_adjusted=_ref2.end_date_adjusted,_setGlobalSchedulerEvent=function(_ref3){var data=_ref3.data,_ref3=_ref3.meta;return schedulerHack.setGlobalSchedulerEvent(data),{event:data,meta:_ref3}},_promiseLoadEditHtml=function(_ref5){var event=_ref5.event,_ref5=_ref5.meta;return services.schedules.serviceReservations.editHtml(event.asset_id,eventId,end_date_adjusted).then(_setHtmlForm).then(function(_ref4){var event=_ref4.event,meta=_ref4.meta;return function(html){return schedulerHack.init({eventId:eventId,assetId:event.asset_id,employee:meta.employee,closeEventModal:_closeEventModal,cancelChanges:_cancelChanges,refreshEventModal:_refreshEventModal,refreshReservations:refreshReservations,showBackgroundMessage:_showBackgroundMessage,closeBackgroundMessage:_closeBackgroundMessage,html:html}),html}}({event:event,meta:_ref5}))};return _serviceAction()},cancelChanges:cancelChanges}}},{"../serviceAction":1763}],1741:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_ramda=(obj=require("ramda"))&&obj.__esModule?obj:{default:obj},_i18n=require("../../../i18n");function _validationOverMaxTime(_ref){var equipment_asset=_ref.equipment_asset,_ref=_ref.reservation,equipment_asset=_maximumTimeMinutes(equipment_asset);return{error:_reservationDurationMinutes(_ref)>equipment_asset,message:(0,_i18n.t)("validations.maximum_time",{time:equipment_asset})}}function _validationBelowMinTime(_ref2){var equipment_asset=_ref2.equipment_asset,_ref2=_ref2.reservation,equipment_asset=_minimumTimeMinutes(equipment_asset);return{error:_reservationDurationMinutes(_ref2)<equipment_asset,message:(0,_i18n.t)("validations.minimum_time",{time:equipment_asset})}}var _reservationDurationMinutes=function(reservation){return(reservation.end_date-reservation.start_date)/6e4},_maximumTimeMinutes=_ramda.default.compose(_ramda.default.defaultTo(40320),_ramda.default.prop("maximum_time")),_minimumTimeMinutes=_ramda.default.compose(_ramda.default.defaultTo(0),_ramda.default.prop("minimum_time"));exports.default=function(_ref3){function _testValidation(validation){return _instanceValidation(validation).error}function _returnOk(){return{error:!1,message:""}}function canUpdate(){var _failedValidation;return!_isEmployee(service_center)&&(_failedValidation=_ramda.default.find(_testValidation,_validations))?{error:!0,message:_messageValidation(_failedValidation)}:_returnOk()}var service_center=_ref3.service_center,equipment_asset=_ref3.equipment_asset,reservation=_ref3.reservation,_isEmployee=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("employee")),_validations=[_validationOverMaxTime,_validationBelowMinTime],_instanceValidation=function(validation){return validation({equipment_asset:equipment_asset,reservation:reservation})},_messageValidation=function(validation){return _instanceValidation(validation).message};return{canUpdate:canUpdate,canCreate:canUpdate}}},{"../../../i18n":1832,ramda:1137}],1742:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _serviceAction=_interopRequireDefault(require("../serviceAction")),_userInfo=_interopRequireDefault(require("../../../common/userInfo"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(services,dispatch){return function(_ref){var assetId=_ref.assetId,dates=_ref.dates,_ref=_ref.user;return(0,_userInfo.default)(_ref).loggedIn&&"month"!==dates.timeframe?(0,_serviceAction.default)({dispatch:dispatch,promise:services.calendarBackgrounds.index(assetId,dates),loadingLense:["calendar_backgrounds","index"],completeAction:"calendarBackgroundIndex"}):Promise.resolve({data:{availabilities:{}}}).then(function(data){return dispatch({type:"calendarBackgroundIndex",data:data}),data})}}},{"../../../common/userInfo":1732,"../serviceAction":1763}],1743:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj=(obj=require("ramda"))&&obj.__esModule?obj:{default:obj},_i18n=require("../../../i18n");var _firstGroupId=obj.default.compose(obj.default.prop("id"),obj.default.defaultTo({}),obj.default.nth(0),obj.default.defaultTo([]),obj.default.prop("groups")),_getGroups=obj.default.compose(obj.default.defaultTo([]),obj.default.prop("groups"));exports.default=function(_ref){var dispatch=_ref.dispatch,serviceReservationSave=_ref.serviceReservationSave;return function(_ref2){var user=_ref2.user,equipment_asset=_ref2.equipment_asset,service_center=_ref2.service_center,_ref2=_ref2.reservation,equipmentId=_ref2.equipment_id,equipment_asset=equipment_asset.id,service_center=service_center.employee,start_time=_ref2.start_date,_ref2=_ref2.end_date;return dispatch({type:"closeAlertBox"}),service_center?dispatch({type:"openModalUserSelect",equipmentId:equipmentId,start_time:start_time,end_time:_ref2}):0===_getGroups(user).length?function(dispatch,message){dispatch({type:"showAlertBox",modal:!0,level:"error",header:(0,_i18n.t)("user_select.create_reservation"),content:message})}(dispatch,(0,_i18n.t)("update_reservation.you_have_no_labs")):1<_getGroups(user).length?dispatch({type:"openModalLabSelect",equipmentId:equipmentId,start_time:start_time,end_time:_ref2}):serviceReservationSave({assetId:equipment_asset,equipmentId:equipmentId,start_time:start_time,end_time:_ref2,ownerId:user.id,groupProfileId:_firstGroupId(user),event_type:"reservation"})}}},{"../../../i18n":1832,ramda:1137}],1744:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _serviceAction=(require=require("../serviceAction"))&&require.__esModule?require:{default:require};exports.default=function(services,dispatch){return function(_ref){var assetId=_ref.assetId,dates=_ref.dates,timeshift=_ref.timeshift,additionalAssets=_ref.additionalAssets,showAdditionalAssets=_ref.showAdditionalAssets,_ref=_ref.cached;return(0,_serviceAction.default)({dispatch:dispatch,promise:services.schedules.serviceReservations.index({assetId:assetId,dates:dates,timeshift:timeshift,additionalAssets:additionalAssets=showAdditionalAssets?additionalAssets:[],cached:_ref}),loadingLense:["schedules","index"],completeAction:"serviceReservationIndex"})}}},{"../serviceAction":1763}],1745:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda")),_serviceAction=_interopRequireDefault(require("../serviceAction")),_i18n=require("../../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _formatTime(date){return(0,_moment.default)(date).format("YYYY-MM-DD HH:mm")}exports.default=function(_ref){var services=_ref.services,dispatch=_ref.dispatch;return function(_ref2){var assetId=_ref2.assetId,equipmentId=_ref2.equipmentId,start_time=_ref2.start_time,end_time=_ref2.end_time,ownerId=_ref2.ownerId,groupProfileId=_ref2.groupProfileId,_ref2=_ref2.event_type,_isEndDateAdjusted=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.view(_ramda.default.lensPath(["meta","end_date_adjusted"]))),_reservationId=_ramda.default.view(_ramda.default.lensPath(["reservation","id"])),_metaError=_ramda.default.view(_ramda.default.lensPath(["meta","error"])),_hasError=_ramda.default.compose(_ramda.default.not,_ramda.default.isEmpty,_metaError);return(0,_serviceAction.default)({dispatch:dispatch,promise:services.schedules.serviceReservations.create(assetId,{event_type:_ramda.default.defaultTo("reservation",_ref2),equipment_id:equipmentId,start_date:_formatTime(start_time),end_date:_formatTime(end_time),owner_id:ownerId,group_profile_id:groupProfileId}).then(function(data){var eventId,content;return _hasError(data)?(content=_metaError(data),dispatch({type:"showAlertBox",show:!0,modal:!0,level:"error",header:(0,_i18n.t)("user_select.save_reservation_error"),content:content})):(content={eventId:_reservationId(data),end_date_adjusted:_isEndDateAdjusted(data)},eventId=content.eventId,content=content.end_date_adjusted,dispatch({type:"showEventModal",eventId:eventId,isNewEvent:!0,end_date_adjusted:content})),data}),loadingLense:["service_reservations","create"],completeAction:"serviceReservationCreated"})}}},{"../../../i18n":1832,"../serviceAction":1763,moment:1031,ramda:1137}],1746:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda")),_serviceAction=_interopRequireDefault(require("../serviceAction")),_reservationValidations=_interopRequireDefault(require("./reservationValidations")),_i18n=require("../../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _meta(meta){function _getField(field){return _ramda.default.view(_ramda.default.lensProp(field))}var result=_getField("result")(meta);return{message:_getField("error")(meta),isError:_ramda.default.equals(result,"error")}}function _showAlertBox(dispatch,message){dispatch({type:"showAlertBox",modal:!0,level:"error",header:(0,_i18n.t)("update_reservation.header"),content:message}),dispatch({type:"resetReservationUpdateModal"})}var _formatTime=function(date){return(0,_moment.default)(date).format("YYYY-MM-DD HH:mm")};exports.default=function(services,dispatch){return function(_ref){var equipment_asset=_ref.equipment_asset,service_center=_ref.service_center,_ref=_ref.reservation,service_center=(0,_reservationValidations.default)({equipment_asset:equipment_asset,service_center:service_center,reservation:_ref}).canUpdate();return service_center.error?_showAlertBox(dispatch,service_center.message):(service_center=services.schedules.serviceReservations.update(equipment_asset.id,_ref.id,function(reservation){return{valid_override:reservation.valid_override,equipment_id:reservation.equipment_id,start_date:_formatTime(reservation.start_date),end_date:_formatTime(reservation.end_date),actual_start_date:_formatTime(reservation.actual_start_date),actual_end_date:_formatTime(reservation.actual_end_date),billing_start_date:_formatTime(reservation.billing_start_date),billing_end_date:_formatTime(reservation.billing_end_date),service_project_id:reservation.service_project_id}}(_ref)).then(function(data){var metaInfo=_meta(data.meta);return metaInfo.isError?data.reservation.overridable?function(dispatch,data){dispatch({type:"showReservationUpdateModal",data:data})}(dispatch,{header:(0,_i18n.t)("update_reservation.header"),content:(0,_i18n.t)("update_reservation.proceed_message",{message:metaInfo.message}),reservation:data.reservation}):_showAlertBox(dispatch,metaInfo.message):function(dispatch,reservation){dispatch({type:"resetReservationUpdateModal",reservation:reservation}),dispatch({type:"updateReservation",reservation:reservation})}(dispatch,data.reservation),data}),(0,_serviceAction.default)({dispatch:dispatch,promise:service_center,loadingLense:["schedules","update"],completeAction:"serviceReservationUpdate"}))}}},{"../../../i18n":1832,"../serviceAction":1763,"./reservationValidations":1741,moment:1031,ramda:1137}],1747:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _bluebird=_interopRequireDefault(require("bluebird")),_ramda=_interopRequireDefault(require("ramda")),_serviceAction=_interopRequireDefault(require("../serviceAction")),_i18n=require("../../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(services,dispatch){return function(_ref){var event_type=_ref.event_type,user=_ref.user,group_profile_id=_ref.group_profile_id,service_center_id=_ref.service_center_id,asset_id=_ref.asset_id,_ref=_ref.usage_capping_enabled,_userGroups=_ramda.default.compose(_ramda.default.defaultTo([]),_ramda.default.prop("group_profiles")),_dispatchSetUserSelect=function(){return dispatch({type:"setUserSelect",user:user})},_alertIfNoGroup=function(data){0===_userGroups(data).length&&!function(dispatch){dispatch({type:"showAlertBox",show:!0,modal:!1,level:"error",header:(0,_i18n.t)("user_select.user_without_groups.header"),content:(0,_i18n.t)("user_select.user_without_groups.content")})}(dispatch)},_dispatchSetUserGroup=function(data){return dispatch({type:"setUserGroups",data:data})},event_type=services.groups.for_user({event_type:event_type,owner_id:user.id,group_profile_id:group_profile_id,service_center_id:service_center_id,asset_id:asset_id,usage_capping_enabled:_ref}).then(function(data){return _dispatchSetUserSelect(),_alertIfNoGroup(data),_dispatchSetUserGroup(data),data}),group_profile_id=services.schedules.usageCappings.index(asset_id,user.id).then(function(data){return dispatch({type:"setUsageCappings",data:data}),data});return(0,_serviceAction.default)({dispatch:dispatch,promise:_bluebird.default.all([event_type,group_profile_id]),loadingLense:["groups","for_user"],completeAction:"setUserSelectFinished"})}}},{"../../../i18n":1832,"../serviceAction":1763,bluebird:112,ramda:1137}],1748:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _serviceReservationIndex=(require=require("./serviceReservationIndex"))&&require.__esModule?require:{default:require};exports.default=function(services,dispatch){var lense=["equipment_asset","additional_assets"],reservationIndex=(0,_serviceReservationIndex.default)(services,dispatch);return function(_ref){var assetId=_ref.assetId,dates=_ref.dates,timeshift=_ref.timeshift,additionalAssets=_ref.additionalAssets,_ref=_ref.showAdditionalAssets;return dispatch({type:"startRequest",lense:lense}),dispatch({type:"toggleAdditionalAssets"}),reservationIndex({assetId:assetId,dates:dates,timeshift:timeshift,additionalAssets:additionalAssets,showAdditionalAssets:!_ref,cached:!1}).then(function(data){return dispatch({type:"stopRequest",lense:lense}),data})}}},{"./serviceReservationIndex":1744}],1749:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=_interopRequireDefault(require("ramda")),_userInfo=_interopRequireDefault(require("../../common/userInfo")),_i18n=require("../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _alertIfForReadOnlyEquipment=function(action){var _getUser=_ramda.default.view(_ramda.default.lensPath(["data","user"])),_getUser=_ramda.default.compose(function(user){return(0,_userInfo.default)(user).loggedIn},_getUser),_equipmentCanRead=_ramda.default.view(_ramda.default.lensPath(["data","equipment_asset","can_read"])),_equipmentCanWrite=_ramda.default.view(_ramda.default.lensPath(["data","equipment_asset","can_write"]));return _equipmentCanRead(action)&&!_equipmentCanWrite(action)&&_getUser(action)?_ramda.default.always({show:!0,modal:!1,level:"info",header:(0,_i18n.t)("restricted_schedule.readonly_accesss.header"),content:(0,_i18n.t)("restricted_schedule.readonly_accesss.content")}):_ramda.default.identity},_closeKeepModal=function(state){return{show:!1,modal:state.modal,resetTimeout:!1,timeoutId:null}},_resetTimeoutAlertBox=_ramda.default.set(_ramda.default.lensProp("resetTimeout"),!1),_setAlertBoxTimeoutId=function(action){return _ramda.default.set(_ramda.default.lensProp("timeoutId"),_ramda.default.prop("timeoutId",action))};exports.default=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return{showAlertBox:_ramda.default.flip(_ramda.default.merge)({show:!0,modal:action.modal,level:action.level,header:action.header,content:action.content,resetTimeout:!0}),closeAlertBox:_closeKeepModal,resetTimeoutAlertBox:_resetTimeoutAlertBox,setAlertBoxTimeoutId:_setAlertBoxTimeoutId(action),schedulesShow:_alertIfForReadOnlyEquipment(action)}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0)(state)}}},{"../../common/userInfo":1732,"../../i18n":1832,ramda:1137}],1750:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};exports.default=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return{}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0)(state)}}},{ramda:1137}],1751:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BackgroundMessageReducer=exports.BackgroundMessagePropTypes=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _setField(field){return _ramda.default.set(_ramda.default.lensProp(field))}var _setShowProp=_ramda.default.set(_ramda.default.lensProp("show")),_setMessage=_ramda.default.compose(_setField("message"),_ramda.default.prop("message")),_showBackgroundMessage=function(action){return _ramda.default.compose(_setShowProp(!0),_setMessage(action))},_closeBackgroundMessage=function(){return _ramda.default.compose(_setShowProp(!1),_setField("message")(null))},require=(exports.BackgroundMessageReducer=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return _ramda.default.defaultTo(_ramda.default.identity,{showBackgroundMessage:_showBackgroundMessage(action),closeBackgroundMessage:_closeBackgroundMessage()}[action.type])}(1<arguments.length?arguments[1]:void 0)(state)}},_propTypes.default.shape({show:_propTypes.default.boolean,message:_propTypes.default.string}));exports.BackgroundMessagePropTypes=require},{"prop-types":1046,ramda:1137}],1752:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};var _calendarBackgroundAvailabilitiesData=_ramda.default.compose(_ramda.default.flatten,_ramda.default.values,_ramda.default.defaultTo([]),_ramda.default.view(_ramda.default.lensPath(["data","availabilities"])));exports.default=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return{calendarBackgroundIndex:function(){return _calendarBackgroundAvailabilitiesData(action)}}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0)(state)}}},{ramda:1137}],1753:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PropTypesDatesReducer=exports.DatesReducer=void 0;var _dateCalculator=_interopRequireDefault(require("../schedule/dateCalculator")),_moment=_interopRequireDefault(require("moment")),_propTypes=require("prop-types"),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _transformState(state){var timeframe=_defaultTimeframe(state.timeframe),moment=_toMoment(state.date),date=_toDate(moment),week_starts_on_monday=_defaultToFalse(state.week_starts_on_monday);return _ramda.default.merge({timeframe:timeframe,date:date,moment:moment,week_starts_on_monday:week_starts_on_monday,params:state.params},(0,_dateCalculator.default)({timeframe:timeframe,moment:moment,week_starts_on_monday:week_starts_on_monday}))}var _defaultToFalse=_ramda.default.defaultTo(!1),_defaultTimeframe=_ramda.default.defaultTo("week7"),_toDate=function(date){return date.format("YYYY-MM-DD")},_toMoment=_ramda.default.compose(function(date){var upperLimit=(0,_moment.default)().add(20,"year"),lowerLimit=(0,_moment.default)().subtract(20,"year");return(0,_moment.default)(date).isBefore(lowerLimit,"day")?lowerLimit:(0,_moment.default)(date).isAfter(upperLimit,"day")?upperLimit:(0,_moment.default)(date)},function(date){return(0,_moment.default)(date,"YYYY-MM-DD").isValid()?(0,_moment.default)(date):(0,_moment.default)()},_ramda.default.defaultTo((0,_moment.default)())),_getDate=function(action){return _ramda.default.compose(_toDate,_toMoment)(action.date)},_getInstitutionWeekStartsOnMonday=_ramda.default.compose(_defaultToFalse,_ramda.default.view(_ramda.default.lensPath(["data","institution","week_starts_on_monday"]))),_getEquipmentAssetDefaultTimeframe=function(params_timeframe){return params_timeframe?_ramda.default.always(params_timeframe):_ramda.default.compose(_defaultTimeframe,_ramda.default.view(_ramda.default.lensPath(["data","equipment_asset","default_timeframe"])))},_saveParams=_ramda.default.set(_ramda.default.lensProp("params")),require=(exports.DatesReducer=function(_ref){var initialState=_ref.initialState;return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:_saveParams(initialState)(_transformState(initialState));return _ramda.default.compose(_transformState,function(action,state){return{timeframeSelect:_ramda.default.set(_ramda.default.lensProp("timeframe"),action.timeframe),dateSelect:_ramda.default.set(_ramda.default.lensProp("date"),_getDate(action)),prevDate:_ramda.default.set(_ramda.default.lensProp("date"),state.prev),nextDate:_ramda.default.set(_ramda.default.lensProp("date"),state.next),timeframeDateSelect:_ramda.default.evolve({timeframe:_ramda.default.always(action.timeframe),date:_ramda.default.always(_getDate(action))}),schedulesShow:_ramda.default.flip(_ramda.default.merge)({week_starts_on_monday:_getInstitutionWeekStartsOnMonday(action),timeframe:_getEquipmentAssetDefaultTimeframe(state.params.timeframe)(action)})}[action.type]||_ramda.default.identity}(1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},state))(state)}},_propTypes.PropTypes.shape({timeframe:_propTypes.PropTypes.string,date:_propTypes.PropTypes.string,moment:_propTypes.PropTypes.object,first:_propTypes.PropTypes.object,last:_propTypes.PropTypes.object,week_starts_on_monday:_propTypes.PropTypes.bool,default_timeframe:_propTypes.PropTypes.string}));exports.PropTypesDatesReducer=require},{"../schedule/dateCalculator":1814,moment:1031,"prop-types":1046,ramda:1137}],1754:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.EquipmentAssetReducer=exports.EquipmentAssetPropTypes=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _transformState(state){return _ramda.default.set(_ramda.default.lensProp("showAdditionalAssets"),_showAdditionalAssets(state),state)}var _toggleFavorite=function(action){return _ramda.default.set(_ramda.default.lensProp("bookmarked_by_user"),_ramda.default.view(_ramda.default.lensPath(["data","bookmarked"]),action))},_toggleCancellationSubscription=function(action){return _ramda.default.set(_ramda.default.lensProp("cancellation_subscriber"),_ramda.default.view(_ramda.default.lensPath(["data","subscribed"]),action))},_showAdditionalAssets=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("showAdditionalAssets")),_toggleAdditionalAssets=function(){return function(state){return _ramda.default.set(_ramda.default.lensProp("showAdditionalAssets"),!_showAdditionalAssets(state),state)}},require=(exports.EquipmentAssetReducer=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return _ramda.default.compose(_transformState,function(action){return{toggleCancellationSubscription:_toggleCancellationSubscription(action),toggleFavorite:_toggleFavorite(action),toggleAdditionalAssets:_toggleAdditionalAssets(),schedulesShow:_ramda.default.always(_ramda.default.view(_ramda.default.lensPath(["data","equipment_asset"]),action))}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0))(state)}},_propTypes.default.shape({id:_propTypes.default.number,name:_propTypes.default.string,schedule_description:_propTypes.default.string,bookmarked_by_user:_propTypes.default.bool,cancellation_subscriber:_propTypes.default.bool,unconfirmed_reservations:_propTypes.default.bool,description:_propTypes.default.string,time_zone:_propTypes.default.string,hour_height:_propTypes.default.number,open_hour:_propTypes.default.number,close_hour:_propTypes.default.number,time_step:_propTypes.default.number,time_tracked_in:_propTypes.default.string,maximum_time:_propTypes.default.number,minimum_time:_propTypes.default.number,can_read:_propTypes.default.bool,can_write:_propTypes.default.bool,default_timeframe:_propTypes.default.string,online:_propTypes.default.bool,equipments:_propTypes.default.arrayOf(_propTypes.default.shape({id:_propTypes.default.number.isRequired,name:_propTypes.default.string.isRequired})),public_can_view_reservation_owners:_propTypes.default.bool,asset_users_can_view_reservation_owners:_propTypes.default.bool,additional_assets:_propTypes.default.arrayOf(Number)}));exports.EquipmentAssetPropTypes=require},{"prop-types":1046,ramda:1137}],1755:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.EventModalReducer=exports.EventModalPropTypes=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _setField(field){return _ramda.default.set(_ramda.default.lensProp(field))}var _actionNewEventValue=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("isNewEvent")),_actionEndDateAdjusted=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("end_date_adjusted")),_setShowProp=_ramda.default.set(_ramda.default.lensProp("show")),_setEventId=_ramda.default.compose(_setField("eventId"),_ramda.default.prop("eventId")),_setHtmlForm=_ramda.default.compose(_setField("htmlForm"),_ramda.default.prop("data")),_clearHtmlForm=function(){return _setField("htmlForm")(null)},_showEventModal=function(action){return _ramda.default.compose(_setShowProp(!0),_setEventId(action),function(action){return _ramda.default.set(_ramda.default.lensProp("isNewEvent"),_actionNewEventValue(action))}(action),function(action){return _ramda.default.set(_ramda.default.lensProp("end_date_adjusted"),_actionEndDateAdjusted(action))}(action))},_closeEventModal=function(){return _ramda.default.compose(_setShowProp(!1),_setField("eventId")(null),_clearHtmlForm())},_eventIdFromParams=function(urlParams){urlParams=_ramda.default.compose(_ramda.default.defaultTo(null),_ramda.default.prop("event_id"))(urlParams);return urlParams&&parseInt(urlParams,10)},require=(exports.EventModalReducer=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:function(urlParams){urlParams=_eventIdFromParams(urlParams);return{show:!!urlParams,eventId:urlParams}}(initialState);return function(action){return _ramda.default.defaultTo(_ramda.default.identity,{showEventModal:_showEventModal(action),closeEventModal:_closeEventModal(),setHtmlForm:_setHtmlForm(action),clearHtmlForm:_clearHtmlForm()}[action.type])}(1<arguments.length?arguments[1]:void 0)(state)}},_propTypes.default.shape({isNewEvent:_propTypes.default.bool,show:_propTypes.default.bool,end_date_adjusted:_propTypes.default.bool,eventId:_propTypes.default.number,htmlForm:_propTypes.default.string}));exports.EventModalPropTypes=require},{"prop-types":1046,ramda:1137}],1756:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FormSelectLabReducerReducerPropTypes=exports.FormSelectLabReducer=void 0;var _moment=_interopRequireDefault(require("moment")),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _toMoment(date){return(0,_moment.default)(date)}function _transformState(state){return _ramda.default.merge(state,{canSaveReservation:_canSaveReservation(state)})}var _setReservationTime=function(start_time,end_time){return _ramda.default.flip(_ramda.default.merge)({reservation_start_time:start_time,reservation_end_time:end_time,reservation_start_moment:_toMoment(start_time),reservation_end_moment:_toMoment(end_time)})},_firstGroupId=_ramda.default.compose(_ramda.default.prop("id"),_ramda.default.nth(0),_ramda.default.defaultTo([]),_ramda.default.view(_ramda.default.lensPath(["data","user","groups"]))),_openModalLabSelect=function(action){return _ramda.default.compose(_ramda.default.set(_ramda.default.lensProp("equipmentId"),action.equipmentId),_setReservationTime(action.start_time,action.end_time),_ramda.default.flip(_ramda.default.merge)({showModal:!0,canSaveReservation:!1}))},_isServiceCenterEmployee=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("employee"),_ramda.default.view(_ramda.default.lensPath(["data","service_center"]))),_schedulesShow=function(action){return function(state){return _ramda.default.merge(state,{showModal:function(action){return function(state){return!(!(state=state.urlParams).reservation_start_time||!state.reservation_end_time||_isServiceCenterEmployee(action))&&function(action){return 1<action.data.user.groups.length}(action)}}(action)(state),groupIdSelected:_firstGroupId(action)})}},_closeModalSelect=_ramda.default.flip(_ramda.default.merge)({showModal:!1}),_canSaveReservation=function(state){return!!_ramda.default.prop("groupIdSelected",state)},require=(exports.FormSelectLabReducer=function(initialState){return function(){var urlParams=0<arguments.length&&void 0!==arguments[0]?arguments[0]:(urlParams=initialState,_ramda.default.compose(_setReservationTime(urlParams.reservation_start_time,urlParams.reservation_end_time),_ramda.default.merge({urlParams:urlParams,showModal:!_ramda.default.isNil(urlParams.reservation_start_time)&&!_ramda.default.isNil(urlParams.reservation_end_time),canSaveReservation:!1,showLabDropdown:!1}))(urlParams));return _ramda.default.compose(_transformState,function(action){return{openModalLabSelect:_openModalLabSelect(action),closeModalLabSelect:_closeModalSelect,schedulesShow:_schedulesShow(action),setGroupSelect:_ramda.default.set(_ramda.default.lensProp("groupIdSelected"),action.group_id),serviceReservationCreated:_closeModalSelect}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0))(urlParams)}},_propTypes.default.shape({showModal:_propTypes.default.bool,canSaveReservation:_propTypes.default.bool,reservation_start_moment:_propTypes.default.object.isRequired,reservation_end_moment:_propTypes.default.object.isRequired,groupIdSelected:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),userGroups:_propTypes.default.arrayOf(_propTypes.default.object)}));exports.FormSelectLabReducerReducerPropTypes=require},{moment:1031,"prop-types":1046,ramda:1137}],1757:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FormSelectUserReducer=exports.FormReducerPropTypes=void 0;var _moment=_interopRequireDefault(require("moment")),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _toMoment(date){return(0,_moment.default)(date)}function _transformState(state){return _ramda.default.merge(state,{canSaveReservation:_canSaveReservation(state),showLabDropdown:!!state.userSelected&&1<_userGroups(state).length,userGroups:_ramda.default.compose(_ramda.default.defaultTo([]),_ramda.default.prop("userGroups"))(state)})}var _defaultPersonSelectScope=_ramda.default.view(_ramda.default.lensPath(["data","service_center","default_person_select_scope"])),_userGroups=_ramda.default.compose(_ramda.default.defaultTo([]),_ramda.default.prop("userGroups")),_resetUsageCappings=_ramda.default.set(_ramda.default.lensProp("usageCappings"),null),_setReservationType=_ramda.default.set(_ramda.default.lensProp("reservationType")),_resetReservationType=_setReservationType("reservation"),_resetUserGroupSelection=_ramda.default.flip(_ramda.default.merge)({userSelected:null,groupIdSelected:null}),_canSaveReservation=function(state){return"unavailable"===state.reservationType||!(!state.groupIdSelected||!state.userSelected)},_selectReservationType=function(action){return _ramda.default.compose(_setReservationType(action.reservationType),_resetUsageCappings,_resetUserGroupSelection)},_selectUserSearchScope=function(action){return _ramda.default.compose(_ramda.default.set(_ramda.default.lensProp("userSearchScope"),action.userSearchScope))},_setReservationTime=function(start_time,end_time){return _ramda.default.flip(_ramda.default.merge)({reservation_start_time:start_time,reservation_end_time:end_time,reservation_start_moment:_toMoment(start_time),reservation_end_moment:_toMoment(end_time)})},_setUserGroups=function(action){var action=_ramda.default.compose(_ramda.default.defaultTo([]),_ramda.default.view(_ramda.default.lensPath(["data","group_profiles"])))(action),groupIdSelected=null;return 1===action.length&&(groupIdSelected=_ramda.default.compose(_ramda.default.prop("id"),_ramda.default.nth(0))(action)),_ramda.default.flip(_ramda.default.merge)({userGroups:action,groupIdSelected:groupIdSelected})},_openModalUserSelect=function(action){return _ramda.default.compose(_resetReservationType,_ramda.default.set(_ramda.default.lensProp("equipmentId"),action.equipmentId),_setReservationTime(action.start_time,action.end_time),_ramda.default.flip(_ramda.default.merge)({showModal:!0}))},_isServiceCenterEmployee=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("employee"),_ramda.default.view(_ramda.default.lensPath(["data","service_center"]))),_schedulesShow=function(action){return function(state){return _ramda.default.merge(state,{userSearchScope:_defaultPersonSelectScope(action),showModal:function(action){return function(state){return!(!(state=state.urlParams).reservation_start_time||!state.reservation_end_time)&&_isServiceCenterEmployee(action)}}(action)(state)})}},_closeModalSelect=_ramda.default.compose(_ramda.default.set(_ramda.default.lensProp("showModal"),!1),_resetUsageCappings,_resetUserGroupSelection),require=(exports.FormSelectUserReducer=function(initialState){return function(){var urlParams=0<arguments.length&&void 0!==arguments[0]?arguments[0]:(urlParams=initialState,_ramda.default.compose(_setReservationTime(urlParams.reservation_start_time,urlParams.reservation_end_time),_ramda.default.merge({urlParams:urlParams,showModal:!1,reservationType:"reservation",userSearchScope:"customers",canSaveReservation:!1,showLabDropdown:!1,usageCappings:null}))(urlParams));return _ramda.default.compose(_transformState,function(action){return{openModalUserSelect:_openModalUserSelect(action),closeModalUserSelect:_closeModalSelect,selectReservationType:_selectReservationType(action),selectUserSearchScope:_selectUserSearchScope(action),schedulesShow:_schedulesShow(action),setUserDropdownText:_ramda.default.set(_ramda.default.lensProp("userDropdownText"),action.text),setUserSelect:_ramda.default.set(_ramda.default.lensProp("userSelected"),action.user),setGroupSelect:_ramda.default.set(_ramda.default.lensProp("groupIdSelected"),action.group_id),setUserGroups:_setUserGroups(action),serviceReservationCreated:_closeModalSelect,setUsageCappings:_ramda.default.set(_ramda.default.lensProp("usageCappings"),action.data)}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0))(urlParams)}},_propTypes.default.shape({name:_propTypes.default.string,booked_usage_amount:_propTypes.default.number,cap_amount:_propTypes.default.number})),_propTypes=_propTypes.default.shape({showModal:_propTypes.default.bool,showLabDropdown:_propTypes.default.bool,canSaveReservation:_propTypes.default.bool,reservationType:_propTypes.default.string.isRequired,userSearchScope:_propTypes.default.string.isRequired,reservation_start_moment:_propTypes.default.object.isRequired,reservation_end_moment:_propTypes.default.object.isRequired,userDropdownText:_propTypes.default.string,userSelected:_propTypes.default.object,groupIdSelected:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.string]),userGroups:_propTypes.default.arrayOf(_propTypes.default.object),usageCappings:_propTypes.default.shape({service_center:require,equipment_asset:require})});exports.FormReducerPropTypes=_propTypes},{moment:1031,"prop-types":1046,ramda:1137}],1758:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InstitutionReducer=exports.InstitutionPropTypes=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.InstitutionReducer=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return{schedulesShow:_ramda.default.always(_ramda.default.view(_ramda.default.lensPath(["data","institution"]),action))}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0)(state)}};require=_propTypes.default.shape({id:_propTypes.default.number,name:_propTypes.default.string,week_starts_on_monday:_propTypes.default.bool});exports.InstitutionPropTypes=require},{"prop-types":1046,ramda:1137}],1759:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LinkedReservationModalReducer=exports.LinkedReservationModalPropTypes=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _setField(field){return _ramda.default.set(_ramda.default.lensProp(field))}var _setShowProp=_ramda.default.set(_ramda.default.lensProp("show")),_setEventId=_ramda.default.compose(_setField("eventId"),_ramda.default.prop("eventId")),_setParentEventId=_ramda.default.compose(_setField("parentEventId"),_ramda.default.prop("parentEventId")),_showLinkedReservationModal=function(action){return _ramda.default.compose(_setShowProp(!0),_setEventId(action),_setParentEventId(action))},_closeLinkedReservationModal=function(){return _ramda.default.compose(_setShowProp(!1),_setField("eventId")(null),_setField("parentEventId")(null))},require=(exports.LinkedReservationModalReducer=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return _ramda.default.defaultTo(_ramda.default.identity,{showLinkedReservationModal:_showLinkedReservationModal(action),closeLinkedReservationModal:_closeLinkedReservationModal()}[action.type])}(1<arguments.length?arguments[1]:void 0)(state)}},_propTypes.default.shape({show:_propTypes.default.boolean,eventId:_propTypes.default.number,parentEventId:_propTypes.default.number}));exports.LinkedReservationModalPropTypes=require},{"prop-types":1046,ramda:1137}],1760:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderableItemsReducer=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};var _orderableItemsData=_ramda.default.compose(_ramda.default.defaultTo([]),_ramda.default.view(_ramda.default.lensPath(["data","orderable_items"])));exports.OrderableItemsReducer=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return{orderableItemsIndex:_ramda.default.always(_orderableItemsData(action))}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0)(state)}}},{ramda:1137}],1761:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};exports.default=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return{startRequest:_ramda.default.compose(_ramda.default.set(_ramda.default.lensProp("loading"),!0),_ramda.default.set(_ramda.default.lensPath(action.lense),!0)),stopRequest:_ramda.default.compose(_ramda.default.set(_ramda.default.lensProp("loading"),!1),_ramda.default.set(_ramda.default.lensPath(action.lense),!1))}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0)(state)}}},{ramda:1137}],1762:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReservationsReducer=exports.PropTypesReservationsReducer=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_schedules=require("../../common/services/schedules"),_ramda=_interopRequireDefault(require("ramda")),_util=require("./util");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _transformState(state){return _ramda.default.compose(_setRefreshScheduler(_canRefresh(state)),_setDragged(_draggerValue(state)))(state)}var _actionsReservationsData=_ramda.default.compose(_ramda.default.defaultTo([]),_ramda.default.view(_ramda.default.lensPath(["data","reservations"]))),_getReservations=_ramda.default.prop("records"),_setUpdateModal=_ramda.default.set(_ramda.default.lensProp("updateModal")),_setReservations=_ramda.default.set(_ramda.default.lensProp("records")),_setDragged=function(value){return _ramda.default.set(_ramda.default.lensProp("dragged"),_ramda.default.clone(value))},_resetDragged=_ramda.default.set(_ramda.default.lensProp("dragged"),null),_setRefreshScheduler=_ramda.default.set(_ramda.default.lensProp("refreshScheduler")),require=_ramda.default.compose(_ramda.default.not,_ramda.default.isNil,_ramda.default.view(_ramda.default.lensProp("dragged"))),_isModalOpen=_ramda.default.view(_ramda.default.lensPath(["updateModal","header"])),_canRefresh=_ramda.default.compose(_ramda.default.not,_ramda.default.anyPass([require,_isModalOpen])),_draggerValue=_ramda.default.compose(_ramda.default.defaultTo(null),_ramda.default.prop("dragged")),_updateReservation=function(reservation){return function(state){return _setReservations((0,_util.UpdateRecordById)(reservation,_getReservations(state)))(state)}},_showReservationUpdateModal=function(action){return function(state){return _setUpdateModal({header:action.data.header,content:action.data.content,reservation:action.data.reservation})(state)}},require=(exports.ReservationsReducer=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return _ramda.default.compose(_transformState,function(action){return{serviceReservationIndex:function(state){return action.data?_ramda.default.compose(_setReservations,_actionsReservationsData)(action)(state):state},onStartDragReservation:_setDragged(action.reservation),onEndDragReservation:_resetDragged,resetReservationUpdateModal:_setUpdateModal({}),serviceReservationCreate:_setUpdateModal({}),showReservationUpdateModal:_showReservationUpdateModal(action),updateReservation:_updateReservation(action.reservation)}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0))(state)}},_propTypes.default.shape({records:_propTypes.default.arrayOf(_schedules.PropTypesEventModel),dragged:_propTypes.default.shape({id:_propTypes.default.number.isRequired}),updateModal:_propTypes.default.shape({header:_propTypes.default.string,content:_propTypes.default.string,reservation:_schedules.PropTypesEventModel}),refreshScheduler:_propTypes.default.boolean}));exports.PropTypesReservationsReducer=require},{"../../common/services/schedules":1723,"./util":1765,"prop-types":1046,ramda:1137}],1763:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(_ref){function _dispatchDataReceived(data){return dispatch({type:completeAction,data:data})}var dispatch=_ref.dispatch,promise=_ref.promise,loadingLense=_ref.loadingLense,completeAction=_ref.completeAction;return dispatch({type:"startRequest",lense:loadingLense}),promise.then(_dispatchDataReceived).catch(function(dispatch){return function(){dispatch({type:"showAlertBox",modal:!1,show:!0,header:"Server Error",level:"error",content:"Something happened connecting with server"})}}(dispatch)).then(function(){return dispatch({type:"stopRequest",lense:loadingLense})})}},{}],1764:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UserReducer=exports.UserPropTypes=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _serviceReservationIndex=function(action){return function(state){return action.data?_ramda.default.view(_ramda.default.lensPath(["data","meta","user"]),action,state):state}},require=(exports.UserReducer=function(initialState){return function(){var state=0<arguments.length&&void 0!==arguments[0]?arguments[0]:initialState;return function(action){return{schedulesShow:_ramda.default.always(_ramda.default.view(_ramda.default.lensPath(["data","user"]),action)),serviceReservationIndex:_serviceReservationIndex(action)}[action.type]||_ramda.default.identity}(1<arguments.length?arguments[1]:void 0)(state)}},_propTypes.default.shape({id:_propTypes.default.number,name:_propTypes.default.string}));exports.UserPropTypes=require},{"prop-types":1046,ramda:1137}],1765:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UpdateRecordById=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};exports.UpdateRecordById=function(record,array){var id;return _ramda.default.update((id=record.id,_ramda.default.findIndex(_ramda.default.propEq("id",id),array)),_ramda.default.clone(record),array)}},{ramda:1137}],1766:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=_interopRequireDefault(require("ramda")),_userInfo=_interopRequireDefault(require("../../common/userInfo"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _removeLeftRightFromCss=_ramda.default.compose(_ramda.default.join(" "),_ramda.default.reject(function(text){return text.includes("left")||text.includes("right")}),_ramda.default.split(" "));exports.default=function(timeframe){return{filter:function(_ref){var timeframe=_ref.timeframe,user=_ref.user;return function(calendarBackgrounds){return!(0,_userInfo.default)(user).loggedIn||"month"==timeframe?[]:"multi"!=timeframe?calendarBackgrounds:_ramda.default.map(_ramda.default.evolve({css:_removeLeftRightFromCss}),calendarBackgrounds)}}(timeframe)}}},{"../../common/userInfo":1732,ramda:1137}],1767:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_datesReducer=require("../../reducers/datesReducer"),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleAdditionalAssetButton(props){var _tooltip;return _ramda.default.compose(_ramda.default.isEmpty,_ramda.default.defaultTo([]),_ramda.default.prop("additionalAssets"))(props)?null:(_tooltip=props.showAdditionalAssets?props.texts.hide_tooltip:props.texts.show_tooltip,_react.default.createElement(_semanticUiReact.Popup,{trigger:_react.default.createElement(_semanticUiReact.Button,{size:"small",style:{position:"relative"},"data-test":"schedule_additional_asset_btn",loading:props.loading,onClick:function(){props.loading||props.toggleAdditionalAsset({assetId:props.assetId,dates:props.dates,timeshift:props.timeshift,additionalAssets:props.additionalAssets,showAdditionalAssets:props.showAdditionalAssets})}},props.texts.label),content:_tooltip,position:"bottom right",wide:!0}))}ScheduleAdditionalAssetButton.propTypes={loading:_propTypes.default.bool,assetId:_propTypes.default.number,dates:_datesReducer.PropTypesDatesReducer,timeshift:_propTypes.default.number,showAdditionalAssets:_propTypes.default.bool,additionalAssets:_propTypes.default.arrayOf(Number),toggleAdditionalAsset:_propTypes.default.func,texts:_propTypes.default.shape({label:_propTypes.default.string.isRequired,show_tooltip:_propTypes.default.string.isRequired,hide_tooltip:_propTypes.default.string.isRequired})},exports.default=ScheduleAdditionalAssetButton},{"../../reducers/datesReducer":1753,"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1768:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.AlertBoxPropTypes=exports.AlertBox=void 0;var _semanticUiReact=require("semantic-ui-react"),_react=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("react")),_alertMessageComponent=_interopRequireDefault(require("../../../common/components/alertMessageComponent")),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),require=require("../../../common/timerObject");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}function AlertBox(props){var _onClose=function(){_stopTimeout(),props.onConfirm()},_content=_ramda.default.prop("content"),_content=_ramda.default.compose(function(html){return _react.default.createElement("div",{dangerouslySetInnerHTML:{__html:html}})},function(content){return content.replace(/(\r\n|\n|\r)/g,"<br />")},_content),_stopTimeout=function(){props.timeoutId&&(props.timerObject.stopTimeout(props.timeoutId),props.setAlertBoxTimeoutId(null))};return(0,_react.useEffect)(function(){var intervalId;!props.modal&&props.resetTimeout&&(_stopTimeout(),intervalId=props.timerObject.startTimeout(_onClose,props.closePeriodTime),props.setAlertBoxTimeoutId(intervalId)),props.resetTimeoutAlertBox()},[props.resetTimeout]),props.show?_react.default.createElement("div",{className:props.className},_react.default.createElement(_semanticUiReact.Modal,{open:props.show&&props.modal},_react.default.createElement(_semanticUiReact.Modal.Header,null,props.header),_react.default.createElement(_semanticUiReact.Modal.Content,null,_content(props)),_react.default.createElement(_semanticUiReact.Modal.Actions,null,_react.default.createElement(_semanticUiReact.Button,{primary:!0,onClick:_onClose},props.texts.close))),_react.default.createElement(_alertMessageComponent.default,{show:!(!props.show||props.modal),level:props.level,header:props.header,content:props.content,onConfirm:_onClose})):null}exports.AlertBox=AlertBox;require={className:_propTypes.default.string,show:_propTypes.default.bool,modal:_propTypes.default.bool,level:_propTypes.default.oneOf(["info","error","positive","warning"]),header:_propTypes.default.string,content:_propTypes.default.string,resetTimeout:_propTypes.default.bool,onConfirm:_propTypes.default.func,resetTimeoutAlertBox:_propTypes.default.func,setAlertBoxTimeoutId:_propTypes.default.func,timeoutId:_propTypes.default.number,closePeriodTime:_propTypes.default.number,timerObject:require.TimerObjectPropTypes,texts:_propTypes.default.shape({close:_propTypes.default.string})},_propTypes=_propTypes.default.shape(require);exports.AlertBoxPropTypes=_propTypes,AlertBox.propTypes=require},{"../../../common/components/alertMessageComponent":1706,"../../../common/timerObject":1730,"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1769:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ScheduleAssetSelector=exports.AssetSelectorPresenter=void 0;var _semanticUiReact=require("semantic-ui-react"),_serviceCenterReducer=require("../../../common/reducers/serviceCenterReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),_stringUtils=require("../../../common/stringUtils");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function AssetSelectorPresenter(_ref){function _filterByText(text){return function(equipment){return _ramda.default.filter(function(text){return _ramda.default.compose(_ramda.default.includes((0,_stringUtils.toLowerCase)(text)),_stringUtils.toLowerCase,_ramda.default.prop("name"))}(text),equipment)}}function _concatAccumlatorAndRenderers(acc,categoryData){return acc.push(_callCategoryRendererFn(categoryData)),acc.push(_ramda.default.map(equipmentRenderer,categoryData.equipment)),_ramda.default.flatten(acc)}var showEquipmentByCategory=_ref.showEquipmentByCategory,equipmentByCategory=_ref.equipmentByCategory,searchInputRenderer=_ref.searchInputRenderer,categoryRenderer=_ref.categoryRenderer,equipmentRenderer=_ref.equipmentRenderer,_ref=_ramda.default.map(_ramda.default.compose(_ramda.default.defaultTo([]),_ramda.default.prop("equipment"))),_ref=_ramda.default.compose(_ramda.default.length,_ramda.default.flatten,_ref)(equipmentByCategory),_removeEmptyCategories=_ramda.default.reject(_ramda.default.compose(_ramda.default.isEmpty,_ramda.default.prop("equipment"))),_isRenderingSearcher=_ramda.default.lte(15,_ref),_categoryFilterAndRemove=function(equipmentTextFilter){return _ramda.default.compose(_removeEmptyCategories,_ramda.default.map(_ramda.default.evolve({equipment:(equipmentTextFilter=equipmentTextFilter,_ramda.default.ifElse(_ramda.default.always(_isRenderingSearcher),_filterByText(equipmentTextFilter),_ramda.default.identity))})))},_callCategoryRendererFn=showEquipmentByCategory?categoryRenderer:_ramda.default.always([]);return{searcherRender:_isRenderingSearcher?searchInputRenderer:_ramda.default.always(null),traverseRender:function(equipmentTextFilter){return _ramda.default.reduce(_concatAccumlatorAndRenderers,[],function(equipmentTextFilter){return _ramda.default.isEmpty(equipmentTextFilter)?equipmentByCategory:_categoryFilterAndRemove(equipmentTextFilter)(equipmentByCategory)}(equipmentTextFilter))}}}function ScheduleAssetSelector(props){function _title(){return _react.default.createElement("h3",{id:"schedule-title",className:props.className},props.assetName)}var _onVoidClick,_onSpace,_onChangeText,_assetSelectorPresenter,_textValue=_ramda.default.compose(_ramda.default.defaultTo(""),_ramda.default.prop("equipmentTextFilter"))(props);return _ramda.default.compose(_ramda.default.isEmpty,_ramda.default.defaultTo([]),_ramda.default.prop("equipmentByCategory"))(props)?_title():(_onVoidClick=function(e){e.preventDefault(),e.stopPropagation()},_onSpace=function(event){32===event.keyCode&&(props.serviceCentersEquipmentTextFilterAction(_textValue+" "),event.stopPropagation())},_onChangeText=function(event,data){event.preventDefault(),props.serviceCentersEquipmentTextFilterAction(data.value)},_assetSelectorPresenter=AssetSelectorPresenter({showEquipmentByCategory:props.showEquipmentByCategory,searchInputRenderer:function(searchInputValue){return _react.default.createElement(_semanticUiReact.Input,{icon:"search",iconPosition:"left",className:"search",onChange:_onChangeText,value:searchInputValue,onClick:_onVoidClick,placeholder:props.texts.search_tooltip,onKeyUp:_onSpace})},categoryRenderer:function(_ref2){var cat_id=_ref2.cat_id,_ref2=_ref2.cat_name;return[_react.default.createElement(_semanticUiReact.Dropdown.Item,{key:"category_".concat(cat_id,"_").concat(_ref2),onClick:_onVoidClick},_react.default.createElement("b",null,_ref2)),_react.default.createElement(_semanticUiReact.Dropdown.Divider,{key:"category__div_".concat(cat_id,"_").concat(_ref2)})]},equipmentRenderer:function(_ref3){var asset_id,id=_ref3.id,_ref3=_ref3.name;return _react.default.createElement(_semanticUiReact.Dropdown.Item,{className:"equipment",key:"equipment_".concat(id),text:_ref3,onClick:(asset_id=id,function(event){event.preventDefault(),props.clickScheduleLinkAction(asset_id)})})},equipmentByCategory:props.equipmentByCategory}),_react.default.createElement(_semanticUiReact.Dropdown,{className:"no_auto_init schedule_asset_selector",trigger:_title(),"data-test":"schedule_asset_selector",closeOnChange:!1,closeOnEscape:!1},_react.default.createElement(_semanticUiReact.Dropdown.Menu,null,_assetSelectorPresenter.searcherRender(_textValue),_react.default.createElement(_semanticUiReact.Dropdown.Menu,{scrolling:!0},_assetSelectorPresenter.traverseRender(_textValue)))))}exports.AssetSelectorPresenter=AssetSelectorPresenter;(exports.ScheduleAssetSelector=ScheduleAssetSelector).propTypes={assetName:_propTypes.default.string.isRequired,equipmentByCategory:_serviceCenterReducer.EquipmentByCategoryListPropType,equipmentTextFilter:_propTypes.default.string,showEquipmentByCategory:_propTypes.default.bool,serviceCentersEquipmentTextFilterAction:_propTypes.default.func.isRequired,clickScheduleLinkAction:_propTypes.default.func.isRequired,texts:{search_tooltip:_propTypes.default.string}}},{"../../../common/reducers/serviceCenterReducer":1714,"../../../common/stringUtils":1729,"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1770:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleAssetSettingsButton(props){return _ramda.default.defaultTo(!1,props.hidden)?null:_react.default.createElement(_semanticUiReact.Popup,{trigger:(params=props,_react.default.createElement("span",{className:"ui icon",id:"schedule-asset-settings-btn","data-test":"schedule_asset_settings_btn",onClick:function(event){event.preventDefault(),params.clickAssetSettingsLink(params.service_center_id,params.asset_id)}},_react.default.createElement(_semanticUiReact.Icon,{name:"cog"}))),content:props.texts.tooltip,position:"top center"});var params}ScheduleAssetSettingsButton.propTypes={asset_id:_propTypes.default.number.isRequired,hidden:_propTypes.default.bool,service_center_id:_propTypes.default.number.isRequired,clickAssetSettingsLink:_propTypes.default.func,texts:_propTypes.default.shape({tooltip:_propTypes.default.string.isRequired})},exports.default=ScheduleAssetSettingsButton},{"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1771:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleBackgroundMessage(props){return props.show?_react.default.createElement("div",{className:props.className},_react.default.createElement(_semanticUiReact.Message,{icon:!0,style:{width:"100%"}},_react.default.createElement(_semanticUiReact.Icon,{name:"circle notched",loading:!0}),_react.default.createElement(_semanticUiReact.Message.Content,null,props.message))):null}ScheduleBackgroundMessage.propTypes={className:_propTypes.default.string,show:_propTypes.default.bool.isRequired,message:_propTypes.default.string},exports.default=ScheduleBackgroundMessage},{"prop-types":1046,react:1427,"semantic-ui-react":1568}],1772:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_urls=_interopRequireDefault(require("../../../common/urls"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleBreadcrumb(props){return props.loggedIn?_react.default.createElement(_semanticUiReact.Breadcrumb,{className:props.className},_react.default.createElement("a",{className:"section",href:_urls.default.serviceCenterUrl(props.service_center_id),"data-test":"schedule_service_center_link",onClick:function(){return props.onClick(props.service_center_id,props.loggedIn)}},props.service_center_name),_react.default.createElement(_semanticUiReact.Breadcrumb.Divider,{icon:"right angle"}),_react.default.createElement(_semanticUiReact.Breadcrumb.Section,null,props.texts.label)):_react.default.createElement(_semanticUiReact.Breadcrumb,{className:props.className},_react.default.createElement("a",{className:"section",href:_urls.default.serviceCenterExternalUrl(props.service_center_id),"data-test":"schedule_service_center_link",onClick:function(){return props.onClick(props.service_center_id,props.loggedIn)}},props.texts.back_to_core))}ScheduleBreadcrumb.propTypes={className:_propTypes.default.string,loggedIn:_propTypes.default.bool,service_center_id:_propTypes.default.number.isRequired,service_center_name:_propTypes.default.string.isRequired,texts:_propTypes.default.shape({label:_propTypes.default.string.isRequired,back_to_core:_propTypes.default.string.isRequired}),onClick:_propTypes.default.func},exports.default=ScheduleBreadcrumb},{"../../../common/urls":1731,"prop-types":1046,react:1427,"semantic-ui-react":1568}],1773:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _eventInfo=_interopRequireDefault(require("../../../../../common/eventInfo")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){function _notifyStartDrag(eventData){_notify("start",eventData)}function _isReadOnlyEvent(event){return event.readonly}function _isNotEmployeeOnOthersEvent(service_center,event,user){return!(service_center.employee||_isAssignee(event,user))}function _onDragEnd(){_notifyEndDrag(draggedEvent),_resetDraggedEvent()}var scheduler=_ref.scheduler,jQuery=_ref.jQuery,draggedEvent=null,_notify=function(eventId,eventData){jQuery.trigger("schedulerdnd.".concat(eventId),eventData)},_notifyCreate=function(eventData){_notify("create",eventData)},_notifyUpdate=function(eventData){_notify("update",eventData)},_notifyEndDrag=function(eventData){_notify("end",eventData)},_resetDraggedEvent=function(){draggedEvent=null},_hasDraggedEvent=function(){return!!draggedEvent},_isDraggedEventNew=function(){return!!_hasDraggedEvent()&&0===draggedEvent.id},_isAssignee=function(event,user){return(0,_eventInfo.default)({user:user})(event).isEventAssignee},_canEquipmentAssetRead=function(equipment_asset){return equipment_asset.can_read};return{onBeforeDrag:function(_ref2){var user=_ref2.user,service_center=_ref2.service_center,equipment_asset=_ref2.equipment_asset;return function(id,mode){if(!function(equipment_asset){return _canEquipmentAssetRead(equipment_asset)&&equipment_asset.can_write}(equipment_asset))return!1;if("create"===mode)_notifyStartDrag(draggedEvent={id:0});else{mode=scheduler.getEvent(id);if(!mode)return!1;if(!_hasDraggedEvent()){if(_isReadOnlyEvent(mode)||mode.no_show)return!1;if(_isNotEmployeeOnOthersEvent(service_center,mode,user))return!1;if(function(event){return event.has_linked_event}(mode))return _notify("linked_reservation",mode),!1;!function(event){draggedEvent=event}(mode),_notifyStartDrag(mode)}}return!0}},onDragEnd:function(){return setTimeout(_onDragEnd,300)},onBeforeEventChanged:function(event){!function(event){_hasDraggedEvent()&&(_isDraggedEventNew()?_ramda.default.compose(_notifyCreate,_ramda.default.clone)(event):_ramda.default.compose(_notifyUpdate,_ramda.default.clone)(draggedEvent))}(event);return _resetDraggedEvent(),!1},onDocumentMouseUp:function(event){var element;return element=event.target,jQuery.contains(scheduler._obj,element)||scheduler._on_mouse_up(event),!1},showLightbox:function(_ref3){var showEventModal=_ref3.showEventModal,equipment_asset=_ref3.equipment_asset,service_center=_ref3.service_center,user=_ref3.user;return function(eventId){var ev;return _resetDraggedEvent(),_canEquipmentAssetRead(equipment_asset)&&(ev=scheduler.getEvent(eventId),_isReadOnlyEvent(ev)||_isNotEmployeeOnOthersEvent(service_center,ev,user)||showEventModal(parseInt(eventId,10),!1)),!1}}}}},{"../../../../../common/eventInfo":1708,ramda:1137}],1774:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};exports.default=function(_ref){function _detachEvent(key){return scheduler.detachEvent(events[key])}var scheduler=_ref.scheduler,SchedulerDragDropBehaviour=_ref.SchedulerDragDropBehaviour,events={onDragEnd:null,onBeforeDrag:null,onBeforeEventChanged:null};return{init:function(_ref2){var user=_ref2.user,service_center=_ref2.service_center,_ref2=_ref2.equipment_asset;events.onBeforeDrag=scheduler.attachEvent("onBeforeDrag",SchedulerDragDropBehaviour.onBeforeDrag({user:user,service_center:service_center,equipment_asset:_ref2})),events.onDragEnd=scheduler.attachEvent("onDragEnd",SchedulerDragDropBehaviour.onDragEnd),events.onBeforeEventChanged=scheduler.attachEvent("onBeforeEventChanged",SchedulerDragDropBehaviour.onBeforeEventChanged),$j(document).on("mouseup",SchedulerDragDropBehaviour.onDocumentMouseUp)},destroy:function(){_ramda.default.forEach(_detachEvent,_ramda.default.keys(events)),$j(document).off("mouseup",SchedulerDragDropBehaviour.onDocumentMouseUp)}}}},{ramda:1137}],1775:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _cache=_interopRequireDefault(require("../../../../common/cache")),_ramda=_interopRequireDefault(require("ramda")),_day=_interopRequireDefault(require("./schedulers/day")),_month=_interopRequireDefault(require("./schedulers/month")),_multi=_interopRequireDefault(require("./schedulers/multi")),_week=_interopRequireDefault(require("./schedulers/week5")),_week2=_interopRequireDefault(require("./schedulers/week7")),_schedulerBehaviour2=_interopRequireDefault(require("./dragDrop/schedulerBehaviour")),_schedulerEvents=_interopRequireDefault(require("./dragDrop/schedulerEvents")),_schedulerFix2=_interopRequireDefault(require("./schedulerFix"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _callCalendarMethod(calendarObjects,method,options){_ramda.default.forEach(function(calendar){if(calendar[method])return calendar[method](options)},calendarObjects)}function _getSchedulerHeight(jQuery){return jQuery.getHeight(window)-_topUIElementsHeight(jQuery)}var _calendars=[_day.default,_month.default,_multi.default,_week.default,_week2.default],_topUIElementsHeight=function(jQuery){return 50+_ramda.default.compose(_ramda.default.sum,_ramda.default.map(jQuery.getOuterHeight))(["#top_nav"])},_nowWithOffset=function(equipment_offset){equipment_offset=(new Date).getTimezoneOffset()-equipment_offset;return $j.now()+6e4*equipment_offset};exports.default=function(_ref){function _viewByTimeframe(timeframe){return _findCalendarByTimeframe(timeframe).schedulerView}function setHeight(height){return jQuery.height(".dhx_cal_container",height)}var options,scheduler=_ref.scheduler,schedulerTemplates=_ref.schedulerTemplates,jQuery=_ref.jQuery,calendarObjects=_ramda.default.map((options={scheduler:scheduler,schedulerId:"scheduler_here",jQuery:jQuery},function(calendar){return calendar(options)}),_calendars),_timeframeEquals=_ramda.default.propEq("timeframe"),_findCalendarByTimeframe=function(timeframe){return _ramda.default.find(_timeframeEquals(timeframe),calendarObjects)},_schedulerBehaviour=(0,_schedulerBehaviour2.default)({scheduler:scheduler,jQuery:jQuery}),_dragDropSupport=(0,_schedulerEvents.default)({scheduler:scheduler,SchedulerDragDropBehaviour:_schedulerBehaviour}),_cachedRenderReservations=(0,_cache.default)(function(records){scheduler.clearAll(),scheduler.parse(records,"json")}),_ref=(0,_cache.default)(function(_ref3){var refreshScheduler=_ref3.refreshScheduler,records=_ref3.records,moment=_ref3.moment,timeframe=_ref3.timeframe,_ref3=_ref3.tz_correction_offset;refreshScheduler&&(_cachedRenderReservations(records),updateView({timeframe:timeframe,moment:moment,tz_correction_offset:_ref3}))}),_cachedRenderBackgrounds=(0,_cache.default)(function(calendarBackgrounds){scheduler.deleteMarkedTimespan({days:[0,1,2,3,4,5,6]}),_ramda.default.forEach(scheduler.addMarkedTimespan,calendarBackgrounds)}),updateView=function(_ref4){var timeframe=_ref4.timeframe,moment=_ref4.moment,_ref4=_ref4.tz_correction_offset;!function(scheduler,tz_correction_offset){tz_correction_offset=_nowWithOffset(tz_correction_offset);scheduler.config.now_date=tz_correction_offset}(scheduler,_ref4),jQuery.show(".dhx_cal_header"),scheduler.config.cascade_event_display=!1,scheduler.config.mark_now=!0,_callCalendarMethod(calendarObjects,"updateView",{timeframe:timeframe,moment:moment}),scheduler.setCurrentView(moment.toDate(),_viewByTimeframe(timeframe))};return{schedulerId:"scheduler_here",init:function(_ref2){var readOnly=_ref2.readOnly,moment=_ref2.moment,user=_ref2.user,institution=_ref2.institution,service_center=_ref2.service_center,equipment_asset=_ref2.equipment_asset,onDateChange=_ref2.onDateChange,_ref2=_ref2.showEventModal,_schedulerFix=(0,_schedulerFix2.default)({scheduler:scheduler,originCorrectShift:scheduler._correct_shift});scheduler._correct_shift=_schedulerFix.correct_shift,scheduler.xy.nav_height=0,scheduler.config.cascade_event_count=4,scheduler.config.cascade_event_margin=30,scheduler.config.start_on_monday=institution.week_starts_on_monday,scheduler.config.hour_date=service_center.calendar_display_24h?"%H:%i":"%h:%i %A",scheduler.config.xml_date="%Y-%m-%d %H:%i",scheduler.config.default_date="%l, %M %d",scheduler.config.day_date="%D, %j %M",scheduler.config.details_on_dblclick=!0,scheduler.config.details_on_create=!0,scheduler.config.show_loading=!0,scheduler.config.icons_select=["icon_details"],scheduler.config.icons_edit=[],scheduler.config.hour_size_px=equipment_asset.hour_height,scheduler.xy.scale_width=55,scheduler.config.cascade_event_display=!1,scheduler.config.mark_now=!0,scheduler.ignore_week=_ramda.default.F,scheduler.config.dblclick_create=!0,scheduler.config.first_hour=equipment_asset.open_hour,scheduler.config.last_hour=equipment_asset.close_hour,scheduler.config.limit_time_select=!0,scheduler.config.readonly=readOnly,scheduler.showLightbox=_schedulerBehaviour.showLightbox({showEventModal:_ref2,equipment_asset:equipment_asset,service_center:service_center,user:user}),scheduler.config.time_step=equipment_asset.time_step,scheduler.clear_event=function(scheduler){return function(id){scheduler.for_rendered(id,function(node,i){node.parentNode&&"month"!==scheduler.getState().mode&&node.parentNode.removeChild(node),scheduler._rendered.splice(i,1)})}}(scheduler),scheduler.config.all_timed=service_center.enable_multi_day_events,scheduler.attachEvent("onTemplatesReady",function(){scheduler.templates=_ramda.default.merge(scheduler.templates,schedulerTemplates(scheduler,{equipment_asset:equipment_asset,service_center:service_center,user:user}))}),setHeight(_getSchedulerHeight(jQuery)),_callCalendarMethod(calendarObjects,"init",{moment:moment,institution:institution,service_center:service_center,equipment_asset:equipment_asset,onDateChange:onDateChange}),scheduler.init("scheduler_here",moment.toDate()),_dragDropSupport.init({user:user,service_center:service_center,equipment_asset:equipment_asset})},destroy:function(){return _dragDropSupport.destroy()},setHeight:setHeight,renderReservations:_ref,renderBackgrounds:function(timeframe,moment,calendarBackgrounds){_cachedRenderBackgrounds(calendarBackgrounds),scheduler.setCurrentView(moment.toDate(),_viewByTimeframe(timeframe))},updateView:updateView,updateHeight:function(){setHeight(_getSchedulerHeight(jQuery))}}}},{"../../../../common/cache":1705,"./dragDrop/schedulerBehaviour":1773,"./dragDrop/schedulerEvents":1774,"./schedulerFix":1776,"./schedulers/day":1780,"./schedulers/month":1781,"./schedulers/multi":1782,"./schedulers/week5":1783,"./schedulers/week7":1784,ramda:1137}],1776:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){function _toMoment(dateObject){return(0,_moment.default)(dateObject)}var scheduler=_ref.scheduler,originCorrectShift=_ref.originCorrectShift,_isMove=_ramda.default.compose(_ramda.default.equals("move"),_ramda.default.prop("_drag_mode")),_substractDateMinutes=function(date,offset){return date.subtract(offset,"minutes")},_addDateMinutes=function(date,offset){return date.add(offset,"minutes")};return{correct_shift:function(start,back){var date=_toMoment(start),minDate=_toMoment(scheduler._min_date),minDate=(minDate=minDate,date.utcOffset()-minDate.utcOffset());return _isMove(scheduler)?originCorrectShift(start,back):(_substractDateMinutes(date,minDate),function(back){return back?_substractDateMinutes:_addDateMinutes}(back)(date,minDate).valueOf())}}}},{moment:1031,ramda:1137}],1777:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_ramda=(obj=require("ramda"))&&obj.__esModule?obj:{default:obj},_i18n=require("../../../../i18n");function _tabElement(){return $j(".bh_popup_wrapper .menu .item")}function _emptyRefLinks(){return $j('#schedule-event-modal a[href="#"]')}function _commentLinks(){return $j(".comment_content a")}function _scrollingElement(){return $j(".scrolling")}function _addCommentButton(){return $j("form#event-add-comment")}function _disableReservationDetailsLink(event){if(function(event){return $j(event.currentTarget).text().includes("reservation details")}(event))return _tabElement().tab("change tab","main"),event.preventDefault(),!1}function _checkBodyComment(){if(_ramda.default.isEmpty(_commentBody().val().trim()))return alert("A comment must have a body."),!1;window.Tipped.hideAll()}var _commentBody=function(){return $j("#comment_comment")};exports.default={init:function(_ref){var eventId=_ref.eventId,assetId=_ref.assetId,employee=_ref.employee,closeEventModal=_ref.closeEventModal,cancelChanges=_ref.cancelChanges,refreshEventModal=_ref.refreshEventModal,html=_ref.html,showBackgroundMessage=_ref.showBackgroundMessage,_ref=_ref.closeBackgroundMessage;window.old_is_employee=window.is_employee,window.is_employee=employee,window.asset_id=assetId,window.oldUpdateEventFromXML=window.updateEventFromXML,window.updateEventFromXML=function(sid,action,tid,btag){return"error"!==action||(action=btag.getAttribute("qstring"),btag=btag.firstChild.data,action?confirm("".concat(btag," Do you want to proceed anyway?"))&&window.resaveServiceEvent(eventId,JSON.parse(action)):alert(btag),!1)},window.oldCancelServiceEvent=window.cancelServiceEvent,window.cancelServiceEvent=function(){return cancelChanges()},window.oldAfterSaveCallback=window.afterSaveCallback,window.afterSaveCallback=function(transport){window.dhtmlXTooltip.hide();var transport=window.serializeXmlNode(transport.documentElement),loader=new window.dtmlXMLLoaderObject(function(){}),transport=(loader.loadXMLString(transport),!function(btag){window.customFormsRequiredFieldsPanel&&btag&&window.customFormsRequiredFieldsPanel.addErrors({id:btag.getAttribute("id"),name:btag.getAttribute("name")},JSON.parse(btag.getAttribute("required_fields_empty")))}(loader.doXPath("//data/custom_form")[0]),loader.doXPath("//data/action")[0]),loader=window.updateEventFromXML(transport.getAttribute("sid"),transport.getAttribute("type"),transport.getAttribute("tid"),transport);window.enableSaveAndHideSpinner(),window.unbindConfirmClose(),loader&&closeEventModal()},window.oldSchedulerRefresh=window.scheduler_refresh,window.scheduler_refresh=function(toggle_relevant_schedules,callback){"function"==typeof callback&&callback()},window.oldSchedulerGetEvent=window.scheduler.getEvent,window.scheduler.getEvent=function(){return window.schedulerEvent},window.oldSchedulerClearAll=window.scheduler.clearAll,window.scheduler.clearAll=function(){return window.oldSchedulerClearAll},window.oldbhPop=$j.bhPopup,Object.assign($j,{bhPopup:{hide:function(){return null},show:function(){return null}}}),window.string_to_date=window.scheduler.date.str_to_date("%Y-%m-%d %H:%i"),window.date_to_string=window.scheduler.date.date_to_str("%Y-%m-%d %H:%i"),window.tinyMCE={ui:{FloatPanel:{hideAll:function(){return null}}}},window.oldSaveGroupChange=window.saveGroupChange,window.saveGroupChange=function(event){var element=$j(event.currentTarget),event=$j("#group_change_form_".concat(eventId," :input")).serializeArray();return event.push({name:"klass",value:element.data("item_class")}),$j.ajax({url:"/split_payment/save_group_change/".concat(eventId,".json"),type:"POST",data:event,beforeSend:function(){return window.showSpinner(element)},success:function(data){data.errors?($j("#change_group_form_".concat(eventId," .error_explanation")).html(_ramda.default.join("<br />",data.errors)).show(),window.Tipped.refresh("*")):(window.Tipped.hideAll(),refreshEventModal().then(function(){_tabElement().tab("change tab","contacts")}))},complete:function(){return window.hideSpinner(element)}}),!1},window.oldGetCancellationFee=window.getCancellationFee,window.getCancellationFee=function(event,event_id,asset_id,from_ui){_tabElement().tab("change tab","main"),window.oldGetCancellationFee(event,event_id,asset_id,from_ui)},window.oldRecurrentEventCallback=window.recurrentEventCallback,window.recurrentEventCallback=function(recurrent_event_id,is_error,error_message){window.oldRecurrentEventCallback(recurrent_event_id,is_error,error_message),is_error||closeEventModal()},window.oldRecurrentEventRemoveCallback=window.recurrentEventRemoveCallback,window.recurrentEventRemoveCallback=function(recurrent_event_id){closeEventModal(),window.oldRecurrentEventRemoveCallback(recurrent_event_id)},window.oldShowRecurringNotifier=window.showRecurringNotifier,window.showRecurringNotifier=function(process){var scope=employee?"employee":"regular";showBackgroundMessage((0,_i18n.t)("background.recurring_events.".concat(process,".").concat(scope)))},window.oldHideRecurringNotifier=window.hideRecurringNotifier,window.hideRecurringNotifier=_ref,$j(".bh_popup").html(html),_tabElement().tab(),_tabElement().tab("change tab","main"),_emptyRefLinks().on("click",function(e){return e.preventDefault()}),_commentLinks().on("click",_disableReservationDetailsLink),_scrollingElement().on("scroll",function(){window.Tipped.refresh(".tipped_target")}),_addCommentButton().on("ajax:beforeSend",_checkBodyComment)},destroy:function(){window.is_employee=window.old_is_employee,window.updateEventFromXML=window.oldUpdateEventFromXML,window.cancelServiceEvent=window.oldCancelServiceEvent,window.scheduler.getEvent=window.oldSchedulerGetEvent,window.scheduler.clearAll=window.oldSchedulerClearAll,Object.assign($j,window.oldbhPop),window.afterSaveCallback=window.oldAfterSaveCallback,window.scheduler_refresh=window.oldSchedulerRefresh,window.saveGroupChange=window.oldSaveGroupChange,window.getCancellationFee=window.oldGetCancellationFee,window.recurrentEventCallback=window.oldRecurrentEventCallback,window.recurrentEventRemoveCallback=window.oldRecurrentEventRemoveCallback,_emptyRefLinks().off("click"),_commentLinks().off("click"),_scrollingElement().off("scroll"),window.Tipped.remove("*"),_addCommentButton().off("ajax:beforeSend",_checkBodyComment)},setGlobalSchedulerEvent:function(event){window.schedulerEvent=event,window.scheduler.addEvent(event.start_date,event.end_date,event.text,event.id)},removeServiceEvent:function(){return window.removeServiceEvent(!1)}}},{"../../../../i18n":1832,ramda:1137}],1778:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _body=_interopRequireDefault(require("./texts/body")),_multiday=_interopRequireDefault(require("./texts/multiday")),_tooltip=_interopRequireDefault(require("./texts/tooltip")),_ramda=_interopRequireDefault(require("ramda")),_htmlTags=require("./texts/htmlTags"),_i18n=require("../../../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(sch,_ref){var equipment_asset=_ref.equipment_asset,service_center=_ref.service_center,user=_ref.user,_dateFormat=sch.templates.event_date;return{event_bar_text:function(start,end,event){return(0,_multiday.default)({event:event,scheduler:sch,texts:{cancelled:(0,_i18n.t)("cancelled")}}).html()},event_header:function(start,end,event){var texts=[];return event.urgent_comments&&texts.push((0,_htmlTags.iconTag)("red warning sign")),event.no_show?texts.push((0,_i18n.t)("no_show")):"cancelled"===event.status?texts.push((0,_i18n.t)("cancelled")):texts.push("".concat(_dateFormat(start)," - ").concat(_dateFormat(end))),_ramda.default.join("",texts)},tooltip_text:function(start,end,event){return(0,_tooltip.default)({equipment_asset:equipment_asset,service_center:service_center,user:user,event:event,texts:(0,_i18n.t)("event_text")}).html()},event_text:function(start,end,event){return(0,_body.default)({equipment_asset:equipment_asset,user:user,event:event,service_center:service_center,texts:(0,_i18n.t)("event_text")}).html()},event_class:function(start,end,event){return event.no_show?"no_show_reservation":event.css_class}}}},{"../../../../i18n":1832,"./texts/body":1785,"./texts/htmlTags":1786,"./texts/multiday":1787,"./texts/tooltip":1789,ramda:1137}],1779:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(scheduler){function format(fmt){return scheduler.date.date_to_str(fmt)}return{format:format,formatDb:function(date){return format("%Y-%m-%d")(date)},formatHeader:function(date){return format("%D, %d %M")(date)},formatMonthDayHeader:function(date){return format("%d")(date)}}}},{}],1780:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(_ref){var jQuery=_ref.jQuery;return{timeframe:"day",updateView:function(_ref2){"day"===_ref2.timeframe&&jQuery.hide(".dhx_cal_header")},schedulerView:"day"}}},{}],1781:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _dates=(require=require("./dates"))&&require.__esModule?require:{default:require};exports.default=function(_ref){function _monthDay(date){var dbDate=(0,_dates.default)(scheduler).formatDb(date),date=(0,_dates.default)(scheduler).formatMonthDayHeader(date);return"<span class='schedule_day_header_wrapper'><a href='#' class='schedule_header_link' data-test='schedule_header_link' data-testid=".concat(dbDate," data-date=").concat(dbDate," data-timeframe='day'>").concat(date,"</a></span>")}var scheduler=_ref.scheduler;return{timeframe:"month",schedulerView:"month",init:function(_ref2){_ref2=_ref2.onDateChange;scheduler.attachEvent("onTemplatesReady",function(){return scheduler.templates.month_day=_monthDay}),scheduler.attachEvent("onEmptyClick",function(onDateChange){return function(date,e){var targetDate=e.target.dataset.date,timeframe=e.target.dataset.timeframe;targetDate&&timeframe&&(e.preventDefault(),onDateChange(timeframe,targetDate))}}(_ref2))},updateView:function(_ref3){"month"===_ref3.timeframe&&(scheduler.config.mark_now=!1)}}}},{"./dates":1779}],1782:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};exports.default=function(_ref){var scheduler=_ref.scheduler;return{timeframe:"multi",schedulerView:"unit",init:function(_ref2){_ref2=_ref2.equipment_asset;scheduler.createUnitsView({name:"unit",property:"equipment_id",list:function(equipment_asset){return _ramda.default.map(function(obj){return{key:obj.id,label:obj.name}},equipment_asset.equipments)}(_ref2)})},updateView:function(_ref3){"multi"===_ref3.timeframe&&(scheduler.config.cascade_event_display=!0,scheduler.ignore_week=_ramda.default.F)}}}},{ramda:1137}],1783:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_dates=_interopRequireDefault(require("./dates")),_dateCalculator=_interopRequireDefault(require("../../../dateCalculator"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){function _weekScaleDate(date){var dbDate=(0,_dates.default)(scheduler).formatDb(date),date=(0,_dates.default)(scheduler).formatHeader(date);return"<a href='#' class='schedule_header_link' data-test='schedule_header_link' data-testid=".concat(dbDate," data-date=").concat(dbDate," data-timeframe='day'>").concat(date,"</a>")}function _weekStart(date){return(0,_dateCalculator.default)({timeframe:currentTimeframe,moment:(0,_moment.default)(date),week_starts_on_monday:scheduler.config.start_on_monday}).first.toDate()}var scheduler=_ref.scheduler,currentTimeframe="week5";return{timeframe:currentTimeframe,schedulerView:"week",init:function(){scheduler.attachEvent("onTemplatesReady",function(){return scheduler.templates.week_scale_date=_weekScaleDate})},updateView:function(_ref2){_ref2.timeframe===currentTimeframe&&(scheduler.date.week_start=_weekStart,scheduler.config.cascade_event_display=!0,scheduler.ignore_week=function(date){return 6==date.getDay()||0==date.getDay()})}}}},{"../../../dateCalculator":1814,"./dates":1779,moment:1031}],1784:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda")),_dates=_interopRequireDefault(require("./dates")),_dateCalculator=_interopRequireDefault(require("../../../dateCalculator"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function(_ref){function _weekScaleDate(date){var dbDate=(0,_dates.default)(scheduler).formatDb(date),date=(0,_dates.default)(scheduler).formatHeader(date);return"<a href='#' class='schedule_header_link' data-test='schedule_header_link' data-testid=".concat(dbDate," data-date=").concat(dbDate," data-timeframe='day'>").concat(date,"</a>")}function _weekStart(date){return(0,_dateCalculator.default)({timeframe:currentTimeframe,moment:(0,_moment.default)(date),week_starts_on_monday:scheduler.config.start_on_monday}).first.toDate()}var scheduler=_ref.scheduler,currentTimeframe="week7";return{timeframe:currentTimeframe,schedulerView:"week",init:function(){scheduler.config.cascade_event_display=!0,scheduler.attachEvent("onTemplatesReady",function(){scheduler.templates.week_scale_date=_weekScaleDate})},updateView:function(_ref2){_ref2.timeframe===currentTimeframe&&(scheduler.date.week_start=_weekStart,scheduler.config.cascade_event_display=!0,scheduler.ignore_week=_ramda.default.F)}}}},{"../../../dateCalculator":1814,"./dates":1779,moment:1031,ramda:1137}],1785:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _htmlTags=require("./htmlTags"),_eventInfo=_interopRequireDefault(require("../../../../../common/eventInfo")),_texts=_interopRequireDefault(require("./texts")),_ramda=_interopRequireDefault(require("ramda")),_urls=_interopRequireDefault(require("../../../../../common/urls"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _joinStrings=_ramda.default.join("");exports.default=function(_ref){function _availabilityUsageTypeTag(){return(0,_htmlTags.spanTag)({class:"type"},eventTexts.availabilityName())}function _poorMatchTag(){return _joinStrings([(0,_htmlTags.iconTag)("red warning sign"),texts.poor_match.text,(0,_htmlTags.linkTag)({href:_urls.default.poorMatchChangeUrl(equipment_asset.id,event.start_date),target:"_blank"},texts.poor_match.link_text)])}var user=_ref.user,equipment_asset=_ref.equipment_asset,event=_ref.event,service_center=_ref.service_center,texts=_ref.texts,eventInfo=(0,_eventInfo.default)({user:user,equipment_asset:equipment_asset,service_center:service_center})(event),eventTexts=(0,_texts.default)({user:user,equipment_asset:equipment_asset,eventInfo:eventInfo,texts:texts}),_collaboratorsInfoIcon=function(){return eventTexts.collaboratorsInfo()?(0,_htmlTags.iconTag)("users icon"):null},_ownerTag=function(){return eventInfo.showOwnerName?(0,_htmlTags.divTag)({class:"owner"},_joinStrings([_collaboratorsInfoIcon(),eventTexts.emailTag()])):null},_usageType=function(){return eventInfo.showOwnerInfo?(0,_htmlTags.divTag)({class:"availability_info"},function(){return eventInfo.isServiceReservation?eventInfo.showPrice?(separator=" / ",_ramda.default.compose(_ramda.default.join(_ramda.default.defaultTo("",separator)),_ramda.default.reject(_ramda.default.isNil))([_availabilityUsageTypeTag(),(0,_htmlTags.spanHeaderValueTag)({class:"price_type"},function(){return"".concat(texts.availability_info.price,":")},eventTexts.availabilityPrice)])):_availabilityUsageTypeTag():"";var separator}):null},canShowNotes=eventInfo.hasNotes,_notes=function(){return canShowNotes?(0,_htmlTags.divTag)({class:"notes"},event.notes):null},showPoorMatch=eventInfo.poorMatch&&eventInfo.showOwnerInfo,_poorMatch=function(){return showPoorMatch?(0,_htmlTags.divTag)({class:"poor_match_text"},_poorMatchTag):null},_ref=_ramda.default.compose((0,_htmlTags.divTag)({class:"event_body"}),function(){return eventInfo.isServiceReservation?_joinStrings([_ownerTag(),_usageType(),_poorMatch(),_notes()]):eventInfo.isMaintenanceEvent?_joinStrings([(0,_htmlTags.divTag)({class:"maintenance"},texts.maintenance),_notes()]):""});return{ownerTag:_ownerTag,usageType:_usageType,notes:_notes,html:_ref}}},{"../../../../../common/eventInfo":1708,"../../../../../common/urls":1731,"./htmlTags":1786,"./texts":1788,ramda:1137}],1786:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.strongTag=exports.spanTag=exports.spanHeaderValueTag=exports.linkTag=exports.iconTag=exports.htmlTag=exports.divTag=exports.divHeaderValueTag=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};function _hashToAttrs(options){return _ramda.default.compose((separator=" ",_ramda.default.compose(_ramda.default.join(_ramda.default.defaultTo("",separator)),_ramda.default.reject(_ramda.default.isNil))),_ramda.default.map(function(key){return"".concat(key,"='").concat(options[key],"'")}),_ramda.default.keys)(options);var separator}var require=_ramda.default.curry(function(tag,options,contentcb){options=_hashToAttrs(options),contentcb="function"==typeof(contentcb=contentcb)?contentcb():contentcb;return(_ramda.default.isEmpty(options)?"<".concat(tag,">"):"<".concat(tag," ").concat(options,">")).concat(contentcb,"</").concat(tag,">")}),linkTag=(exports.htmlTag=require)("a"),divTag=(exports.linkTag=linkTag,require("div")),spanTag=(exports.divTag=divTag,require("span")),linkTag=(exports.spanTag=spanTag,require("strong",{}));exports.strongTag=linkTag,exports.iconTag=function(iconName){return"<i class='ui icon ".concat(iconName,"'></i>")},exports.spanHeaderValueTag=function(options,headercb,contentcb){return spanTag(options,function(){return"".concat(spanTag({class:"header"},headercb)).concat(contentcb())})};exports.divHeaderValueTag=function(options,headercb,contentcb){return divTag(options,function(){return"".concat(spanTag({class:"header"},headercb)).concat(contentcb())})}},{ramda:1137}],1787:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _htmlTags=require("./htmlTags"),_moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _joinValidTexts(separator){return _ramda.default.compose(_ramda.default.join(_ramda.default.defaultTo("",separator)),_ramda.default.reject(_ramda.default.isNil))}exports.default=function(_ref){var scheduler=_ref.scheduler,event=_ref.event,texts=_ref.texts,_dateFormat=_ramda.default.compose(scheduler.templates.event_date,function(date){return(0,_moment.default)(date).toDate()}),_textCancelled=function(){return"cancelled"===event.status?texts.cancelled:null};return{html:_ramda.default.compose((0,_htmlTags.divTag)({class:"event_multiday"}),function(){return _joinValidTexts()([event.urgent_comments?(0,_htmlTags.iconTag)("red warning sign"):null,(output=[_textCancelled(),_dateFormat(event.start_date),_dateFormat(event.end_date)],_joinValidTexts(" - ")(output))]);var output})}}},{"./htmlTags":1786,moment:1031,ramda:1137}],1788:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var obj,_ramda=(obj=require("ramda"))&&obj.__esModule?obj:{default:obj},_htmlTags=require("./htmlTags");exports.default=function(_ref){function availabilityPermissionName(){return _firstAvailabilityWithPermissionName?" (".concat(_firstAvailability.permission_names,")"):""}function _availabilityText(_ref2){var onlyOneText=_ref2.onlyOneText,severalText=_ref2.severalText,_ref2=_ref2.emptyText;return _firstAvailabilityWithValidPrice?1===eventInfo.availabilityInfo.length?onlyOneText:severalText:_ref2}function _messurementText(){return texts.availability_info.time_tracked_in[_timeTrackedIn]}var eventInfo=_ref.eventInfo,texts=_ref.texts,_ref=_ref.equipment_asset,_firstAvailability=_ramda.default.nth(0,eventInfo.availabilityInfo),_firstAvailabilityWithValidPrice=_firstAvailability&&_firstAvailability["valid_price?"],_firstAvailabilityWithPermissionName=_firstAvailability&&_firstAvailability.permission_names,availabilityName=_availabilityText({onlyOneText:function(){return _firstAvailability.name},severalText:function(){return"".concat(_firstAvailability.name," ").concat(texts.availability_info.more_name)},emptyText:function(){return texts.availability_info.empty_name}}),_timeTrackedIn=_ramda.default.compose(_ramda.default.defaultTo("hours"),_ramda.default.prop("time_tracked_in"))(_ref),_ref=_availabilityText({onlyOneText:function(){return"".concat(_firstAvailability.price,"/").concat(_messurementText()).concat(availabilityPermissionName())},severalText:function(){return"".concat(_firstAvailability.price,"/").concat(_messurementText()," ").concat(texts.availability_info.more_name).concat(availabilityPermissionName())},emptyText:function(){return texts.availability_info.empty_price}});return{emailTag:function(){return(0,_htmlTags.linkTag)({href:"mailto:".concat(eventInfo.ownerEmail)},eventInfo.ownerName)},collaboratorsInfo:function(){return eventInfo.showOwnerName?eventInfo.collaboratorsInfo:null},availabilityName:availabilityName,availabilityPermissionName:availabilityPermissionName,availabilityPrice:_ref}}},{"./htmlTags":1786,ramda:1137}],1789:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _htmlTags=require("./htmlTags"),_eventInfo=_interopRequireDefault(require("../../../../../common/eventInfo")),_texts=_interopRequireDefault(require("./texts")),_moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda")),_urls=_interopRequireDefault(require("../../../../../common/urls"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _joinValidTexts(separator){return _ramda.default.compose(_ramda.default.join(_ramda.default.defaultTo("",separator)),_ramda.default.reject(_ramda.default.isNil))}var _joinStrings=_ramda.default.join("");exports.default=function(_ref){function _dayTag(field,contentcb){return(0,_htmlTags.divHeaderValueTag)({class:field},function(){return"".concat(texts.time_lines[field],":")},contentcb)}function _formatWith24h(){return _calendarDisplay24h(service_center)?texts.time_lines.with24h:texts.time_lines.no24h}function _formatDuration(){var measurement=_ramda.default.compose(_ramda.default.defaultTo("hours"),_ramda.default.prop("time_tracked_in"))(equipment_asset),value=eventInfo.minutes/("hours"===measurement?60:1),scope=1<value?"plural":"singular";return"".concat(parseFloat(value.toFixed(2))," ").concat(texts.time_lines[measurement][scope])}function _durationTag(){return(0,_htmlTags.divHeaderValueTag)({class:"duration"},function(){return"".concat(texts.time_lines.duration,":")},_formatDuration)}function _equipmentTag(){return _joinValidTexts(" ")([event.equipment_name,_confirmedText(),_approvedText()])}function _availabilityUsageTypeTag(){return(0,_htmlTags.spanHeaderValueTag)({class:"type"},function(){return"".concat(texts.availability_info.type,":")},eventTexts.availabilityName)}function _piLabNameTag(){return eventInfo.piName?(0,_htmlTags.divTag)({},_joinStrings([_piTag(),_labTag()])):(0,_htmlTags.divTag)({},_labTag)}function _poorMatchTag(){return _joinStrings([(0,_htmlTags.iconTag)("red warning sign"),texts.poor_match.text,_poorMatchLinkTag()])}function _pendingApprovalTag(){return _joinStrings([(0,_htmlTags.iconTag)("yellow warning sign"),"(".concat(_pendingApprovalText(),")")])}function _temporaryReservationTag(){return _joinStrings([(0,_htmlTags.iconTag)("yellow warning sign"),texts.temporary_reservation])}function _missingEquipmentTag(){return _joinStrings([(0,_htmlTags.iconTag)("red warning sign"),(0,_htmlTags.strongTag)(texts.missing_equipment)])}function _linkedReservationsTag(){return _joinStrings([_linkedIcon,(0,_htmlTags.strongTag)(texts.has_linked_reservations)])}function _notesTag(){return _joinStrings([(0,_htmlTags.spanTag)({class:"header"},"".concat(texts.note,":")),event.notes])}function _lastUrgentCommentTag(){return _joinStrings([_urgentCommentIcon(),(0,_htmlTags.spanTag)({class:"header"},"".concat(texts.last_urgent_comment,":")),event.last_urgent_comment])}var user=_ref.user,equipment_asset=_ref.equipment_asset,event=_ref.event,service_center=_ref.service_center,texts=_ref.texts,eventInfo=(0,_eventInfo.default)({user:user,equipment_asset:equipment_asset,service_center:service_center})(event),eventTexts=(0,_texts.default)({user:user,equipment_asset:equipment_asset,eventInfo:eventInfo,texts:texts}),_ownerTag=function(){return eventInfo.showOwnerName?(0,_htmlTags.divTag)({class:"owner"},function(){return _joinStrings([eventTexts.emailTag(),eventInfo.ownerPhone?(0,_htmlTags.divTag)({class:"phone"},function(){return eventInfo.ownerPhone}):null])}):null},_calendarDisplay24h=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("calendar_display_24h")),_startDayTag=function(){return _dayTag("start",function(){return(0,_moment.default)(event.start_date).format(_formatWith24h().multiline_format)})},_timelineSameDayTag=function(){return _joinStrings([_dayTag("start",function(){return _joinStrings([(0,_moment.default)(event.start_date).format(_formatWith24h().oneline_start_format),(0,_moment.default)(event.end_date).format(_formatWith24h().oneline_end_format)])}),_durationTag()])},_timelineMultipleDayTag=function(){return _joinStrings([_joinStrings([_startDayTag(),_dayTag("end",function(){return(0,_moment.default)(event.end_date).format(_formatWith24h().multiline_format)})]),_durationTag()])},_timeLines=function(){return(0,_htmlTags.divTag)({class:"time_lines"},eventInfo.noShow?_startDayTag:eventInfo.isSameDay?_timelineSameDayTag:_timelineMultipleDayTag)},showApproved=!eventInfo.isConfirmed&&eventInfo.needsApproval&&eventInfo.showOwnerInfo,showConfirmed=eventInfo.isConfirmed&&eventInfo.showOwnerInfo,_confirmedTag=(0,_htmlTags.spanTag)({class:"confirmed"},function(){return texts.confirmed}),_approvedTag=(0,_htmlTags.spanTag)({class:"approved"},function(){return texts.approved}),_notApprovedTag=(0,_htmlTags.spanTag)({class:"not_approved"},function(){return texts.not_approved}),_confirmedText=function(){return showConfirmed?_confirmedTag:null},_equipmentName=function(){return(0,_htmlTags.divTag)({class:"equipment_name"},_equipmentTag)},_usageType=function(){return eventInfo.showOwnerInfo&&eventInfo.isServiceReservation?(0,_htmlTags.divTag)({class:"availability_info"},function(){return eventInfo.showPrice?_joinValidTexts()([_availabilityUsageTypeTag(),(0,_htmlTags.spanHeaderValueTag)({class:"price_type"},function(){return"".concat(texts.availability_info.price,":")},eventTexts.availabilityPrice)]):_availabilityUsageTypeTag()}):null},_labTag=function(){return eventInfo.groupProfileName?(0,_htmlTags.spanHeaderValueTag)({class:"lab"},function(){return"".concat(texts.lab,":")},function(){return eventInfo.groupProfileName}):null},_piTag=function(){return eventInfo.piName?(0,_htmlTags.spanHeaderValueTag)({class:"pi_name"},function(){return"".concat(texts.pi,":")},function(){return eventInfo.piName}):null},showPiLabName=eventInfo.isServiceReservation&&eventInfo.groupProfileName&&eventInfo.showOwnerInfo,_piLabName=function(){return showPiLabName?(0,_htmlTags.divTag)({class:"lab"},_piLabNameTag):null},_poorMatchLinkTag=function(){return(0,_htmlTags.linkTag)({href:_urls.default.poorMatchChangeUrl(equipment_asset.id,event.start_date),target:"_blank"},texts.poor_match.link_text)},showPoorMatch=eventInfo.poorMatch&&eventInfo.showOwnerInfo,_poorMatch=function(){return showPoorMatch?(0,_htmlTags.divTag)({class:"poor_match_text"},_poorMatchTag):null},showNoShow=eventInfo.noShow&&eventInfo.showOwnerInfo,_noShow=function(){return showNoShow?(0,_htmlTags.divTag)({class:"no_show"},texts.no_show):null},showCancelled=eventInfo.isCancelled&&eventInfo.showOwnerInfo,_cancelled=function(){return showCancelled?(0,_htmlTags.divTag)({class:"cancelled"},texts.cancelled):null},showPendingApproval=eventInfo.pendingApproval&&eventInfo.showOwnerInfo,_pendingApprovalText=function(){var approval_texts=[texts.pending_approval];return eventInfo.cappingCausedApproval&&approval_texts.push(texts.capping_caused_approval),_ramda.default.join(" ",approval_texts)},_approvedText=function(){return showApproved?showPendingApproval?_notApprovedTag:_approvedTag:null},_pendingApproval=function(){return showPendingApproval?(0,_htmlTags.divTag)({class:"pending_approval"},_pendingApprovalTag):null},_temporaryReservation=function(){return eventInfo.isTemporary?(0,_htmlTags.divTag)({class:"temporary_reservation"},_temporaryReservationTag):null},showMissingEquipment=!eventInfo.hasEquipment&&eventInfo.showOwnerInfo,_missingEquipment=function(){return showMissingEquipment?(0,_htmlTags.divTag)({class:"missing_equipment"},_missingEquipmentTag):null},_linkedIcon=(0,_htmlTags.htmlTag)("i",{class:"icons"},function(){return _joinStrings([(0,_htmlTags.iconTag)("blue calendar alternate outline"),(0,_htmlTags.iconTag)("chain corner")])}),_linkedReservations=function(){return eventInfo.hasLinkedEvent?(0,_htmlTags.divTag)({class:"linked_reservations"},_linkedReservationsTag):null},canShowNotes=eventInfo.hasNotes,_notes=function(){return canShowNotes?(0,_htmlTags.divTag)({class:"notes"},_notesTag):null},_urgentCommentIcon=function(){return eventInfo.hasUrgentComments?(0,_htmlTags.iconTag)("red warning sign"):null},showLastUrgentComment=event.last_urgent_comment&&eventInfo.showOwnerInfo,_lastUrgentComment=function(){return showLastUrgentComment?(0,_htmlTags.divTag)({class:"urgent_comment"},_lastUrgentCommentTag):null},_collaboratorsInfoIcon=function(){return eventTexts.collaboratorsInfo()?(0,_htmlTags.iconTag)("users icon grey"):null},_collaboratorsInfo=function(){return eventTexts.collaboratorsInfo()?(0,_htmlTags.divTag)({class:"collaborators_info"},_joinStrings([_collaboratorsInfoIcon(),eventTexts.collaboratorsInfo()])):null},_bufferTimeFormat=function(from,to){var formatWith24=_calendarDisplay24h(service_center)?texts.buffer_info.with24h:texts.buffer_info.no24h;return"".concat(from.format(formatWith24)," - ").concat(to.format(formatWith24))},_bufferInfo=function(){return event.buffer_after||event.buffer_before?(0,_htmlTags.divHeaderValueTag)({class:"buffer_info"},function(){return"".concat(texts.buffer_info.header,":")},function(){return _joinValidTexts(" ".concat(texts.buffer_info.and," "))([function(){if(event.buffer_before)return _bufferTimeFormat((0,_moment.default)(event.start_date).subtract(event.buffer_before,"minutes"),(0,_moment.default)(event.start_date))}(),function(){if(event.buffer_after)return _bufferTimeFormat((0,_moment.default)(event.end_date),(0,_moment.default)(event.end_date).add(event.buffer_after,"minutes"))}()])}):null},_ref=_ramda.default.compose((0,_htmlTags.divTag)({class:"event_tooltip"}),function(){return eventInfo.isServiceReservation?_joinStrings([_ownerTag(),_collaboratorsInfo(),_equipmentName(),_timeLines(),_bufferInfo(),_usageType(),_piLabName(),_poorMatch(),_noShow(),_cancelled(),_pendingApproval(),_temporaryReservation(),_missingEquipment(),_linkedReservations(),_lastUrgentComment(),_notes()]):eventInfo.isMaintenanceEvent?_joinStrings([_equipmentName(),_timeLines(),_notes()]):""});return{ownerTag:_ownerTag,collaboratorsInfo:_collaboratorsInfo,equipmentName:_equipmentName,bufferInfo:_bufferInfo,timeLines:_timeLines,usageType:_usageType,piLabName:_piLabName,poorMatch:_poorMatch,noShow:_noShow,cancelled:_cancelled,pendingApproval:_pendingApproval,temporaryReservation:_temporaryReservation,missingEquipment:_missingEquipment,linkedReservations:_linkedReservations,notes:_notes,lastUrgentComment:_lastUrgentComment,html:_ref}}},{"../../../../../common/eventInfo":1708,"../../../../../common/urls":1731,"./htmlTags":1786,"./texts":1788,moment:1031,ramda:1137}],1790:[function(require,module,exports){!function(global){!function(){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_react=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("react")),_equipmentAssetReducer=require("../../../reducers/equipmentAssetReducer"),_institutionReducer=require("../../../reducers/institutionReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_calendarBackgrounds=require("../../../../common/services/calendarBackgrounds"),_datesReducer=require("../../../reducers/datesReducer"),_reservationsReducer=require("../../../reducers/reservationsReducer"),_viewHooks=_interopRequireDefault(require("./viewHooks")),_scheduler=_interopRequireDefault(require("../calendar/scheduler")),_schedulerTemplates=_interopRequireDefault(require("../calendar/schedulerTemplates")),_viewDragDrop=_interopRequireDefault(require("./viewDragDrop")),_serviceCenterReducer=require("../../../../common/reducers/serviceCenterReducer"),_userReducer=require("../../../reducers/userReducer"),_jQuery=_interopRequireDefault(require("../../../../common/jQuery"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}function ScheduleCalendarView(props){function _onDestroyComponent(){dragDropCallbacks.destroy(),hooks.destroy()}var hooks=(0,_viewHooks.default)(props,schedulerObject),dragDropCallbacks=(0,_viewDragDrop.default)(_jQuery.default);return(0,_react.useEffect)(function(){return dragDropCallbacks.init(props),hooks.init(),_onDestroyComponent},[]),(0,_react.useEffect)(hooks.renderReservations,[props.reservations]),(0,_react.useEffect)(function(){dragDropCallbacks.reload(props),hooks.updateScheduleView()},[props.dates.date,props.dates.timeframe]),(0,_react.useEffect)(hooks.renderBackgrounds,[props.calendarBackgrounds]),(0,_react.useEffect)(hooks.updateHeight,[props.equipment_asset.schedule_description]),_react.default.createElement("div",null,_react.default.createElement(_semanticUiReact.Dimmer,{active:props.loading,inverted:!0},_react.default.createElement(_semanticUiReact.Loader,{inverted:!0},"Loading")),_react.default.createElement("div",{id:schedulerObject.schedulerId,className:"dhx_cal_container ".concat(props.dates.timeframe,"_view")},_react.default.createElement("div",{className:"dhx_cal_navline"},_react.default.createElement("div",{className:"dhx_cal_date"})),_react.default.createElement("div",{className:"dhx_cal_header",onClick:function(e){e.preventDefault();var date=$j(e.nativeEvent.target).data("date"),e=$j(e.nativeEvent.target).data("timeframe");date&&e&&props.onDateChange(e,date)}}),_react.default.createElement("div",{className:"dhx_cal_data"})))}var schedulerObject=(0,_scheduler.default)({scheduler:global.scheduler,schedulerTemplates:_schedulerTemplates.default,jQuery:_jQuery.default});ScheduleCalendarView.propTypes={loading:_propTypes.default.bool,readOnly:_propTypes.default.bool,texts:_propTypes.default.shape({linked_error_title:_propTypes.default.string.isRequired,linked_error_content:_propTypes.default.string.isRequired}),institution:_institutionReducer.InstitutionPropTypes,service_center:_serviceCenterReducer.ServiceCenterPropTypes,user:_userReducer.UserPropTypes,equipment_asset:_equipmentAssetReducer.EquipmentAssetPropTypes,calendarBackgrounds:_propTypes.default.arrayOf(_calendarBackgrounds.PropTypesCalendarBackgroundModel),dates:_datesReducer.PropTypesDatesReducer,onDateChange:_propTypes.default.func,showEventModal:_propTypes.default.func,reservations:_reservationsReducer.PropTypesReservationsReducer,scheduler:_propTypes.default.object,schedulerId:_propTypes.default.string,onStartDragReservation:_propTypes.default.func,onEndDragReservation:_propTypes.default.func,showAlertBox:_propTypes.default.func,serviceReservationCreate:_propTypes.default.func,serviceReservationUpdate:_propTypes.default.func},exports.default=ScheduleCalendarView}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../../../common/jQuery":1711,"../../../../common/reducers/serviceCenterReducer":1714,"../../../../common/services/calendarBackgrounds":1717,"../../../reducers/datesReducer":1753,"../../../reducers/equipmentAssetReducer":1754,"../../../reducers/institutionReducer":1758,"../../../reducers/reservationsReducer":1762,"../../../reducers/userReducer":1764,"../calendar/scheduler":1775,"../calendar/schedulerTemplates":1778,"./viewDragDrop":1791,"./viewHooks":1792,"prop-types":1046,react:1427,"semantic-ui-react":1568}],1791:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(jQuery){function init(props){jQuery.on(document,"schedulerdnd.create",function(props){return function(_,reservation){return props.serviceReservationCreate({user:props.user,service_center:props.service_center,equipment_asset:props.equipment_asset,reservation:reservation}),!1}}(props)),jQuery.on(document,"schedulerdnd.update",function(props){return function(_,reservation){return props.serviceReservationUpdate({user:props.user,service_center:props.service_center,equipment_asset:props.equipment_asset,reservation:reservation}),!0}}(props)),jQuery.on(document,"schedulerdnd.start",function(props){return function(_,reservation){return props.onStartDragReservation(reservation),!0}}(props)),jQuery.on(document,"schedulerdnd.end",function(props){return function(reservation){return props.onEndDragReservation(reservation),!1}}(props)),jQuery.on(document,"schedulerdnd.linked_reservation",function(props){return function(){return props.showAlertBox(!0,"error",props.texts.linked_error_title,props.texts.linked_error_content),!1}}(props))}function destroy(){jQuery.off(document,"schedulerdnd.create"),jQuery.off(document,"schedulerdnd.update"),jQuery.off(document,"schedulerdnd.start"),jQuery.off(document,"schedulerdnd.linked_reservation")}return{init:init,destroy:destroy,reload:function(props){destroy(),init(props)}}}},{}],1792:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(props,schedulerObject){return{init:function(){schedulerObject.init({readOnly:props.readOnly,user:props.user,moment:props.dates.moment,institution:props.institution,service_center:props.service_center,equipment_asset:props.equipment_asset,schedulerHeight:props.schedulerHeight,onDateChange:props.onDateChange,showEventModal:props.showEventModal,tz_correction_offset:props.tz_correction_offset})},destroy:schedulerObject.destroy,renderReservations:function(){schedulerObject.renderReservations({refreshScheduler:props.reservations.refreshScheduler,records:props.reservations.records,moment:props.dates.moment,timeframe:props.dates.timeframe,tz_correction_offset:props.tz_correction_offset})},renderBackgrounds:function(){schedulerObject.renderBackgrounds(props.dates.timeframe,props.dates.moment,props.calendarBackgrounds)},updateScheduleView:function(){schedulerObject.updateView({timeframe:props.dates.timeframe,moment:props.dates.moment,tz_correction_offset:props.tz_correction_offset})},updateHeight:schedulerObject.updateHeight}}},{}],1793:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_react=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("react")),_propTypes=_interopRequireDefault(require("prop-types")),_orderableItems=require("../../../common/services/schedules/orderableItems"),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}function ScheduleCalendarDetailsModal(props){var _mapIndexed,_priceHtml,_accessabilityEventHtml,_orderableItemColumn,onClick,label;return _show(props)?(_orderableItemColumn=function(orderableItem){var style={borderLeftColor:orderableItem.color};return _react.default.createElement(_semanticUiReact.Grid.Column,{key:orderableItem.id},_react.default.createElement(_semanticUiReact.Header,null,orderableItem.supplier_catalog_number),_react.default.createElement("div",{className:"orderable-item-info",style:style},_ramda.default.compose(_ramda.default.map(_accessabilityEventHtml),_ramda.default.defaultTo([]),_ramda.default.prop("accessability_events"))(orderableItem)))},_mapIndexed=_ramda.default.addIndex(_ramda.default.map),_priceHtml=function(price,index){return _react.default.createElement("div",{key:index},price)},_accessabilityEventHtml=function(accessabilityEvent){var text=_ramda.default.join(" ",[_ramda.default.prop("readable_day_range",accessabilityEvent),_ramda.default.prop("readable_time_range",accessabilityEvent)]);return _react.default.createElement("div",{key:accessabilityEvent.id},text,(text=accessabilityEvent,_ramda.default.compose(_mapIndexed(_priceHtml),_ramda.default.prop("prices"))(text)))},(0,_react.useEffect)(function(){props.open&&props.orderableItemsIndex(props.assetId)},[props.open]),_react.default.createElement("div",{id:"schedule_calendar_details_modal"},_react.default.createElement(_semanticUiReact.Modal,{open:props.open,onClose:props.onClose,trigger:(onClick=props.onClick,label=props.texts.label,_react.default.createElement(_semanticUiReact.Button,{"data-test":"schedule_calendar_details_modal_open_btn",size:"small",onClick:onClick},label)),mountNode:document.getElementById("schedule_calendar_details_modal")},_react.default.createElement(_semanticUiReact.Modal.Header,null,props.header,_react.default.createElement("i",{className:"close icon grey close-modal-icon","data-test":"schedule_calendar_details_modal_close_btn",onClick:props.onClose})),_react.default.createElement(_semanticUiReact.Modal.Content,null,_react.default.createElement("div",{className:"orderable-items-content"},_react.default.createElement(_semanticUiReact.Dimmer,{active:props.loading,inverted:!0},_react.default.createElement(_semanticUiReact.Loader,{inverted:!0},"Loading")),_react.default.createElement(_semanticUiReact.Grid,{columns:2},_ramda.default.map(_orderableItemColumn,props.orderableItems))),(label=(onClick=props).texts.color_code_legend,_orderableItemColumn=props.employee?label.title.employee:label.title.regular,onClick=props.employee?_listColorCodes.employee:_listColorCodes.regular,_react.default.createElement("div",{className:"calendar-details-legend"},_react.default.createElement(_semanticUiReact.Header,null,_orderableItemColumn),_react.default.createElement(_semanticUiReact.Grid,{columns:4},mapIndexed(_iconColorColumn(label),onClick)))))))):null}var mapIndexed=_ramda.default.addIndex(_ramda.default.map),_listColorCodes={regular:["pending","owner","owner_past","unavailable_except_trained","owner_approved","regular_others","no_show","unavailable"],employee:["pending","owner","owner_past","unavailable_except_trained","owner_approved","employee_others","no_show","unavailable"]},_iconColorColumn=function(translations){return function(item,index){return _react.default.createElement(_semanticUiReact.Grid.Column,{key:"color-code-column-".concat(index)},_react.default.createElement("div",{className:"icon_color_".concat(item)},_react.default.createElement("div",{className:"text"},translations[item])))}},_show=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("show"));ScheduleCalendarDetailsModal.propTypes={assetId:_propTypes.default.number,show:_propTypes.default.bool,open:_propTypes.default.bool,employee:_propTypes.default.bool,header:_propTypes.default.string.isRequired,content:_propTypes.default.string.isRequired,orderableItems:_orderableItems.PropTypesOrderableItems,loading:_propTypes.default.bool,texts:_propTypes.default.shape({label:_propTypes.default.string.isRequired,color_code_legend:_propTypes.default.shape({title:_propTypes.default.shape({regular:_propTypes.default.string.isRequired,employee:_propTypes.default.string.isRequired}),owner:_propTypes.default.string.isRequired,owner_past:_propTypes.default.string.isRequired,unavailable_except_trained:_propTypes.default.string.isRequired,owner_approved:_propTypes.default.string.isRequired,regular_others:_propTypes.default.string.isRequired,employee_others:_propTypes.default.string.isRequired,no_show:_propTypes.default.string.isRequired,unavailable:_propTypes.default.string.isRequired})}),orderableItemsIndex:_propTypes.default.func,onClick:_propTypes.default.func,onClose:_propTypes.default.func},exports.default=ScheduleCalendarDetailsModal},{"../../../common/services/schedules/orderableItems":1724,"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1794:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleCalendarLoader(props){return props.loading?_react.default.createElement(_semanticUiReact.Icon,{loading:props.loading,name:"spinner"}):_react.default.createElement("div",{className:"loader-fix-width"})}ScheduleCalendarLoader.propTypes={loading:_propTypes.default.bool.isRequired},exports.default=ScheduleCalendarLoader},{"prop-types":1046,react:1427,"semantic-ui-react":1568}],1795:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function CancellationNotificationToggle(props){var asset_id=props.asset_id,loading=props.loading,onClick=props.onClick;return _ramda.default.defaultTo(!1,props.hidden)?null:_react.default.createElement(_semanticUiReact.Popup,{className:"cancellation_popup",trigger:_react.default.createElement(_semanticUiReact.Checkbox,{toggle:!0,className:"cancellation_toggle","data-test":"cancellation_notification_toggle",label:props.texts.label,onClick:function(asset_id,loading,onClick){return function(){loading||onClick(asset_id)}}(asset_id,loading,onClick),hidden:props.hidden,checked:props.subscribed,disabled:loading}),content:props.texts.tooltip+props.timeWindow,position:"top center",size:"small",wide:!0,"data-test":"cancellation_notification_hover"})}CancellationNotificationToggle.propTypes={asset_id:_propTypes.default.number,loading:_propTypes.default.bool,subscribed:_propTypes.default.bool,hidden:_propTypes.default.bool,onClick:_propTypes.default.func.isRequired,timeWindow:_propTypes.default.string,texts:_propTypes.default.shape({label:_propTypes.default.string,tooltip:_propTypes.default.string})},exports.default=CancellationNotificationToggle},{"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1796:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleCustomerNote(props){return props.show?_react.default.createElement("div",{id:"schedule-customer-note",className:"ui message",dangerouslySetInnerHTML:{__html:props.customer_note}}):null}ScheduleCustomerNote.propTypes={show:_propTypes.default.bool.isRequired,customer_note:_propTypes.default.string},exports.default=ScheduleCustomerNote},{"prop-types":1046,react:1427}],1797:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_datesReducer=require("../../reducers/datesReducer"),_react=_interopRequireDefault(require("react")),_classnames=_interopRequireDefault(require("classnames"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _oneDateFormat(first){return first.format("dddd, DD MMMM YYYY")}function _twoDateFormat(first,last){return"".concat(first.format("ddd, DD MMM")," - ").concat(last.format("ddd, DD MMM YYYY"))}function ScheduleDateNavigator(props){var _prevButton=_react.default.createElement("div",{onClick:props.onPrevDate,className:"prev_button","data-test":"schedule_prev_date_btn"},_react.default.createElement("i",{className:"ui icon chevron left"})),_nextButton=_react.default.createElement("div",{onClick:props.onNextDate,className:"next_button","data-test":"schedule_next_date_btn"},_react.default.createElement("i",{className:"ui icon chevron right"})),_displayHeader=_react.default.createElement("div",{className:"ui centered header date_display"},_formats[props.dates.timeframe](props.dates.first,props.dates.last)),_displayTimeZone=_react.default.createElement("div",{className:"ui centered grid time_zone"},props.time_zone),props=(0,_classnames.default)("date_navigator",props.className);return _react.default.createElement("div",{className:props},_prevButton,_react.default.createElement("div",{className:"date_header"},_displayHeader,_displayTimeZone),_nextButton)}var _formats={day:_oneDateFormat,week5:_twoDateFormat,week7:_twoDateFormat,month:function(first){return first.format("MMMM YYYY")},multi:_oneDateFormat};ScheduleDateNavigator.propTypes={className:_propTypes.default.string,onPrevDate:_propTypes.default.func,onNextDate:_propTypes.default.func,dates:_datesReducer.PropTypesDatesReducer,time_zone:_propTypes.default.string},exports.default=ScheduleDateNavigator},{"../../reducers/datesReducer":1753,classnames:116,"prop-types":1046,react:1427}],1798:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _datepicker=_interopRequireDefault(require("./dateSelect/datepicker")),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,function(arg){arg=function(input,hint){if("object"!==_typeof(input)||null===input)return input;var prim=input[Symbol.toPrimitive];if(void 0===prim)return("string"===hint?String:Number)(input);prim=prim.call(input,hint||"default");if("object"!==_typeof(prim))return prim;throw new TypeError("@@toPrimitive must return a primitive value.")}(arg,"string");return"symbol"===_typeof(arg)?arg:String(arg)}(descriptor.key),descriptor)}}function _setPrototypeOf(o,p){return(_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(o,p){return o.__proto__=p,o})(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}();return function(){var NewTarget,Super=_getPrototypeOf(Derived),Super=(NewTarget=hasNativeReflectConstruct?(NewTarget=_getPrototypeOf(this).constructor,Reflect.construct(Super,arguments,NewTarget)):Super.apply(this,arguments),this);if(NewTarget&&("object"===_typeof(NewTarget)||"function"==typeof NewTarget))return NewTarget;if(void 0!==NewTarget)throw new TypeError("Derived constructors may only return object or undefined");return function(self){if(void 0!==self)return self;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(Super)}}function _getPrototypeOf(o){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o){return o.__proto__||Object.getPrototypeOf(o)})(o)}require=function(_React$Component){var subClass=ScheduleDateSelect;if("function"!=typeof _React$Component&&null!==_React$Component)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(_React$Component&&_React$Component.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),Object.defineProperty(subClass,"prototype",{writable:!1}),_React$Component&&_setPrototypeOf(subClass,_React$Component);var staticProps,_super=_createSuper(ScheduleDateSelect);function ScheduleDateSelect(){var instance=this,Constructor=ScheduleDateSelect;if(instance instanceof Constructor)return _super.apply(this,arguments);throw new TypeError("Cannot call a class as a function")}return subClass=ScheduleDateSelect,(_React$Component=[{key:"_buttonElement",value:function(){return $j(this.buttonNode)}},{key:"_onDatePickerButtonClick",value:function(){this.datepickerElement.isDatePickerOpen()?this.datepickerElement.closeDatePicker(this.props.moment):this.datepickerElement.openDatePicker(this.props.moment)}},{key:"componentDidMount",value:function(){this.datepickerElement=(0,_datepicker.default)($j(this.datepickerNode),this.props.week_starts_on_monday,this.props.texts),this.datepickerElement.init(this.props.onDateSelect)}},{key:"componentWillUnmount",value:function(){this.datepickerElement.destroy()}},{key:"render",value:function(){var _this=this;return _react.default.createElement("span",{className:"schedule_datepicker_btn"},_react.default.createElement("div",{className:"ui small icon button",ref:function(node){return _this.buttonNode=node},"data-test":"schedule_datepicker_btn",onClick:this._onDatePickerButtonClick.bind(this)},_react.default.createElement("i",{className:"ui icon calendar outline"}," ")),_react.default.createElement("input",{type:"text",className:"datepicker",style:{width:0,visibility:"hidden"},ref:function(node){return _this.datepickerNode=node}}))}}])&&_defineProperties(subClass.prototype,_React$Component),staticProps&&_defineProperties(subClass,staticProps),Object.defineProperty(subClass,"prototype",{writable:!1}),ScheduleDateSelect}(_react.default.Component);require.propTypes={moment:_propTypes.default.object.isRequired,onDateSelect:_propTypes.default.func,texts:_propTypes.default.object.isRequired,week_starts_on_monday:_propTypes.default.bool},exports.default=require},{"./dateSelect/datepicker":1799,"prop-types":1046,react:1427}],1799:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=_interopRequireDefault(require("moment")),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=function($el,week_starts_on_monday,texts){function _toDate(date){return(0,_moment.default)(date).toDate()}return{init:function(onSelect){$j.datepicker.regional.schedules=texts,$j.datepicker.setDefaults($j.datepicker.regional.schedules),$j.datepicker._gotoTodayOriginal=$j.datepicker._gotoToday,$j.datepicker._gotoToday=function(id){$j.datepicker._gotoTodayOriginal.apply(this,[id]),$j.datepicker._selectDate.apply(this,[id])},$el.datepicker({firstDay:week_starts_on_monday?1:0,autoclose:!0,onSelect:_ramda.default.compose(onSelect,_toDate),showButtonPanel:!0})},openDatePicker:function(moment){$el.datepicker("setDate",moment.toDate()),$el.datepicker("show")},closeDatePicker:function(){$el.datepicker("hide")},isDatePickerOpen:function(){return $el.datepicker("widget").is(":visible")},destroy:function(){$j.datepicker._gotoToday=$j.datepicker._gotoTodayOriginal}}}},{moment:1031,ramda:1137}],1800:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleDescriptionModal(props){var onClick;return _ramda.default.defaultTo(!1,props.hidden)?null:_react.default.createElement("span",{id:"schedule-description-modal"},_react.default.createElement(_semanticUiReact.Modal,{open:props.show,onClose:props.onClose,trigger:_react.default.createElement(_semanticUiReact.Popup,{trigger:(onClick=props.onClick,_react.default.createElement("span",{className:"ui icon","data-test":"schedule_description_modal_open_btn",size:"small",onClick:onClick},_react.default.createElement(_semanticUiReact.Icon,{name:"info circle"}))),content:props.texts.label,position:"top center",wide:!0}),mountNode:document.getElementById("schedule-description-modal")},_react.default.createElement(_semanticUiReact.Modal.Header,null,props.header,_react.default.createElement("i",{className:"close icon grey close-modal-icon","data-test":"schedule_description_modal_close_btn",onClick:props.onClose})),_react.default.createElement(_semanticUiReact.Modal.Content,null,_react.default.createElement("div",{dangerouslySetInnerHTML:{__html:props.content}}))))}ScheduleDescriptionModal.propTypes={show:_propTypes.default.bool,header:_propTypes.default.string.isRequired,hidden:_propTypes.default.bool,content:_propTypes.default.string.isRequired,texts:_propTypes.default.shape({label:_propTypes.default.string.isRequired}),onClick:_propTypes.default.func,onClose:_propTypes.default.func},exports.default=ScheduleDescriptionModal},{"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1801:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_datesReducer=require("../../reducers/datesReducer"),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleDownloadPdfButton(props){return _react.default.createElement(_semanticUiReact.Popup,{trigger:(params=props,_react.default.createElement(_semanticUiReact.Button,{size:"small",icon:!0,disabled:params.loading,"data-test":"schedule_download_pdf_btn",onClick:function(event){event.preventDefault(),params.loading||params.downloadPdf(params.element,_filename(params.dates))}},_react.default.createElement(_semanticUiReact.Icon,{loading:params.loading,name:"print"}))),content:props.texts.tooltip,position:"bottom right",wide:!0});var params}var _formats={day:"[schedule_view_day_]YYYY_MM_DD[.pdf]",week5:"[schedule_view_week_]YYYY_MM_DD[.pdf]",week7:"[schedule_view_week_]YYYY_MM_DD[.pdf]",month:"[schedule_view_month_]YYYY_MMMM[.pdf]",multi:"[schedule_view_multi_]YYYY_MM_DD_HH_ss[.pdf]"},_filename=function(dates){return dates.moment.format(_formats[dates.timeframe])};ScheduleDownloadPdfButton.propTypes={dates:_datesReducer.PropTypesDatesReducer,loading:_propTypes.default.bool,element:_propTypes.default.object,texts:_propTypes.default.shape({tooltip:_propTypes.default.string.isRequired}),downloadPdf:_propTypes.default.func},exports.default=ScheduleDownloadPdfButton},{"../../reducers/datesReducer":1753,"prop-types":1046,react:1427,"semantic-ui-react":1568}],1802:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_react=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("react")),obj=(obj=require("prop-types"))&&obj.__esModule?obj:{default:obj},_datesReducer=require("../../reducers/datesReducer"),require=require("../../reducers/reservationsReducer");function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}function ScheduleEventModal(props){function _refreshReservations(){props.onRefresh({assetId:props.assetId,dates:props.dates,timeshift:props.timeshift,additionalAssets:props.additionalAssets,showAdditionalAssets:props.showAdditionalAssets})}return(0,_react.useEffect)(function(){props.eventId&&props.loadEventModal({eventId:props.eventId,isNewEvent:props.isNewEvent,refreshReservations:_refreshReservations,end_date_adjusted:props.end_date_adjusted})},[props.eventId]),_react.default.createElement(_semanticUiReact.Modal,{className:"fullscreen",id:"schedule-event-modal",closeOnDimmerClick:!1,open:props.show,closeIcon:!0,onClose:function(){return props.cancelChangesModal(props.isNewEvent,_refreshReservations)}},_react.default.createElement(_semanticUiReact.Segment,{basic:!0,loading:props.loading},_react.default.createElement("div",{className:"bh_popup_wrapper"},_react.default.createElement("input",{type:"hidden",name:"current_event_id",id:"current_event_id",value:props.eventId}),_react.default.createElement("div",{className:"bh_popup"}))))}ScheduleEventModal.propTypes={loading:obj.default.bool,show:obj.default.bool,isNewEvent:obj.default.bool,end_date_adjusted:obj.default.bool,eventId:obj.default.number,loadEventModal:obj.default.func,cancelChangesModal:obj.default.func,assetId:obj.default.number,onRefresh:obj.default.func,dates:_datesReducer.PropTypesDatesReducer,timeshift:obj.default.number.isRequired,reservations:require.PropTypesReservationsReducer.isRequired,additionalAssets:obj.default.arrayOf(Number),showAdditionalAssets:obj.default.bool},exports.default=ScheduleEventModal},{"../../reducers/datesReducer":1753,"../../reducers/reservationsReducer":1762,"prop-types":1046,react:1427,"semantic-ui-react":1568}],1803:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),_classnames=_interopRequireDefault(require("classnames"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleFavoriteButton(props){var asset_id=props.asset_id,loading=props.loading,onClick=props.onClick;return _ramda.default.defaultTo(!1,props.hidden)?null:_react.default.createElement(_semanticUiReact.Popup,{trigger:_react.default.createElement("span",{id:"schedule-favorite-btn",className:"ui icon","data-test":"schedule_favorite_btn",onClick:function(asset_id,loading,onClick){return function(){loading||onClick(asset_id)}}(asset_id,loading,onClick)},function(outline,loading){return loading?_react.default.createElement("i",{className:"spinner loading icon red"}):_react.default.createElement("i",{className:(0,_classnames.default)("red","heart","icon",{outline:outline})})}(props.outline,props.loading)),content:props.outline?props.texts.tooltip_unbookmarked:props.texts.tooltip_bookmarked,position:"bottom right",wide:!0})}ScheduleFavoriteButton.propTypes={asset_id:_propTypes.default.number.isRequired,outline:_propTypes.default.bool.isRequired,loading:_propTypes.default.bool.isRequired,hidden:_propTypes.default.bool,texts:_propTypes.default.shape({tooltip_unbookmarked:_propTypes.default.string.isRequired,tooltip_bookmarked:_propTypes.default.string.isRequired}),onClick:_propTypes.default.func},exports.default=ScheduleFavoriteButton},{classnames:116,"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1804:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleLinkedReservationModal(props){return _react.default.createElement(_semanticUiReact.Modal,{id:"schedule-linked-reservation-modal",open:props.show},_react.default.createElement(_semanticUiReact.Modal.Header,null,props.texts.title),_react.default.createElement(_semanticUiReact.Modal.Content,null,props.texts.content),_react.default.createElement(_semanticUiReact.Modal.Actions,null,_react.default.createElement(_semanticUiReact.Button,{"data-test":"schedule_linked_reservation_modal_cancel",onClick:props.onClose},props.texts.cancel),_react.default.createElement(_semanticUiReact.Button,{primary:!0,"data-test":"schedule_linked_reservation_modal_accept",onClick:function(){props.onClose(),props.showEventModal(props.parentEventId)}},props.texts.accept)))}ScheduleLinkedReservationModal.propTypes={show:_propTypes.default.bool,eventId:_propTypes.default.number,parentEventId:_propTypes.default.number,onClose:_propTypes.default.func,showEventModal:_propTypes.default.func,texts:_propTypes.default.shape({title:_propTypes.default.string,content:_propTypes.default.string,cancel:_propTypes.default.string,accept:_propTypes.default.string})},exports.default=ScheduleLinkedReservationModal},{"prop-types":1046,react:1427,"semantic-ui-react":1568}],1805:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleMainLoader(props){return props.loading?_react.default.createElement("div",{className:"ui active inverted dimmer"},_react.default.createElement("div",{className:"ui loader"})):null}ScheduleMainLoader.propTypes={loading:_propTypes.default.bool.isRequired},exports.default=ScheduleMainLoader},{"prop-types":1046,react:1427}],1806:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleOfflineMessage(props){return props.online?null:_react.default.createElement("div",{id:"schedule-offline-message"},_react.default.createElement("i",{className:"ui icon yellow exclamation triangle"}),props.offline_message)}ScheduleOfflineMessage.propTypes={online:_propTypes.default.bool,offline_message:_propTypes.default.string},exports.default=ScheduleOfflineMessage},{"prop-types":1046,react:1427}],1807:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_datesReducer=require("../../reducers/datesReducer"),_reservationsReducer=require("../../reducers/reservationsReducer"),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),_refreshCalculator=_interopRequireDefault(require("../../../common/services/refreshCalculator")),require=require("../../../common/timerObject");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,function(arg){arg=function(input,hint){if("object"!==_typeof(input)||null===input)return input;var prim=input[Symbol.toPrimitive];if(void 0===prim)return("string"===hint?String:Number)(input);prim=prim.call(input,hint||"default");if("object"!==_typeof(prim))return prim;throw new TypeError("@@toPrimitive must return a primitive value.")}(arg,"string");return"symbol"===_typeof(arg)?arg:String(arg)}(descriptor.key),descriptor)}}function _setPrototypeOf(o,p){return(_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(o,p){return o.__proto__=p,o})(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}();return function(){var NewTarget,Super=_getPrototypeOf(Derived),Super=(NewTarget=hasNativeReflectConstruct?(NewTarget=_getPrototypeOf(this).constructor,Reflect.construct(Super,arguments,NewTarget)):Super.apply(this,arguments),this);if(NewTarget&&("object"===_typeof(NewTarget)||"function"==typeof NewTarget))return NewTarget;if(void 0!==NewTarget)throw new TypeError("Derived constructors may only return object or undefined");return function(self){if(void 0!==self)return self;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(Super)}}function _getPrototypeOf(o){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o){return o.__proto__||Object.getPrototypeOf(o)})(o)}_react=function(_React$Component){var subClass=ScheduleRefreshServiceReservations;if("function"!=typeof _React$Component&&null!==_React$Component)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(_React$Component&&_React$Component.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),Object.defineProperty(subClass,"prototype",{writable:!1}),_React$Component&&_setPrototypeOf(subClass,_React$Component);var staticProps,_super=_createSuper(ScheduleRefreshServiceReservations);function ScheduleRefreshServiceReservations(){var instance=this,Constructor=ScheduleRefreshServiceReservations;if(instance instanceof Constructor)return _super.apply(this,arguments);throw new TypeError("Cannot call a class as a function")}return subClass=ScheduleRefreshServiceReservations,(_React$Component=[{key:"_doRefresh",value:function(){return this.props.reservations.refreshScheduler&&_ramda.default.defaultTo(!0,this.props.refresh)}},{key:"_refresh",value:function(props,cached){this.props.onRefresh({assetId:props.assetId,dates:props.dates,timeshift:props.timeshift,additionalAssets:props.additionalAssets,showAdditionalAssets:props.showAdditionalAssets,cached:cached})}},{key:"_forcedRefresh",value:function(props){this._refresh(props,!1)}},{key:"_cachedRefresh",value:function(props){this._refresh(props,!0)}},{key:"_onTimer",value:function(){this._doRefresh()&&this._cachedRefresh(this.props)}},{key:"componentDidMount",value:function(){this._cachedRefresh(this.props),this.intervalId=this.props.timerObject.startInterval(this._onTimer.bind(this),this.props.period)}},{key:"componentWillUnmount",value:function(){this.intervalId&&this.props.timerObject.stopInterval(this.intervalId)}},{key:"shouldComponentUpdate",value:function(nextProps){return(0,_refreshCalculator.default)().doRefreshReservations(this.props,nextProps)&&this._forcedRefresh(nextProps),!1}},{key:"render",value:function(){return null}}])&&_defineProperties(subClass.prototype,_React$Component),staticProps&&_defineProperties(subClass,staticProps),Object.defineProperty(subClass,"prototype",{writable:!1}),ScheduleRefreshServiceReservations}(_react.default.Component);_react.propTypes={refresh:_propTypes.default.bool,timerObject:require.TimerObjectPropTypes,assetId:_propTypes.default.number,period:_propTypes.default.number,onRefresh:_propTypes.default.func,dates:_datesReducer.PropTypesDatesReducer,timeshift:_propTypes.default.number.isRequired,reservations:_reservationsReducer.PropTypesReservationsReducer.isRequired,additionalAssets:_propTypes.default.arrayOf(Number),showAdditionalAssets:_propTypes.default.bool},exports.default=_react},{"../../../common/services/refreshCalculator":1721,"../../../common/timerObject":1730,"../../reducers/datesReducer":1753,"../../reducers/reservationsReducer":1762,"prop-types":1046,ramda:1137,react:1427}],1808:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_datesReducer=require("../../reducers/datesReducer"),_react=_interopRequireDefault(require("react")),_refreshCalculator=_interopRequireDefault(require("../../../common/services/refreshCalculator"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,function(arg){arg=function(input,hint){if("object"!==_typeof(input)||null===input)return input;var prim=input[Symbol.toPrimitive];if(void 0===prim)return("string"===hint?String:Number)(input);prim=prim.call(input,hint||"default");if("object"!==_typeof(prim))return prim;throw new TypeError("@@toPrimitive must return a primitive value.")}(arg,"string");return"symbol"===_typeof(arg)?arg:String(arg)}(descriptor.key),descriptor)}}function _setPrototypeOf(o,p){return(_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(o,p){return o.__proto__=p,o})(o,p)}function _createSuper(Derived){var hasNativeReflectConstruct=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}();return function(){var NewTarget,Super=_getPrototypeOf(Derived),Super=(NewTarget=hasNativeReflectConstruct?(NewTarget=_getPrototypeOf(this).constructor,Reflect.construct(Super,arguments,NewTarget)):Super.apply(this,arguments),this);if(NewTarget&&("object"===_typeof(NewTarget)||"function"==typeof NewTarget))return NewTarget;if(void 0!==NewTarget)throw new TypeError("Derived constructors may only return object or undefined");return function(self){if(void 0!==self)return self;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(Super)}}function _getPrototypeOf(o){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o){return o.__proto__||Object.getPrototypeOf(o)})(o)}require=function(_React$Component){var subClass=ScheduleRefreshUsageTypes;if("function"!=typeof _React$Component&&null!==_React$Component)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(_React$Component&&_React$Component.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),Object.defineProperty(subClass,"prototype",{writable:!1}),_React$Component&&_setPrototypeOf(subClass,_React$Component);var staticProps,_super=_createSuper(ScheduleRefreshUsageTypes);function ScheduleRefreshUsageTypes(){var instance=this,Constructor=ScheduleRefreshUsageTypes;if(instance instanceof Constructor)return _super.apply(this,arguments);throw new TypeError("Cannot call a class as a function")}return subClass=ScheduleRefreshUsageTypes,(_React$Component=[{key:"componentDidMount",value:function(){this.props.onRefresh(this.props)}},{key:"shouldComponentUpdate",value:function(nextProps){return(0,_refreshCalculator.default)().doRefreshBackgrounds(this.props,nextProps)&&this.props.onRefresh(nextProps),!1}},{key:"render",value:function(){return null}}])&&_defineProperties(subClass.prototype,_React$Component),staticProps&&_defineProperties(subClass,staticProps),Object.defineProperty(subClass,"prototype",{writable:!1}),ScheduleRefreshUsageTypes}(_react.default.Component);require.propTypes={user:_propTypes.default.object,assetId:_propTypes.default.number,onRefresh:_propTypes.default.func,dates:_datesReducer.PropTypesDatesReducer},exports.default=require},{"../../../common/services/refreshCalculator":1721,"../../reducers/datesReducer":1753,"prop-types":1046,react:1427}],1809:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function RestrictedSchedule(props){return _react.default.createElement("h3",null,props.texts.text," ",props.texts.contact_assistance)}RestrictedSchedule.propTypes={texts:_propTypes.default.shape({text:_propTypes.default.string,contact_assistance:_propTypes.default.string}).isRequired},exports.default=RestrictedSchedule},{"prop-types":1046,react:1427}],1810:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleReviewUsageButton(props){return _ramda.default.defaultTo(!1,props.hidden)?null:_react.default.createElement("div",{className:"ui button small",style:{position:"relative"},"data-test":"schedule_review_usage_btn",onClick:function(){return props.clickNewConfirmUsageLink(props.service_center_id,props.asset_id)}},props.texts.label,props.unconfirmed_reservations?_unconfirmedBookingsLabel:null)}var _unconfirmedBookingsLabel=_react.default.createElement("div",{className:"floating circular ui yellow label"});ScheduleReviewUsageButton.propTypes={hidden:_propTypes.default.bool,service_center_id:_propTypes.default.number.isRequired,asset_id:_propTypes.default.number.isRequired,unconfirmed_reservations:_propTypes.default.bool.isRequired,texts:_propTypes.default.shape({label:_propTypes.default.string.isRequired}),clickNewConfirmUsageLink:_propTypes.default.func},exports.default=ScheduleReviewUsageButton},{"prop-types":1046,ramda:1137,react:1427}],1811:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleTimeframeSelect(props){var hasMultiView,onTimeframeSelect,timeframe,options=_ramda.default.map(function(option){return{active:function(timeframe,option){return option===timeframe}(props.timeframe,option),text:props.texts[option],"data-test":"schedule_timeframe_select_item","data-testid":option,value:option}},(hasMultiView=props.hasMultiView,_ramda.default.reject(function(option){return"multi"===option&&!hasMultiView},_options)));return _react.default.createElement(_semanticUiReact.Dropdown,{button:!0,className:"small no_auto_init timeframe_select","data-test":"schedule_timeframe_select",value:props.timeframe,text:(timeframe=props.timeframe,props.texts[timeframe]),onChange:(onTimeframeSelect=props.onTimeframeSelect,function(_,itemProps){onTimeframeSelect&&onTimeframeSelect(itemProps.value)}),options:options})}var _options=["day","week5","week7","month","multi"];ScheduleTimeframeSelect.propTypes={className:_propTypes.default.string,hasMultiView:_propTypes.default.bool.isRequired,timeframe:_propTypes.default.string.isRequired,onTimeframeSelect:_propTypes.default.func,texts:_propTypes.default.shape({day:_propTypes.default.string.isRequired,week5:_propTypes.default.string.isRequired,week7:_propTypes.default.string.isRequired,month:_propTypes.default.string.isRequired})},exports.default=ScheduleTimeframeSelect},{"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1812:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_updateReservationModalActions=_interopRequireDefault(require("./updateReservationModalActions")),_equipmentAssetReducer=require("../../reducers/equipmentAssetReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_reservationsReducer=require("../../reducers/reservationsReducer"),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleUpdateReservationModal(props){var actions=(0,_updateReservationModalActions.default)(props);return actions.show?_react.default.createElement("div",{id:"schedule_update_reservation_modal"},_react.default.createElement(_semanticUiReact.Modal,{open:actions.show,mountNode:document.getElementById("schedule_update_reservation_modal")},_react.default.createElement(_semanticUiReact.Modal.Header,null,_header(props)),_react.default.createElement(_semanticUiReact.Modal.Content,null,_displayContent(props)),_react.default.createElement(_semanticUiReact.Modal.Actions,null,_react.default.createElement(_semanticUiReact.Button,{disabled:props.loading,onClick:actions.onCancel},props.texts.cancel),_react.default.createElement(_semanticUiReact.Button,{primary:!0,disabled:props.loading,loading:props.loading,onClick:actions.onProceed},props.texts.proceed)))):null}var _header=_ramda.default.view(_ramda.default.lensPath(["reservations","updateModal","header"])),require=_ramda.default.view(_ramda.default.lensPath(["reservations","updateModal","content"])),_displayContent=_ramda.default.compose(function(html){return _react.default.createElement("div",{dangerouslySetInnerHTML:{__html:html}})},function(content){return content.replace(/(\r\n|\n|\r)/g,"<br />")},require);ScheduleUpdateReservationModal.propTypes={loading:_propTypes.default.bool,reservations:_reservationsReducer.PropTypesReservationsReducer.isRequired,texts:_propTypes.default.shape({cancel:_propTypes.default.string,proceed:_propTypes.default.proceed}),resetReservationUpdateModal:_propTypes.default.func,serviceReservationUpdate:_propTypes.default.func,equipment_asset:_equipmentAssetReducer.EquipmentAssetPropTypes,onEndDragReservation:_propTypes.default.func},exports.default=ScheduleUpdateReservationModal},{"../../reducers/equipmentAssetReducer":1754,"../../reducers/reservationsReducer":1762,"./updateReservationModalActions":1813,"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1813:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _equipmentAssetReducer=require("../../reducers/equipmentAssetReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_reservationsReducer=require("../../reducers/reservationsReducer"),_ramda=_interopRequireDefault(require("ramda"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function ScheduleUpdateReservationModalActions(props){var show=!!_header(props);return{show:show,onProceed:function(){var reservation;show&&!props.loading&&(reservation=props.reservations.updateModal.reservation,props.serviceReservationUpdate({equipment_asset:props.equipment_asset,service_center:props.service_center,reservation:_ramda.default.merge(reservation,{valid_override:!0})}),props.onEndDragReservation())},onCancel:function(){show&&!props.loading&&(props.onEndDragReservation(),props.resetReservationUpdateModal())}}}var _header=_ramda.default.view(_ramda.default.lensPath(["reservations","updateModal","header"]));ScheduleUpdateReservationModalActions.propTypes={loading:_propTypes.default.bool,reservations:_reservationsReducer.PropTypesReservationsReducer.isRequired,resetReservationUpdateModal:_propTypes.default.func,serviceReservationUpdate:_propTypes.default.func,equipment_asset:_equipmentAssetReducer.EquipmentAssetPropTypes,onEndDragReservation:_propTypes.default.func},exports.default=ScheduleUpdateReservationModalActions},{"../../reducers/equipmentAssetReducer":1754,"../../reducers/reservationsReducer":1762,"prop-types":1046,ramda:1137}],1814:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _moment=(require=require("moment"))&&require.__esModule?require:{default:require};function _firstDayOnMondayWeek(moment){var date=(0,_moment.default)(moment);return(0===moment.day()?date.subtract(1,"days"):date).day("Monday")}function _prevDay(moment){return(0,_moment.default)(moment).subtract(1,"days")}function _nextDay(moment){return(0,_moment.default)(moment).add(1,"day")}function _dayCalculator(){return{prev:_prevDay,next:_nextDay,first:_moment.default,last:_moment.default}}function _week5Calculator(_ref){function first(moment){return _firstDayOfWeek5(moment,week_starts_on_monday)}var week_starts_on_monday=_ref.week_starts_on_monday;return{prev:_prevWeek,next:_nextWeek,first:first,last:function(moment){return first(moment).add(4,"days")}}}function _week7Calculator(_ref2){function first(moment){return _firstDayOfWeek7(moment,week_starts_on_monday)}var week_starts_on_monday=_ref2.week_starts_on_monday;return{prev:_prevWeek,next:_nextWeek,first:first,last:function(moment){return first(moment).add(6,"days")}}}function _monthCalculator(){return{prev:_prevMonth,next:_nextMonth,first:function(moment){return(0,_moment.default)(moment).startOf("month")},last:function(moment){return(0,_moment.default)(moment).endOf("month")}}}var _firstDayOfWeek7=function(moment,week_starts_on_monday){return week_starts_on_monday?_firstDayOnMondayWeek(moment):0===moment.day()?(0,_moment.default)(moment):(0,_moment.default)(moment).day("Sunday")},_firstDayOfWeek5=function(moment,week_starts_on_monday){return week_starts_on_monday?_firstDayOnMondayWeek(moment):(0,_moment.default)(moment).day("Monday")},_prevWeek=function(moment){return(0,_moment.default)(moment).subtract(1,"week")},_nextWeek=function(moment){return(0,_moment.default)(moment).add(1,"week")},_prevMonth=function(moment){return(0,_moment.default)(moment).subtract(1,"month")},_nextMonth=function(moment){return(0,_moment.default)(moment).add(1,"month")},_multiCalculator=_dayCalculator;exports.default=function(_ref3){var timeframe=_ref3.timeframe,moment=_ref3.moment,_ref3=_ref3.week_starts_on_monday,timeframe={day:_dayCalculator,week5:_week5Calculator,week7:_week7Calculator,month:_monthCalculator,multi:_multiCalculator}[timeframe]({week_starts_on_monday:_ref3});return{prev:timeframe.prev(moment),next:timeframe.next(moment),first:timeframe.first(moment),last:timeframe.last(moment)}}},{moment:1031}],1815:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ScheduleLayout=exports.ScheduleContainerPropTypes=void 0;var _alertBox=require("./components/alertBox"),_actions=require("../reducers/actions"),_backgroundMessageReducer=require("../reducers/backgroundMessageReducer"),_calendarBackgrounds2=_interopRequireDefault(require("./calendarBackgrounds")),_cancellationNotificationToggle=_interopRequireDefault(require("./components/cancellationNotificationToggle")),_equipmentAssetReducer=require("../reducers/equipmentAssetReducer"),_eventModalReducer=require("../reducers/eventModalReducer"),_institutionReducer=require("../reducers/institutionReducer"),_linkedReservationModalReducer=require("../reducers/linkedReservationModalReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_app=require("../../app"),_calendarBackgrounds3=require("../../common/services/calendarBackgrounds"),_datesReducer=require("../reducers/datesReducer"),_orderableItems=require("../../common/services/schedules/orderableItems"),_reservationsReducer=require("../reducers/reservationsReducer"),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),_restrictedSchedule2=_interopRequireDefault(require("./components/restrictedSchedule")),_additionalAssetButton=_interopRequireDefault(require("./components/additionalAssetButton")),_assetSelector=require("./components/assetSelector"),_assetSettingsButton=_interopRequireDefault(require("./components/assetSettingsButton")),_backgroundMessage=_interopRequireDefault(require("./components/backgroundMessage")),_breadcrumb=_interopRequireDefault(require("./components/breadcrumb")),_calendarDetailsModal=_interopRequireDefault(require("./components/calendarDetailsModal")),_calendarLoader=_interopRequireDefault(require("./components/calendarLoader")),_view=_interopRequireDefault(require("./components/calendar/view")),_customerNote=_interopRequireDefault(require("./components/customerNote")),_dateNavigator=_interopRequireDefault(require("./components/dateNavigator")),_dateSelect=_interopRequireDefault(require("./components/dateSelect")),_descriptionModal=_interopRequireDefault(require("./components/descriptionModal")),_downloadPdfButton=_interopRequireDefault(require("./components/downloadPdfButton")),_eventModal=_interopRequireDefault(require("./components/eventModal")),_favoriteButton=_interopRequireDefault(require("./components/favoriteButton")),_linkedReservationModal=_interopRequireDefault(require("./components/linkedReservationModal")),_mainLoader=_interopRequireDefault(require("./components/mainLoader")),_offlineMessage=_interopRequireDefault(require("./components/offlineMessage")),_refreshServiceReservations=_interopRequireDefault(require("./components/refreshServiceReservations")),_refreshUsageTypes=_interopRequireDefault(require("./components/refreshUsageTypes")),_reviewUsageButton=_interopRequireDefault(require("./components/reviewUsageButton")),_timeframeSelect=_interopRequireDefault(require("./components/timeframeSelect")),_updateReservationModal=_interopRequireDefault(require("./components/updateReservationModal")),_serviceCenterReducer=require("../../common/reducers/serviceCenterReducer"),_showCalculator2=require("./showCalculator"),_timerObject=require("../../common/timerObject"),_userReducer=require("../reducers/userReducer"),_classnames=_interopRequireDefault(require("classnames")),_i18n=require("../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _extends(){return(_extends=Object.assign?Object.assign.bind():function(target){for(var i=1;i<arguments.length;i++){var key,source=arguments[i];for(key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target}).apply(this,arguments)}function ScheduleLayout(props){function _getLoading(lense){return _ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.view(_ramda.default.lensPath(lense)))}var equipmentCanRead=props.state.equipment_asset.can_read,userIsManager=props.state.service_center.manager,userCanConfirmUsage=props.state.service_center.current_user_can_confirm_usage,_isScheduleCalendarLoading=_ramda.default.anyPass([_getLoading(["schedules","index"]),_getLoading(["schedules","update"]),_getLoading(["calendar_backgrounds","index"]),_getLoading(["service_centers_equipment","index"])]),_isCalendarLoading=_ramda.default.anyPass([_getLoading(["schedules","update"]),_getLoading(["service_reservations","create"])]),_isOrderableItemsLoading=_ramda.default.anyPass([_getLoading(["orderable_items","index"])]),_isTogglingAdditionalAssets=_ramda.default.anyPass([_getLoading(["equipment_asset","additional_assets"])]),_isDownloadPdfLoading=_ramda.default.anyPass([_getLoading(["download","pdf"])]),_loggedInUser=!(_notLoggedUser=_ramda.default.compose(_ramda.default.isNil,_ramda.default.prop("id"))(props.state.user)),_isCalendarReadOnly=_notLoggedUser,_descriptionHidden=!equipmentCanRead||_notLoggedUser,_notLoggedUser=!equipmentCanRead||_notLoggedUser,equipmentCanRead=!equipmentCanRead,_calendarBackgrounds=(0,_calendarBackgrounds2.default)({timeframe:props.state.dates.timeframe,user:props.state.user}).filter(props.state.calendarBackgrounds),_showCalculator=(0,_showCalculator2.ShowCalculator)(props.state);return _react.default.createElement("div",null,_react.default.createElement(_mainLoader.default,{loading:_getLoading(["schedules","show"])(props.state.request)}),_react.default.createElement("div",{className:"ui one column grid"},_react.default.createElement(_alertBox.AlertBox,_extends({},props.state.alertBox,{className:"ui column",onConfirm:props.actions.closeAlertBox,resetTimeoutAlertBox:props.actions.resetTimeoutAlertBox,setAlertBoxTimeoutId:props.actions.setAlertBoxTimeoutId,timerObject:_timerObject.TimerObject,closePeriodTime:5e3,texts:(0,_i18n.t)("alert_box")})),_react.default.createElement("div",{className:"ui row no-bottom-padding"},_react.default.createElement("div",{className:"ui sixteen wide column"},_react.default.createElement(_breadcrumb.default,{loggedIn:_loggedInUser,service_center_id:props.state.service_center.id,service_center_name:props.state.service_center.name,texts:(0,_i18n.t)("breadcrumb"),onClick:props.actions.clickServiceCenterLink}))),_react.default.createElement("div",{className:"ui row"},_react.default.createElement("div",{className:"ui eleven wide column flex-row-center"},_react.default.createElement(_assetSelector.ScheduleAssetSelector,{className:"left floated",assetName:props.state.equipment_asset.name,equipmentByCategory:props.state.service_center.equipment_by_category,equipmentTextFilter:props.state.service_center.equipment_text_filter,showEquipmentByCategory:props.state.service_center.show_equipment_by_category,serviceCentersEquipmentTextFilterAction:props.actions.serviceCentersEquipmentTextFilter,clickScheduleLinkAction:props.actions.scheduleLink,texts:(0,_i18n.t)("asset_select_dropdown")}),_react.default.createElement(_favoriteButton.default,{asset_id:props.state.equipment_asset.id,outline:!props.state.equipment_asset.bookmarked_by_user,texts:(0,_i18n.t)("favorite_btn"),hidden:_notLoggedUser,loading:_getLoading(["equipments","toogleBookmark"])(props.state.request),onClick:props.actions.toggleFavorite}),_react.default.createElement(_descriptionModal.default,{show:props.state.descriptionModal.show,hidden:_descriptionHidden,header:(0,_i18n.t)("description_modal.title",{name:props.state.equipment_asset.name}),content:props.state.equipment_asset.description,texts:(0,_i18n.t)("description_modal"),onClick:props.actions.showDescriptionModal,onClose:props.actions.closeDescriptionModal}),_react.default.createElement(_assetSettingsButton.default,{asset_id:props.state.equipment_asset.id,hidden:!userIsManager,service_center_id:props.state.service_center.id,texts:(0,_i18n.t)("settings_btn"),clickAssetSettingsLink:props.actions.clickAssetSettingsLink})),_react.default.createElement("div",{className:"ui five wide column right aligned"},_react.default.createElement(_cancellationNotificationToggle.default,{asset_id:props.state.equipment_asset.id,subscribed:props.state.equipment_asset.cancellation_subscriber,loading:_getLoading(["equipments","cancellation_subscription"])(props.state.request),hidden:!props.state.equipment_asset.user_can_see_cancellation_toggle,timeWindow:props.state.equipment_asset.cancellation_notification_time_window,texts:(0,_i18n.t)("cancellation_notification_toggle"),onClick:props.actions.toggleCancellationSubscription}),_react.default.createElement(_reviewUsageButton.default,{asset_id:props.state.equipment_asset.id,service_center_id:props.state.service_center.id,hidden:!userCanConfirmUsage,unconfirmed_reservations:props.state.equipment_asset.unconfirmed_reservations,texts:(0,_i18n.t)("confirm_usage_btn"),clickNewConfirmUsageLink:props.actions.clickNewConfirmUsageLink}))),_react.default.createElement("div",{className:"ui row no-top-padding no-bottom-padding"},_react.default.createElement(_backgroundMessage.default,{className:"ui sixteen wide column flex-row-center bottom-padding",show:props.state.backgroundMessage.show,message:props.state.backgroundMessage.message})),_react.default.createElement("div",{className:(0,_classnames.default)("ui","row","no-top-padding",{"hidden-content":!_showCalculator.showCostumerNotes()})},_react.default.createElement("div",{className:"ui sixteen wide column"},_react.default.createElement(_customerNote.default,{show:_showCalculator.showCostumerNotes(),customer_note:props.state.equipment_asset.schedule_description})))),equipmentCanRead?_react.default.createElement(_restrictedSchedule2.default,{texts:(0,_i18n.t)("restricted_schedule")}):_react.default.createElement("div",null,_react.default.createElement("div",{className:(0,_classnames.default)("ui","sixteen","wide","column",{"hidden-content":props.state.equipment_asset.online})},_react.default.createElement(_offlineMessage.default,{online:props.state.equipment_asset.online,offline_message:(0,_i18n.t)("offline_message")})),_react.default.createElement("div",{className:"ui segments printable_area"},_react.default.createElement("div",{className:"ui fluid top attached stackable borderless menu"},_react.default.createElement("div",{className:"item"},_react.default.createElement(_timeframeSelect.default,{hasMultiView:1<props.state.equipment_asset.equipments.length,timeframe:props.state.dates.timeframe,texts:(0,_i18n.t)("timeframe_select"),onTimeframeSelect:props.actions.timeframeSelect}),_react.default.createElement(_dateSelect.default,{moment:props.state.dates.moment,onDateSelect:props.actions.dateSelect,texts:(0,_i18n.t)("datepicker"),week_starts_on_monday:props.state.institution.week_starts_on_monday}),_react.default.createElement(_downloadPdfButton.default,{dates:props.state.dates,element:document.getElementsByClassName("printable_area")[0],loading:_isDownloadPdfLoading(props.state.request),texts:(0,_i18n.t)("pdf_button"),downloadPdf:props.actions.downloadPdf}),_react.default.createElement(_refreshUsageTypes.default,{user:props.state.user,assetId:props.state.equipment_asset.id,onRefresh:props.actions.calendarBackgroundIndex,dates:props.state.dates}),_react.default.createElement(_refreshServiceReservations.default,{refresh:!0,assetId:props.state.equipment_asset.id,timerObject:_timerObject.TimerObject,period:props.state.appConfig.refresh_period,onRefresh:props.actions.serviceReservationIndex,reservations:props.state.reservations,dates:props.state.dates,timeshift:props.state.appConfig.tz_correction_offset,additionalAssets:props.state.equipment_asset.additional_assets,showAdditionalAssets:props.state.equipment_asset.showAdditionalAssets}),_react.default.createElement(_calendarLoader.default,{loading:_isScheduleCalendarLoading(props.state.request)})),_react.default.createElement("div",{className:"menu full-width"},_react.default.createElement("div",{className:"item margin-center"},_react.default.createElement(_dateNavigator.default,{dates:props.state.dates,time_zone:props.state.equipment_asset.time_zone,week_starts_on_monday:props.state.institution.week_starts_on_monday,onPrevDate:props.actions.prevDate,onNextDate:props.actions.nextDate}))),_react.default.createElement("div",{className:"item right aligned"},_react.default.createElement(_additionalAssetButton.default,{loading:_isTogglingAdditionalAssets(props.state.request),assetId:props.state.equipment_asset.id,dates:props.state.dates,timeshift:props.state.appConfig.tz_correction_offset,additionalAssets:props.state.equipment_asset.additional_assets,toggleAdditionalAsset:props.actions.toggleAdditionalAssets,showAdditionalAssets:props.state.equipment_asset.showAdditionalAssets,texts:(0,_i18n.t)("additional_assets_btn")}),_react.default.createElement(_calendarDetailsModal.default,{assetId:props.state.equipment_asset.id,open:_showCalculator.openCalendarDetails(),show:_showCalculator.showCalendarDetails(),employee:props.state.service_center.employee,header:(0,_i18n.t)("calendar_details_modal.title",{name:props.state.equipment_asset.name}),content:props.state.equipment_asset.description,texts:(0,_i18n.t)("calendar_details_modal"),orderableItems:props.state.orderableItems,loading:_isOrderableItemsLoading(props.state.request),orderableItemsIndex:props.actions.orderableItemsIndex,onClick:props.actions.showCalendarDetailsModal,onClose:props.actions.closeCalendarDetailsModal}))),_react.default.createElement("div",{className:"ui segment"},_react.default.createElement(_view.default,{loading:_isCalendarLoading(props.state.request),readOnly:_isCalendarReadOnly,texts:(0,_i18n.t)("calendar_component"),tz_correction_offset:props.state.appConfig.tz_correction_offset,institution:props.state.institution,user:props.state.user,service_center:props.state.service_center,equipment_asset:props.state.equipment_asset,calendarBackgrounds:_calendarBackgrounds,dates:props.state.dates,reservations:props.state.reservations,scheduler:scheduler,onDateChange:props.actions.timeframeDateSelect,onStartDragReservation:props.actions.onStartDragReservation,onEndDragReservation:props.actions.onEndDragReservation,serviceReservationCreate:props.actions.serviceReservationCreate,serviceReservationUpdate:props.actions.serviceReservationUpdate,showAlertBox:props.actions.showAlertBox,showEventModal:props.actions.showEventModal}),_react.default.createElement(_updateReservationModal.default,{loading:_isCalendarLoading(props.state.request),reservations:props.state.reservations,texts:(0,_i18n.t)("update_reservation"),serviceReservationUpdate:props.actions.serviceReservationUpdate,resetReservationUpdateModal:props.actions.resetReservationUpdateModal,equipment_asset:props.state.equipment_asset,onEndDragReservation:props.actions.onEndDragReservation}),_react.default.createElement(_eventModal.default,{assetId:props.state.equipment_asset.id,show:props.state.eventModal.show,isNewEvent:props.state.eventModal.isNewEvent,end_date_adjusted:props.state.eventModal.end_date_adjusted,eventId:props.state.eventModal.eventId,loadEventModal:props.actions.loadEventModal.load,cancelChangesModal:props.actions.loadEventModal.cancelChanges,loading:_getLoading(["calendar_events","show"])(props.state.request),onRefresh:props.actions.serviceReservationIndex,reservations:props.state.reservations,dates:props.state.dates,timeshift:props.state.appConfig.tz_correction_offset,additionalAssets:props.state.equipment_asset.additional_assets,showAdditionalAssets:props.state.equipment_asset.showAdditionalAssets}),_react.default.createElement(_linkedReservationModal.default,{show:props.state.linkedReservationModal.show,eventId:props.state.linkedReservationModal.eventId,parentEventId:props.state.linkedReservationModal.parentEventId,onClose:props.actions.closeLinkedReservationModal,showEventModal:props.actions.showEventModal,texts:(0,_i18n.t)("linked_reservation_modal")})))))}require={state:_propTypes.default.shape({appConfig:_app.PropTypesAppConfig,request:_propTypes.default.shape({loading:_propTypes.default.bool,equipments:_propTypes.default.shape({toogleBookmark:_propTypes.default.bool,toggleCancellationSubscription:_propTypes.default.bool})}).isRequired,institution:_institutionReducer.InstitutionPropTypes,user:_userReducer.UserPropTypes,service_center:_serviceCenterReducer.ServiceCenterPropTypes,equipment_asset:_equipmentAssetReducer.EquipmentAssetPropTypes,descriptionModal:_propTypes.default.shape({modalType:_propTypes.default.string,show:_propTypes.default.bool}),calendarDetailsModal:_propTypes.default.shape({modalType:_propTypes.default.string,show:_propTypes.default.bool}),alertBox:_alertBox.AlertBoxProcTypes,dates:_datesReducer.PropTypesDatesReducer,reservations:_reservationsReducer.PropTypesReservationsReducer,calendarBackgrounds:_propTypes.default.arrayOf(_calendarBackgrounds3.PropTypesCalendarBackgroundModel),eventModal:_eventModalReducer.EventModalProptypes,backgroundMessage:_backgroundMessageReducer.BackgroundMessageProptypes,linkedReservationModal:_linkedReservationModalReducer.LinkedReservationModalPropTypes,orderableItems:_orderableItems.PropTypesOrderableItems}).isRequired,actions:_actions.ActionsProptypes};exports.ScheduleContainerPropTypes=require;(exports.ScheduleLayout=ScheduleLayout).propTypes=require},{"../../app":1704,"../../common/reducers/serviceCenterReducer":1714,"../../common/services/calendarBackgrounds":1717,"../../common/services/schedules/orderableItems":1724,"../../common/timerObject":1730,"../../i18n":1832,"../reducers/actions":1738,"../reducers/backgroundMessageReducer":1751,"../reducers/datesReducer":1753,"../reducers/equipmentAssetReducer":1754,"../reducers/eventModalReducer":1755,"../reducers/institutionReducer":1758,"../reducers/linkedReservationModalReducer":1759,"../reducers/reservationsReducer":1762,"../reducers/userReducer":1764,"./calendarBackgrounds":1766,"./components/additionalAssetButton":1767,"./components/alertBox":1768,"./components/assetSelector":1769,"./components/assetSettingsButton":1770,"./components/backgroundMessage":1771,"./components/breadcrumb":1772,"./components/calendar/view":1790,"./components/calendarDetailsModal":1793,"./components/calendarLoader":1794,"./components/cancellationNotificationToggle":1795,"./components/customerNote":1796,"./components/dateNavigator":1797,"./components/dateSelect":1798,"./components/descriptionModal":1800,"./components/downloadPdfButton":1801,"./components/eventModal":1802,"./components/favoriteButton":1803,"./components/linkedReservationModal":1804,"./components/mainLoader":1805,"./components/offlineMessage":1806,"./components/refreshServiceReservations":1807,"./components/refreshUsageTypes":1808,"./components/restrictedSchedule":1809,"./components/reviewUsageButton":1810,"./components/timeframeSelect":1811,"./components/updateReservationModal":1812,"./showCalculator":1816,classnames:116,"prop-types":1046,ramda:1137,react:1427}],1816:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ShowCalculator=void 0;var _ramda=_interopRequireDefault(require("ramda")),_userInfo=_interopRequireDefault(require("../../common/userInfo"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.ShowCalculator=function(_ref){function _userLoggedIn(user){return(0,_userInfo.default)(user).loggedIn}var equipment_asset=_ref.equipment_asset,user=_ref.user,calendarDetailsModal=_ref.calendarDetailsModal,_hasScheduleDescription=_ramda.default.compose(_ramda.default.not,_ramda.default.isEmpty,_ramda.default.defaultTo(""),_ramda.default.prop("schedule_description")),_canRead=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("can_read")),_show=_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.prop("show"));return{showCostumerNotes:function(){return _userLoggedIn(user)&&_hasScheduleDescription(equipment_asset)&&_canRead(equipment_asset)},openCalendarDetails:function(){return _userLoggedIn(user)&&_show(calendarDetailsModal)},showCalendarDetails:function(){return _userLoggedIn(user)}}}},{"../../common/userInfo":1732,ramda:1137}],1817:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_actions=require("../../reducers/actions"),_alertBox=require("../../schedule/components/alertBox"),_alertMessageComponent=_interopRequireDefault(require("../../../common/components/alertMessageComponent")),_formSelectLabReducer=require("../../reducers/formSelectLabReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),require=require("../../reducers/userReducer");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _onCancel(props){return function(){props.actions.closeModalLabSelect()}}function SelectLabModal(props){var _getLoading,_creatingReservation,_disabledCancel,_dropdownOptions;return props.formSelectLab.showModal?(_getLoading=function(lense){return _ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.view(_ramda.default.lensPath(lense)))},_disabledCancel=_creatingReservation=function(){return _getLoading(["service_reservations","create"])(props.request)},_dropdownOptions=_ramda.default.compose(_ramda.default.map(function(group){return{key:group.is,value:group.id,text:group.name}}),_ramda.default.defaultTo([]),_ramda.default.view(_ramda.default.lensPath(["user","groups"]))),_react.default.createElement("div",{id:"schedule_select_lab_modal"},_react.default.createElement(_semanticUiReact.Modal,{open:!0,onClose:_onCancel(props),mountNode:document.getElementById("schedule_select_lab_modal")},props.loading?_react.default.createElement("div",{className:"ui active inverted dimmer"},_react.default.createElement("div",{className:"ui loader"})):null,_react.default.createElement(_semanticUiReact.Modal.Header,null,props.title),_react.default.createElement(_semanticUiReact.Modal.Content,null,_react.default.createElement(_alertMessageComponent.default,{show:props.alertBox.show,level:props.alertBox.level,header:props.alertBox.header,content:props.alertBox.content,onConfirm:props.actions.closeAlertBox}),_react.default.createElement(_semanticUiReact.Form,null,_react.default.createElement(_semanticUiReact.Form.Field,null,_react.default.createElement(_semanticUiReact.Dropdown,{className:"no_auto_init",selection:!0,fluid:!0,options:_dropdownOptions(props),value:props.formSelectLab.groupIdSelected,onChange:function(event,data){props.actions.setGroupSelect(data.value)}})))),_react.default.createElement(_semanticUiReact.Modal.Actions,null,_react.default.createElement(_semanticUiReact.Button,{onClick:_onCancel(props),disabled:_disabledCancel()},props.texts.cancel),_react.default.createElement(_semanticUiReact.Button,{primary:!0,onClick:function(props){return function(){props.formSelectLab.canSaveReservation&&props.actions.serviceReservationSave({assetId:props.assetId,equipmentId:props.formSelectLab.equipmentId,start_time:props.formSelectLab.reservation_start_time,end_time:props.formSelectLab.reservation_end_time,ownerId:props.user.id,groupProfileId:props.formSelectLab.groupIdSelected,event_type:"reservation"})}}(props),disabled:_creatingReservation()||!props.formSelectLab.canSaveReservation,loading:_creatingReservation()},props.texts.next))))):null}SelectLabModal.propTypes={title:_propTypes.default.string,loading:_propTypes.default.bool,assetId:_propTypes.default.number,serviceCenterId:_propTypes.default.number,formSelectLab:_formSelectLabReducer.FormSelectLabReducerReducerPropTypes,timeframe:_propTypes.default.string,date:_propTypes.default.string,alertBox:_propTypes.default.shape(_alertBox.AlertBoxProcTypes),actions:_actions.ActionsProptypes,request:_propTypes.default.object,user:require.UserPropTypes,employee:_propTypes.default.bool,texts:_propTypes.default.shape({cancel:_propTypes.default.string,next:_propTypes.default.string,lab_dropdown:_propTypes.default.object})},exports.default=SelectLabModal},{"../../../common/components/alertMessageComponent":1706,"../../reducers/actions":1738,"../../reducers/formSelectLabReducer":1756,"../../reducers/userReducer":1764,"../../schedule/components/alertBox":1768,"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1818:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _actions=require("../reducers/actions"),_alertBox=require("../schedule/components/alertBox"),_dateFormatting=_interopRequireDefault(require("../../common/dateFormatting")),_equipmentAssetReducer=require("../reducers/equipmentAssetReducer"),_formSelectLabReducer=require("../reducers/formSelectLabReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_datesReducer=require("../reducers/datesReducer"),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),_selectLabModal=_interopRequireDefault(require("./components/selectLabModal")),_serviceCenterReducer=require("../../common/reducers/serviceCenterReducer"),_userReducer=require("../reducers/userReducer"),_i18n=require("../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function SelectLabApp(props){var lense,dateFormatting=(0,_dateFormatting.default)({calendar_display_24h:props.state.service_center.calendar_display_24h});return _react.default.createElement(_selectLabModal.default,{assetId:props.state.equipment_asset.id,loading:(lense=["schedules","show"],_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.view(_ramda.default.lensPath(lense)))(props.state.request)),formSelectLab:props.state.formSelectLab,alertBox:props.state.alertBox,user:props.state.user,actions:props.actions,request:props.state.request,title:(0,_i18n.t)("user_select.modal.title",{from:dateFormatting.formatTime(props.state.formSelectLab.reservation_start_moment),to:dateFormatting.formatTime(props.state.formSelectLab.reservation_end_moment)}),texts:(0,_i18n.t)("lab_select.modal"),employee:props.state.service_center.employee})}SelectLabApp.propTypes={state:_propTypes.default.shape({dates:_datesReducer.PropTypesDatesReducer,equipment_asset:_equipmentAssetReducer.EquipmentAssetPropTypes,service_center:_serviceCenterReducer.ServiceCenterPropTypes,formSelectLab:_formSelectLabReducer.FormSelectLabReducerReducerPropTypes,request:_propTypes.default.object.isRequired,alertBox:_alertBox.AlertBoxProcTypes,user:_userReducer.UserPropTypes}).isRequired,actions:_actions.ActionsProptypes},exports.default=SelectLabApp},{"../../common/dateFormatting":1707,"../../common/reducers/serviceCenterReducer":1714,"../../i18n":1832,"../reducers/actions":1738,"../reducers/datesReducer":1753,"../reducers/equipmentAssetReducer":1754,"../reducers/formSelectLabReducer":1756,"../reducers/userReducer":1764,"../schedule/components/alertBox":1768,"./components/selectLabModal":1817,"prop-types":1046,ramda:1137,react:1427}],1819:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _react=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("react")),_semanticUiReact=require("semantic-ui-react"),require=(require=require("prop-types"))&&require.__esModule?require:{default:require};function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}function SelectUserLabDropdown(props){function _reloadComponent(){if(props.showLabDropdown)return _select2Object().reload({userGroups:props.userGroups})}var _select2Object=function(){return props.select2({element:$j(selectNode),setSelectCallback:props.setGroupSelect,placeholder:props.texts.placeholder})},selectNode=null,_onDestroyComponent=_select2Object().destroy;return(0,_react.useEffect)(function(){return function(){if(props.showLabDropdown)_select2Object().init({userGroups:props.userGroups})}(),_onDestroyComponent},[]),(0,_react.useEffect)(_reloadComponent,[props.userGroups]),props.showLabDropdown?_react.default.createElement(_semanticUiReact.Form.Field,null,_react.default.createElement("label",null,props.texts.label),_react.default.createElement("input",{"data-test":"select_user_lab_dropdown",ref:function(node){return selectNode=node},type:"hidden",className:"lab_select_input"})):null}SelectUserLabDropdown.propTypes={select2:require.default.func.isRequired,showLabDropdown:require.default.bool.isRequired,serviceCenterId:require.default.number,userSearchScope:require.default.string,labDropdownText:require.default.string,userSelect:require.default.string,texts:require.default.object,setLabDropdownText:require.default.func,setGroupSelect:require.default.func,userGroups:require.default.arrayOf(require.default.object),groupIdSelected:require.default.oneOfType([require.default.number,require.default.string])},exports.default=SelectUserLabDropdown},{"prop-types":1046,react:1427,"semantic-ui-react":1568}],1820:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _ramda=(require=require("ramda"))&&require.__esModule?require:{default:require};function _formatResult(item){return"<div class='result'>".concat(_formatSelection(item),"</div>")}var _formatSelection=function(item){var tags=["<span class='name'>".concat(item.name,"</span>")];return item.funding&&tags.push("<span class='funding'>".concat(item.funding,"</span>")),_ramda.default.join("",tags)};exports.default=function(_ref){function _input(){return $j(element)}function _onInputChange(event){return setSelectCallback($j(event.target).val())}function init(_ref2){_ref2=_ref2.userGroups,_input().select2({containerCss:{width:"400px"},dropdownCss:{"min-width":"400px"},placeholder:placeholder,minimumInputLength:0,formatSelection:_formatSelection,formatResult:_formatResult,initSelection:function(elem,callback){elem=elem.data("initial");elem&&callback(elem)},escapeMarkup:function(m){return m},nextSearchTerm:function(selectedObject,currentSearchTerm){return currentSearchTerm},data:{results:_ref2,text:"name"}}),_input().on("change",_onInputChange)}function destroy(){_input().off("change"),_input().select2("destroy")}var placeholder=_ref.placeholder,element=_ref.element,setSelectCallback=_ref.setSelectCallback;return{init:init,destroy:destroy,reload:function(options){destroy(),init(options)},open:function(){_input().find("open")}}}},{ramda:1137}],1821:[function(require,module,exports){"use strict";function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _react=function(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule)return obj;if(null===obj||"object"!==_typeof(obj)&&"function"!=typeof obj)return{default:obj};nodeInterop=_getRequireWildcardCache(nodeInterop);if(nodeInterop&&nodeInterop.has(obj))return nodeInterop.get(obj);var key,newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(key in obj){var desc;"default"!==key&&Object.prototype.hasOwnProperty.call(obj,key)&&((desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null)&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key])}newObj.default=obj,nodeInterop&&nodeInterop.set(obj,newObj);return newObj}(require("react")),_semanticUiReact=require("semantic-ui-react"),require=(require=require("prop-types"))&&require.__esModule?require:{default:require};function _getRequireWildcardCache(nodeInterop){var cacheBabelInterop,cacheNodeInterop;return"function"!=typeof WeakMap?null:(cacheBabelInterop=new WeakMap,cacheNodeInterop=new WeakMap,(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop))}function SelectUserUserDropdown(props){function _reloadComponent(){return _select2Object().reload({serviceCenterId:props.serviceCenterId,scope:props.userSearchScope,searchText:props.userDropdownText,userSelected:props.userSelected})}var _select2Object=function(){return props.select2({element:$j(selectNode),setTextCallback:props.setUserDropdownText,setSelectCallback:_onSelectUser,placeholder:props.texts.placeholder})},selectNode=null,_select2Destroy=_select2Object().destroy,_onSelectUser=function(owner){props.setUserSelect({asset_id:props.assetId,event_type:props.reservationType,service_center_id:props.serviceCenterId,user:owner,usage_capping_enabled:0})},_onDestroyComponent=_select2Destroy;return(0,_react.useEffect)(function(){return _select2Object().init({serviceCenterId:props.serviceCenterId,scope:props.userSearchScope,searchText:props.userDropdownText,userSelected:props.userSelected}),_onDestroyComponent},[]),(0,_react.useEffect)(_reloadComponent,[props.userSearchScope,props.userSelected]),_react.default.createElement(_semanticUiReact.Form.Field,null,_react.default.createElement("label",null,props.texts.label),_react.default.createElement("input",{"data-test":"select_user_user_dropdown",ref:function(node){return selectNode=node},type:"hidden",className:"person_select_input"}))}SelectUserUserDropdown.propTypes={select2:require.default.func.isRequired,assetId:require.default.number,serviceCenterId:require.default.number,reservationType:require.default.string,userSearchScope:require.default.string,userDropdownText:require.default.string,userSelected:require.default.object,texts:require.default.object,setUserDropdownText:require.default.func,setUserSelect:require.default.func},exports.default=SelectUserUserDropdown},{"prop-types":1046,react:1427,"semantic-ui-react":1568}],1822:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;function _formatSelection(el){return"<span class='owner'>".concat(el.name,"</span>\n    <span class='group'>").concat(el.lab,"</span>\n    <span class='name'>").concat(el.email,"</span>\n    <span class='category'>").concat(el.phone,"</span>\n    <span class='funding'>").concat(el.funding,"</span>")}function _formatResult(el,container,query,escapeMarkup){function mark(html){var markup=[];return window.Select2.util.markMatch(html.toString(),query.term,markup,escapeMarkup),markup.join("")}return"\n    <div class=\"result\">\n      <span class='owner'>".concat(mark(el.name),"</span>\n      <span class='group'>").concat(mark(el.lab),"</span>\n      <span class='name'>").concat(mark(el.email),"</span>\n      <span class='category'>").concat(mark(el.phone),"</span>\n      <span class='funding'>").concat(mark(el.funding),"</span>\n    </div>")}var _liveSearchProfilesUrl="/live_search/profiles_for_select2";exports.default=function(_ref2){function init(_ref3){var serviceCenterId=_ref3.serviceCenterId,scope=_ref3.scope,searchText=_ref3.searchText,userSelected=_ref3.userSelected;_input().select2({containerCss:{width:"100%"},dropdownCss:{"min-width":"860px"},placeholder:placeholder,minimumInputLength:2,formatSelection:_formatSelection,formatResult:_formatResult,escapeMarkup:function(m){return m},nextSearchTerm:function(selectedObject,currentSearchTerm){return currentSearchTerm},initSelection:function(event,callback){return callback(userSelected)},ajax:function(_ref){var scope=_ref.scope,serviceCenterId=_ref.serviceCenterId;return{url:_liveSearchProfilesUrl,data:function(term,page){return{sc_id:serviceCenterId,scope:scope,query:term,page:page}},dataType:"jsonp",results:function(data){return{results:data.profiles,more:data.more}}}}({scope:scope,serviceCenterId:serviceCenterId})}).select2("val",userSelected),_attachEvents({searchText:searchText})}function _attachEvents(_ref4){_ref4=_ref4.searchText,_searchInput().on("propertychange change click keyup input paste",_onSearchInputSave),_input().on("select2-open",_onInputOpen(_ref4)),_input().on("change",_onInputChange),_input().on("select2-opening",_cleanVal)}function destroy(){_searchInput()&&_searchInput().off("propertychange change click keyup input paste"),_input().off("select2-open"),_input().off("change"),_input().off("select2-opening"),_input().select2("destroy")}var placeholder=_ref2.placeholder,element=_ref2.element,setTextCallback=_ref2.setTextCallback,setSelectCallback=_ref2.setSelectCallback,_input=function(){return $j(element)},_searchInput=function(){if(_input()&&_input().data("select2"))return _input().data("select2").search},_onSearchInputSave=function(){return setTextCallback(_searchInput().val())},_onInputOpen=function(searchText){return function(){return _input().select2("search",searchText||"")}},_onInputChange=function(event){setSelectCallback(event.added)},_cleanVal=function(){return _input().val(null)};return{init:init,destroy:destroy,reload:function(options){destroy(),init(options)},open:function(){_input().find("open")}}}},{}],1823:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _actions=require("../../reducers/actions"),_semanticUiReact=require("semantic-ui-react"),_formSelectUserReducer=require("../../reducers/formSelectUserReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_selectEventType=_interopRequireDefault(require("./selectEventType"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function SelectUserMaintenanceForm(props){return _react.default.createElement(_semanticUiReact.Form,null,_react.default.createElement(_selectEventType.default,{reservationType:props.formSelectUser.reservationType,selectReservationType:props.actions.selectReservationType,texts:props.texts}))}SelectUserMaintenanceForm.propTypes={formSelectUser:_formSelectUserReducer.FormReducerPropTypes,actions:_actions.ActionsProptypes,texts:_propTypes.default.shape({event_type:_propTypes.default.string,reservation_text:_propTypes.default.string,unavailable_text:_propTypes.default.string,cancel:_propTypes.default.string,save:_propTypes.default.string,user_scope:_propTypes.default.object,user_dropdown:_propTypes.default.object,lab_dropdown:_propTypes.default.object})},exports.default=SelectUserMaintenanceForm},{"../../reducers/actions":1738,"../../reducers/formSelectUserReducer":1757,"./selectEventType":1825,"prop-types":1046,react:1427,"semantic-ui-react":1568}],1824:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _actions=require("../../reducers/actions"),_semanticUiReact=require("semantic-ui-react"),_formSelectUserReducer=require("../../reducers/formSelectUserReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react")),_labSelect=_interopRequireDefault(require("./inputs/labSelect2")),_userSelect=_interopRequireDefault(require("./inputs/userSelect2")),_selectEventType=_interopRequireDefault(require("./selectEventType")),_labDropdown=_interopRequireDefault(require("./inputs/labDropdown")),_selectUserScope=_interopRequireDefault(require("./selectUserScope")),_usageCappings=_interopRequireDefault(require("./usageCappings")),_userDropdown=_interopRequireDefault(require("./inputs/userDropdown")),require=require("../../reducers/userReducer");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function SelectUserReservationForm(props){return _react.default.createElement(_semanticUiReact.Form,null,_react.default.createElement(_semanticUiReact.Form.Group,null,_react.default.createElement(_selectEventType.default,{reservationType:props.formSelectUser.reservationType,selectReservationType:props.actions.selectReservationType,texts:props.texts}),_react.default.createElement(_selectUserScope.default,{userSearchScope:props.formSelectUser.userSearchScope,selectUserSearchScope:props.actions.selectUserSearchScope,texts:props.texts.user_scope,allUsersLabel:props.allUsersLabel})),_react.default.createElement(_userDropdown.default,{select2:_userSelect.default,assetId:props.assetId,serviceCenterId:props.serviceCenterId,reservationType:props.formSelectUser.reservationType,userSearchScope:props.formSelectUser.userSearchScope,userDropdownText:props.formSelectUser.userDropdownText,setUserDropdownText:props.actions.setUserDropdownText,userSelected:props.formSelectUser.userSelected,setUserSelect:props.actions.setUserSelect,texts:props.texts.user_dropdown}),_react.default.createElement(_labDropdown.default,{select2:_labSelect.default,showLabDropdown:props.formSelectUser.showLabDropdown,userGroups:props.formSelectUser.userGroups,groupIdSelected:props.formSelectUser.groupIdSelected,userSelected:props.formSelectUser.userSelected,serviceCenterId:props.serviceCenterId,texts:props.texts.lab_dropdown,setGroupSelect:props.actions.setGroupSelect}),_react.default.createElement(_semanticUiReact.Form.Field,null,_react.default.createElement(_usageCappings.default,{user:props.user,formSelectUser:props.formSelectUser})))}SelectUserReservationForm.propTypes={assetId:_propTypes.default.number,serviceCenterId:_propTypes.default.number,formSelectUser:_formSelectUserReducer.FormReducerPropTypes,allUsersLabel:_propTypes.default.string,actions:_actions.ActionsProptypes,user:require.UserPropTypes,texts:_propTypes.default.shape({event_type:_propTypes.default.string,reservation_text:_propTypes.default.string,unavailable_text:_propTypes.default.string,cancel:_propTypes.default.string,save:_propTypes.default.string,user_scope:_propTypes.default.object,user_dropdown:_propTypes.default.object,lab_dropdown:_propTypes.default.object})},exports.default=SelectUserReservationForm},{"../../reducers/actions":1738,"../../reducers/formSelectUserReducer":1757,"../../reducers/userReducer":1764,"./inputs/labDropdown":1819,"./inputs/labSelect2":1820,"./inputs/userDropdown":1821,"./inputs/userSelect2":1822,"./selectEventType":1825,"./selectUserScope":1827,"./usageCappings":1828,"prop-types":1046,react:1427,"semantic-ui-react":1568}],1825:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function SelectEventType(props){return _react.default.createElement(_semanticUiReact.Form.Field,{inline:!0},_react.default.createElement("label",null,props.texts.event_type),_react.default.createElement(_semanticUiReact.Dropdown,{"data-test":"select_user_event_type",className:"no_auto_init",selection:!0,value:props.reservationType,options:(reservationText=props.texts.reservation_text,unavailableText=props.texts.unavailable_text,[{key:"reservation",text:reservationText,value:"reservation"},{key:"unavailable",text:unavailableText,value:"unavailable"}]),onChange:(selectReservationType=props.selectReservationType,function(e,_ref){_ref=_ref.value;return selectReservationType(_ref)})}));var selectReservationType,reservationText,unavailableText}SelectEventType.propTypes={reservationType:_propTypes.default.string,selectReservationType:_propTypes.default.func,texts:_propTypes.default.shape({event_type:_propTypes.default.string,reservation_text:_propTypes.default.string,unavailable_text:_propTypes.default.string})},exports.default=SelectEventType},{"prop-types":1046,react:1427,"semantic-ui-react":1568}],1826:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_actions=require("../../reducers/actions"),_alertBox=require("../../schedule/components/alertBox"),_alertMessageComponent=_interopRequireDefault(require("../../../common/components/alertMessageComponent")),_formSelectUserReducer=require("../../reducers/formSelectUserReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),_maintenanceForm=_interopRequireDefault(require("./maintenanceForm")),_reservationForm=_interopRequireDefault(require("./reservationForm")),require=require("../../reducers/userReducer");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _onCancel(props){return function(){props.actions.closeModalUserSelect()}}function SelectUserModal(props){var _getLoading,_creatingReservation,_disabledCancel;return props.formSelectUser.showModal?(_getLoading=function(lense){return _ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.view(_ramda.default.lensPath(lense)))},_disabledCancel=_creatingReservation=function(){return _getLoading(["service_reservations","create"])(props.request)},_react.default.createElement("div",{id:"schedule_select_user_modal"},_react.default.createElement(_semanticUiReact.Modal,{open:!0,onClose:_onCancel(props),mountNode:document.getElementById("schedule_select_user_modal")},props.loading?_react.default.createElement("div",{className:"ui active inverted dimmer"},_react.default.createElement("div",{className:"ui loader"})):null,_react.default.createElement(_semanticUiReact.Modal.Header,null,props.title),_react.default.createElement(_semanticUiReact.Modal.Content,null,_react.default.createElement(_alertMessageComponent.default,{show:props.alertBox.show,level:props.alertBox.level,header:props.alertBox.header,content:props.alertBox.content,onConfirm:props.actions.closeAlertBox}),function(props){return"reservation"===props.formSelectUser.reservationType?_react.default.createElement(_reservationForm.default,props):_react.default.createElement(_maintenanceForm.default,props)}(props)),_react.default.createElement(_semanticUiReact.Modal.Actions,null,_react.default.createElement(_semanticUiReact.Button,{onClick:_onCancel(props),disabled:_disabledCancel()},props.texts.cancel),_react.default.createElement(_semanticUiReact.Button,{primary:!0,onClick:function(props){return function(){props.formSelectUser.canSaveReservation&&props.actions.serviceReservationSave({assetId:props.assetId,equipmentId:props.formSelectUser.equipmentId,start_time:props.formSelectUser.reservation_start_time,end_time:props.formSelectUser.reservation_end_time,event_type:props.formSelectUser.reservationType,ownerId:_ownerId(props),groupProfileId:props.formSelectUser.groupIdSelected})}}(props),disabled:_creatingReservation()||!props.formSelectUser.canSaveReservation,loading:_creatingReservation()},props.texts.next))))):null}var _ownerId=function(props){return"unavailable"===props.formSelectUser.reservationType?_ramda.default.view(_ramda.default.lensPath(["user","id"]),props):_ramda.default.view(_ramda.default.lensPath(["formSelectUser","userSelected","id"]),props)};SelectUserModal.propTypes={title:_propTypes.default.string.isRequired,loading:_propTypes.default.bool,assetId:_propTypes.default.number,serviceCenterId:_propTypes.default.number,formSelectUser:_formSelectUserReducer.FormReducerPropTypes,timeframe:_propTypes.default.string,date:_propTypes.default.string,allUsersLabel:_propTypes.default.string,alertBox:_propTypes.default.shape(_alertBox.AlertBoxProcTypes),actions:_actions.ActionsProptypes,request:_propTypes.default.object,user:require.UserPropTypes,employee:_propTypes.default.bool,texts:_propTypes.default.shape({event_type:_propTypes.default.string,reservation_text:_propTypes.default.string,unavailable_text:_propTypes.default.string,cancel:_propTypes.default.string,next:_propTypes.default.string,user_scope:_propTypes.default.object,user_dropdown:_propTypes.default.object,lab_dropdown:_propTypes.default.object})},exports.default=SelectUserModal},{"../../../common/components/alertMessageComponent":1706,"../../reducers/actions":1738,"../../reducers/formSelectUserReducer":1757,"../../reducers/userReducer":1764,"../../schedule/components/alertBox":1768,"./maintenanceForm":1823,"./reservationForm":1824,"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1827:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _isAllUsersLabelEmpty(props){return _ramda.default.isEmpty(props.allUsersLabel)||_ramda.default.isNil(props.allUsersLabel)}function SelectUserScope(props){return _react.default.createElement(_semanticUiReact.Form.Group,{inline:!0,className:"select-user-scope"},_react.default.createElement("label",{className:"header"},props.texts.search_within),function(props){return _ramda.default.compose(_ramda.default.reject(_ramda.default.isNil),_ramda.default.map(_userSearchTypeRadio(props)))(["customers","institution","all"])}(props))}var _userSearchTypeRadio=function(params){return function(key){return function(props,key){return"all"===key&&_isAllUsersLabelEmpty(props)}(params,key)?null:_react.default.createElement(_semanticUiReact.Form.Field,{key:key},_react.default.createElement(_semanticUiReact.Radio,{key:key,label:function(props,key){return"all"===key?props.allUsersLabel:props.texts&&props.texts[key]?props.texts[key]:key}(params,key),name:"selectUserScope",value:key,checked:function(props,key){return _isAllUsersLabelEmpty(props)&&"all"===props.userSearchScope?"customers"===key:props.userSearchScope===key}(params,key),"data-test":"select_user_search_scope","data-testid":key,onChange:function(){return params.selectUserSearchScope(key)}}))}};SelectUserScope.propTypes={userSearchScope:_propTypes.default.string,selectUserSearchScope:_propTypes.default.func,allUsersLabel:_propTypes.default.string,texts:_propTypes.default.shape({search_within:_propTypes.default.string,customer:_propTypes.default.string,institution:_propTypes.default.string,all:_propTypes.default.string})},exports.default=SelectUserScope},{"prop-types":1046,ramda:1137,react:1427,"semantic-ui-react":1568}],1828:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _semanticUiReact=require("semantic-ui-react"),_formSelectUserReducer=require("../../reducers/formSelectUserReducer"),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),_userReducer=require("../../reducers/userReducer"),_i18n=require("../../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _toInt(value){return parseInt(value,10)}function SelectUserUsageCappings(props){return _usageCappingsEquipmentAsset(props)||_usageCappingsServiceCenter(props)?_react.default.createElement("div",null,_react.default.createElement(_semanticUiReact.Header,{as:"h4"},function(props){return _currentUser(props)===_usageCappingsUser(props)?(0,_i18n.t)("user_select.modal.usage_cappings.you_are_affected"):(0,_i18n.t)("user_select.modal.usage_cappings.other_is_affected")}(props)),function(props){return _react.default.createElement(_semanticUiReact.Table,{basic:!0},_react.default.createElement(_semanticUiReact.Table.Header,null,_react.default.createElement(_semanticUiReact.Table.Row,null,_react.default.createElement(_semanticUiReact.Table.HeaderCell,null,(0,_i18n.t)("user_select.modal.usage_cappings.scope")),_react.default.createElement(_semanticUiReact.Table.HeaderCell,null,(0,_i18n.t)("user_select.modal.usage_cappings.booked_amount")),_react.default.createElement(_semanticUiReact.Table.HeaderCell,null,(0,_i18n.t)("user_select.modal.usage_cappings.capped_amount")))),_react.default.createElement(_semanticUiReact.Table.Body,null,_ramda.default.compose(_usageCappingsRow,_usageCappingsServiceCenter)(props),_ramda.default.compose(_usageCappingsRow,_usageCappingsEquipmentAsset)(props)))}(props)):null}var _usageCappingsEquipmentAsset=_ramda.default.view(_ramda.default.lensPath(["formSelectUser","usageCappings","equipment_asset"])),_usageCappingsServiceCenter=_ramda.default.view(_ramda.default.lensPath(["formSelectUser","usageCappings","service_center"])),_currentUser=_ramda.default.compose(_toInt,_ramda.default.view(_ramda.default.lensPath(["user","id"]))),_usageCappingsUser=_ramda.default.compose(_toInt,_ramda.default.view(_ramda.default.lensPath(["formSelectUser","userSelected","id"]))),_usageCappingsRow=function(usageCappings){return usageCappings?_react.default.createElement(_semanticUiReact.Table.Row,{"data-test":"select_user_capping","data-testid":usageCappings.name},_react.default.createElement(_semanticUiReact.Table.Cell,{"data-test":"select_user_capping_name"},usageCappings.name),_react.default.createElement(_semanticUiReact.Table.Cell,{"data-test":"select_user_capping_usage_amount"},(0,_i18n.t)("user_select.modal.usage_cappings.booked_usage_amount",{amount:usageCappings.booked_usage_amount})),_react.default.createElement(_semanticUiReact.Table.Cell,{"data-test":"select_user_capping_cap_amount"},(0,_i18n.t)("user_select.modal.usage_cappings.cap_amount",{amount:usageCappings.cap_amount}))):null};SelectUserUsageCappings.propTypes={user:_userReducer.UserPropTypes,formSelectUser:_formSelectUserReducer.FormReducerPropTypes.isRequired},exports.default=SelectUserUsageCappings},{"../../../i18n":1832,"../../reducers/formSelectUserReducer":1757,"../../reducers/userReducer":1764,ramda:1137,react:1427,"semantic-ui-react":1568}],1829:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _actions=require("../reducers/actions"),_alertBox=require("../schedule/components/alertBox"),_dateFormatting=_interopRequireDefault(require("../../common/dateFormatting")),_equipmentAssetReducer=require("../reducers/equipmentAssetReducer"),_formSelectUserReducer=require("../reducers/formSelectUserReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_datesReducer=require("../reducers/datesReducer"),_ramda=_interopRequireDefault(require("ramda")),_react=_interopRequireDefault(require("react")),_selectUserModal=_interopRequireDefault(require("./components/selectUserModal")),_serviceCenterReducer=require("../../common/reducers/serviceCenterReducer"),_userReducer=require("../reducers/userReducer"),_i18n=require("../../i18n");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function SelectUserApp(props){var dateFormatting=(0,_dateFormatting.default)({calendar_display_24h:props.state.service_center.calendar_display_24h});return _react.default.createElement(_selectUserModal.default,{title:(0,_i18n.t)("user_select.modal.title",{from:dateFormatting.formatTime(props.state.formSelectUser.reservation_start_moment),to:dateFormatting.formatTime(props.state.formSelectUser.reservation_end_moment)}),loading:(dateFormatting=["schedules","show"],_ramda.default.compose(_ramda.default.defaultTo(!1),_ramda.default.view(_ramda.default.lensPath(dateFormatting)))(props.state.request)),serviceCenterId:props.state.service_center.id,assetId:props.state.equipment_asset.id,alertBox:props.state.alertBox,formSelectUser:props.state.formSelectUser,allUsersLabel:props.state.service_center.all_users_label,timeframe:props.state.dates.timeframe,date:props.state.dates.date,texts:(0,_i18n.t)("user_select.modal"),actions:props.actions,request:props.state.request,user:props.state.user,employee:props.state.service_center.employee})}SelectUserApp.propTypes={state:_propTypes.default.shape({dates:_datesReducer.PropTypesDatesReducer,equipment_asset:_equipmentAssetReducer.EquipmentAssetPropTypes,service_center:_serviceCenterReducer.ServiceCenterPropTypes,formSelectUser:_formSelectUserReducer.FormReducerPropTypes,request:_propTypes.default.object.isRequired,user:_userReducer.UserPropTypes,alertBox:_alertBox.AlertBoxProcTypes}).isRequired,actions:_actions.ActionsProptypes},exports.default=SelectUserApp},{"../../common/dateFormatting":1707,"../../common/reducers/serviceCenterReducer":1714,"../../i18n":1832,"../reducers/actions":1738,"../reducers/datesReducer":1753,"../reducers/equipmentAssetReducer":1754,"../reducers/formSelectUserReducer":1757,"../reducers/userReducer":1764,"../schedule/components/alertBox":1768,"./components/selectUserModal":1826,"prop-types":1046,ramda:1137,react:1427}],1830:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StoreCreator=exports.PropTypesStore=void 0;var _redux=require("redux"),_backgroundMessageReducer=require("./reducers/backgroundMessageReducer"),_datesReducer=require("./reducers/datesReducer"),_equipmentAssetReducer=require("./reducers/equipmentAssetReducer"),_eventModalReducer=require("./reducers/eventModalReducer"),_formSelectLabReducer=require("./reducers/formSelectLabReducer"),_formSelectUserReducer=require("./reducers/formSelectUserReducer"),_institutionReducer=require("./reducers/institutionReducer"),_linkedReservationModalReducer=require("./reducers/linkedReservationModalReducer"),_orderableItemsReducer=require("./reducers/orderableItemsReducer"),_propTypes=_interopRequireDefault(require("prop-types")),_reservationsReducer=require("./reducers/reservationsReducer"),_serviceCenterReducer=require("../common/reducers/serviceCenterReducer"),_userReducer=require("./reducers/userReducer"),_alertReducer=_interopRequireDefault(require("./reducers/alertReducer")),_appConfigReducer=_interopRequireDefault(require("./reducers/appConfigReducer")),_calendarBackgroundsReducer=_interopRequireDefault(require("./reducers/calendarBackgroundsReducer")),_modalReducer=_interopRequireDefault(require("../common/reducers/modalReducer")),_requestReducer=_interopRequireDefault(require("./reducers/requestReducer")),_reduxThunk=_interopRequireDefault(require("redux-thunk"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.StoreCreator=function(_ref){var logoutMiddleware=_ref.logoutMiddleware,paramsMiddleware=_ref.paramsMiddleware,appConfig=_ref.appConfig,urlParams=_ref.urlParams;return{init:function(){return(0,_redux.createStore)((0,_redux.combineReducers)({appConfig:(0,_appConfigReducer.default)(appConfig),request:(0,_requestReducer.default)({}),alertBox:(0,_alertReducer.default)({show:!1}),descriptionModal:(0,_modalReducer.default)("description",{show:!1}),calendarDetailsModal:(0,_modalReducer.default)("calendarDetails",{show:!1}),eventModal:(0,_eventModalReducer.EventModalReducer)(urlParams),dates:(0,_datesReducer.DatesReducer)({initialState:urlParams}),reservations:(0,_reservationsReducer.ReservationsReducer)({records:[]}),calendarBackgrounds:(0,_calendarBackgroundsReducer.default)([]),orderableItems:(0,_orderableItemsReducer.OrderableItemsReducer)([]),user:(0,_userReducer.UserReducer)({}),institution:(0,_institutionReducer.InstitutionReducer)({}),service_center:(0,_serviceCenterReducer.ServiceCenterReducer)(),equipment_asset:(0,_equipmentAssetReducer.EquipmentAssetReducer)({}),formSelectUser:(0,_formSelectUserReducer.FormSelectUserReducer)(urlParams),formSelectLab:(0,_formSelectLabReducer.FormSelectLabReducer)(urlParams),backgroundMessage:(0,_backgroundMessageReducer.BackgroundMessageReducer)({show:!1}),linkedReservationModal:(0,_linkedReservationModalReducer.LinkedReservationModalReducer)({show:!1})}),(0,_redux.applyMiddleware)(_reduxThunk.default,paramsMiddleware,logoutMiddleware))}}};require={init:_propTypes.default.func.isRequired};exports.PropTypesStore=require},{"../common/reducers/modalReducer":1713,"../common/reducers/serviceCenterReducer":1714,"./reducers/alertReducer":1749,"./reducers/appConfigReducer":1750,"./reducers/backgroundMessageReducer":1751,"./reducers/calendarBackgroundsReducer":1752,"./reducers/datesReducer":1753,"./reducers/equipmentAssetReducer":1754,"./reducers/eventModalReducer":1755,"./reducers/formSelectLabReducer":1756,"./reducers/formSelectUserReducer":1757,"./reducers/institutionReducer":1758,"./reducers/linkedReservationModalReducer":1759,"./reducers/orderableItemsReducer":1760,"./reducers/requestReducer":1761,"./reducers/reservationsReducer":1762,"./reducers/userReducer":1764,"prop-types":1046,redux:1429,"redux-thunk":1428}],1831:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SchedulesHistory=exports.SchedulePath=exports.PropTypesScheduleHistory=void 0;var _propTypes=_interopRequireDefault(require("prop-types")),_ramda=_interopRequireDefault(require("ramda")),_reactRouter=require("react-router");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.SchedulePath="/schedule/:timeframe?/:date?";exports.SchedulesHistory=function(historyBrowser){var _match=(0,_reactRouter.matchPath)(historyBrowser.location.pathname,{path:["/schedule/events/:event_id","/schedule/:timeframe?/:date?","/schedule/:timeframe/:date/events/new/:reservation_start_time/:reservation_end_time","/schedule/:timeframe/:date/events/:event_id","/schedule/:date/events/:event_id"],exact:!0,strict:!1});return{historyBrowser:historyBrowser,params:function(){return _ramda.default.compose(_ramda.default.defaultTo({}),_ramda.default.prop("params"),_ramda.default.defaultTo({}))(_match)}}};require=_propTypes.default.shape({historyBrowser:_propTypes.default.object.isRequired,params:_propTypes.default.func.isRequired});exports.PropTypesScheduleHistory=require},{"prop-types":1046,ramda:1137,"react-router":1424}],1832:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.t=void 0;exports.t=function(key,options){return options=Object.assign({},{scope:"js.frontend.schedules"},options||{}),I18n.t(key,options)}},{}],1833:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _reactRouterDom=require("react-router-dom"),_propTypes=_interopRequireDefault(require("prop-types")),_app=require("./app"),_react=_interopRequireDefault(require("react")),_history=require("./history"),_provider=_interopRequireDefault(require("./containers/provider"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function AppRouter(props){return _react.default.createElement("div",null,_react.default.createElement(_reactRouterDom.Switch,null,_react.default.createElement(_reactRouterDom.Route,{path:_history.SchedulePath,history:props.scheduleApp.history.historyBrowser},_react.default.createElement(_provider.default,{store:props.scheduleApp.store,appConfig:props.scheduleApp.appConfig,jsPDF:props.jsPDF,sentry:props.sentry})),_react.default.createElement(_reactRouterDom.Route,{exact:!0,path:"/"},_react.default.createElement(_reactRouterDom.Redirect,{to:"/schedule"}))))}AppRouter.propTypes={scheduleApp:_app.PropTypesScheduleApp,jsPDF:_propTypes.default.func.isRequired,sentry:_propTypes.default.object.isRequired},exports.default=AppRouter},{"./app":1704,"./containers/provider":1737,"./history":1831,"prop-types":1046,react:1427,"react-router-dom":1421}]},{},[1703])(1703)});
(function() {
  var CollaboratorSearch;

  CollaboratorSearch = function() {
    var _$accessHelpText, _$bodyGroup, _$colaboratorSearch, _$collaboratorIds, _$groupCollaborator, _$groupCollaborators, _$parent, _$sanitizer, _$sharingPanelSpinner, _IdToRemove, _accessData, _activateCollaboratorGroup, _activateElement, _collaboratorColor, _collaboratorGroupHandler, _collaboratorIdHandler, _disableElement, _extractPreselectedProfiles, _formatPreselectedProfiles, _formatResult, _formatSelection, _getCollaboratorData, _getCollaboratorIds, _getGroupAccess, _getGroupData, _getGroupIds, _getProfiles, _htmlSanitizer, _initCollaborator, _initCollaboratorSelect, _isElementDisabled, _mark, _onErrorRequestGetMostSharedUrl, _onSuccessRequestGetMostSharedUrl, _profileName, _profilesData, _pullProfileName, _pullRequiredAccess, _pushProfilename, _pushRequiredAccess, _requestColaborators, _requestGetMostSharedUrl, _researcherText, _select2RemovingHandler, _select2selectingHandler, _setBackgroundColor, _setBackgroundImage, _setCollaboratorData, _showAccessHelpText, _showSharingPanelSpinner, _triggerGroupCollaboratorCheckboxChange, init;
    _$colaboratorSearch = (function(_this) {
      return function() {
        return $j('.collaborator_search');
      };
    })(this);
    _$accessHelpText = (function(_this) {
      return function() {
        return _$colaboratorSearch().find('.access_help_text');
      };
    })(this);
    _$parent = (function(_this) {
      return function(container) {
        return $j(container).parent();
      };
    })(this);
    _setBackgroundColor = (function(_this) {
      return function(el, color) {
        return el.css({
          'background-color': color
        });
      };
    })(this);
    _setBackgroundImage = (function(_this) {
      return function(el, image) {
        return el.css({
          'background-image': image
        });
      };
    })(this);
    _showAccessHelpText = (function(_this) {
      return function() {
        return _$accessHelpText().removeClass('hide');
      };
    })(this);
    _researcherText = (function(_this) {
      return function(el) {
        if ($j.parseJSON(el.required_access)) {
          return 'access_request';
        } else {
          return 'collab';
        }
      };
    })(this);
    _profileName = (function(_this) {
      return function(el) {
        if (el.text) {
          return el.text;
        } else {
          return [el.first_name, el.last_name].join(' ');
        }
      };
    })(this);
    _collaboratorColor = function(el) {
      if (el.disabled) {
        return "disabled";
      }
      if (el.required_access) {
        return "required_access";
      }
      return '';
    };
    _$sanitizer = Object.create(HtmlSanitizer);
    _htmlSanitizer = (function(_this) {
      return function(data) {
        return _$sanitizer.SanitizeHtml(data);
      };
    })(this);
    _formatSelection = function(el, container) {
      if ($j.parseJSON(el.required_access)) {
        _setBackgroundColor(_$parent(container), '#FFA500');
        _setBackgroundImage(_$parent(container), 'none');
        _showAccessHelpText();
      }
      return "<span class='" + (_researcherText(el)) + "'>" + (_htmlSanitizer(_profileName(el))) + "</span>";
    };
    _mark = function(html, query, escapeMarkup) {
      var markup;
      if (!html) {
        return '';
      }
      markup = [];
      window.Select2.util.markMatch(html.toString(), query.term, markup, escapeMarkup);
      return markup.join('');
    };
    _formatResult = function(el, container, query, escapeMarkup) {
      return "<div class='result " + (_collaboratorColor(el)) + "' > <span style='width:20%'> " + (_mark([el.first_name, el.last_name].join(' '), query, escapeMarkup)) + " </span> <span style='width:20%'>" + (_mark(el.lab_name, query, escapeMarkup)) + "</span> <span style='width:40%'>" + (_mark(el.email, query, escapeMarkup)) + "</span> <span style='width:10%'>" + (_mark(el.phone_number, query, escapeMarkup)) + "</span> </div>";
    };
    _formatPreselectedProfiles = function(profile_names, core_access) {
      return function(val, index) {
        return {
          id: $j.trim(val),
          text: profile_names[index],
          required_access: core_access[index]
        };
      };
    };
    _extractPreselectedProfiles = function(element) {
      var profile_ids;
      profile_ids = element.val().split(',').filter(Boolean);
      profile_ids = $j.map(profile_ids, _formatPreselectedProfiles(element.data().profiles, element.data().access));
      return $j.grep(profile_ids, function(val) {
        return !!val;
      });
    };
    _requestColaborators = function(url, keyword, page, success) {
      return $j.ajax({
        url: url,
        data: {
          keyword: keyword,
          page: page
        },
        dataType: 'json',
        success: success
      });
    };
    _profilesData = function(el) {
      return $j(el).data('profiles');
    };
    _accessData = function(el) {
      return $j(el).data('access');
    };
    _pushProfilename = function(el, profile) {
      return _profilesData(el).push([profile["first_name"], profile["last_name"]].join(' '));
    };
    _pushRequiredAccess = function(el, object) {
      return _accessData(el).push(object['required_access']);
    };
    _select2selectingHandler = function(e) {
      _pushProfilename(e.target, e.object);
      return _pushRequiredAccess(e.target, e.object);
    };
    _select2RemovingHandler = function(el) {
      _activateCollaboratorGroup(el);
      _pullProfileName(el);
      return _pullRequiredAccess(el);
    };
    _activateElement = function(el) {
      return $j(el).removeClass('disable').addClass('active');
    };
    _activateCollaboratorGroup = function(el) {
      return _activateElement($j(el.target).closest('div.sharing_panel').find("[data-profile-id='" + el.val + "']"));
    };
    _pullProfileName = function(el) {
      return _profilesData(el.target).splice(_IdToRemove(el), 1);
    };
    _pullRequiredAccess = function(el) {
      return _accessData(el.target).splice(_IdToRemove(el), 1);
    };
    _IdToRemove = function(el) {
      return $j(el.target).val().split(',').indexOf(el.choice.id);
    };
    _initCollaboratorSelect = function(input, options) {
      var default_data;
      options = options != null ? options : {};
      default_data = options.default_data;
      input.select2({
        containerCss: {
          'width': '100%'
        },
        minimumInputLength: 0,
        multiple: options.multiple,
        formatResult: _formatResult,
        initSelection: function(elem, callback) {
          return callback(_extractPreselectedProfiles(elem));
        },
        formatSelection: _formatSelection,
        escapeMarkup: function(m) {
          return _htmlSanitizer(m);
        },
        query: function(options) {
          if (options.term.length > 1) {
            return _requestColaborators(input.attr('url'), options.term, options.page, function(data) {
              return options.callback({
                results: data.collaborators,
                more: data.meta.next_page
              });
            });
          } else {
            return options.callback({
              results: default_data
            });
          }
        }
      });
      input.on('select2-open', function() {
        return $j('.select2-search-choice-close').css('float', 'right');
      });
      input.on('select2-selecting', _select2selectingHandler);
      return input.on('select2-removing', _select2RemovingHandler);
    };
    _$collaboratorIds = function() {
      return $j('input[type="hidden"].collaborator_ids');
    };
    _$sharingPanelSpinner = function() {
      return $j('#sharing_pannel_spinner');
    };
    _showSharingPanelSpinner = function(show) {
      if (show) {
        return _$sharingPanelSpinner().show();
      } else {
        return _$sharingPanelSpinner().hide();
      }
    };
    _isElementDisabled = function(element) {
      return element.attr('disabled') === 'disabled';
    };
    _initCollaborator = function(element, default_data) {
      return _initCollaboratorSelect(element, {
        placeholer: '',
        multiple: true,
        default_data: default_data
      });
    };
    _onSuccessRequestGetMostSharedUrl = function(element) {
      return function(data) {
        return _initCollaborator(element, data.collaborators);
      };
    };
    _onErrorRequestGetMostSharedUrl = function(element) {
      return function(err) {
        return _initCollaborator(element, '');
      };
    };
    _requestGetMostSharedUrl = function(element, onSuccess, onError) {
      _showSharingPanelSpinner(true);
      return $j.ajax({
        url: element.attr('most_shared_url'),
        dataType: 'json',
        success: onSuccess(element),
        error: onError(element),
        complete: function() {
          return _showSharingPanelSpinner(false);
        }
      });
    };
    _collaboratorIdHandler = function() {
      var element;
      element = $j(this);
      if (_isElementDisabled(element)) {
        return _initCollaborator(element, '');
      }
      return _requestGetMostSharedUrl(element, _onSuccessRequestGetMostSharedUrl, _onErrorRequestGetMostSharedUrl);
    };
    _$bodyGroup = function() {
      return $j('body');
    };
    _$groupCollaborators = function(element) {
      return $j(element).closest('div').find('input[type="hidden"].collaborator_ids');
    };
    _$groupCollaborator = function(element) {
      return $j(element).closest('li');
    };
    _getCollaboratorData = function(element) {
      return _$groupCollaborators(element).data();
    };
    _getCollaboratorIds = function(element) {
      return _$groupCollaborators(element).val().split(',').filter(Boolean);
    };
    _getGroupData = function(element) {
      return _$groupCollaborator(element).data();
    };
    _getProfiles = function(element) {
      var profiles_names;
      profiles_names = _getCollaboratorData(element).profiles;
      profiles_names.push(_getGroupData(element).name);
      return profiles_names;
    };
    _getGroupAccess = function(element) {
      var group_access_requests;
      group_access_requests = _getCollaboratorData(element).access;
      group_access_requests.push(_getGroupData(element).access);
      return group_access_requests;
    };
    _getGroupIds = function(element) {
      var groups_ids;
      groups_ids = _getCollaboratorIds(element);
      groups_ids.push(_getGroupData(element).profileId);
      return groups_ids;
    };
    _setCollaboratorData = function(element) {
      var collaborators;
      collaborators = _$groupCollaborators(element);
      collaborators.data('profiles', _getProfiles(element));
      collaborators.data('access', _getGroupAccess(element));
      return collaborators.val(_getGroupIds(element));
    };
    _disableElement = function(element) {
      return element.removeClass('active').addClass('disable');
    };
    _triggerGroupCollaboratorCheckboxChange = function(element) {
      return _$groupCollaborators(element).trigger('change');
    };
    _collaboratorGroupHandler = function(ev) {
      ev.preventDefault();
      _disableElement(_$groupCollaborator(ev.target));
      _setCollaboratorData(ev.target);
      return _triggerGroupCollaboratorCheckboxChange(ev.target);
    };
    init = function() {
      _$collaboratorIds().livequery(_collaboratorIdHandler);
      return _$bodyGroup().on('click', '.collaborator_group', _collaboratorGroupHandler);
    };
    return {
      init: init
    };
  };

  $j(CollaboratorSearch().init);

}).call(this);
(function() {
  window.hideiLabNotice = function() {
    $j('#ilab_notice').slideUp();
    $j('#ilab_notice').hide();
    return false;
  };

  window.setiLabNotice = function(notice_text) {
    $j('#ilab_notice_text').html(notice_text);
    $j('#ilab_notice').slideDown();
    setTimeout(hideiLabNotice, 12000);
    return false;
  };

  window.setupDatePicker = function(use24h, timeStep) {
    var timeFormat;
    timeFormat = use24h ? "H:i" : "h:i A";
    $j('.time_period input.datepart, .asset_availability input.datepart').datetimepicker({
      todayButton: false,
      scrollInput: false,
      timepicker: false,
      format: "M d, Y"
    });
    return $j('.time_period input.timepart, .asset_availability input.timepart').timepicker({
      step: timeStep,
      timeFormat: timeFormat
    });
  };

}).call(this);
